Canny edge detector implementation in Python

Faisal Qureshi
Professor
Faculty of Science
Ontario Tech University
Oshawa ON Canada
http://vclab.science.ontariotechu.ca

© Faisal Qureshi

License

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

In [10]:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

Developing our own Canny edge detector

In [11]:
filename = 'data/lena.png'
In [12]:
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 [26]:
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 [27]:
img_gray = cv2.cvtColor(img_rgb, cv2.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 [28]:
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(img,cv2.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.