How to implement Sobel operator

Viewed 448

I have implemented Sobel operator in vertical direction. But the result which I am getting is very poor. 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 input to the algorithm is enter image description here

My output is enter image description here

I have also tried using Gaussian blur before actually convolving an image and the output I got is enter image description here

The output which I am expecting isenter image description here

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

1 Answers
Related