Python cv2 模块,fitEllipse() 实例源码

我们从Python开源项目中,提取了以下7个代码示例,用于说明如何使用cv2.fitEllipse()

项目:DoNotSnap    作者:AVGInnovationLabs    | 项目源码 | 文件源码
def findEllipses(edges):
    contours, _ = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    ellipseMask = np.zeros(edges.shape, dtype=np.uint8)
    contourMask = np.zeros(edges.shape, dtype=np.uint8)

    pi_4 = np.pi * 4

    for i, contour in enumerate(contours):
        if len(contour) < 5:
            continue

        area = cv2.contourArea(contour)
        if area <= 100:  # skip ellipses smaller then 10x10
            continue

        arclen = cv2.arcLength(contour, True)
        circularity = (pi_4 * area) / (arclen * arclen)
        ellipse = cv2.fitEllipse(contour)
        poly = cv2.ellipse2Poly((int(ellipse[0][0]), int(ellipse[0][1])), (int(ellipse[1][0] / 2), int(ellipse[1][1] / 2)), int(ellipse[2]), 0, 360, 5)

        # if contour is circular enough
        if circularity > 0.6:
            cv2.fillPoly(ellipseMask, [poly], 255)
            continue

        # if contour has enough similarity to an ellipse
        similarity = cv2.matchShapes(poly.reshape((poly.shape[0], 1, poly.shape[1])), contour, cv2.cv.CV_CONTOURS_MATCH_I2, 0)
        if similarity <= 0.2:
            cv2.fillPoly(contourMask, [poly], 255)

    return ellipseMask, contourMask
项目:OpenCV2    作者:SarathM1    | 项目源码 | 文件源码
def lipSegment(self, img):
        # self.t1 = cv2.getTickCount()
        lipHull = self.dlib_obj.get_landmarks(img)
        cv2.drawContours(img, lipHull, -1, (255, 0, 0), 2)
        (x, y), (MA, ma), angle = cv2.fitEllipse(lipHull)
        a = ma/2
        b = MA/2

        eccentricity = sqrt(pow(a, 2)-pow(b, 2))
        eccentricity = round(eccentricity/a, 2)

        cv2.putText(img, 'E = '+str(round(eccentricity, 3)), (10, 350),
                    self.font, 1, (255, 0, 0), 1)

        if(eccentricity < 0.9):
            self.flags.cmd = 'b'
        else:
            self.flags.cmd = 'f'

        if angle < 80:
            self.flags.cmd = 'l'
        elif angle > 100:
            self.flags.cmd = 'r'

        cv2.putText(img, 'Cmd = ' + self.flags.cmd, (10, 300),  self.font,  1,
                    (0, 0, 255), 1, 16)
        # self.t2 = cv2.getTickCount()
        # print "Time = ", (self.t2-self.t1)/cv2.getTickFrequency()
        return img
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def find_concetric_circles(gray_img,min_ring_count=3, visual_debug=False):

    # get threshold image used to get crisp-clean edges using blur to remove small features
    edges = cv2.adaptiveThreshold(cv2.blur(gray_img,(3,3)), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 11)
    _, contours, hierarchy = cv2.findContours(edges,
                                    mode=cv2.RETR_TREE,
                                    method=cv2.CHAIN_APPROX_NONE,offset=(0,0)) #TC89_KCOS
    if visual_debug is not False:
        cv2.drawContours(visual_debug,contours,-1,(200,0,0))
    if contours is None or hierarchy is None:
        return []
    clusters = get_nested_clusters(contours,hierarchy[0],min_nested_count=min_ring_count)
    concentric_cirlce_clusters = []

    #speed up code by caching computed ellipses
    ellipses = {}

    # for each cluster fit ellipses and cull members that dont have good ellipse fit
    for cluster in clusters:
        if visual_debug is not False:
            cv2.drawContours(visual_debug, [contours[i] for i in cluster],-1, (0,0,255))
        candidate_ellipses = []
        for i in cluster:
            c = contours[i]
            if len(c)>5:
                if not i in ellipses:
                    e = cv2.fitEllipse(c)
                    fit = max(dist_pts_ellipse(e,c))
                    ellipses[i] = e,fit
                else:
                    e,fit = ellipses[i]
                a,b = e[1][0]/2.,e[1][1]/2.
                if fit<max(2,max(e[1])/20):
                    candidate_ellipses.append(e)
                    if visual_debug is not False:
                        cv2.ellipse(visual_debug, e, (0,255,0),1)

        if candidate_ellipses:
            cluster_center = np.mean(np.array([e[0] for e in candidate_ellipses]),axis=0)
            candidate_ellipses = [e for e in candidate_ellipses if np.linalg.norm(e[0]-cluster_center)<max(3,min(e[1])/20) ]
            if len(candidate_ellipses) >= min_ring_count:
                concentric_cirlce_clusters.append(candidate_ellipses)
                if visual_debug is not False:
                    cv2.ellipse(visual_debug, candidate_ellipses[-1], (0,255,255),4)

    #return clusters sorted by size of outmost cirlce biggest first.
    return sorted(concentric_cirlce_clusters,key=lambda e:-max(e[-1][1]))
