OpenCV 旋转矩形边界

边界矩形是用最小面积绘制的,所以它也考虑了旋转。使用的函数是**cv.minAreaRect**()。

复制代码
import cv2
import numpy as np

img=cv2.imread(r'D:\PythonProject\thunder.jpg')
img1=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
print(img.dtype)
ret,thresh=cv2.threshold(img1,127,255,cv2.THRESH_BINARY)
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt=contours[0]
M=cv2.moments(cnt)
area=cv2.contourArea(cnt)
perimeter=cv2.arcLength(cnt,True)
epsilon=0.5*cv2.arcLength(cnt,True)
approx=cv2.approxPolyDP(cnt,epsilon,True)
hull=cv2.convexHull(cnt)
k=cv2.isContourConvex(cnt)
#矩形
x,y,w,h=cv2.boundingRect(cnt)
print(x,y,w,h)
img=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),3)
#旋转矩形
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
print(f'box:{box}')
box = np.int64(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
#相切⚪
(x,y),radius=cv2.minEnclosingCircle(cnt)
center=(int(x),int(y))
radius=int(radius)
print(f'center:{center}')
img=cv2.circle(img,center,radius,(0,255,0))
#拟合椭圆
ellipse=cv2.fitEllipse(cnt)
im=cv2.ellipse(img,ellipse,(0,0,255),2)
#拟合直线
rows,cols=img.shape[:2]
[vx,vy,x,y]=cv2.fitLine(cnt,cv2.DIST_L2,0,0.01,0.01)
lefty=int(-x*vy/vx+y)
righty=int(((cols-x)*vy/vx)+y)
img=cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)
cv2.imshow('img',img)
cv2.waitKey(0)
print(M)

一个对象最上面,最下面,最左边,最右边的点

leftmost = tuple(cntcnt\[:,:,0.argmin()]0)

rightmost = tuple(cntcnt\[:,:,0.argmax()]0)

topmost = tuple(cntcnt\[:,:,1.argmin()]0)

bottommost = tuple(cntcnt\[:,:,1.argmax()]0)

相关推荐
weixin_446260855 小时前
基于熵的选择性智能体引导:从非完美视觉语言模型教师学习自主策略
人工智能·学习·语言模型
夜雪一千5 小时前
如何写一个数据分析 Skill
人工智能·数据挖掘·数据分析
桃西西呀5 小时前
RAG 接个向量库就完事?从切块到重排的 7 步流水线,我替你踩了 8 个深坑
人工智能·llm·ai编程
YOLO数据集集合5 小时前
无人机屋顶与地物分割数据集 | 屋顶分割 航拍识别 城市规划 材质分类 实例分割9036期
人工智能·分类·无人机·材质·中国城市建筑·建筑识别
zhangfeng11335 小时前
CodeBuddy‑CLI 默认授权(权限模式)命令行参数
人工智能·ai编程
道可云5 小时前
工赋·青听 | 从AI素养到专属智能体,共探化工行业数字化转型新路径
人工智能
baopixiaoz5 小时前
BeeQuant × BeeAgent:AI量化新范式
大数据·人工智能·python·区块链
海兰5 小时前
【部署】升级现有的 OpenClaw 到最新版(v2026.8.2)
人工智能·openclaw
Raas1005 小时前
AI网关在架构中的位置?MAI Gateway(魔芋企业级AI网关)给出企业级答案
大数据·网络·人工智能·架构·gateway·ai网关·mai gateway
十铭忘5 小时前
HMM(隐马尔可夫模型)的理解7——Baum–Welch 算法
人工智能·算法