Python cv2.fitEllipse() Examples
The following are 11
code examples of cv2.fitEllipse().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cv2
, or try the search function
.
Example #1
Source File: ChickenVision.py From ChickenVision with MIT License | 13 votes |
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 #############
Example #2
Source File: RegionOfInterest.py From DoNotSnap with GNU General Public License v3.0 | 7 votes |
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
Example #3
Source File: Ring_Detector.py From Precland with GNU General Public License v3.0 | 7 votes |
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
Example #4
Source File: markers.py From Zozo-Measurer with GNU General Public License v3.0 | 6 votes |
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
Example #5
Source File: contours_analysis.py From Mastering-OpenCV-4-with-Python with MIT License | 6 votes |
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
Example #6
Source File: EdgeBased.py From ImageProcessingProjects with MIT License | 5 votes |
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
Example #7
Source File: contours_ellipses.py From Mastering-OpenCV-4-with-Python with MIT License | 5 votes |
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
Example #8
Source File: extract.py From dreampower with GNU General Public License v3.0 | 5 votes |
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
Example #9
Source File: eyes.py From stytra with GNU General Public License v3.0 | 4 votes |
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
Example #10
Source File: markers.py From Zozo-Measurer with GNU General Public License v3.0 | 4 votes |
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
Example #11
Source File: process.py From deepdiy with MIT License | 4 votes |
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]