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)

相关推荐
破烂pan19 小时前
AI-Agent-Book第一章思考题
人工智能·agent
AI服务老曹20 小时前
AI视频分析API常见问题和排查清单
人工智能·音视频
youngerwang20 小时前
【从“聊天“到“执行“:MATLAB Agentic AI + MCP Server 实战——以 5G NR PDSCH 波形仿真为例】
人工智能·5g·matlab
沸速存储20 小时前
CPU 和 GPU 核心差别在哪?为什么 AI 训练离不开 GPU
服务器·人工智能·科技·嵌入式硬件·电脑
leoZ23120 小时前
AI 辅助开发的五道坎
开发语言·人工智能·视觉检测·bert·php·超分辨率重建·openvino
火云牌神20 小时前
前后端分离:约束 AI 分工,避免接口耦合与职责错乱
人工智能·系统架构·ai编程·前后端分离·vibecoding
凌杰20 小时前
关于机器恐惧症的个人观点汇总
人工智能
IT_陈寒21 小时前
Vue的v-for不听话?我被这个Key的坑整懵了
前端·人工智能·后端
水獭比特21 小时前
localhost 不是安全边界:给 Agent Web 入口补上四层门禁
人工智能·python
赟爸21 小时前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python