Welcome Guest, you are in: Login

Search the wiki
»

MUST Corp.

www.must.or.kr

# Sobel operator

Modified on 2010/05/04 17:15 Categorized as Digital Image Processing
http://en.wikipedia.org/wiki/Sobel_operator

The Sobel operator is a discrete differentiation operator, calculating an approximation of the gradient of the image intensity function. The operator calculates the gradient of the image intensity at each point, giving the direction of the largest possible increase from light to dark and the rate of change in that direction. The result therefore shows how sharply or smoothly  the image changes at that point.

The operator uses two 3×3 kernels which are convolved with the original image to calculate approximations of the derivatives - one for vertical changes, and one for horizontal

Image source

wikipedia

Here Gx and Gy are the two kernels and A is the original image.

At each point in the image, the resulting gradient approximations can be combined to give the gradient magnitude, using:

Image source :wikipedia Code for sobel filter

```namespace sobel
{
class sobel
{
Bitmap b, b1;
public Image apply(Image im)
{
int[,] gx = new int[,] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };   //  The matrix Gx
int[,] gy = new int[,] { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };  //  The matrix Gy
b = (Bitmap)im;
Bitmap b1 = new Bitmap(im);
for (int i = 1; i < b.Height - 1; i++)   // loop for the image pixels height
{
for (int j = 1; j < b.Width - 1; j++) // loop for image pixels width
{
float new_x = 0, new_y = 0;
float c;
for (int hw = -1; hw < 2; hw++)  //loop for cov matrix
{
for (int wi = -1; wi < 2; wi++)
{
c =(b.GetPixel(j+wi,i+hw).B +b.GetPixel(j+wi,i+hw).R +b.GetPixel(j+ wi,i+hw).G)/3;
new_x += gx[hw + 1, wi + 1] * c;
new_y += gy[hw + 1, wi + 1] * c;
}
}
if (new_x * new_x + new_y * new_y > 128*128)
b1.SetPixel(j, i, Color.Black);
else
b1.SetPixel(j, i, Color.White);
}
}
return (Image)b1;
}
}
The class takes as input a grayscale image .The code to convert an image to grayscale is
given below if required .
```
```public Image gray(Image Im)
{
Bitmap b = (Bitmap)Im;
for (int i = 1; i < b.Height ; i++)   // loop for the image pixels height
{
for (int j = 1; j < b.Width ; j++)  // loop for the image pixels width
{
Color col;
col = b.GetPixel(j,i );
b.SetPixel(j , i , Color.FromArgb((col.R + col.G + col.B) / 3, (col.R + col.G + col.B) / 3, (col.R + col.G + col.B) / 3));
}
}
return (Image)b;
}```
```http://www.eggheadcafe.com/tutorials/aspnet/c833c86a-677a-4ff3-b820-43126cbeb1a7/net-gdi-graphics-edge-d.aspx

```