contours, hierarchy = cv.findContours(binary, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)什么意思
时间: 2023-08-13 08:49:19 浏览: 157
这行代码是使用OpenCV库对二值化图像进行轮廓检测的操作。其中,cv是OpenCV库的别名,binary是二值化图像,contours是检测到的轮廓,hierarchy是轮廓之间的层级关系。findContours()函数是OpenCV中用于轮廓检测的函数,它的第一个参数是输入的二值化图像,第二个参数是轮廓检测模式,这里是检测所有轮廓并建立轮廓间的完整层级关系,第三个参数是轮廓逼近方法,这里是压缩水平、垂直和对角线方向的像素,只保留端点。因此,这行代码的作用是对二值图像binary进行轮廓检测,返回检测到的轮廓contours以及轮廓之间的层级关系hierarchy。
相关问题
import cv2import numpy as np# 读取图像image = cv2.imread('工件图像.jpg')# 转换为灰度图像gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用二值化处理获取缺陷图像ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)# 使用形态学操作进行缺陷的去噪和填充kernel = np.ones((3,3), np.uint8)closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)# 获取缺陷轮廓contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)# 遍历每一个缺陷,提取几何特征并绘制位置for i in range(len(contours)): # 获取面积和周长 area = cv2.contourArea(contours[i]) perimeter = cv2.arcLength(contours[i], True) # 获取质心 moments = cv2.moments(contours[i]) cx = int(moments['m10'] / moments['m00']) cy = int(moments['m01'] / moments['m00']) # 绘制位置和特征 cv2.drawContours(image, [contours[i]], -1, (0, 255, 0), 2) cv2.circle(image,(cx,cy), 5, (0,0,255), -1) cv2.putText(image, "Area: {:.2f}".format(area), (cx+10, cy-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2) cv2.putText(image, "Perimeter: {:.2f}".format(perimeter), (cx+10, cy+10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)# 显示结果cv2.imshow('Defect Detection', image)cv2.waitKey(0)# 保存结果cv2.imwrite('Defect Detection.jpg', image)
这是Python中的两个库,cv2是OpenCV库,用于图像和视频处理,包括读取、写入、显示、处理、分析等。numpy是一个数学库,用于处理数字和数组。一般情况下,当我们读取图像时,使用cv2,而对图片进行处理时,使用numpy。
triangle = cv2.minEnclosingTriangle(max_contour) triangle = np.int0(triangle)报错:valueerror
这个错误可能是由于`cv2.minEnclosingTriangle()`函数返回值的数据类型不是整数类型,而`cv2.drawContours()`函数需要的轮廓数据类型是整数型的。
为了解决这个错误,我们需要将`cv2.minEnclosingTriangle()`函数返回的三角形数据类型转换为整数型。可以使用`np.int0()`函数将其转换为整数型。
以下是修改后的代码示例:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('example.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)
# 找到最大轮廓
max_contour = max(contours, key=cv2.contourArea)
# 计算最小外接三角形
triangle = cv2.minEnclosingTriangle(max_contour)
triangle = np.int0(triangle)
# 绘制最小外接三角形
cv2.drawContours(img, [triangle], 0, (0, 0, 255), 2)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在此示例中,我们使用`np.int0()`函数将三角形数据类型转换为整数型。
阅读全文
相关推荐















