contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img_bgr = cv2.cvtColor(imm, cv2.COLOR_GRAY2BGR) # 绘制边缘 # imm = cv2.drawContours(img_bgr, contours, -1, (0, 0, 255), 1) # 遍历轮廓 rects = [] for contour in contours: rect = cv2.minAreaRect(contour) rects.append(rect) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_bgr, [box], 0, (0, 0, 255), 2) for i, rect in enumerate(sorted(rects, key=lambda x: x[1][0] * x[1][1], reverse=True)): print(f'Rank {i + 1}: Size={rect[1][0] * rect[1][1]:.0f}, ({int(rect[0][0])}, {int(rect[0][1])}), Width={rect[1][0]:.0f}, Height={rect[1][1]:.0f}, Angle={rect[2]:.0f}')打印的具体是什么帮我再加上矩形轮廓的左上角和右下角的坐标也是按矩形大小排名打印
时间: 2024-01-16 22:02:42 浏览: 86
python cv2截取不规则区域图片实例
这段代码使用 OpenCV 库对图像进行轮廓检测,并在检测到的每个轮廓周围绘制一个矩形框。然后,它会按照矩形框的大小对检测到的所有轮廓进行排序,并输出每个矩形框的大小、中心点坐标、宽度、高度和旋转角度。
如果您想要在输出中添加每个矩形框的左上角和右下角坐标,可以将代码修改为如下所示:
```
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
img_bgr = cv2.cvtColor(imm, cv2.COLOR_GRAY2BGR)
# 绘制边缘
# imm = cv2.drawContours(img_bgr, contours, -1, (0, 0, 255), 1)
# 遍历轮廓
rects = []
for contour in contours:
rect = cv2.minAreaRect(contour)
rects.append(rect)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img_bgr, [box], 0, (0, 0, 255), 2)
# 按照矩形框大小对轮廓进行排序并打印
for i, rect in enumerate(sorted(rects, key=lambda x: x[1][0] * x[1][1], reverse=True)):
print(f'Rank {i + 1}: Size={rect[1][0] * rect[1][1]:.0f}, Top Left=({int(rect[0][0] - rect[1][0]/2)}, {int(rect[0][1] - rect[1][1]/2)}), Bottom Right=({int(rect[0][0] + rect[1][0]/2)}, {int(rect[0][1] + rect[1][1]/2)}), Width={rect[1][0]:.0f}, Height={rect[1][1]:.0f}, Angle={rect[2]:.0f}')
```
这样,每个矩形框的左上角和右下角坐标也会在输出中打印出来。
阅读全文