# Using Sobel Filter in Edge Detection

Using Sobel Filter in Edge Detection

# Using Sobel Filter in Edge Detection¶

Sobel filter or Sobel operator are commonly used in image processing and computer vision for edge detection purpose.

The Sobel operator utilizes two 3x3 kernals to calculate approximations of the derivatives - one for horizontal, one for vertical direction: $G_x = \begin{bmatrix} -1 & 0 & +1\\ -2 & 0 & +2 \\ -1 & 0 & +1 \end{bmatrix} \quad \textrm{and} \quad G_y = \begin{bmatrix} -1 & -2 & -1\\ 0 & 0 & 0 \\ +1 & +2 & +1 \end{bmatrix}$

For each point in a given image, the approximation of gradient is $G = \sqrt{G_x^2 + G_y^2}$

Pros

• Simplicity (hence attractive in realtime applications)
• $G_x$ and $G_y$ can be used to calculate direction of edges

Cons

• Sensitive to noise
• Not good at thin and smooth edges

For more details see the wiki page on Sobel Filter

In [1]:
# Load packagesimport osfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as pltfrom scipy.ndimage import filters#Ensure plots embeded in notebook%matplotlib inlineplt.rcParams['figure.figsize']= (8.0, 6.0)plt.rcParams['image.interpolation'] = 'nearest'plt.rcParams['image.cmap'] = 'gray'
In [2]:
im = np.array(Image.open('hummingbird.jpg').convert('L'));plt.imshow(im, cmap='gray');
In [3]:
# Calculate gradients on x and y directionimx = np.zeros(im.shape);imy = np.zeros(im.shape);filters.sobel(im, 1, imx)filters.sobel(im, 0, imy)magnitude = np.sqrt(imx**2 + imy**2)plt.subplot(2,2,1)plt.imshow(imx, cmap='gray')plt.title('X Derivative')plt.axis('off')plt.subplot(2,2,2)plt.imshow(imy, cmap='gray')plt.title('Y Derivative')plt.axis('off')plt.subplot(2,2,3)plt.imshow(magnitude, cmap='gray')plt.title('Gradient Magnitude')plt.axis('off')plt.subplot(2,2,4)plt.imshow(im, cmap='gray')plt.title('Original')plt.axis('off')plt.show()

Published: September 10 2016

• category:
• tags: