Image Processing - Implementing Sobel Filter

Ahmad Siavosh picture Ahmad Siavosh · Jul 23, 2013 · Viewed 77.9k times · Source

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 processing field, to the extent that I don't even know how images are represented in computer. Totally no knowledge in this field.

I've read some papers and PDFs but they focus on many topics which I feel that I may not need them for my task.

I'd be happy to know your suggestions or if there is any particular paper, PDF, tutorial or quick guide for this purpose.

Thank you

EDIT:

Thank you all :) The result of our work can be downloaded from here.

Answer

azer89 picture azer89 · Jul 24, 2013

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 )