In this blog, we will learn the edge detection in OpenCV Python using Canny’s edge detection algorithm. Edge Detection has great importance in computer vision.
Edge Detection deals with the contours of an image that is usually denoted in an image as an outline of a particular object.
There’s a lot of edge detection algorithms like Sobel, Laplacian, and Canny.
The Canny Edge Detection algorithm is the most commonly used for ease of use as well as the degree of accuracy.
Imports for Canny Edge Detection OpenCV Algorithm
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
Composition of Canny Edge Detection
The Canny edge detection OpenCV algorithm is composed of 5 steps:
- Noise Reduction – If noise is not removed it may cause the image to detect incorrect edges.
- Gradient Calculation
- Non-maximum Suppressions
- Double threshold
- Edge Tracking by Hysteresis
Canny Edge Detection Code
First of all, the image is loaded into a variable using the OpenCV function
cv.imread(). The image is loaded in Gray Scale as edges can be easily identified in a grayscale image.
canny() function takes 3 parameters from the user.
First the image, then the threshold value for the first and second.
The Edge Detection relies on the threshold values and so the values are identified by shuffling the threshold values together.
After canny edge detection is over we store the title and images in separate arrays and display them using
plt.subplot() function present in the matplotlib library.
def canny(): img = cv.imread("./img/image.jpg", 0) canny = cv.Canny(img, 150, 200) title = ["Original Image", "Canny"] images = [img, canny] for i in range(len(images)): plt.subplot(2, 2, i+1), plt.imshow(images[i], 'gray') plt.title(title[i]) plt.xticks(), plt.yticks() plt.show()
Edge Detected Image
Learn More Python OpenCV topics like lane detection OpenCV python, line detection, etc.
Get the full source code of all OpenCV projects from the Github page.