最小包围




import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# 旋转矩形
vertices=cv.boxPoints(((200,200),(90,150),-30))
# 打印四个点
print(vertices.dtype)
print(vertices) # 打印四个点
img= np.zeros((400,400),np.uint8)
for i in range(4):  # 矩形要画四条线
    p1=vertices[i,:]
    cv.line(img, tuple(p1), tuple(p1), 255, 15) # 将P1转换为元组

    j=(i+1)%4 # 取余数
    p2=vertices[j,:]
    # 画出直线
    cv.line(img,(p1[0],p1[1]),(p2[0],p2[1]),255,2)

# 计算最小外包圆
circle=cv.minEnclosingCircle(vertices)
print('circle=',circle)
cv.circle(img,(200,200),int(circle[1]),(255),1)
# cv.circle()  图片 圆心 半径(整数) 颜色 线粗细(-1为实心 否则为圆)
plt.imshow(img,cmap='gray')
plt.title('circle')
plt.show()


# 构建凸包型
points=np.random.randint(100,300,(80,2),np.int32)
img_convex=np.zeros((400,400),np.uint8)
for i in points:
    cv.line(img_convex,tuple(i),tuple(i),255,10)
con=cv.convexHull(points) # 返回[n,1,2] n是点数,2是坐标点

for i in range(con.shape[0]-1):
    cv.line(img_convex,tuple(con[i,0,:]),tuple(con[i+1,0,:]),255,4)
cv.line(img_convex,tuple(con[0,0,:]),tuple(con[con.shape[0]-1,0,:]),255,4)
plt.imshow(img_convex, cmap='gray')
plt.title('convexhull')
plt.show()


points=np.random.randint(250,550,(80,1,2),np.int32)

area,triangle=cv.minEnclosingTriangle(points)
img_triangle=np.zeros((800,800), np.uint8)
for i in range(points.shape[0]): # 将每个点划在图片中
    cv.line(img_triangle, tuple(points[i, 0, :]), tuple(points[i, 0, :]), 255, 5)

cv.line(img_triangle, tuple(triangle[0,0,:]),tuple(triangle[1,0,:]),255,3)
cv.line(img_triangle, tuple(triangle[1,0,:]),tuple(triangle[2,0,:]),255,3)
cv.line(img_triangle, tuple(triangle[2,0,:]),tuple(triangle[0,0,:]),255,3)
plt.imshow(img_triangle,cmap='gray')
plt.title('triangle')
plt.show()
最小外包圆代码

 


结果显示:

 

 




posted @ 2023-03-03 09:57  tangjunjun  阅读(25)  评论(0编辑  收藏  举报
https://rpc.cnblogs.com/metaweblog/tangjunjun