2
votes

Can someone tell me a fast function to find the square of each pixel of an int image. I need it for iOS app dev. I am working directly on the memory of the image defined as

int *image_sqr_Baseaaddr = (int *) malloc(noOfPixels * sizeof(int));

for (int i=0; i<newNoOfPixels; i++)
     image_sqr_Baseaaddr[i] = (int) image_scaled_Baseaaddr[i] * (int) image_scaled_Baseaaddr[i];

This is obviously the slowest function possible. I heard that ARM Neon intrinsics on the iOS can be used to make several operations in 1 cycle. Maybe that's the way to go ?

The problem is that I am not very familiar and don't have enough time to learn assembly language at the moment. So it would be great if anyone can post a Neon intrinsics code for the problem mentioned above or any other fast implementation in C/C++.

The only code in NEON intrinsics that I am able to find online is the code for RGB to gray http://computer-vision-talks.com/2011/02/a-very-fast-bgra-to-grayscale-conversion-on-iphone/

1

1 Answers

3
votes

Here's a simple NEON implementation:

#include <arm_neon.h>

// ...

int i;

for (i = 0; i <= newNoOfPixels - 16; i += 16)           // SIMD loop
{
    uint8x16_t v = vld1q_u8(&image_scaled_Baseaaddr[i]);// load 16 x 8 bit pixels

    int16x8_t vl = (int16x8_t)vmovl_u8(vget_low_u8(v)); // unpack into 2 x 16 bit vectors
    int16x8_t vh = (int16x8_t)vmovl_u8(vget_high_u8(v));

    vl = vmulq_s16(vl, vl);                             // square them
    vh = vmulq_s16(vh, vh);

    int32x4_t vll = vmovl_s16(vget_low_s16(vl));        // unpack to 4 x 32 bit vectors
    int32x4_t vlh = vmovl_s16(vget_high_s16(vl));
    int32x4_t vhl = vmovl_s16(vget_low_s16(vh));
    int32x4_t vhh = vmovl_s16(vget_high_s16(vh));

    vst1q_s32(&image_sqr_Baseaaddr[i], vll);            // store 32 bit squared values
    vst1q_s32(&image_sqr_Baseaaddr[i + 4], vlh);
    vst1q_s32(&image_sqr_Baseaaddr[i + 8], vhl);
    vst1q_s32(&image_sqr_Baseaaddr[i + 12], vhh);
}
for ( ; i < newNoOfPixels; ++i)                         // scalar clean up loop
{
    int32_t p = (int32_t)image_scaled_Baseaaddr[i];
    image_sqr_Baseaaddr[i] = p * p;
}

Note that this will perform best if both image_scaled_Baseaaddr and image_sqr_Baseaaddr are 16 byte aligned.

Note also that the above code is untested and may need some further work.