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])

相关推荐
大彬聊编程12 分钟前
清华大学102页PPT 《deepseek从入门到精通》
人工智能
明月与玄武17 分钟前
Apifox 增强 AI 接口调试功能:自动合并 SSE 响应、展示DeepSeek思考过程
人工智能·apifox·增强 ai 接口调试功能
虚假程序设计30 分钟前
opencv 自适应阈值
人工智能·opencv·计算机视觉
沐欣工作室_lvyiyi41 分钟前
基于物联网的家庭版防疫面罩设计与实现(论文+源码)
人工智能·stm32·单片机·物联网·目标跟踪
xzzd_jokelin1 小时前
Spring AI 接入 DeepSeek:开启智能应用的新篇章
java·人工智能·spring·ai·大模型·rag·deepseek
简简单单做算法1 小时前
基于WOA鲸鱼优化的BiLSTM双向长短期记忆网络序列预测算法matlab仿真,对比BiLSTM和LSTM
人工智能·lstm·bilstm·woa-bilstm·双向长短期记忆网络·woa鲸鱼优化·序列预测
星霜旅人1 小时前
开源机器学习框架
人工智能·机器学习·开源
资源大全免费分享1 小时前
清华大学第五版《DeepSeek与AI幻觉》附五版合集下载方法
人工智能
龚大龙1 小时前
机器学习(李宏毅)——RL(强化学习)
人工智能·机器学习
LaughingZhu1 小时前
PH热榜 | 2025-02-23
前端·人工智能·经验分享·搜索引擎·产品运营