我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用cv2.RETR_CCOMP。
def polygonize_cv(mask, epsilon=1., min_area=10.): contours, hierarchy = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) # create approximate contours to have reasonable submission size approx_contours = [cv2.approxPolyDP(cnt, epsilon, True) for cnt in contours] approx_contours = contours if not contours: return MultiPolygon() # now messy stuff to associate parent and child contours cnt_children = defaultdict(list) child_contours = set() assert hierarchy.shape[0] == 1 # http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]): if parent_idx != -1: child_contours.add(idx) cnt_children[parent_idx].append(approx_contours[idx]) # create actual polygons filtering by area (removes artifacts) all_polygons = [] for idx, cnt in enumerate(approx_contours): if idx not in child_contours and cv2.contourArea(cnt) >= min_area: assert cnt.shape[1] == 1 poly = Polygon( shell=cnt[:, 0, :], holes=[c[:, 0, :] for c in cnt_children.get(idx, []) if cv2.contourArea(c) >= min_area]) all_polygons.append(poly) # approximating polygons might have created invalid ones, fix them all_polygons = MultiPolygon(all_polygons) if not all_polygons.is_valid: all_polygons = all_polygons.buffer(0) # Sometimes buffer() converts a simple Multipolygon to just a Polygon, # need to keep it a Multi throughout if all_polygons.type == 'Polygon': all_polygons = MultiPolygon([all_polygons]) return all_polygons
def recognize_text(original): idcard = original gray = cv2.cvtColor(idcard, cv2.COLOR_BGR2GRAY) # Morphological gradient: kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) opening = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, kernel) # Binarization ret, binarization = cv2.threshold(opening, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # Connected horizontally oriented regions kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1)) connected = cv2.morphologyEx(binarization, cv2.MORPH_CLOSE, kernel) # find countours _, contours, hierarchy = cv2.findContours( connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE ) return contours, hierarchy
def get_image_xy_corner(self): """get ?artesian coordinates from raster""" import cv2 if not self.image_path: return False image_xy_corners = [] img = cv2.imread(self.image_path, cv2.IMREAD_GRAYSCALE) imagem = (255 - img) try: ret, thresh = cv2.threshold(imagem, 10, 128, cv2.THRESH_BINARY) try: contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) except Exception: im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) hierarchy = hierarchy[0] hierarhy_contours = [[] for _ in range(len(hierarchy))] for fry in range(len(contours)): currentContour = contours[fry] currentHierarchy = hierarchy[fry] cc = [] # epsilon = 0.0005 * cv2.arcLength(contours[len(contours) - 1], True) approx = cv2.approxPolyDP(currentContour, self.epsilon, True) if len(approx) > 2: for c in approx: cc.append([c[0][0], c[0][1]]) parent_index = currentHierarchy[3] index = fry if parent_index < 0 else parent_index hierarhy_contours[index].append(cc) image_xy_corners = [c for c in hierarhy_contours if len(c) > 0] return image_xy_corners except Exception as ex: self.error(ex) return image_xy_corners
def do(self, bin_img): tmp_bin_img = np.copy(bin_img) if cv2.__version__[0] == "2": contours, hierarchy = cv2.findContours( tmp_bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) else: _, contours, hierarchy = cv2.findContours( tmp_bin_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) filtered_contours = [] for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) if w * h > self.max_area or w * h < self.min_area: bin_img[y:y+h, x:x+w] = 0 contours = filtered_contours
def do_touch(self): width, height = 1080, 1920 screen = self.device.screenshot_cv2() h, w = screen.shape[:2] img = cv2.resize(screen, (w/2, h/2)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 80, 200) _, thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_OTSU) contours, _ = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) contours.sort(key=lambda cnt: len(cnt), reverse=True) rects = [] for cnt in contours: hull = cv2.convexHull(cnt) hull_area = cv2.contourArea(hull) x,y,w,h = cv2.boundingRect(cnt) rect_area = float(w*h) if w<20 or h<20 or rect_area<100: continue if hull_area/rect_area < 0.50: continue rects.append((x, y, x+w, y+h)) cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2) if not rects: x, y = randint(1, width), randint(1, height) else: x1, y1, x2, y2 = choice(rects) x, y = randint(x1, x2), randint(y1, y2) cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) x, y = self.device.screen2touch(x*2, y*2) self.device.touch(x, y) cv2.imshow('img', img) cv2.waitKey(1)
def mask_to_polygons(mask, epsilon=1, min_area=1.): """ Create a Multipolygon from a mask of 0-1 pixels. """ # find contours of mask of pixels image, contours, hierarchy = cv2.findContours( ((mask == 1) * 255).astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) # create approximate contours to have reasonable submission size approx_contours = [cv2.approxPolyDP(cnt, epsilon, True) for cnt in contours] if not contours: return MultiPolygon() # now messy stuff to associate parent and child contours cnt_children = defaultdict(list) child_contours = set() assert hierarchy.shape[0] == 1 # http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]): if parent_idx != -1: child_contours.add(idx) cnt_children[parent_idx].append(approx_contours[idx]) # create actual polygons filtering by area (removes artifacts) all_polygons = [] for idx, cnt in enumerate(approx_contours): if idx not in child_contours and cv2.contourArea(cnt) >= min_area: assert cnt.shape[1] == 1 poly = Polygon( shell=cnt[:, 0, :], holes=[c[:, 0, :] for c in cnt_children.get(idx, []) if cv2.contourArea(c) >= min_area]) all_polygons.append(poly) # approximating polygons might have created invalid ones, fix them all_polygons = MultiPolygon(all_polygons) if not all_polygons.is_valid: all_polygons = all_polygons.buffer(0) # Sometimes buffer() converts a simple Multipolygon to just a Polygon, # need to keep it a Multi throughout if all_polygons.type == 'Polygon': all_polygons = MultiPolygon([all_polygons]) return all_polygons
def get_filtered_contours(self,img): # convert image to color space hsv hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # threshold the image to remove all colors that are not yellpw thresh = cv2.inRange(hsv_img, self.COLOR[0], self.COLOR[1]) # create the list of filtered contours to return filtered_contours = [] # find all contours in the thresholded image img_mod, contours, hierarchy = cv2.findContours(\ thresh,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE) # sort all contours by area, largest to smallest contour_area = [ (cv2.contourArea(c), (c) ) for c in contours] contour_area = sorted(contour_area,reverse=True, key=lambda x: x[0]) for j, (area,(cnt)) in enumerate(contour_area): # only report MAX_DETECTIONS number of controus if j >=self.MAX_DETECTIONS: break # create a bounding box around the contour x,y,w,h = cv2.boundingRect(cnt) box = (x,y,w,h) # add this contour to the list filtered_contours.append( (cnt, box) ) if DEMO: cv2.imshow('hsv_image', hsv_img) cv2.imshow('in_range', thresh) mask = cv2.bitwise_and(img, img, mask= thresh) cv2.imshow('mask', mask) cnts = img.copy() cv2.drawContours(cnts, contours, -1, (0,255,0), 3) cv2.imshow('contours', cnts) cv2.waitKey(1) return filtered_contours
def detect_contours(self): blurred = cv2.GaussianBlur(self.src, (self.kernel_size, self.kernel_size), self.sigma) # apply canny detector detected_edges = cv2.Canny(blurred, self.threshold, self.threshold * self.ratio, apertureSize=self.apertureSize, L2gradient=True) if self.use_dilate: kernel = np.ones((3, 3), np.uint8) detected_edges = cv2.morphologyEx(detected_edges, cv2.MORPH_CLOSE, kernel) self.contours_img, self.simple_contours, self.hierarchy = cv2.findContours(detected_edges.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) # pdb.gimp_message(self.hierarchy) _, self.full_contours, _ = cv2.findContours(detected_edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
def mask_to_polygons(mask: np.ndarray, epsilon=5., min_area=10., fix=False) -> MultiPolygon: if fix: epsilon *= 4 image, contours, hierarchy = cv2.findContours( ((mask == 1) * 255).astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) approx_contours = [cv2.approxPolyDP(cnt, epsilon, True) for cnt in contours] if not contours: return MultiPolygon() cnt_children = defaultdict(list) child_contours = set() assert hierarchy.shape[0] == 1 # http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]): if parent_idx != -1: child_contours.add(idx) cnt_children[parent_idx].append(approx_contours[idx]) all_polygons = [] for idx, cnt in enumerate(approx_contours): if idx not in child_contours and cv2.contourArea(cnt) >= min_area: assert cnt.shape[1] == 1 poly = Polygon( shell=cnt[:, 0, :], holes=[c[:, 0, :] for c in cnt_children.get(idx, []) if cv2.contourArea(c) >= min_area]) all_polygons.append(poly) all_polygons = to_multipolygon(MultiPolygon(all_polygons).buffer(0)) # return all_polygons - this was used to generate the final merges if fix: all_polygons = all_polygons.buffer(-1e-7) all_polygons = all_polygons.buffer(-1e-7) # FIXME - a great idea, but should be done after conversion to final coordinates all_polygons = shapely.wkt.loads( shapely.wkt.dumps(all_polygons, rounding_precision=8)) while not all_polygons.is_valid: all_polygons = to_multipolygon(all_polygons.buffer(0)) all_polygons = shapely.wkt.loads( shapely.wkt.dumps(all_polygons, rounding_precision=8)) return all_polygons
def mask_to_poly(mask, xymax, epsilon=2, min_area=1., threshold=0.5): # __author__ = Konstantin Lopuhin # https://www.kaggle.com/lopuhin/dstl-satellite-imagery-feature-detection/full-pipeline-demo-poly-pixels-ml-poly # first, find contours with cv2: it's much faster than shapely contours, hierarchy = cv2.findContours(((mask >= threshold) * 255).astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) # create approximate contours to have reasonable submission size approx_contours = [cv2.approxPolyDP(cnt, epsilon, True) for cnt in contours] if not contours: return MultiPolygon() # now messy stuff to associate parent and child contours cnt_children = defaultdict(list) child_contours = set() assert hierarchy.shape[0] == 1 # http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]): if parent_idx != -1: child_contours.add(idx) cnt_children[parent_idx].append(approx_contours[idx]) # create actual polygons filtering by area (removes artifacts) all_polygons = [] for idx, cnt in enumerate(approx_contours): if idx not in child_contours and cv2.contourArea(cnt) >= min_area: assert cnt.shape[1] == 1 poly = Polygon( shell=cnt[:, 0, :], holes=[c[:, 0, :] for c in cnt_children.get(idx, []) if cv2.contourArea(c) >= min_area]) all_polygons.append(poly) # approximating polygons might have created invalid ones, fix them all_polygons = MultiPolygon(all_polygons).buffer(0) # Sometimes buffer() converts a simple Multipolygon to just a Polygon, # need to keep it a Multi throughout if all_polygons.type == 'Polygon': all_polygons = MultiPolygon([all_polygons]) return convert_poly_to_geo_coords(all_polygons, mask.shape, xymax)
def _locate(segmented, offset=None): """Inspired from: https://goo.gl/HYPrR1""" # clean invalid patterns from the mask segmented = process_mask(segmented) # CV_RETR_EXTERNAL to only get external contours. _, contours, hierarchy = cv2.findContours(segmented.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # Note: points are represented as (col, row)-tuples apparently transform = identity if offset is not None: col_off, row_off = offset transform = affine_transform(delta_x=col_off, delta_y=row_off) components = [] if len(contours) > 0: top_index = 0 tops_remaining = True while tops_remaining: exterior = contours[top_index][:, 0, :].tolist() interiors = [] # check if there are childs and process if necessary if hierarchy[0][top_index][2] != -1: sub_index = hierarchy[0][top_index][2] subs_remaining = True while subs_remaining: interiors.append(contours[sub_index][:, 0, :].tolist()) # check if there is another sub contour if hierarchy[0][sub_index][0] != -1: sub_index = hierarchy[0][sub_index][0] else: subs_remaining = False # add component tuple to components only if exterior is a polygon if len(exterior) > 3: polygon = Polygon(exterior, interiors) polygon = transform(polygon) if polygon.is_valid: # some polygons might be invalid components.append(polygon) else: print (explain_validity(polygon)) # check if there is another top contour if hierarchy[0][top_index][0] != -1: top_index = hierarchy[0][top_index][0] else: tops_remaining = False del contours del hierarchy return components