当前位置: 首页>>代码示例>>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;未经允许,请勿转载。