Opencv Python 简明教程
OpenCV Python - Edge Detection
此处的边缘表示图像中对象的边界。OpenCV 有一个 cv2.Canny() 函数,通过实现 Canny 算法识别图像中各种对象的边缘。
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 边缘检测算法由 John Canny 发明。据此,对象的边缘通过执行以下步骤确定 −
Canny edge detection algorithm was developed by John Canny. According to it, object’s edges are determined by performing following steps −
第一步是减少图像中的噪声像素。这通过应用 5X5 高斯滤波器来完成。
First step is to reduce the noisy pixels in the image. This is done by applying 5X5 Gaussian Filter.
第二步涉及查找图像的强度梯度。通过应用 Sobel 算子来滤波第一阶段的平滑图像,以获得水平和垂直方向上的 一 阶导数 (Gx 和 Gy)。
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{边缘\:梯度\:G\:=\:\sqrt{G_x 2+G_y 2}}
\mathrm{Edge \:gradient\:G\:=\:\sqrt{G_x2+G_y2}}
\mathrm{角度\:\theta\:=\:\tan^{-1}(\frac{G_{y}}{G_{x}})}
\mathrm{Angle\:\theta\:=\:\tan^{-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.
所有这些步骤都通过 OpenCV 的 cv2.Canny() 函数执行,该函数需要输入图像数组和最小值和最大值参数。
All these steps are performed by OpenCV’s cv2.Canny() function which needs the input image array and minval and maxval parameters.
Example
以下是 Canny 边缘检测的示例。程序如下所示:
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 matplotlib 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()