Image Processing - Implementing Sobel Filter

后端 未结 8 1736
梦毁少年i
梦毁少年i 2020-12-13 02:46

I\'ve got a task to implement Sobel filter which is, as you know, an image processing filter for edge detection. But unfortunately, I\'ve got no experience in image processi

相关标签:
8条回答
  • 2020-12-13 03:29

    It's pretty easy, you just need to convolve your image with a Sobel filter. A Sobel filter has two kernels, x-direction kernel and y-direction kernel. The x-direction kernel detects horizontal edges, and y-direction kernels detects vertical edges.

    x-direction kernel (the size is 3x3)

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

    y-direction kernel

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

    To calculate the convolution at pixel (x,y), define a window of size equal to the kernel size (source code to calculate magnitude in x and magnitude in y are identical):

    double magX = 0.0; // this is your magnitude
    
    for(int a = 0; a < 3; a++)
    {
        for(int b = 0; b < 3; b++)
        {            
            int xn = x + a - 1;
            int yn = y + b - 1;
    
            int index = xn + yn * width;
            magX += image[index] * kernelx[a][b];
        }
     }
    

    Note that the input is a grayscale image and it can be represented as 1D array of double (This is just a trick, since a pixel value in coordinate (x,y) can be accessed with index = [x + y * width] )

    To calculate magnitude in pixel (x,y) given magX and magY :

    mag = sqrt( magX^2 + magY^2 )

    0 讨论(0)
  • 2020-12-13 03:30

    Gx is estimating the gradient in the x-direction (columns) and Gy is estimating the gradient in the y-direction (rows). So Gy detects horizontal lines, and Gx detects vertical lines.

    0 讨论(0)
提交回复
热议问题