用python检测轮廓代码
以下是使用Python OpenCV库检测轮廓的示例代码:
import cv2
# 读取图像
img = cv2.imread('example.jpg')
# 转换成灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 检测轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
# 显示图像
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
其中,cv2.findContours()函数返回的是轮廓的列表和层级信息,而cv2.drawContours()函数用于绘制轮廓。
原文地址: https://www.cveoy.top/t/topic/bpV7 著作权归作者所有。请勿转载和采集!