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(cnt[cnt[:,:,0].argmin()][0])

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

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

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

相关推荐
ezl1fe16 分钟前
RAG 每日一技(十八):手写SQL-RAG太累?LangChain的SQL智能体(Agent)前来救驾!
数据库·人工智能·后端
我星期八休息21 分钟前
大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
大数据·人工智能·python
飞哥数智坊26 分钟前
等了这么久,企业微信的AI终于来了!
人工智能
Christo327 分钟前
SIGKDD-2023《Complementary Classifier Induced Partial Label Learning》
人工智能·深度学习·机器学习
AIGC安琪39 分钟前
Transformer中的编码器和解码器是什么?
人工智能·深度学习·ai·语言模型·大模型·transformer·ai大模型
算家计算1 小时前
3秒搞定产品换装换背景!【ComfyUI-万物迁移工作流】本地部署教程:基于FLUX.1 Kontext上下文感知图像编辑
人工智能
山烛1 小时前
OpenCV 图像处理基础操作指南(二)
人工智能·python·opencv·计算机视觉
聚客AI1 小时前
🧩万亿级Token训练!解密大模型预训练算力黑洞与RLHF对齐革命
人工智能·llm·强化学习
CoovallyAIHub2 小时前
线性复杂度破局!Swin Transformer 移位窗口颠覆高分辨率视觉建模
深度学习·算法·计算机视觉
爱疯生活2 小时前
车e估牵头正式启动乘用车金融价值评估师编制
大数据·人工智能·金融