當前位置: 首頁>>代碼示例>>Python>>正文


Python cv2.fitEllipse方法代碼示例

本文整理匯總了Python中cv2.fitEllipse方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.fitEllipse方法的具體用法?Python cv2.fitEllipse怎麽用?Python cv2.fitEllipse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cv2的用法示例。


在下文中一共展示了cv2.fitEllipse方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: getEllipseRotation

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def getEllipseRotation(image, cnt):
    try:
        # Gets rotated bounding ellipse of contour
        ellipse = cv2.fitEllipse(cnt)
        centerE = ellipse[0]
        # Gets rotation of ellipse; same as rotation of contour
        rotation = ellipse[2]
        # Gets width and height of rotated ellipse
        widthE = ellipse[1][0]
        heightE = ellipse[1][1]
        # Maps rotation to (-90 to 90). Makes it easier to tell direction of slant
        rotation = translateRotation(rotation, widthE, heightE)

        cv2.ellipse(image, ellipse, (23, 184, 80), 3)
        return rotation
    except:
        # Gets rotated bounding rectangle of contour
        rect = cv2.minAreaRect(cnt)
        # Creates box around that rectangle
        box = cv2.boxPoints(rect)
        # Not exactly sure
        box = np.int0(box)
        # Gets center of rotated rectangle
        center = rect[0]
        # Gets rotation of rectangle; same as rotation of contour
        rotation = rect[2]
        # Gets width and height of rotated rectangle
        width = rect[1][0]
        height = rect[1][1]
        # Maps rotation to (-90 to 90). Makes it easier to tell direction of slant
        rotation = translateRotation(rotation, width, height)
        return rotation

#################### FRC VISION PI Image Specific ############# 
開發者ID:team3997,項目名稱:ChickenVision,代碼行數:36,代碼來源:ChickenVision.py

示例2: find_marker_ellipses

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def find_marker_ellipses(im):
    im_gray = cvtColor(im, COLOR_BGR2GRAY)
    im_blur = GaussianBlur(im_gray, (3, 3), 0)
    ret, th = threshold(im_blur, 0, 255, THRESH_BINARY_INV + THRESH_OTSU)
    imgEdge, contours, hierarchy = findContours(th, RETR_TREE, CHAIN_APPROX_NONE)
    points = []
    origins = []
    ellipses = []
    id_point_candidates = []
    small_point_candidates = []
    for cnt in contours:
        if contour_sanity_check(cnt, im.shape[0], point_d=0.02):
            id_point_candidates.append(cnt)
        elif contour_sanity_check(cnt, im.shape[0], point_d=0.01):
            small_point_candidates.append(cnt)
    for cnt in id_point_candidates:
        x, y, w, h = boundingRect(cnt)
        ellipse = fitEllipse(cnt)
        points.append(im_gray[y:y + h, x:x + w])
        origins.append((x, y))
        ellipses.append(ellipse)
    return points, origins, ellipses 
開發者ID:pinae,項目名稱:Zozo-Measurer,代碼行數:24,代碼來源:markers.py

示例3: fit_circle

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def fit_circle(self, contour, eccentricity, area_ratio,min_radius = 0, max_radius = 500000):
		#convert to convex hull
		hull = cv2.convexHull(contour)
		min_area = math.pi * min_radius * min_radius
		max_area = math.pi * max_radius * max_radius
		c_area = cv2.contourArea(hull)

		#check for a shape of a certain size and corner resolution
		if len(hull) > 4:

			#fit an ellipse
			ellipse = cv2.fitEllipse(hull)
			radius = int((ellipse[1][0] + ellipse[1][0]) /4.0)
			#check for a circular ellipse
			if ellipse[1][0] * 1.0/ ellipse[1][1] > eccentricity and max_radius > radius > min_radius:
				#compare area of raw hull vs area of ellipse to ellinate objects with corners
				e_area = (ellipse[1][0]/2.0) * (ellipse[1][1]/2.0) * math.pi
				if (c_area / e_area) > area_ratio:
					center = Point(int(ellipse[0][0]), int(ellipse[0][1]))
					radius = int((ellipse[1][0] + ellipse[1][0]) /4.0) #average  and diameter -> radius
					return Circle(center,radius,contour,ellipse)
		return None 
開發者ID:djnugent,項目名稱:Precland,代碼行數:24,代碼來源:Ring_Detector.py

示例4: findEllipses

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
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 
開發者ID:AVGInnovationLabs,項目名稱:DoNotSnap,代碼行數:33,代碼來源:RegionOfInterest.py

