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

相关推荐
过期动态2 小时前
【动手学深度学习】卷积神经网络(CNN)入门
人工智能·python·深度学习·pycharm·cnn·numpy
蔗理苦5 小时前
2025-04-05 吴恩达机器学习5——逻辑回归(2):过拟合与正则化
人工智能·python·机器学习·逻辑回归
程序猿阿伟6 小时前
《SQL赋能人工智能:解锁特征工程的隐秘力量》
数据库·人工智能·sql
csssnxy6 小时前
叁仟数智指路机器人是否支持远程监控和管理?
大数据·人工智能
车斗7 小时前
win10 笔记本电脑安装 pytorch+cuda+gpu 大模型开发环境过程记录
人工智能·pytorch·电脑
KY_chenzhao7 小时前
数据驱动防灾:AI 大模型在地质灾害应急决策中的关键作用。基于DeepSeek/ChatGPT的AI智能体开发
人工智能·chatgpt·智能体·deepseek·本地化部署
大多_C7 小时前
量化方法分类
人工智能·分类·数据挖掘
www_pp_7 小时前
# 基于 OpenCV 的人脸识别实战:从基础到进阶
人工智能·opencv·计算机视觉
三月七(爱看动漫的程序员)8 小时前
LLM面试题六
数据库·人工智能·gpt·语言模型·自然语言处理·llama·milvus
蹦蹦跳跳真可爱5899 小时前
Python----计算机视觉处理(Opencv:道路检测之车道线拟合)
开发语言·人工智能·python·opencv·计算机视觉