Allie
Allie

Reputation: 1

What am I doing wrong when executing the sobel filter function in c++

Here is my sobel filter function performed on a grayscale image. Apparently I'm not doing my calculations correct because I keep getting an all black image. I have already turned in the project but it is bothering me that the results aren't right.

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

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

//variable declaration
int mag;
int pix_x, pix_y = 0;
int img_x, img_y;

for (img_x = 0; img_x < img->x; img_x++)
{
    for (img_y = 0; img_y < img->y; img_y++)
    {
            pix_x = 0;
            pix_y = 0;

            //calculating the X and Y convolutions
            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    pix_x += (img->data[img_y * img->x + img_x].red + img->data[img_y * img->x + img_x].green + img->data[img_y * img->x + img_x].blue) * sobelH[1 + i][1 + j];
                    pix_y += (img->data[img_y * img->x + img_x].red + img->data[img_y * img->x + img_x].green + img->data[img_y * img->x + img_x].blue) * sobelV[1 + i][1 + j];
                }
            }

        //Gradient magnitude
        mag = sqrt((pix_x * pix_x) + (pix_y * pix_y));

        if (mag > RGB_COMPONENT_COLOR)
            mag = 255;
        if (mag < 0)
            mag = 0;

        //Setting the new pixel value
        img->data[img_y * img->x + img_x].red = mag;
        img->data[img_y * img->x + img_x].green = mag;
        img->data[img_y * img->x + img_x].blue = mag;
    }
}

Upvotes: 0

Views: 354

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60799

Another mistake is that you're writing in the input image. You write at location (x,y), then compute the filter result for location (x+1,y) using the modified value at (x,y), which is the wrong value to use.

You need to write your result to a new image.

Upvotes: 0

Urukann
Urukann

Reputation: 485

Although your code could use some improvement, the main reason is that you compute the convolution at constant img_y and img_x. What you need to do is:

pix_x += (img->data[img_y * img->x + img_x + i].red + img->data[img_y * img->x + img_x + i].green + img->data[img_y * img->x + img_x + i].blue) * sobelH[1 + i][1 + j];

Indeed, the Sobel convolution is symmetric, so if you compute the convolution with a constant image, it will result in only black.

Note that in the above example I do not take into account the border of the image. You should make sure to not access pixels that are outside your pixel array.

Upvotes: 1

Related Questions