2

I need to write an OpenCL kernel. Via kernel argument I get an input image with a certain dimension (example: width: 600px, height: 400px). The algorithm I need to run is: "Nearest Neighbor Interpolation".

In the image below, one starts from pixel (1,1) (left image, green pixel). My scaling factor is 3. This means that in my output image this pixel must appear 9 times.

Now my question is, how can I give each green pixel the value (pixelValue) of the SourceImage using the code below (using 2 for-loops).

Input dimentions: width = 600px, height: 400px
Ouput dimentions: width = 1800px, height: 1200px

Scetch

scetch - nearest neighbour interpolation

OpenCL code

__kernel

void NearestNeighbourScaling(__read_only image2d_t SourceImage, __write_only image2d_t DestinationImage, int width, int height, int scalingFactor)
{
    int row = get_global_id(0);
    int col = get_global_id(1);

    const int scaledWidth = width * scalingFactor;
    const int scaledHeight = height * scalingFactor;

    // Declaring sampler    
    const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_LINEAR | CLK_ADDRESS_CLAMP;

    float4 pixelValue = read_imagef(SourceImage, sampler, (int2)(col, row));

    for(int i = 0; i < scalingFactor; i++)
    {
        for(int j = 0; j < scalingFactor; j++)
        {
            write_imagef(DestinationImage, (int2)(?, ?), pixelValue);
        }
    }
}
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
AntoBoy
  • 64
  • 5

2 Answers2

2

In short: The trick to do nearest neighbor interpolation is integer arithmetic or in some cases float->integer casting.

In your case, the solution for the ?? in the double loop is:

write_imagef(DestinationImage, (int2)(scalingFactor*col+i, scalingFactor*row+j), pixelValue);

How this works: for each of the scalingFactorxscalingFactor pixels, it sets the same color from the one pixel in the input image. The x-position of the pixels in the output image is scalingFactor*col+i, so with scalingFactor=3 this is 3*col+0, 3*col+1, 3*col+2. If col=1 like in the image for the green pixels, this leads to x positions 3, 4, 5 all being colored green. y direction works the same.

ProjectPhysX
  • 4,535
  • 2
  • 14
  • 34
2

You need to take your scaling in consideration when calculating the position. You know that the fields that you are going to fill are going to be n (scalingFactor) times larger than the original.

This means that first you need to make sure that your output image sizes is equal to the input image times scalingsfactor.

For the write_imagef(DestinationImage, (int2)(?, ?), pixelValue); you also need to take the scaling inconsideration for the position.

For the row you want to do this: row * scalingFactor + i for the column you want to do the same but with the j.

write_imagef(DestinationImage, (int2)(row * scalingFacor + i, col * scalingsfactor + j), pixelValue);
Seppe Mariën
  • 355
  • 1
  • 13