You are calculating the input and output indices incorrectly.
First point to remember while working with OpenCV images is that they are aligned, i.e. each row is padded at the end with some random values. So while calculating the linear index of a pixel in color and grayscale images, widthStep
should be used instead of width
.
The generic formula to calculate index of a pixel is:
i * widthStep/sizeof(type) + (channels * j)
Where i
is the row number, and j
is the column number.
Translating the above formula for the current case, the indices will be calculated as follows:
Input:
int index = i * colorWidthStep + (3 * j);
Output:
h_out[i * grayWidthStep + j] = (unsigned char)temp;
You may create 2 additional global variables colorWidthStep
and grayWidthStep
along with width
and height
. Initialize the variables as follows:
width = image_input->width;
height = image_input->height;
colorWidthStep = image_input->widthStep;
grayWidthStep = image_output->widthStep;