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

 外接矩形、外接圆:

 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()

 

1、cv2.boundingRect() Method 和 cv2.minAreaRect() Merhod:前者只寻找和 x、y轴 平行的矩形,后者则可以出现旋转角度。

2、cv2.drawContours() Method:第二个参数接收的是轮廓信息,但是这个轮廓信息需要以 tuple or list or set类型(或者说是iterable)才可以传入。

  请注意:当我们对 box 变量进行 tuple() list() set() 操作时,都会报错,这是因为,在针对numpy数组进行可迭代转换时,前面的三种方式,都会对numpy数组中的每个元素都视为单独的一个 ”列表元素“ ,而不是将整个 box 视为一个列表 这会导致如:

  box = [[ -8 410] [ 57 -21] [444 37] [379 469]],

  在使用 list() 后:

  box = [array([ -8, 410], dtype=int64), array([ 57, -21], dtype=int64), array([444,  37], dtype=int64), array([379, 469], dtype=int64)]

  但是我们需要的正确的格式是:

  [array([[ -8, 410], [ 57, -21], [444, 37], [379, 469]], dtype=int64)]

 

总结:针对numpy数组转换为可迭代对象时,[ ]、(, )、{ } 和 list()、tuple()、set() 会得到不用的结果,即是否会将元素视为单独的一个”列表元素“,这种情况只针对 numpy 数组(就笔者目前所接触过的各种类型)。

 

posted @ 2023-12-05 21:33  VanGoghpeng  阅读(267)  评论(0编辑  收藏  举报