Monday, September 12, 2016

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 square
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from scipy import ndimage as ndi
from skimage import feature

# Ensure plots embeded in notebook
%matplotlib inline
plt.rcParams['figure.figsize']= (8.0, 6.0)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
In [11]:
# Generate a square with noise
im = np.zeros((256, 256))
im[64:-64, 64:-64] = 1
im = 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 values
edges_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 example
bird_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()

No comments:

Post a Comment