Python OpenCV 轮廓检测代码示例
以下是使用 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, 255, 0), 3)
# 显示图像
cv2.imshow('contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
在此代码中,我们首先读取图像,然后将其转换为灰度图像。接下来,我们对图像进行二值化处理,以便更容易地检测轮廓。然后使用cv2.findContours()函数检测轮廓,并使用cv2.drawContours()函数将轮廓绘制在原始图像上。最后,我们显示带有轮廓的图像。
原文地址: https://www.cveoy.top/t/topic/mTh1 著作权归作者所有。请勿转载和采集!