I have images as showing below (Figure 1) and I would like to fit two ellipses to the inner and outer shape.
if img is None:
print("Failed to load the image")
exit()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.uint8)
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
ret,thresh = cv2.threshold(gray,65,255,cv2.THRESH_BINARY)
ksize = 15
med= cv2.medianBlur(thresh, ksize = ksize)
def detect_ellipses(img, contours):
ellipses = []
for contour in contours:
relevant_points = np.reshape(contour, (contour.shape[0], 2))
try:
ellipse = cv2.fitEllipse(relevant_points)
#print(ellipse)
ellipses.append(ellipse)
except:
pass
return ellipses
# # Apply edge detection to the grayscale image with adjusted parameters
edges = cv2.Canny(med, 65, 255)
# # # Find the contours in the edge map
contours, hierarchy = cv2.findContours(
edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# plt.figure('outer')
# plt.imshow(contours)
# plt.show()
# # # Detect ellipses from the contours
ellipses = detect_ellipses(img, contours)
# # Draw the ellipses on the original image
for ellipse in ellipses:
try:
cv2.ellipse(img, ellipse, (0, 255, 0), 2)
print(ellipse)
except:
pass
# #Show the original image with the fitted ellipses
cv2.imshow('Ellipse Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
I have been using OpenCV and am able to consistently fit the inner ellipse. The outer has been tricky due to the noises that I have not able to remove completely, which causes undesired fittings (Figure 2). Currently, I am able to fit individual images through trial and error but not ideal.
Thanks!