【Python】【OpenCV】绘制外接矩形和外接圆

发布时间 2023-12-05 21:38:23作者: VanGoghpeng

 

 1 import cv2
 2 import numpy
 3 
 4 img = cv2.imread('../img/img.png', -1)
 5 ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
 6 contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 7 
 8 for c in contours:
 9     # 寻找平行于 x轴、y轴 的外接矩形坐标 -> 左上角坐标、宽度、高度
10     rectangle = cv2.boundingRect(c)
11     x, y, w, h = rectangle
12     # 绘制外接矩形
13     cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
14 
15     # 寻找包含前景图的 可旋转 最小外接矩形 -> 中心点坐标、宽度、高度
16     rect = cv2.minAreaRect(c)
17     # 寻找旋转矩形的四个顶点 -> 左上角、右上角、右下角和左下角的顶点坐标
18     box = cv2.boxPoints(rect)
19     # 取整
20     box = numpy.int0(box)
21     # 绘制外接矩形,对box打包成列表是因为drawContours希望接收为tuple or list
22     # 或者说是一个iterable
23     cv2.drawContours(img, [box], 0, (0, 0, 255), 3)
24 
25     # 计算最小外接圆 -> 圆心坐标、半径
26     (x, y), radius = cv2.minEnclosingCircle(c)
27     # 取整
28     center = int(x), int(y)
29     radius = int(radius)
30     # 绘制圆形
31     img = cv2.circle(img, center, radius, (0, 255, 0), 2)
32 
33 
34 img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
35 img = cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
36 cv2.imshow('', img)
37 cv2.waitKey()
38 cv2.destroyAllWindows()