Question

i have some problem about convert to grayscale using openCV in make the manual function. And this is my code.

main.cpp

unsigned int height, width;
int main(int argc, char** argv)
{

  IplImage* image_input = cvLoadImage("duck.jpg", CV_LOAD_IMAGE_UNCHANGED);
  IplImage* image_output = cvCreateImage(cvGetSize(image_input),IPL_DEPTH_8U,1);

  unsigned char *h_out = (unsigned char*)image_output->imageData;
  unsigned char *h_in =  (unsigned char*)image_input->imageData;

  width     = image_input->width;
  height    = image_input->height;

  h_grayscale(h_in, h_out);

  cvShowImage("Original", image_input);
  cvShowImage("CPU", image_output);
  cvReleaseImage(&image_input);
  cvReleaseImage(&image_output);
  waitKey(0);
}

in this my grayscale code.

void h_grayscale( unsigned char* h_in, unsigned char* h_out)
{
for(int i=0;i<height;i++){
    for(int j=0;j<width;j++){
       int index = (i*j)*3;
       double temp = 0.3*h_in[index]+0.6*h_in[index+1]+0.1*h_in[index+2];
       h_out[i*j] = (unsigned char)temp;
   }
}

but the results are not performing as it should, it appears some noise in it. appears some noise of grayscale image

I still have not found where the code that makes the error. :( thx before.

Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top