opencv-python 最小外接矩形_转载
所用函数:
cv2.threshold() —— 阈值处理
cv2.findContours() —— 轮廓检测
cv2.boundingRect() —— 最大外接矩阵
cv2.rectangle() —— 画出矩形
cv2.minAreaRect —— 找到最小外接矩形(矩形具有一定的角度)
cv2.boxPoints —— 外接矩形的坐标位置
cv2.drawContours(image, [box], 0, (0, 0, 255), 3) —— 根据点画出矩形
1 import cv2 2 import numpy as np 3 4 image = cv2.imread('new.jpg') 5 img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 6 ret, thresh = cv2.threshold(img, 230, 255, cv2.THRESH_BINARY_INV) 7 contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 8 9 for c in contours: 10 # 找到边界坐标 11 x, y, w, h = cv2.boundingRect(c) # 计算点集最外面的矩形边界 12 cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) 13 14 # 找面积最小的矩形 15 rect = cv2.minAreaRect(c) 16 # 得到最小矩形的坐标 17 box = cv2.boxPoints(rect) 18 # 标准化坐标到整数 19 box = np.int0(box) 20 # 画出边界 21 cv2.drawContours(image, [box], 0, (0, 0, 255), 3) 22 # 计算最小封闭圆的中心和半径 23 (x, y), radius = cv2.minEnclosingCircle(c) 24 # 换成整数integer 25 center = (int(x),int(y)) 26 radius = int(radius) 27 # 画圆 28 cv2.circle(image, center, radius, (0, 255, 0), 2) 29 30 cv2.drawContours(image, contours, -1, (255, 0, 0), 1) 31 cv2.imshow("img", image) 32 cv2.imwrite("img_1.jpg", image) 33 cv2.waitKey(0)
作者:你的雷哥
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!