Understanding and Implementing Edge Detection in C with Sobel Operator

Roshan
3 min readMay 2, 2024

--

Introduction:

Begin by introducing the concept of edge detection in image processing. Explain why it’s important and how it’s used in various applications such as computer vision, medical imaging, and more. Briefly mention the Sobel operator as one of the popular techniques for edge detection.

What is the Sobel Operator?

Provide an overview of the Sobel operator. Explain how it works by convolving an image with a pair of 3x3 kernels to calculate the gradient magnitude. Discuss the role of these kernels in detecting horizontal and vertical edges.

Implementing Sobel Edge Detection in C:

Break down the C code you provided into smaller, digestible sections. Explain each part, including:

  • Opening and reading a PGM image file.
  • Checking the file format and dimensions.
  • Performing Sobel edge detection on the image data.
  • Writing the edge-detected image to an output file.

Basic Convolution Concept :

Let’s consider an input image of size 𝑚×𝑛 and a kernel 𝐾 of size 𝑝×𝑞.

The convolution operation, denoted by 𝐼∗𝐾, is performed by sliding the kernel over the input image such that each element of the kernel 𝐾(𝑖,𝑗) is multiplied with the corresponding element of the image 𝐼(𝑥,𝑦) and then summed up. This sum represents the new value for the central pixel in the output image.

Mathematically, the convolution operation at position (𝑥,𝑦)(x,y) of the output image can be expressed as:

where:

  • (𝑥,𝑦) represents the coordinates of the current pixel in the output image.
  • (𝑖,𝑗) represents the coordinates of the current element in the kernel K.
  • 𝑝p and 𝑞q are the dimensions of the kernel.
  • 𝐼(𝑥+𝑖,𝑦+𝑗) represents the pixel value in the input image at position (𝑥+𝑖,𝑦+𝑗).
  • 𝐾(𝑖,𝑗)K(i,j) represents the corresponding element in the kernel 𝐾K.

This operation is repeated for every pixel in the output image by sliding the kernel across the input image.

int gx[3][3] = {
{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}
};
int gy[3][3] = {
{-1, -2, -1},
{0, 0, 0},
{1, 2, 1}
};

Here is how the convolution is done :

for (int i = 1; i < height - 1; i++) {
for (int j = 1; j < width - 1; j++) {
sumx = 0.0;
sumy = 0.0;
for (int p = -1; p <= 1; p++) {
for (int q = -1; q <= 1; q++) {
sumx += (image[i + p][j + q] * gx[p + 1][q + 1]);
sumy += (image[i + p][j + q] * gy[p + 1][q + 1]);
}
}
edgeImage[i][j] = (unsigned char)sqrt(sumx * sumx + sumy * sumy);
}
}

The remaining part of the code contains only input-taking and output writings.

Testing and Results:

Input image given for edge detection
Output image after Edge detection.

Good to see you, Spending time in reading meaning full content.

GoodLuck!!

Let me know if you need further assistance!

Linkedin: https://www.linkedin.com/in/roshantwinn09/

--

--