1

I am trying to apply a sobel operator by iterating through an image and applying a mask to surrounding pixels.

For now, I am trying to apply the vertical portion of the mask, which is:

-1 0 1
-2 0 2
-1 0 1

In my implementaiton, I am iterating through the rows and columns as follows:

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

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

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

            int sum = pixel1 + pixel2 + pixel3 + pixel4 + pixel5 + pixel6 + pixel7 + pixel8 + pixel9;
            verticalSobel.at<Vec3b>(i,j)[0] = sum;
            verticalSobel.at<Vec3b>(i,j)[1] = sum;
            verticalSobel.at<Vec3b>(i,j)[2] = sum;
        }
    }

Where the pixels are labeled as:

1 2 3
4 5 6
7 8 9

However, the resulting image is far off of what it should look like.

For reference, the resulting image is enter image description here

Where it should look similar to: enter image description here

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

I am not sure if I am simply implementing the operator incorrectly, or just iterating through the image incorrectly.

Any help would be greatly appreciated. Thanks!

0

1 Answer 1

1

You seem to have problems where the sum is negative. Take the absolute value of sum, and clamp it to 255 (or instead of absolute value, clamp it to 0 - depending of what you want to achieve. A "full" sobel operator usually uses 2d distance formula, so a horizonal/vertical only variant should use the absolute value)

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Using abs(sum) when setting my pixel value fixed it. I'm just curious as to what you mean by clamping the value. Are you saying if the value is > 255, then set it to 255?
@ecatalano: yes, as sum can be larger than 255
you can use opencv's saturate_cast function to prevent over- and underflows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.