# Canny Edge Detector

Canny Edge Detector

# Canny Edge Detector¶

Canny edge dector uses several steps to extract edges in image:

• Apply Gaussian filter to smooth image (reduce noise)
• Calculate gradients of the image (1 and 2 can be combined into one step)
• Use high threshold to extract "significant" gradients (strong edge pixels)
• "Thin" to reduce edge pixels to the local peak of gradient (along gradient direction)
• Linking stage: using low threshold to extend edges extracted the strong edges (clever!)

It is very easy to apply Canny Edge Detector in Matlab:

    edge_img = edge(org_img, 'canny');

In this blog, we will use the Canny edge dector from skimage package

In [18]:
# First part borrow from scikit webpage# Simple demo using squareimport numpy as npimport matplotlib.pyplot as pltfrom PIL import Imagefrom scipy import ndimage as ndifrom skimage import feature# 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 [11]:
# Generate a square with noiseim = np.zeros((256, 256))im[64:-64, 64:-64] = 1im = ndi.rotate(im, 30, mode='constant')im = ndi.gaussian_filter(im, 5)im += 0.2 * np.random.randn(*im.shape)plt.imshow(im)plt.show()
In [14]:
# Extract edges using two different sigma valuesedges_default = feature.canny(im)edges_major = feature.canny(im, sigma=3)edges_overMajor =  feature.canny(im, sigma=5)plt.subplot(131)plt.title('Default Canny Filter')plt.imshow(edges_default, cmap='gray')plt.axis('off')plt.subplot(132)plt.title('Canny Filter, Sigma = 3')plt.imshow(edges_major, cmap='gray')plt.axis('off')plt.subplot(133)plt.title('Canny Filter, Sigma = 5')plt.imshow(edges_overMajor, cmap='gray')plt.axis('off')plt.show()
In [24]:
# Second Part, Hummingbird examplebird_im = np.array(Image.open('hummingbird.jpg').convert('L'))bird_edge_default = feature.canny(bird_im)bird_edge_sigma2 = feature.canny(bird_im, sigma=2)bird_edge_sigma3 = feature.canny(bird_im, sigma=3)plt.subplot(2,2,1)plt.title('Original Image')plt.axis('off')plt.imshow(bird_im)plt.subplot(2,2,2)plt.title('Default Canny')plt.axis('off')plt.imshow(bird_edge_default)plt.subplot(2,2,3)plt.title('Canny, Sigma = 2')plt.axis('off')plt.imshow(bird_edge_sigma2)plt.subplot(2,2,4)plt.title('Canny, Sigma = 3')plt.axis('off')plt.imshow(bird_edge_sigma3)plt.show()

Published: September 12 2016

• category:
• tags: