Python cv2.RETR_EXTERNAL Examples
The following are 30
code examples of cv2.RETR_EXTERNAL().
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: thresholding.py From smashscan with MIT License | 12 votes |
def contour_filter(self, frame): _, contours, _ = cv2.findContours(frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) new_frame = np.zeros(frame.shape, np.uint8) for i, contour in enumerate(contours): c_area = cv2.contourArea(contour) if self.contour_min_area <= c_area <= self.contour_max_area: mask = np.zeros(frame.shape, np.uint8) cv2.drawContours(mask, contours, i, 255, cv2.FILLED) mask = cv2.bitwise_and(frame, mask) new_frame = cv2.bitwise_or(new_frame, mask) frame = new_frame if self.contour_disp_flag: frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) cv2.drawContours(frame, contours, -1, (255, 0, 0), 1) return frame # A number of methods corresponding to the various trackbars available.
Example #2
Source File: segment.py From gesture-recognition with MIT License | 12 votes |
def segment(image, threshold=25): global bg # find the absolute difference between background and current frame diff = cv2.absdiff(bg.astype("uint8"), image) # threshold the diff image so that we get the foreground thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1] # get the contours in the thresholded image (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # return None, if no contours detected if len(cnts) == 0: return else: # based on contour area, get the maximum contour which is the hand segmented = max(cnts, key=cv2.contourArea) return (thresholded, segmented) #----------------- # MAIN FUNCTION #-----------------
Example #3
Source File: motion.py From object-detection with MIT License | 10 votes |
def prediction(self, image): image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.GaussianBlur(image, (21, 21), 0) if self.avg is None: self.avg = image.copy().astype(float) cv2.accumulateWeighted(image, self.avg, 0.5) frameDelta = cv2.absdiff(image, cv2.convertScaleAbs(self.avg)) thresh = cv2.threshold( frameDelta, DELTA_THRESH, 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) cnts = cv2.findContours( thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) self.avg = image.copy().astype(float) return cnts
Example #4
Source File: load_saved_model.py From document-ocr with Apache License 2.0 | 7 votes |
def mask_to_bbox(mask, image, num_class, area_threhold=0, out_path=None, out_file_name=None): bbox_list = [] im = copy.copy(image) mask = mask.astype(np.uint8) for i in range(1, num_class, 1): c_bbox_list = [] c_mask = np.zeros_like(mask) c_mask[np.where(mask==i)] = 255 bimg , countours, hier = cv2.findContours(c_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for cnt in countours: area = cv2.contourArea(cnt) if area < area_threhold: continue epsilon = 0.005 * cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) (x, y, w, h) = cv2.boundingRect(approx) c_bbox_list.append([x, y, x+w, y+h]) if out_path is not None: color = COLOR_LIST[i-1] im=cv2.rectangle(im, pt1=(x, y), pt2=(x+w, y+h),color=color, thickness=2) bbox_list.append(c_bbox_list) if out_path is not None: outf = os.path.join(out_path, out_file_name) cv2.imwrite(outf, im) return bbox_list
Example #5
Source File: SudokuExtractor.py From SolveSudoku with MIT License | 7 votes |
def find_corners_of_largest_polygon(img): """Finds the 4 extreme corners of the largest contour in the image.""" opencv_version = cv2.__version__.split('.')[0] if opencv_version == '3': _, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours else: contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours contours = sorted(contours, key=cv2.contourArea, reverse=True) # Sort by area, descending polygon = contours[0] # Largest image # Use of `operator.itemgetter` with `max` and `min` allows us to get the index of the point # Each point is an array of 1 coordinate, hence the [0] getter, then [0] or [1] used to get x and y respectively. # Bottom-right point has the largest (x + y) value # Top-left has point smallest (x + y) value # Bottom-left point has smallest (x - y) value # Top-right point has largest (x - y) value bottom_right, _ = max(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1)) top_left, _ = min(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1)) bottom_left, _ = min(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1)) top_right, _ = max(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1)) # Return an array of all 4 points using the indices # Each point is in its own array of one coordinate return [polygon[top_left][0], polygon[top_right][0], polygon[bottom_right][0], polygon[bottom_left][0]]
Example #6
Source File: transforms_rbbox.py From AerialDetection with Apache License 2.0 | 7 votes |
def mask2poly_single(binary_mask): """ :param binary_mask: :return: """ try: contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # contour_lens = np.array(list(map(len, contours))) # max_id = contour_lens.argmax() # max_contour = contours[max_id] max_contour = max(contours, key=len) rect = cv2.minAreaRect(max_contour) poly = cv2.boxPoints(rect) # poly = TuplePoly2Poly(poly) except: import pdb pdb.set_trace() return poly
Example #7
Source File: img_roi_builder.py From ethoscope with GNU General Public License v3.0 | 6 votes |
def _rois_from_img(self, img): if len(self._mask.shape) == 3: self._mask = cv2.cvtColor(self._mask, cv2.COLOR_BGR2GRAY) if CV_VERSION == 3: _, contours, hiera = cv2.findContours(np.copy(self._mask), RETR_EXTERNAL, CHAIN_APPROX_SIMPLE) else: contours, hiera = cv2.findContours(np.copy(self._mask), RETR_EXTERNAL, CHAIN_APPROX_SIMPLE) rois = [] for i,c in enumerate(contours): tmp_mask = np.zeros_like(self._mask) cv2.drawContours(tmp_mask, [c],0, 1) value = int(np.median(self._mask[tmp_mask > 0])) rois.append(ROI(c, i+1, value)) return rois
Example #8
Source File: segmentation_mask.py From Parsing-R-CNN with MIT License | 6 votes |
def _findContours(self): contours = [] masks = self.masks.detach().numpy() for mask in masks: mask = cv2.UMat(mask) contour, hierarchy = cv2.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1 ) reshaped_contour = [] for entity in contour: assert len(entity.shape) == 3 assert entity.shape[1] == 1, "Hierarchical contours are not allowed" reshaped_contour.append(entity.reshape(-1).tolist()) contours.append(reshaped_contour) return contours
Example #9
Source File: segmentation_mask.py From Clothing-Detection with GNU General Public License v3.0 | 6 votes |
def _findContours(self): contours = [] masks = self.masks.detach().numpy() for mask in masks: mask = cv2.UMat(mask) contour, hierarchy = cv2_util.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1 ) reshaped_contour = [] for entity in contour: assert len(entity.shape) == 3 assert ( entity.shape[1] == 1 ), "Hierarchical contours are not allowed" reshaped_contour.append(entity.reshape(-1).tolist()) contours.append(reshaped_contour) return contours
Example #10
Source File: segmentation_mask.py From EmbedMask with MIT License | 6 votes |
def _findContours(self): contours = [] masks = self.masks.detach().numpy() for mask in masks: mask = cv2.UMat(mask) contour, hierarchy = cv2.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1 ) reshaped_contour = [] for entity in contour: assert len(entity.shape) == 3 assert entity.shape[1] == 1, "Hierarchical contours are not allowed" reshaped_contour.append(entity.reshape(-1).tolist()) contours.append(reshaped_contour) return contours
Example #11
Source File: plate_locate.py From EasyPR-python with Apache License 2.0 | 6 votes |
def sobelSecSearchPart(self, bound, refpoint, out): bound_threshold = self.sobelOperT(bound, 3, 6, 2) tempBoundThread = bound_threshold.copy() clearLiuDingOnly(tempBoundThread) posLeft, posRight, flag = bFindLeftRightBound(tempBoundThread) if flag: if posRight != 0 and posLeft != 0 and posLeft < posRight: posY = int(bound_threshold.shape[0] * 0.5) for i in range(posLeft + int(bound_threshold.shape[0] * 0.1), posRight - 4): bound_threshold[posY, i] = 255 for i in range(bound_threshold.shape[0]): bound_threshold[i, posLeft] = 0 bound_threshold[i, posRight] = 0 _, contours, _ = cv2.findContours(bound_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for it in contours: mr = cv2.minAreaRect(it) if self.verifySizes(mr): tmp = (mr[0][0] + refpoint[0], mr[0][1] + refpoint[1]) out.append((tmp, mr[1], mr[2]))
Example #12
Source File: plate_locate.py From EasyPR-python with Apache License 2.0 | 6 votes |
def sobelFrtSearch(self, src): out_rects = [] src_threshold = self.sobelOper(src, self.m_GaussianBlurSize, self.m_MorphSizeWidth, self.m_MorphSizeHeight) _, contours, _ = cv2.findContours(src_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for it in contours: mr = cv2.minAreaRect(it) if self.verifySizes(mr): safeBoundRect, flag = self.calcSafeRect(mr, src) if not flag: continue out_rects.append(safeBoundRect) return out_rects
Example #13
Source File: plate_locate.py From EasyPR-python with Apache License 2.0 | 6 votes |
def colorSearch(self, src, color, out_rect): """ :param src: :param color: :param out_rect: minAreaRect :return: binary """ color_morph_width = 10 color_morph_height = 2 match_gray = colorMatch(src, color, False) _, src_threshold = cv2.threshold(match_gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY) element = cv2.getStructuringElement(cv2.MORPH_RECT, (color_morph_width, color_morph_height)) src_threshold = cv2.morphologyEx(src_threshold, cv2.MORPH_CLOSE, element) out = src_threshold.copy() _, contours, _ = cv2.findContours(src_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for cnt in contours: mr = cv2.minAreaRect(cnt) if self.verifySizes(mr): out_rect.append(mr) return out
Example #14
Source File: segmentation_mask.py From maskrcnn-benchmark with MIT License | 6 votes |
def _findContours(self): contours = [] masks = self.masks.detach().numpy() for mask in masks: mask = cv2.UMat(mask) contour, hierarchy = cv2_util.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1 ) reshaped_contour = [] for entity in contour: assert len(entity.shape) == 3 assert ( entity.shape[1] == 1 ), "Hierarchical contours are not allowed" reshaped_contour.append(entity.reshape(-1).tolist()) contours.append(reshaped_contour) return contours
Example #15
Source File: recognize.py From gesture-recognition with MIT License | 6 votes |
def segment(image, threshold=25): global bg # find the absolute difference between background and current frame diff = cv2.absdiff(bg.astype("uint8"), image) # threshold the diff image so that we get the foreground thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1] # get the contours in the thresholded image (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # return None, if no contours detected if len(cnts) == 0: return else: # based on contour area, get the maximum contour which is the hand segmented = max(cnts, key=cv2.contourArea) return (thresholded, segmented) #-------------------------------------------------------------- # To count the number of fingers in the segmented hand region #--------------------------------------------------------------
Example #16
Source File: ImageMiniLab.py From ImageMiniLab with GNU General Public License v3.0 | 6 votes |
def find_contours(self): src = self.cv_read_img(self.src_file) if src is None: return dst = cv.GaussianBlur(src, (3, 3), 0) gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY) ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) cloneImage, contous, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) for i,contou in enumerate(contous): cv.drawContours(src, contous, i, (0, 0, 255), 1) # 轮廓 self.decode_and_show_dst(src) # 轮廓覆盖 for i,contou in enumerate(contous): cv.drawContours(src, contous, i, (0, 0, 255), -1) self.decode_and_show_dst(src) #人脸识别 正脸 需要下载xml模型 haarcascade_frontalface_alt.xml
Example #17
Source File: locate_tissue.py From tissueloc with MIT License | 6 votes |
def find_tissue_cnts(bw_img): """ Fint contours of tissues Parameters ---------- bw_img : np.array 2D binary image. Returns ------- cnts: list List of all contours coordinates of tissues. """ cnts, _ = cv2.findContours(img_as_ubyte(bw_img), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE) return cnts
Example #18
Source File: segmentation_mask.py From sampling-free with MIT License | 6 votes |
def _findContours(self): contours = [] masks = self.masks.detach().numpy() for mask in masks: mask = cv2.UMat(mask) contour, hierarchy = cv2_util.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1 ) reshaped_contour = [] for entity in contour: assert len(entity.shape) == 3 assert ( entity.shape[1] == 1 ), "Hierarchical contours are not allowed" reshaped_contour.append(entity.reshape(-1).tolist()) contours.append(reshaped_contour) return contours
Example #19
Source File: image.py From uiautomator2 with MIT License | 6 votes |
def compare_ssim_debug(image_a, image_b, color=(255, 0, 0)): """ Args: image_a, image_b: opencv image or PIL.Image color: (r, g, b) eg: (255, 0, 0) for red Refs: https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/ """ ima, imb = conv2cv(image_a), conv2cv(image_b) score, diff = compare_ssim(ima, imb, full=True) diff = (diff * 255).astype('uint8') _, thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cv2color = tuple(reversed(color)) im = ima.copy() for c in cnts: x, y, w, h = cv2.boundingRect(c) cv2.rectangle(im, (x, y), (x+w, y+h), cv2color, 2) # todo: show image cv2pil(im).show() return im
Example #20
Source File: siam_mask_tracker.py From models with MIT License | 6 votes |
def _mask_post_processing(mask, center_pos, size, track_mask_threshold): target_mask = (mask > track_mask_threshold) target_mask = target_mask.astype(np.uint8) if cv2.__version__[-5] == '4': contours, _ = cv2.findContours(target_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) else: _, contours, _ = cv2.findContours( target_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cnt_area = [cv2.contourArea(cnt) for cnt in contours] if len(contours) != 0 and np.max(cnt_area) > 100: contour = contours[np.argmax(cnt_area)] polygon = contour.reshape(-1, 2) prbox = cv2.boxPoints(cv2.minAreaRect(polygon)) rbox_in_img = prbox else: # empty mask location = cxy_wh_2_rect(center_pos, size) rbox_in_img = np.array([[location[0], location[1]], [location[0] + location[2], location[1]], [location[0] + location[2], location[1] + location[3]], [location[0], location[1] + location[3]]]) return rbox_in_img
Example #21
Source File: auxiliary_function.py From roc with MIT License | 6 votes |
def find_bounding_box(pane, bounding_box_lower_thresholds, bounding_box_upper_thresholds, sort=True): # thresholds: turple # dimension_resized: turple segmented_pictures = [] rect_coordinates = [] width_lower_threshold, height_lower_threshold = bounding_box_lower_thresholds width_upper_threshold, height_upper_threshold = bounding_box_upper_thresholds contours, hierarchy = cv2.findContours(pane, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: (x, y, w, h) = cv2.boundingRect(contour) if h > height_lower_threshold and w > width_lower_threshold and h <= height_upper_threshold and w <= width_upper_threshold: rect_coordinates.append((x, y, w, h)) else: continue if sort: x_coordinates = [x for (x,y,w,h) in rect_coordinates] rect_coordinates= [e for _,e in sorted(zip(x_coordinates,rect_coordinates))] return rect_coordinates
Example #22
Source File: segmentation_mask.py From DetNAS with MIT License | 6 votes |
def _findContours(self): contours = [] masks = self.masks.detach().numpy() for mask in masks: mask = cv2.UMat(mask) contour, hierarchy = cv2_util.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1 ) reshaped_contour = [] for entity in contour: assert len(entity.shape) == 3 assert ( entity.shape[1] == 1 ), "Hierarchical contours are not allowed" reshaped_contour.append(entity.reshape(-1).tolist()) contours.append(reshaped_contour) return contours
Example #23
Source File: rotate_aug.py From AerialDetection with Apache License 2.0 | 5 votes |
def mask2poly_single(binary_mask): """ :param binary_mask: :return: """ # try: contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) max_contour = max(contours, key=len) rect = cv2.minAreaRect(max_contour) poly = cv2.boxPoints(rect) poly = TuplePoly2Poly(poly) return poly
Example #24
Source File: eval.py From document-ocr with Apache License 2.0 | 5 votes |
def mask_to_bbox(mask, image, num_class, out_path=None, out_file_name=None): bbox_list = [] im = copy.copy(image) mask = mask.astype(np.uint8) for i in range(1, num_class, 1): c_bbox_list = [] c_mask = np.zeros_like(mask) c_mask[np.where(mask==i)] = 255 bimg , countours, hier = cv2.findContours(c_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for cnt in countours: area = cv2.contourArea(cnt) if area < 50: continue epsilon = 0.005 * cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) (x, y, w, h) = cv2.boundingRect(approx) c_bbox_list.append([x, y, x+w, y+h]) if out_path is not None: color = COLOR_LIST[i-1] im=cv2.rectangle(im, pt1=(x, y), pt2=(x+w, y+h),color=color, thickness=2) bbox_list.append(c_bbox_list) if out_path is not None: outf = os.path.join(out_path, out_file_name) print(outf) cv2.imwrite(outf, im) return bbox_list
Example #25
Source File: drawer.py From Handwriting-Recognition with Apache License 2.0 | 5 votes |
def get_contours(self): """ Method to find contours in an image and crop them and return a list with cropped contours """ images = [] main_image = self.img orig_image = main_image.copy() # convert to greyscale and apply Gaussian filtering main_image = cv2.cvtColor(src=main_image, code=cv2.COLOR_BGR2GRAY) main_image = cv2.GaussianBlur(src=main_image, ksize=(5, 5), sigmaX=0) # threshold the image _, main_image = cv2.threshold(src=main_image, thresh=127, maxval=255, type=cv2.THRESH_BINARY) # find contours in the image contours, _ = cv2.findContours(image=main_image.copy(), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE) # get rectangles containing each contour bboxes = [cv2.boundingRect(array=contour) for contour in contours] for bbox in bboxes: x, y, width, height = bbox[:4] images.append(orig_image[y:y + height, x:x + width]) return images
Example #26
Source File: pdf-to-csv-cv.py From pdf-to-csv-table-extactor with Do What The F*ck You Want To Public License | 5 votes |
def extract_main_table(gray_image): inverted = cv2.bitwise_not(gray_image) blurred = cv2.GaussianBlur(inverted, (5, 5), 0) thresholded = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] if DEBUG: show_wait_destroy("thresholded",thresholded) cnts = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[1]# if imutils.is_cv2() else cnts[1] cnts = sorted(cnts, key=cv2.contourArea, reverse=True) rect = cv2.minAreaRect(cnts[0]) box = cv2.boxPoints(rect) box = np.int0(box) extracted = four_point_transform(gray_image.copy(), box.reshape(4, 2)) if DEBUG: color_image = cv2.cvtColor(gray_image.copy(), cv2.COLOR_GRAY2BGR) cv2.drawContours(color_image,[box],0,(0,0,255),2) cv2.drawContours(color_image, [cnts[0]], -1, (0, 255, 0), 2) return extracted
Example #27
Source File: demo.py From ActionAI with GNU General Public License v3.0 | 5 votes |
def motion_detector(self, img): occupied = False # resize the frame, convert it to grayscale, and blur it gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (15, 15), 0) if self.avg is None: print("[INFO] starting background model...") self.avg = gray.copy().astype("float") # accumulate the weighted average between the current frame and # previous frames, then compute the difference between the current # frame and running average cv2.accumulateWeighted(gray, self.avg, 0.5) frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg)) # threshold the delta image, dilate the thresholded image to fill # in holes, then find contours on thresholded image thresh = cv2.threshold(frameDelta, 5, 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[1] # loop over the contours for c in cnts: # if the contour is too small, ignore it if cv2.contourArea(c) < 5000: pass occupied = True return occupied
Example #28
Source File: dota_utils.py From AerialDetection with Apache License 2.0 | 5 votes |
def seg2poly_old(rle): # TODO: debug for this function """ This function transform a single encoded RLE to a single poly :param seg: RlE :return: poly """ # try: # binary_mask = mask_utils.decode(rle) # contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL) # contour_lens = np.array(list(map(len, contours))) # max_id = contour_lens.argmax() # max_contour = contours[max_id] # rect = cv2.minAreaRect(max_contour) # poly = cv2.boxPoints(rect) # return poly # except: # return -1 try: binary_mask = mask_utils.decode(rle) contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # len is not appropriate # contour_lens = np.array(list(map(len, contours))) # max_id = contour_lens.argmax() contour_areas = np.array(list(map(cv2.contourArea, contours))) max_id = contour_areas.argmax() max_contour = contours[max_id] rect = cv2.minAreaRect(max_contour) poly = cv2.boxPoints(rect) poly = TuplePoly2Poly(poly) return poly except: return []
Example #29
Source File: generate_sub_final_ensemble.py From kaggle_carvana_segmentation with MIT License | 5 votes |
def biggest_contour(im): im2, contours, hierarchy = cv2.findContours(np.copy(im), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) biggest, maxarea = None, 0 for cnt in contours: a = cv2.contourArea(cnt) if a > maxarea: biggest, maxarea = cnt, a return biggest
Example #30
Source File: page_dewarp.py From page_dewarp with MIT License | 5 votes |
def get_contours(name, small, pagemask, masktype): mask = get_mask(name, small, pagemask, masktype) _, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) contours_out = [] for contour in contours: rect = cv2.boundingRect(contour) xmin, ymin, width, height = rect if (width < TEXT_MIN_WIDTH or height < TEXT_MIN_HEIGHT or width < TEXT_MIN_ASPECT*height): continue tight_mask = make_tight_mask(contour, xmin, ymin, width, height) if tight_mask.sum(axis=0).max() > TEXT_MAX_THICKNESS: continue contours_out.append(ContourInfo(contour, rect, tight_mask)) if DEBUG_LEVEL >= 2: visualize_contours(name, small, contours_out) return contours_out