OpenCV实现图形轮廓检测
轮廓在计算机视觉和图像处理中扮演着重要的角色,特别是在图形识别和物体检测方面。OpenCV是一个强大的计算机视觉库,在模式识别和图像处理领域非常受欢迎。在本文中,我们将讨论如何使用OpenCV库实现图形轮廓检测。
1. 安装OpenCV
在开始之前,我们需要安装OpenCV库。OpenCV支持多种编程语言,如Python、C++、Matlab等。我们将在Python中使用OpenCV库进行图形轮廓检测。在安装OpenCV之前,你需要在你的计算机上安装Python。
在安装OpenCV之前,我们需要安装Python的一些包,如numpy和matplotlib,这些包可以帮助我们更好地处理图像和数据。
pip install numpy matplotlib opencv-python
2. 加载图像
在OpenCV中,我们可以使用imread()函数从图像文件中读取图像。我们需要将图像转换为灰度图像,因为在灰度图像中轮廓更容易检测。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 加载图像
img = cv2.imread('test.png')
# 转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 显示原图和灰度图像
plt.subplot(121), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)), plt.title('Original')
plt.subplot(122), plt.imshow(gray, cmap='gray'), plt.title('Gray')
plt.show()
3. 轮廓检测
在OpenCV中,我们可以使用findContours()函数查找图像的轮廓。此函数具有三个参数:
- 输入图像,要求图像为8位单通道图像,如灰度图像。
- 轮廓检测模式,表示如何查找轮廓,包括轮廓树、简单轮廓、中心轮廓等。
- 轮廓逼近方法,确定轮廓的精度。我们可以选择使用点到轮廓的最大距离或使用Ramer-Douglas-Peucker算法。
# 轮廓检测
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 画出轮廓
img_contour = np.zeros(gray.shape)
cv2.drawContours(img_contour, contours, -1, (255, 255, 255), 3)
# 显示轮廓检测结果
plt.imshow(img_contour, cmap='gray')
plt.show()
示例1
现在让我们使用真实的图像进行轮廓检测。在此示例中,我们将使用包含多个图形的图像进行轮廓检测。
# 加载图像
img = cv2.imread('shapes.png')
# 转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 轮廓检测
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 画出轮廓
img_contour = np.zeros(gray.shape)
cv2.drawContours(img_contour, contours, -1, (255, 255, 255), 3)
# 显示轮廓检测结果
plt.imshow(img_contour, cmap='gray')
plt.show()
示例2
在此示例中,我们将使用一个更复杂的图像进行轮廓检测。这个图像有多个轮廓,我们将对每个轮廓进行不同的操作。
# 加载图像
img = cv2.imread('shapes2.png')
# 转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 轮廓检测
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 对每个轮廓进行操作
for i in range(len(contours)):
# 计算轮廓长度
perimeter = cv2.arcLength(contours[i], True)
print("Perimeter of contour {}: {}".format(i, perimeter))
# 计算轮廓面积
area = cv2.contourArea(contours[i])
print("Area of contour {}: {}".format(i, area))
# 绘制包含当前轮廓的最小矩形
rect = cv2.minAreaRect(contours[i])
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
# 绘制包含当前轮廓的最小圆形
(x, y), radius = cv2.minEnclosingCircle(contours[i])
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 255, 0), 2)
# 显示轮廓检测结果
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
以上就是使用OpenCV库实现图形轮廓检测的详细攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:opencv实现图形轮廓检测 - Python技术站