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


Python cv2.findContours方法代碼示例

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


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

示例1: canny

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def canny(filepathname, left=70, right=140):
    v = cv2.imread(filepathname)
    s = cv2.cvtColor(v, cv2.COLOR_BGR2GRAY)
    s = cv2.Canny(s, left, right)
    cv2.imshow('nier',s)
    return s

    # 圈出最小方矩形框,這裏Canny算法後都是白色線條,所以取色範圍 127-255 即可。
    # ret, binary = cv2.threshold(s,127,255,cv2.THRESH_BINARY) 
    # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # for c in contours:
    #     x,y,w,h = cv2.boundingRect(c)
    #     if w>5 and h>10: # 有約束的畫框
    #         cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1)
    # # cv2.drawContours(s,contours,-1,(0,0,255),3) # 畫所有框
    # cv2.imshow('nier2',v)

    # cv2.waitKey()
    # cv2.destroyAllWindows() 
開發者ID:cilame,項目名稱:vrequest,代碼行數:21,代碼來源:pycv2.py

示例2: FindHullDefects

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def FindHullDefects(self, segment):
        _,contours,hierarchy = cv2.findContours(segment, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        # find largest area contour
        max_area = -1
        for i in range(len(contours)):
            area = cv2.contourArea(contours[i])
            if area>max_area:
                cnt = contours[i]
                max_area = area

        cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        hull = cv2.convexHull(cnt, returnPoints=False)
        defects = cv2.convexityDefects(cnt, hull)

        return [cnt,defects] 
開發者ID:PacktPublishing,項目名稱:OpenCV-Computer-Vision-Projects-with-Python,代碼行數:18,代碼來源:chapter2.py

示例3: _find_size_candidates

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def _find_size_candidates(self, image):
        binary_image = self._filter_image(image)

        _, contours, _ = cv2.findContours(binary_image,
                                          cv2.RETR_LIST,
                                          cv2.CHAIN_APPROX_SIMPLE)

        size_candidates = []
        for contour in contours:
            bounding_rect = cv2.boundingRect(contour)
            contour_area = cv2.contourArea(contour)
            if self._is_valid_contour(contour_area, bounding_rect):
                candidate = (bounding_rect[2] + bounding_rect[3]) / 2
                size_candidates.append(candidate)

        return size_candidates 
開發者ID:nemanja-m,項目名稱:gaps,代碼行數:18,代碼來源:size_detector.py

示例4: laplacian

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def laplacian(filepathname):
    v = cv2.imread(filepathname)
    s = cv2.cvtColor(v, cv2.COLOR_BGR2GRAY)
    s = cv2.Laplacian(s, cv2.CV_16S, ksize=3)
    s = cv2.convertScaleAbs(s)
    cv2.imshow('nier',s)
    return s

    # ret, binary = cv2.threshold(s,40,255,cv2.THRESH_BINARY)
    # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # for c in contours:
    #     x,y,w,h = cv2.boundingRect(c)
    #     if w>5 and h>10:
    #         cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1)
    # cv2.imshow('nier2',v)

    # cv2.waitKey()
    # cv2.destroyAllWindows() 
開發者ID:cilame,項目名稱:vrequest,代碼行數:20,代碼來源:pycv2.py

示例5: segment

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
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
#----------------- 
開發者ID:Gogul09,項目名稱:gesture-recognition,代碼行數:24,代碼來源:segment.py

示例6: contour_filter

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

示例7: __get_annotation__

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def __get_annotation__(self, mask, image=None):

        _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        segmentation = []
        for contour in contours:
            # Valid polygons have >= 6 coordinates (3 points)
            if contour.size >= 6:
                segmentation.append(contour.flatten().tolist())
        RLEs = cocomask.frPyObjects(segmentation, mask.shape[0], mask.shape[1])
        RLE = cocomask.merge(RLEs)
        # RLE = cocomask.encode(np.asfortranarray(mask))
        area = cocomask.area(RLE)
        [x, y, w, h] = cv2.boundingRect(mask)

        if image is not None:
            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
            cv2.drawContours(image, contours, -1, (0,255,0), 1)
            cv2.rectangle(image,(x,y),(x+w,y+h), (255,0,0), 2)
            cv2.imshow("", image)
            cv2.waitKey(1)

        return segmentation, [x, y, w, h], area 
開發者ID:hazirbas,項目名稱:coco-json-converter,代碼行數:25,代碼來源:generate_coco_json.py

示例8: _append_boxes_from_saliency

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def _append_boxes_from_saliency(self, proto_objects_map, box_all):
        """Adds to the list all bounding boxes found with the saliency map

            A saliency map is used to find objects worth tracking in each
            frame. This information is combined with a mean-shift tracker
            to find objects of relevance that move, and to discard everything
            else.

            :param proto_objects_map: proto-objects map of the current frame
            :param box_all: append bounding boxes from saliency to this list
            :returns: new list of all collected bounding boxes
        """
        # find all bounding boxes in new saliency map
        box_sal = []
        cnt_sal, _ = cv2.findContours(proto_objects_map, 1, 2)
        for cnt in cnt_sal:
            # discard small contours
            if cv2.contourArea(cnt) < self.min_cnt_area:
                continue

            # otherwise add to list of boxes found from saliency map
            box = cv2.boundingRect(cnt)
            box_all.append(box)

        return box_all 
開發者ID:PacktPublishing,項目名稱:OpenCV-Computer-Vision-Projects-with-Python,代碼行數:27,代碼來源:tracking.py

示例9: prediction

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
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 
開發者ID:cristianpb,項目名稱:object-detection,代碼行數:19,代碼來源:motion.py

示例10: contours

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def contours(mask):
    """Extracts contours and the relationship between them from a binary mask.

    Args:
      mask: the binary mask to find contours in.

    Returns:
      The detected contours as a list of points and the contour hierarchy.

    Note: the hierarchy can be used to re-construct polygons with holes as one entity.
    """

    contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    return contours, hierarchy


# Todo: should work for lines, too, but then needs other epsilon criterion than arc length 
開發者ID:mapbox,項目名稱:robosat,代碼行數:19,代碼來源:core.py

示例11: findContours

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def findContours(*args, **kwargs):
    """
    Wraps cv2.findContours to maintain compatiblity between versions
    3 and 4

    Returns:
        contours, hierarchy
    """
    if cv2.__version__.startswith('4'):
        contours, hierarchy = cv2.findContours(*args, **kwargs)
    elif cv2.__version__.startswith('3'):
        _, contours, hierarchy = cv2.findContours(*args, **kwargs)
    else:
        raise AssertionError(
            'cv2 must be either version 3 or 4 to call this method')

    return contours, hierarchy 
開發者ID:Res2Net,項目名稱:Res2Net-maskrcnn,代碼行數:19,代碼來源:cv2_util.py

示例12: mask2poly_single

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

示例13: vis_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def vis_mask(img, mask, bbox_color, show_parss=False):
    """Visualizes a single binary mask."""
    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    border_color = cfg.VIS.SHOW_SEGMS.BORDER_COLOR
    border_thick = cfg.VIS.SHOW_SEGMS.BORDER_THICK

    mask_color = bbox_color if cfg.VIS.SHOW_SEGMS.MASK_COLOR_FOLLOW_BOX else _WHITE
    mask_color = np.asarray(mask_color)
    mask_alpha = cfg.VIS.SHOW_SEGMS.MASK_ALPHA

    _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    if cfg.VIS.SHOW_SEGMS.SHOW_BORDER:
        cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)

    if cfg.VIS.SHOW_SEGMS.SHOW_MASK and not show_parss:
        img[idx[0], idx[1], :] *= 1.0 - mask_alpha
        img[idx[0], idx[1], :] += mask_alpha * mask_color

    return img.astype(np.uint8) 
