【Python】【OpenCV】绘制外接矩形、外接圆 以及 凸轮廓和Douglas-Peucker算法
  4KCgAKgIRRBi 2023年12月06日 23 0

 外接矩形、外接圆:

 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 类型(或者说是iterable)才可以传入。

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月06日 0

暂无评论

推荐阅读
  2Fnpj8K6xSCR   2024年05月17日   78   0   0 Python
  xKQN3Agd2ZMK   2024年05月17日   60   0   0 Python
  fwjWaDlWXE4h   2024年05月17日   31   0   0 Python
  YpHJ7ITmccOD   2024年05月17日   33   0   0 Python
4KCgAKgIRRBi