Search code examples
c++edge-detectionsobel

How to treat the ouput-values after convolution with sobel-kernel


I'm trying to write a program (to practice C++) which can detect the edges of an image. I'm using SFML to load in the image.

I tried the Sobel-operation and got confused with the output values. I'm getting the intensity value from the pixels around my current pixel, and I multiply those with the appropriate value of the Sobel-kernel. Those values get added together.

My Problem is, that the input intensity values range from 0 to 255, but my output value can range from some negative value (can be smaller than -255) to some positive value (can be bigger than 255).

I couldn't find any hint on how to convert them into greyscale values; my InputImage is Greyscale, meaning r,g,b are similar. As a the Sobel-matrix/kernel I used a custom Matrix Class.

// The Sobel-kernel-x looks like that
int kernel_x[] = { 1, 0, -1,
                  2, 0, -2,
                  1, 0, -1 }



for (int y = 1; y < height - 1; y++)
{
    for (int x = 1; x < width - 1; x++)
    {
        int sum = 0;
        for (int i = -1; i <= 1; i++)
        {
            for (int j = -1; j <= 1; j++)
            {
                sum += img.getPixel(x + j, y + i).r * sobelkernel_x.at(j + 1, i + 1);
            }
        }
        //std::cout << sum << std::endl;
        cur_img->setPixel(x, y, sf::Color(sum, sum, sum));
    }
}

Solution

  • Try something like this:

    int MIN_SOBEL_VAL = minValue(sobelMatrix[][]);
    int MAX_SOBEL_VAL = maxValue(sobelMatrix[][]);
    
    int outputMatrix[][];
    
    void normalizer(sobelMatrix, MIN_SOBEL_VAL, MAX_SOBEL_VAL, outputMatrix, 0, 255) {
        for(i = 0 -> N)
            for(j = 0 -> M)
                outputMatrix[i][j] = g(sobelMatrix[i][j],MIN_SOBEL_VAL, MAX_SOBEL_VAL, 0, 255);
    }
    

    where g(n, a, b, x, y) is a function that maps an interval a,b => x,y linearly.

    For your case;

    g(...) = (n - MIN_SOBEL_VAL)/(MAX_SOBEL_VAL - MIN_SOBEL_VAL) * (255 - 0)
    

    This will map your sobelMatrix into and outputMatrix with values in between 255-0.