Edge detection with the Sobel filter

The Sobel operator (for more information on Sobel operator visit http://en.wikipedia.org/wiki/Sobel_operator) can be used for edge detection in images. The edge detection is based on performing a discrete differentiation on the image intensity. Because an image is two-dimensional, the gradient also has two components; unless we limit ourselves to one dimension, of course. We will apply the Sobel filter to the picture of Lena Soderberg.

How to do it...

In this section, we will learn how to apply the Sobel filter to detect edges in the Lena image.

  1. Apply the Sobel filter in the x direction.

    To apply the Sobel filter in the x direction, we need to set the axis parameter to 0:

    sobelx = scipy.ndimage.sobel(lena, axis=0, mode='constant')
  2. Apply the Sobel filter in the y direction.

    To apply the Sobel filter in the y direction, we need to set the axis parameter to 1:

    sobely = scipy.ndimage.sobel(lena, axis=1, mode='constant')
  3. Apply the default Sobel filter.

    The default Sobel filter only requires the input array:

    default = scipy.ndimage.sobel(lena)

    The original and resulting image plots showing edge detection with the Sobel filter:

    How to do it...

The complete edge detection code is as follows:

import scipy
import scipy.ndimage
import matplotlib.pyplot

lena = scipy.misc.lena()

matplotlib.pyplot.subplot(221)
matplotlib.pyplot.imshow(lena)
matplotlib.pyplot.title('Original')
matplotlib.pyplot.axis('off')

# Sobel X filter
sobelx = scipy.ndimage.sobel(lena, axis=0, mode='constant')

matplotlib.pyplot.subplot(222)
matplotlib.pyplot.imshow(sobelx)
matplotlib.pyplot.title('Sobel X')
matplotlib.pyplot.axis('off')

# Sobel Y filter
sobely = scipy.ndimage.sobel(lena, axis=1, mode='constant')

matplotlib.pyplot.subplot(223)
matplotlib.pyplot.imshow(sobely)
matplotlib.pyplot.title('Sobel Y')
matplotlib.pyplot.axis('off')

# Default Sobel filter
default = scipy.ndimage.sobel(lena)

matplotlib.pyplot.subplot(224)
matplotlib.pyplot.imshow(default)
matplotlib.pyplot.title('Default Filter')
matplotlib.pyplot.axis('off')

matplotlib.pyplot.show()

How it works...

We applied the Sobel filter to the picture of the famous Playboy model Lena Soderberg. As we saw in this example, we can specify the axis along which to do the computation. The default setting is axis independent.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset