在opencv中检测半完整椭圆

2024-04-20 11:35:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用opencv测量椭圆的最小和最大半径但该椭圆未完全完成,如图enter image description here

我试过霍夫圆法。但是它没有给我所需要的输出

这是我期望得到的输出。 **enter image description here**


Tags: 半径opencv椭圆圆法
1条回答
网友
1楼 · 发布于 2024-04-20 11:35:36

您可以通过查找区域的凸包,然后在Python/OpenCV中拟合椭圆来实现这一点

输入:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('half_ellipses.jpg')
hh, ww = img.shape[:2]
print(hh,ww)

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold to binary and invert
thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)[1]
thresh = 255 - thresh

# get convex hull of white pixels
points = np.column_stack(np.where(thresh.transpose() > 0))
hull = cv2.convexHull(points)
((centx,centy), (width,height), angle) = cv2.fitEllipse(hull)
print ((centx,centy), (width,height), angle)

# draw polygon
result = img.copy()
cv2.ellipse(result, (int(centx),int(centy)), (int(width/2),int(height/2)), angle, 0, 360, (0,0,255), 2)

cv2.imshow('image', img)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('half_ellipses_hull_ellipse.png', result)


结果:

enter image description here

相关问题 更多 >