Tharaka
Tharaka

Reputation: 57

Detect a half complete ellipse in opencv

I am trying to measure the min and max radius of an ellipse using opencv. But this ellipse is not fully complete as shown in the image enter image description here

I have tried hough circles method. But it doesn't give me the output which I need.

This is the output I expect to get. **enter image description here**

Upvotes: 1

Views: 1347

Answers (1)

fmw42
fmw42

Reputation: 53089

You can do that by finding the convex hull of the regions and then fitting an ellipse to it in Python/OpenCV.

Input:

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)


Result:

enter image description here

Upvotes: 3

Related Questions