项目:object-detection-python-opencv    作者:hasanaliqureshi    | 项目源码 | 文件源码
def circle_contour(image, contour):
    # Bounding ellipse
    image_with_ellipse = image.copy()
    #easy function
    ellipse = cv2.fitEllipse(contour)
    #add it
    cv2.ellipse(image_with_ellipse, ellipse, green, 2,cv2.LINE_AA)
    return image_with_ellipse
项目:OpenCV2    作者:SarathM1    | 项目源码 | 文件源码
def lipSegment(img):
    img = imutils.resize(img,width=300)
    img_copy = img.copy()

    landmarks = dlib_obj.get_landmarks(img)
    dlib_obj.get_face_mask(img_copy, landmarks)

    output_img = img-img_copy
    output_img = cv2.cvtColor(output_img,cv2.COLOR_BGR2GRAY)

    contours,hierarchy = cv2.findContours(output_img.copy(), cv2.cv.CV_RETR_EXTERNAL, cv2.cv.CV_CHAIN_APPROX_SIMPLE)  #cv2.findContours(image, mode, method
    cv2.drawContours(img, contours, -1, (0,255,0), 2,maxLevel=0)

    cnt = contours[0]
    ellipse = cv2.fitEllipse(cnt)
    (x,y),(MA,ma),angle = cv2.fitEllipse(cnt)


    a = ma/2
    b = MA/2


    eccentricity = sqrt(pow(a,2)-pow(b,2))
    eccentricity = round(eccentricity/a,2)

    font = cv2.FONT_HERSHEY_SIMPLEX

    cv2.putText(img,'Eccentr= '+str(round(eccentricity,3)),(10,350), font, 1,(255,0,0),2,16)

    if(eccentricity < 0.9):
        cv2.putText(img,'Commands = O',(10,300), font, 1,(0,0,255),2,16)
    else:
        cv2.putText(img,'Commands = E',(10,300), font, 1,(0,0,255),2,16)

    return img
项目:Semi-automatic-Annotation    作者:Luoyadan    | 项目源码 | 文件源码
def draw_groupRect(self, img_arr, ID):
        ID = int(ID)
        img = Image.fromarray(img_arr)
        draw = ImageDraw.Draw(img, mode='RGBA')
        bi_ID = bi_t = np.zeros(self.final_BI.shape, np.uint8)
        bi_ID[self.final_ID == ID] = 255

        # Image.fromarray(bi_ID).show()

        ## get contour -- cnt of polygon
        if self.parent().line2_mode == "polygonOtsu":
            bi_ID = cv2.GaussianBlur(bi_ID, (11, 11), 0)
            bi_ID = cv2.dilate(bi_ID, None, iterations=4)

        im2, contours, hierarchy = cv2.findContours(bi_ID, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        cnt_union = contours[0]
        for i, cnt in enumerate(contours):
            if i > 0:
                cnt_union = np.concatenate((cnt_union, cnt), axis=0)


        ellipse = cv2.fitEllipse(cnt_union)
        cv2.ellipse(img_arr,ellipse,(0,255,0,175),2)
        extBottom = tuple(cnt_union[cnt_union[:, :, 1].argmax()][0])

        font = cv2.FONT_HERSHEY_PLAIN
        cv2.putText(img_arr, "ID_"+str(ID), extBottom, font, 1.5, (255, 49, 12), 2)

        return img_arr
项目:SkinLesionNeuralNetwork    作者:Neurality    | 项目源码 | 文件源码
def fit_ellipse(masks):
    ellipses = []

    k = 0
    for i in range(0,len(masks)):
        mask = masks[0]
        #cv2.imwrite("./input/ellipses/10_1_"+str(k)+"_mask.tif", mask)

        contours, hierarchy = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

        #immagine nera
        temp = np.zeros(mask.shape, dtype=np.uint8)
        #cv2.imwrite("./input/ellipses/10_1_mask_black.tif", temp)

        #disegno i contorni su sfondo nero
        cv2.drawContours(temp, contours, -1, (255,255,255), 3)

        #voglio scrivere quest'immagine che, in teoria, e' nera con 
        #i contorni individuati in bianco.. ma esplode il kernel se usata

        #cv2.imwrite("./input/ellipses/10_1_mask_cont.tif", temp)


        #cv2.imwrite("./input/ellipses/10_1_mask_after.tif", mask)
        for cnt in contours:

            param_ellipse = []
            #print "fitto"
            ellipse = cv2.fitEllipse(cnt)

            #cv2.imwrite("./input/ellipses/10_1_"+str(k)+"_mask.tif", mask)

            #disegna l'ellisse
            black = np.zeros(mask.shape, dtype=np.uint8)
            cv2.ellipse(black, ellipse, (255,255,255), 2)
            #cv2.imwrite("./input/ellipses/10_1_"+str(k)+"_mask_ellipse.tif", black)
            k=k+1


            '''
            Coordinate necessarie/ritornate: 
            (ellipse.center.x,
            ellipse.center.y),
            (ellipse.size.height*2,
            ellipse.size.width*2),
            ellipse.angle
            '''
            #print "ellipse"
            #print ellipse

            ellipses.append(ellipse)

    return np.array(ellipses)