Edge Detection

Get introduced to different types of edge detection and learn how to detect edges using these techniques.

One of the most frequent uses of OpenCV is the detection of shapes, edges, faces, and various other components in images. In this chapter, we’ll learn about some of those detections.

Detecting edges helps us solve many practical problems. It helps us detect shapes, documents, and various other components of the image. Here, we’ll discuss three different methods of detecting edges—Canny edge detection, Laplacian edge detection, and Sobel edge detection.

First, we need to convert our image to grayscale:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Canny edge detection

For Canny edge detection, we use the cv2.Canny() function of the OpenCV library. This function requires three parameters, which are listed below:

  • The first parameter is the input image.

  • The second parameter is the minimum value of the intensity gradient. The edges with an intensity gradient lower than the minimum value are not considered edges. So, increasing the minimum value reduces the number of edges.

  • The third parameter is the maximum value of the intensity gradient. The edges with an intensity gradient more than the maximum value are considered as edges.

The values that lie between these two thresholds are classified as edges or non-edges based on their connectivity.

cannyEdge = cv2.Canny(gray, 150, 150)
cv2.imshow('Canny', canny)

The Canny edge detection algorithm goes through four main stages. First, it uses Gaussian blur to reduce noise. Then it finds the intensity gradient of the image. It goes through non-maximum suppression where the image is scanned, and removes the unwanted pixels. The final step is hysteresis thresholding. In this step, the algorithm decides whether the edges detected are edges or not based on the minimum and maximum value of the intensities provided as the parameter.

Get hands-on with 1200+ tech skills courses.