
Canny edge detector implementation in Python¶
Faisal Qureshi
Professor
Faculty of Science
Ontario Tech University
Oshawa ON Canada
http://vclab.science.ontariotechu.ca
Copyright information¶
© Faisal Qureshi
License¶

This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
Lesson Plan¶
- Sobel filters
- Image gradient magnitude
- Using color to depict edge orientation
- Non-maxima suppression
- Hysteresis and edge-linking
- Difference of Gaussian
In [1]:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Developing our own Canny edge detector¶
In [2]:
filename = 'data/lena.png'
In [3]:
weak = 64
strong = 255
hysteresis_value = 128
weak_color=[0.0,0.3,0.6]
strong_color=[1,0,0]
hysteresis_color=[0,1,0]
lowThresholdRatio=0.05
highThresholdRatio=0.09
In [4]:
img_bgr = cv.imread(filename)
img_rgb = cv.cvtColor(img_bgr, cv.COLOR_BGR2RGB)
plt.figure(figsize=(7,7))
plt.imshow(img_rgb)
plt.title(filename)
plt.xticks([])
plt.yticks([]);
In [5]:
img_gray = cv.cvtColor(img_rgb, cv.COLOR_RGB2GRAY)
img = img_gray.astype('float32') / 255.0
plt.figure(figsize=(10,10))
plt.imshow(img, cmap='gray')
plt.yticks([])
plt.xticks([]);
Sobel filters to compute image derivatives¶
In [6]:
sobelx = cv.Sobel(img,cv.CV_64F,1,0,ksize=5)
sobely = cv.Sobel(img,cv.CV_64F,0,1,ksize=5)
plt.figure(figsize=(20,10))
plt.subplot(121)
plt.imshow(sobelx, cmap='gray')
plt.title('$I_x$')
plt.xticks([])
plt.yticks([])
plt.subplot(122)
plt.title('$I_y$')
plt.imshow(sobely, cmap='gray')
plt.xticks([])
plt.yticks([]);
Computing image gradient magnitude¶
In [7]:
g = np.sqrt(np.square(sobelx)+np.square(sobely))
plt.figure(figsize=(10,10))
plt.xticks([])
plt.yticks([])
plt.imshow(g, cmap='gray');
In [8]:
plt.figure(figsize=(30,10))
plt.subplot(131)
plt.xticks([])
plt.yticks([])
plt.imshow(img_rgb)
plt.subplot(132)
plt.imshow(img, cmap='gray')
plt.xticks([])
plt.yticks([])
plt.subplot(133)
plt.xticks([])
plt.yticks([])
plt.imshow(g, cmap='gray');