Canny Edge Detector OpenCV Python
In this post, you will learn how to detect the edges of an image using a canny edge detector (cv2.canny) in OpenCV Python.
The Canny Edge Detector(cv2.canny) uses a large number of algorithms to detect the edges of image. It solves the edge detection problem of an image processing. It was developed by John F. Canny in 1986. This is used in various computer vision systems. This process extracts structural information and reduces the amount of data to be processed.
There are several edge detector algorithms developed, such as Sobel, Scharr, and Laplacian filters. But, the Canny Edge Detector method is famous among them as it is a multi-stage algorithm that goes through each stage. It is a good and reliable detector. It catches as many edges shown in the image as possible with good accuracy.
cv2.canny()
Python OpenCV provides the cv2.canny() method to detect the edges of an image.
Syntax of cv2.canny()
cv2.canny(image, edges, threshold1, threshold2[, apertureSize[, L2gradient]])
image- single channel input image,
edges- output (edges), it has the same size and type as the image,
threshold1- first threshold for the hysteresis procedure,
threshold2- second threshold for the hysteresis procedure,
apertureSize- the size of Sobel kernel used for finding image gradients, the default value is 3.
L2gradient- the equation for finding gradient magnitude.
Canny Edge Detector Algorithm
The Canny Edge Detection uses multi-step algorithms to detect edges of an image. OpenCV puts all the following in a single function, cv2.Canny() -
- Noise Reduction- The edges of an image are not properly detected if the image has noise. So the first step is to remove the noise from an image. This process can be done by Gaussian filter. It smooths the image and removes high frequency noise.
- Gradient Computation- It computes the intensity gradient representation of an image.
- Non-maximum Suppression- After applying the Gradient Computation, some of the edges of an image are thick while some are thin. The non-maximum suppression is used to overcome this issue. It removes 'false' responses to the edge detection and makes them uniform.
- Hysteresis Thresholding- It takes two threshold values, minVal and maxVal. Any edges with an intensity gradient between these minVal and maxVal are sure to be classified edges and to be considered.
Required Modules for opencv canny
These are the modules that we have used in this article with the Canny Edge Detector module cv2.canny().
- OpenCV (cv2)
- NumPy
- Matplotlib
Canny Edge Detection High Threshold Example
In the given Python code, we have read the image in OpenCV format and performed canny edge processing. This process is performed on the corresponding grayscale image.
import cv2
import numpy as np
from matplotlib import pyplot as plt
# loading the image using imread built-in function
img = cv2.imread('cat.jpg',0)
# detect edges using canny edge detection
edges = cv2.Canny(img,100,200)
// display both original and canny edge detecting images
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()
The leftmost is the original image. The rightmost image has a high threshold (100,200). It did not detect the unnecessary info in the image.
Canny Edge Detection Low Threshold Example
Now, let's check the output with a low threshold (50,60).
import cv2
import numpy as np
from matplotlib import pyplot as plt
# loading the image using imread built-in function
img = cv2.imread('cat.jpg',0)
# detect edges using canny edge detection with given threshold
edges = cv2.Canny(img,50,70)
// display both original and canny edge detecting images
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()
Automatic Canny Edge Detector Program
Here, we have defined the function auto_detect_canny(). It takes two arguments: source image and sigma value. The sigma is the percentage threshold. For computing the lower and upper threshold values, we will first compute the median of the single channel pixel intensities and then calculate the lower and upper thresholds.
import cv2
import numpy as np
from matplotlib import pyplot as plt
def auto_detect_canny(image, sigma):
# compute the median
mi = np.median(image)
# computer lower & upper thresholds
lower = int(max(0, (1.0 - sigma) * mi))
upper = int(min(255, (1.0 + sigma) * mi))
image_edged = cv2.Canny(image, lower, upper)
return image_edged
img = cv2.imread('cat.jpg',0)
edges = auto_detect_canny(img, 0.33)
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()
Output of the above code:
Related Articles
How to capture a video in Python OpenCV and savePython OpenCV Overlaying or Blending Two Images
Contour Detection using Python OpenCV
Harris Corner Detection using Python OpenCV
Human Body Detection Program In Python OpenCV
Face Recognition OpenCV Source Code
OpenCV Logical Operators- Bitwise AND, OR, NOR, XOR
Python NumPy: Overview and Examples
Image processing using Python Pillow
Python OpenCV Histogram Equalization
Python OpenCV Histogram of Color Image
Python OpenCV Histogram of Grayscale Image
Python OpenCV Image Filtering
Python OpenCV ColorMap
Python OpenCV Gaussian Blur Filtering
Python OpenCV Overview and Examples