開發者ID:soeaver,項目名稱:Parsing-R-CNN,代碼行數:23,代碼來源:vis.py

示例14: vis_parsing

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
def vis_parsing(img, parsing, colormap, show_segms=True):
    """Visualizes a single binary parsing."""
    img = img.astype(np.float32)
    idx = np.nonzero(parsing)

    parsing_alpha = cfg.VIS.SHOW_PARSS.PARSING_ALPHA
    colormap = colormap_utils.dict2array(colormap)
    parsing_color = colormap[parsing.astype(np.int)]

    border_color = cfg.VIS.SHOW_PARSS.BORDER_COLOR
    border_thick = cfg.VIS.SHOW_PARSS.BORDER_THICK

    img[idx[0], idx[1], :] *= 1.0 - parsing_alpha
    # img[idx[0], idx[1], :] += alpha * parsing_color
    img += parsing_alpha * parsing_color

    if cfg.VIS.SHOW_PARSS.SHOW_BORDER and not show_segms:
        _, contours, _ = cv2.findContours(parsing.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
開發者ID:soeaver,項目名稱:Parsing-R-CNN,代碼行數:23,代碼來源:vis.py

示例15: _findContours

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findContours [as 別名]
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 
開發者ID:soeaver,項目名稱:Parsing-R-CNN,代碼行數:18,代碼來源:segmentation_mask.py


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