示例5: _fit_ellipse

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def _fit_ellipse(thresholded_image):
    """Finds contours and fits an ellipse to thresholded image

    Parameters
    ----------
    thresholded_image :
        Binary image containing two eyes

    Returns
    -------
    type
        When eyes were found, the two ellipses, otherwise False

    """
    cont_ret = cv2.findContours(
        thresholded_image.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
    )

    # API change, in OpenCV 4 there are 2 values unlike OpenCV3
    if len(cont_ret) == 3:
        _, contours, hierarchy = cont_ret
    else:
        contours, hierarchy = cont_ret

    if len(contours) >= 2:

        # Get the two largest ellipses (i.e. the eyes, not any dirt)
        contours = sorted(contours, key=lambda c: c.shape[0], reverse=True)[:2]
        # Sort them that first ellipse is always the left eye (in the image)
        contours = sorted(contours, key=np.max)

        # Fit the ellipses for the two eyes
        if len(contours[0]) > 4 and len(contours[1]) > 4:
            e = [cv2.fitEllipse(contours[i]) for i in range(2)]
            return e
        else:
            return False

    else:
        # Not at least two eyes + maybe dirt found...
        return False 
開發者ID:portugueslab,項目名稱:stytra,代碼行數:43,代碼來源:eyes.py

示例6: filter_contours

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def filter_contours(contours, min_area=100, max_area=300, angle_thresh=15.0):
    filtered = []
    for cnt in contours:
        if len(cnt) < 5:
            continue
        # rect = cv2.minAreaRect(cnt)
        (x, y), (major, minor), angle = cv2.fitEllipse(cnt)
        area = cv2.contourArea(cnt)
        # cv2.ellipse(image, ((x,y), (major,minor), angle), (0,255,0), 2)

        if abs(angle - 90) < angle_thresh:
            c = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, False), False)
            filtered.append(c)
    return filtered 
開發者ID:shekkizh,項目名稱:ImageProcessingProjects,代碼行數:16,代碼來源:EdgeBased.py

示例7: eccentricity_from_ellipse

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def eccentricity_from_ellipse(contour):
    """Calculates the eccentricity fitting an ellipse from a contour"""

    (x, y), (MA, ma), angle = cv2.fitEllipse(contour)

    a = ma / 2
    b = MA / 2

    ecc = np.sqrt(a ** 2 - b ** 2) / a
    return ecc 
開發者ID:PacktPublishing,項目名稱:Mastering-OpenCV-4-with-Python,代碼行數:12,代碼來源:contours_ellipses.py

