用python写一个检测轮廓的代码
以下是用Python和OpenCV库编写的检测轮廓的代码:
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.imread('image.jpg')读取图像cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)将图像转为灰度图像cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)二值化图像,将灰度值大于127的像素设置为255(白色),否则设置为0(黑色)cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)查找轮廓,返回轮廓和层级信息cv2.drawContours(img, contours, -1, (0, 255, 0), 3)绘制轮廓,将所有轮廓绘制在原始图像上,颜色为绿色,线宽为3cv2.imshow('Contours', img)显示结果
注意:在OpenCV 3及以上版本中,cv2.findContours返回两个值:轮廓和层级信息。在OpenCV 2中,只返回轮廓。因此,如果您使用OpenCV 3及以上版本,请将contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)改为_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)。
原文地址: https://www.cveoy.top/t/topic/bpWc 著作权归作者所有。请勿转载和采集!