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.
In this section, we will learn how to apply the Sobel filter to detect edges in the Lena image.
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')
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')
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:
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()