English 中文(简体)
OpenCV Python - Edge Detection
  • 时间:2024-11-03

OpenCV Python - Edge Detection


Previous Page Next Page  

An edge here means the boundary of an object in the image. OpenCV has a cv2.Canny() function that identifies the edges of various objects in an image by implementing Canny’s algorithm.

Canny edge detection algorithm was developed by John Canny. According to it, object’s edges are determined by performing following steps −

First step is to reduce the noisy pixels in the image. This is done by applying 5X5 Gaussian Filter.

Second step involves finding the intensity gradient of the image. The smooth image of the first stage is filtered by applying the Sobel operator to obtain first order derivatives in horizontal and vertical directions (Gx and Gy).

The root mean square value gives edge gradient and tan inverse ratio of derivatives gives the direction of edge.

$$mathrm{Edge :gradient:G:=:sqrt{G_x^2+G_y^2}}$$

$$mathrm{Angle: heta:=: an^{-1}(frac{G_{y}}{G_{x}})}$$

After getting gradient magnitude and direction, a full scan of the image is done to remove any unwanted pixels which may not constitute the edge.

Next step is to perform hysteresis thresholding by using minval and maxval thresholds. Intensity gradients less than minval and maxval are non-edges so discarded. Those in between are treated as edge points or non-edges based on their connectivity.

All these steps are performed by OpenCV’s cv2.Canny() function which needs the input image array and minval and maxval parameters.

Example

Here’s the example of canny edge detection. The program for the same is as follows −


import numpy as np
import cv2 as cv
from matplotpb import pyplot as plt
img = cv.imread( lena.jpg , 0)
edges = cv.Canny(img,100,200)
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( Edges of original Image ), plt.xticks([]), plt.yticks([])
plt.show()

Output

Canny Edge Advertisements