contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
时间: 2023-08-13 12:26:47 浏览: 206
cv2.findContours()是OpenCV中的一个函数,用于在二进制图像中查找轮廓。该函数的语法如下:
contours, hierarchy = cv2.findContours(image, mode, method, offset)
其中,image是需要查找轮廓的二进制图像,mode是轮廓检索模式,method是轮廓近似方法,offset是可选参数,表示轮廓点坐标的偏移量。
在给定的二进制图像中,cv2.findContours()函数会找到所有的轮廓,并将每个轮廓表示为一组点的集合。这些点的集合存储在contours变量中。hierarchy变量包含关于轮廓层次结构的信息。
cv2.RETR_LIST表示提取所有轮廓,不建立轮廓间的层次关系。cv2.CHAIN_APPROX_SIMPLE表示轮廓近似方法,表示只保留轮廓的拐点信息,将轮廓形状用直线来逼近。
相关问题
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。
cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
This line of code uses the OpenCV library's "findContours" function to find the contours (boundaries) of the white regions in a binary mask image.
The function takes three arguments:
1. The binary mask image (in this case, a copy of the original mask image)
2. The retrieval mode (cv2.RETR_EXTERNAL) which retrieves only the extreme outer contours (ignoring contours within contours)
3. The contour approximation method (cv2.CHAIN_APPROX_SIMPLE) which compresses horizontal, vertical, and diagonal segments and leaves only their end points.
The function returns two values: the contours themselves and the hierarchy of the contours (which is not needed in this case, so only the contours are returned using the [-2] index).
阅读全文