简体   繁体   English

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

[英]Grayscale C++ with OpenCV (appears some noise)

i have some problem about convert to grayscale using openCV in make the manual function. 我在使用手动功能使用openCV转换为灰度时遇到一些问题。 And this is my code. 这是我的代码。

main.cpp 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. 但结果并未达到应有的效果,其中似乎有些杂音。 出现一些灰度图像的噪点

I still have not found where the code that makes the error. 我仍然没有找到导致错误的代码。 :( thx before. :(在此之前。

You are calculating the input and output indices incorrectly. 您正在错误地计算输入和输出索引。 First point to remember while working with OpenCV images is that they are aligned, ie each row is padded at the end with some random values. 使用OpenCV图像时要记住的第一点是它们是对齐的,即在每一行的末尾都填充了一些随机值。 So while calculating the linear index of a pixel in color and grayscale images, widthStep should be used instead of width . 因此,在计算彩色和灰度图像中像素的线性索引时,应使用widthStep而不是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. 其中, i是行号, j是列号。

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 . 您可以创建两个额外的全局变量colorWidthStepgrayWidthStep以及widthheight Initialize the variables as follows: 初始化变量,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM