Is there a way to draw inscribed ellipse in a almost rectangular contour?

732 Views Asked by At

I am wondering if there is a way to inscribe an ellipse in almost rectangular contour? I am using openCV findcontours() method in my image and my aim is to fit biggest possible ellipses inside every object in the following image: enter image description here

Code I am using:

import cv2
import numpy as np



def find_contours(preprocessed, min_perimeter):
    contours, hierarchy = cv2.findContours(preprocessed,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)        #find contours
    contours_new = []                                                                               #new empty list of contours
    for cnts in contours:                                                                           #looping trough contours
        perimeter = cv2.arcLength(cnts,True)                                                        #arc length
        if perimeter > min_perimeter:                                                               #leave only significant contours
            contours_new.append(cnts)      

    return contours_new


min_perimeter = 7000                                                           
img_num = 6
results_path = 'results/'
image_path = 'images/'
mask = image_path+str(img_num)+'_predicted_mask.bmp'                           
empty = np.empty([9452, 6144], dtype=np.uint16)
empty = cv2.cvtColor(empty, cv2.COLOR_GRAY2BGR)

gray = cv2.imread(mask)                                                        
ret,thresholded_mask = cv2.threshold(gray,150,255,0)                           
gray_mask = cv2.cvtColor(thresholded_mask, cv2.COLOR_BGR2GRAY)


contours_new = find_contours(gray_mask, min_perimeter)                         
cv2.drawContours(empty, contours_new, -1, (255,255,255), 3)
for cnt in contours_new:

    ellipse = cv2.fitEllipse(cnt)
    cv2.ellipse(empty, ellipse, (0, 0, 255), 3)

cv2.imwrite('contours.bmp',empty)

Result (as you can see elipses are not inscribed): enter image description here

0

There are 0 best solutions below