0

我正在尝试使用基本代码(自己的代码)从灰度创建边缘检测(sobel)过滤器。这里的代码:

int dx [3][3] = { -1 , 0 , 1 ,
                 -2 , 0 , 2 ,
                 -1 , 0 , 1};

int dy [3][3] = {1 ,2 ,1 ,
                 0 ,0 ,0 ,
                -1 , -2 , -1};

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 = h_in[i*widthStep + j*channels];
       int gray = 0.3*(index)+0.6*(index+1)+0.1*(index+2);
       h_out[i*widthStepOutput+j]=gray;
   }
}

}

void h_EdgeDetect( unsigned char* h_in, unsigned char* h_out)
{
//int widthStep2 = image_input->widthStep2/sizeof(uchar);
int s;
for (int i=1; i < height-2; i++)
    for (int j=1; j < width-2; j++)
    {
        // apply kernel in X direction
        int sum_x=0;
        for(int m=-1; m<=1; m++)
            for(int n=-1; n<=1; n++)
            {
                s=h_in[(i+m)*widthStep+(j+channels)+n]; // get the (i,j) pixel value
                sum_x+=s*dx[m+1][n+1];
            }
        // apply kernel in Y direction
        int sum_y=0;
        for(int m=-1; m<=1; m++)
            for(int n=-1; n<=1; n++)
            {
                s=h_in[(i+m)*widthStep+(j+channels)+n]; // get the (i,j) pixel value
                sum_y+=s*dy[m+1][n+1];
            }
        int sum=abs(sum_x)+abs(sum_y);
        if (sum>255)
            sum=255;
        h_out[i*widthStepOutput + j+channels]=sum; // set the (i,j) pixel value
    }

}

主文件

int main(int argc, char** argv)
{
    starttime = getTickCount();
    int c;  
     CvCapture* capture = cvCaptureFromCAM(1); 

   while(1)
   {
      image_input=cvQueryFrame(capture);
      channels  = 1;
      IplImage* image_output = cvCreateImage(cvGetSize(image_input),IPL_DEPTH_8U,channels); 
      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;
      widthStep = image_input->widthStep;
      widthStepOutput = image_output->widthStep;

      //grayscale operation
      h_grayscale(h_in , h_out );

      //Edge Detection
      h_EdgeDetect ( h_in , h_out ) ;

      cvShowImage("Original", image_input);
      cvShowImage("CPU", image_output);

      c=cvWaitKey(10);
      if(c == 27)
          break;  
 }

  return 0;
  }

但是来自网络的结果是这样的 在此处输入图像描述

问题是 Sobel 滤波操作时图像变大。可能是因为灰度滤镜和Sobel滤镜时的通道不同。如何将通道 1 更改为 3 (RGB)?T_T

谢谢之前:)

4

0 回答 0