Canny Edge Detection

OpenCV also offers a very handy function called Canny (after the algorithm’s inventor, John F. Canny), which is very popular not only because of its effectiveness, but also the simplicity of its implementation in an OpenCV program, as it is a one-liner:

# Import Necessary library
import cv2
import numpy as np
# Read MyPic.jpg from system as grayscale
img = cv2.imread("MyPic.jpg", 0)
# Create Canny Edge Detection and saving image
cv2.imwrite("canny.jpg", cv2.Canny(img, 200, 300))

Our input Image:

Output Image for Canny Edge Detection will be:

The Canny edge detection algorithm is quite complex but also interesting: it’s a five-step process that denoises the image with a Gaussian filter, calculates gradients, applies non maximum suppression (NMS) on edges, a double threshold on all the detected edges to eliminate false positives, and, lastly, analyzes all the edges and their connection to each other to keep the real edges and discard the weak ones.