实施Sobel运营商

时间:2017-08-23 06:54:42

标签: c++ opencv vision

我正在尝试在水平和垂直方向上实施sobel算子。但不知何故,我得到了反向输出。我在下面附上的代码。对于水平蒙版

char mask [3][3]=  {{-1,-2,-1},{0,0,0},{1,2,1}};

void masking(Mat image){

Mat temImage= image.clone();
for (int i = 1; i < image.rows-1; i++)
{
    for (int j = 1; j < image.cols-1; j++)
    {   
        for(int k=0;k<3;k++)
        {
            int pixel1 = image.at<Vec3b>(i-1,j-1)[k] * -1;
            int pixel2 = image.at<Vec3b>(i,j-1)[k] * -2;
            int pixel3 = image.at<Vec3b>(i+1,j-1)[k] * -1;

            int pixel4 = image.at<Vec3b>(i-1,j)[k] * 0;
            int pixel5 = image.at<Vec3b>(i,j)[k] * 0;
            int pixel6 = image.at<Vec3b>(i+1,j)[k] * 0;

            int pixel7 = image.at<Vec3b>(i-1,j+1)[k] * 1;
            int pixel8 = image.at<Vec3b>(i,j+1)[k] * 2;
            int pixel9 = image.at<Vec3b>(i+1,j+1)[k] * 1;

            int sum = pixel1 + pixel2 + pixel3 + pixel4 + pixel5 + pixel6 + pixel7 + pixel8 + pixel9;
            if(sum < 0)
            {
                sum = 0;
            }

            if(sum > 255)
                sum = 255;

            temImage.at<Vec3b>(i,j)[k] = sum;


        }
    }
}
//printf("conter = %d",counter);
imshow( "Display", temImage );
imwrite("output1.png",temImage);

}

我的输出为

enter image description here

垂直掩码

char mask [3][3]=  {{-1,0,1},{-2,0,2},{-1,0,1}}; 

void masking(Mat image){

Mat temImage= image.clone();
for (int i = 1; i < image.rows-1; i++)
{
    for (int j = 1; j < image.cols-1; j++)
    {   
        for(int k=0;k<3;k++)
        {
            int pixel1 = image.at<Vec3b>(i-1,j-1)[k] * -1;
            int pixel2 = image.at<Vec3b>(i,j-1)[k] * 0;
            int pixel3 = image.at<Vec3b>(i+1,j-1)[k] * 1;

            int pixel4 = image.at<Vec3b>(i-1,j)[k] * -2;
            int pixel5 = image.at<Vec3b>(i,j)[k] * 0;
            int pixel6 = image.at<Vec3b>(i+1,j)[k] * 2;

            int pixel7 = image.at<Vec3b>(i-1,j+1)[k] * -1;
            int pixel8 = image.at<Vec3b>(i,j+1)[k] * 0;
            int pixel9 = image.at<Vec3b>(i+1,j+1)[k] * 1;

            int sum = pixel1 + pixel2 + pixel3 + pixel4 + pixel5 + pixel6 + pixel7 + pixel8 + pixel9;
            if(sum < 0)
            {
                sum = 0;
            }

            if(sum > 255)
                sum = 255;

            temImage.at<Vec3b>(i,j)[k] = sum;


        }
    }
}
//printf("conter = %d",counter);
imshow( "Display", temImage );
imwrite("output1.png",temImage);

}

我的输出为

enter image description here

主要功能见

int main( int argc, char** argv ){
Mat input_image = imread("sobel1.jpg",1);
masking(input_image);
waitKey(0);
return 0;

}

根据指南https://www.tutorialspoint.com/dip/sobel_operator.htm,我应该得到反向输出。任何人都可以帮助我

原始图片是

enter image description here

1 个答案:

答案 0 :(得分:1)

不,the tutorial没有错,它谈的是面具而不是渐变。该教程的弱点在于它没有提到我们使用他们称之为垂直蒙版的方式来计算水平渐变。