How to implement the Sobel operator

I have implemented the sobel operator vertically. But the result I am getting is very low. I have attached my code below.

int mask_size= 3;

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

      

void sobel (Mat input_image) {

/**Padding m-1 and n-1 zeroes to the result where m and n are mask_size**/

Mat result=Mat::zeros(input_image.rows+(mask_size - 1) * 2,input_image.cols+(mask_size - 1) * 2,CV_8UC1);
Mat result1=Mat::zeros(result.rows,result.cols,CV_8UC1);            
int sum= 0;

/*For loop for copying original values to new padded image **/

for(int i=0;i<input_image.rows;i++)
    for(int j=0;j<input_image.cols;j++)
        result.at<uchar>(i+(mask_size-1),j+(mask_size-1))=input_image.at<uchar>(i,j);

GaussianBlur( result, result, Size(5,5), 0, 0, BORDER_DEFAULT );
/**For loop to implement the convolution **/

for(int i=0;i<result.rows-(mask_size - 1);i++)
    for(int j=0;j<result.cols-(mask_size - 1);j++)
    {
        int counter=0;
        int counterX=0,counterY=0;
        sum= 0;
        for(int k= i ; k < i + mask_size ; k++)
        {
            for(int l= j ; l< j + mask_size ; l++)
            {
                sum+=result.at<uchar>(k,l) * mask[counterX][counterY];
                counterY++;
            }
            counterY=0;
            counterX++;
        }
        result1.at<uchar>(i+mask_size/2,j+mask_size/2)=sum/(mask_size * mask_size);
    }

/** Truncating all the extras rows and columns **/

result=Mat::zeros( result1.rows  - (mask_size - 1) * 2, result1.cols - (mask_size - 1) * 2,CV_8UC1);
for(int i=0;i<result.rows;i++)
    for(int j=0;j<result.cols;j++)                      
        result.at<uchar>(i,j)=result1.at<uchar>(i+(mask_size - 1),j+(mask_size - 1));

imshow("Input",result);
imwrite("output2.tif",result);

      

}

My contribution to the algorithm enter image description here

My conclusion enter image description here

I have also tried blurring wanggang gauss before actually convolving the image and the result was enter image here

The result I expect is enter image description here

The guide I'm using is: https://www.tutorialspoint.com/dip/sobel_operator.htm

+3


source to share


1 answer


Your bundle looks fine, although I just took a quick look.

Check the output type. It is an unsigned char.

Now think about the values ​​your output pixels might have if you have negative kernel values ​​and if it's a good idea to store them directly in uchar.



If you store -1 in an unsigned char, it will be wrapped around and your result will be 255. If you're wondering where all this extra white stuff comes from. These are really small negative gradients.

The desired result looks like the absolute of the Sobel output values.

+1


source







All Articles