python怎么实现轮廓检测并得知轮廓编号分别是多少
要实现轮廓检测并得知轮廓编号分别是多少,可以使用OpenCV库中的findContours函数。
示例代码:
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 转化为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 寻找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓并显示轮廓编号
for i in range(len(contours)):
cv2.drawContours(img, contours, i, (0, 0, 255), 2)
cv2.putText(img, str(i), tuple(contours[i][0][0]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
解释:
- 读取图像
- 转化为灰度图像
- 二值化处理
- 寻找轮廓
- 第一个返回值是轮廓的列表
- 第二个返回值是每个轮廓的层次结构
- 绘制轮廓并显示轮廓编号
- 使用drawContours函数绘制轮廓
- 使用putText函数显示轮廓编号
- 显示图像
原文地址: https://www.cveoy.top/t/topic/bp39 著作权归作者所有。请勿转载和采集!