用Python写一段轮廓检测的程序
以下是使用OpenCV库实现的Python轮廓检测程序:
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)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示结果
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
解释一下代码:
- 首先读取一张图片,并将其转换为灰度图像。
- 对灰度图像进行二值化处理,以便更好地查找轮廓。
- 使用
cv2.findContours函数查找图像的轮廓。这个函数返回两个值:轮廓列表和层次结构。在这里我们只使用轮廓列表。 - 使用
cv2.drawContours函数将轮廓绘制在原始图像上。 - 显示结果图像。
原文地址: https://www.cveoy.top/t/topic/bpV2 著作权归作者所有。请勿转载和采集!