带OpenCV的灰度C ++(出现一些噪音)

时间:2013-11-19 05:23:56

标签: c++ image opencv grayscale

我有一些关于使用openCV转换为灰度的问题来制作手动功能。 这是我的代码。

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

在我的灰度代码中。

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

但结果没有按预期执行,它中出现了一些噪音。 appears some noise of grayscale image

我仍然没有找到导致错误的代码。 :( thx之前。

1 个答案:

答案 0 :(得分:1)

您正在错误地计算输入和输出索引。 在使用OpenCV图像时要记住的第一点是它们是对齐的,即每行在末尾用一些随机值填充。因此,在计算彩色和灰度图像中像素的线性索引时,应使用widthStep代替width

计算像素索引的通用公式为:

i * widthStep/sizeof(type) + (channels * j)

i是行号,j是列号。

翻译当前案例的上述公式,指数计算如下:

<强>输入:

int index = i * colorWidthStep + (3 * j);

<强>输出:

h_out[i * grayWidthStep + j] = (unsigned char)temp;

您可以创建另外两个全局变量colorWidthStepgrayWidthStep以及widthheight。按如下方式初始化变量:

width     = image_input->width;
height    = image_input->height;
colorWidthStep = image_input->widthStep;
grayWidthStep = image_output->widthStep;