示例8: find_body_part

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def find_body_part(image, part_name):
    """
    Find body part.

    :param image: <RGB> image
    :param part_name: <string> part_name
    :return: <BodyPart[]>list
    """
    bodypart_list = []  # empty BodyPart list

    color_mask = get_correct_filter_color(image, part_name)

    # find contours:
    contours, _ = cv2.findContours(color_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # for every contour:
    for cnt in contours:

        if len(cnt) > 5:  # at least 5 points to fit ellipse

            # (x, y), (MA, ma), angle = cv2.fitEllipse(cnt)
            ellipse = cv2.fitEllipse(cnt)

            # Fit Result:
            x = ellipse[0][0]  # center x
            y = ellipse[0][1]  # center y
            angle = ellipse[2]  # angle
            a_min = ellipse[1][0]  # asse minore
            a_max = ellipse[1][1]  # asse maggiore

            h, w = detect_direction(a_max, a_min, angle)

            h, w = normalize_belly_vag(h, part_name, w)

            xmax, xmin, ymax, ymin = BoundingBox.calculate_bounding_box(h, w, x, y)

            BodyPart.add_body_part_to_list(part_name, BoundingBox(xmin, ymin, xmax, ymax), Center(x, y),
                                           Dimension(w, h), bodypart_list)

    return bodypart_list 
開發者ID:dreamnettech,項目名稱:dreampower,代碼行數:42,代碼來源:extract.py

示例9: contour_sanity_check

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def contour_sanity_check(contour, image_height, point_d=0.02):
    # We assume a persons height is between 1,3m and 2,2m.
    # In a reasonably sane photographed image the person is either
    # head to toe in the image or uses at least half the frame.
    # Points with ID have a diameter of 2cm. The small points at
    # the neck have a diameter of 1cm.
    x, y, w, h = boundingRect(contour)
    # Calculate a lower bound for the size of one pixel
    lb = 1.3 / image_height
    # Calculate an upper bound for the size of one pixel
    ub = 2 * 2.2 / image_height
    # Checking bounds for width and height
    if max(w, h) * ub < point_d or max(w, h) * lb > point_d:
        return False
    # The maximum area of a point is a circle
    if contourArea(contour) > np.pi * (point_d / 2 / lb) ** 2:
        return False
    # The maximum perimeter of a point is a circle
    if arcLength(contour, True) * lb > np.pi * point_d:
        return False
    # The minimum perimeter of a point is 2*d
    if arcLength(contour, True) * ub < 2 * point_d:
        return False
    # The perimeter should not be much bigger than that of the
    # minimal ellipse with the same area
    epsilon_factor = 1.5
    if arcLength(contour, True) > epsilon_factor * approx_ellipse_perimeter(w, h):
        return False
    # Calculate the average quadratic distance of the contour to a fitted ellipse
    if len(contour) < 5:
        return False
    ellipse = fitEllipse(contour)
    if ellipse[1][0] <= 0 or ellipse[1][1] <= 0:
        return False
    # For very flat ellipses there is no hope to detect a point id later
    if min(ellipse[1]) < 0.1 * max(ellipse[1]):
        return False
    # Check if the contour is roughly elliptical
    quad_dist = 0
    for p in contour:
        tp = p[0][0] - ellipse[0][0], p[0][1] - ellipse[0][1]
        rtp = rotate_point(tp, (0, 0), -ellipse[2] + 90)
        poe = find_nearest_point_on_ellipse(ellipse[1][1] / 2, ellipse[1][0] / 2, rtp)
        poer = rotate_point(poe, (0, 0), ellipse[2] - 90)
        poert = poer[0] + ellipse[0][0], poer[1] + ellipse[0][1]
        quad_dist += (p[0][0] - poert[0]) ** 2 + (p[0][1] - poert[1]) ** 2
    if quad_dist / len(contour) > 1.0:
        return False
    # This contour could be a point
    return True 
開發者ID:pinae,項目名稱:Zozo-Measurer,代碼行數:52,代碼來源:markers.py

示例10: process

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import fitEllipse [as 別名]
def process(frame):
    # plt.subplot(231)
    # plt.imshow(frame)

    # # step1: extract bright field
    # 轉為灰度圖
    frame = nomalize_to_8_bit_BGR(frame)
    frame = cv2.resize(frame,(256,256))
    img_gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 中值模糊去噪點
    MEDIUM_BLUR_RADIUM=5
    img_blur=cv2.medianBlur(img_gray,MEDIUM_BLUR_RADIUM)
    # plt.subplot(232)
    # plt.imshow(img_blur,'gray')

    # 閾值分割
    _,thresh = cv2.threshold(img_blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    # plt.subplot(233)
    # plt.imshow(thresh,'gray')

    # 提取明亮區域
    img=thresh.copy()
    bright_area_masks=[]
    contours, hierarchy = cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # 提取輪廓
    for cnt in contours:# 遍曆輪廓
        mask = np.zeros(img.shape,np.uint8)# 空mask
        hull = cv2.convexHull(cnt)#考慮到小球可能接觸到明場邊緣, 需要使用輪廓的凸包
        cv2.drawContours(mask,[hull],0,255,-1) # 用輪廓填充mask
        mean_val = cv2.mean(img,mask = mask)[0]# 用mask計算輪廓內平均灰度
        if mean_val>128:# 如果輪廓內亮度>128
            bright_area_masks.append(mask) # 收集這個mask
    # 一張圖可能有多個明亮區域, 但明場視野應該是像素亮度總和最高的
    idx=np.argmax([cv2.mean(img,mask=area)[0]*cv2.countNonZero(area) for area in bright_area_masks])
    bright_field_mask=bright_area_masks[idx]
    # plt.subplot(234)
    # plt.imshow(bright_field_mask,'gray')

    # # step2: 明場內找黑斑

    img_balls=thresh+255-bright_field_mask # 將明場外區域填白
    # plt.subplot(235)
    # plt.imshow(img_balls,'gray')

    contours, hierarchy = cv2.findContours(255-img_balls,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # 提取輪廓(外框需要是黑的,所以反相一下)
    cnt=max(contours,key=cv2.contourArea) # 取麵積最大的輪廓
    mask = np.zeros(img_balls.shape,np.uint8)# 空mask
    cv2.drawContours(mask,[cnt],0,255,-1) # 用輪廓填充mask
    ellipse=cv2.fitEllipse(cnt)
    img_label=cv2.ellipse(frame,ellipse,(0,255,0),2)
    # plt.subplot(236)
    # plt.imshow(img_label,'gray')
    return img_label,ellipse[2] 
開發者ID:deepdiy,項目名稱:deepdiy,代碼行數:54,代碼來源:process.py


注:本文中的cv2.fitEllipse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。