Search code examples
kernelopenclinterpolationnearest-neighborimage-scaling

Nearest Neigbour Interpolation code using OpenCL kernel


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);
        }
    }
}

Solution

  • 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);