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


Python cv2.drawContours方法代碼示例

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


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

示例1: canny

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [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: contour_filter

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [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

示例3: __get_annotation__

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [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

示例4: vis_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [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

示例5: vis_parsing

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [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

示例6: overlay_masks

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def overlay_masks(im, masks, alpha=0.5):
    colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255.
    
    if isinstance(masks, np.ndarray):
        masks = [masks]

    assert len(colors) >= len(masks), 'Not enough colors'

    ov = im.copy()
    im = im.astype(np.float32)
    total_ma = np.zeros([im.shape[0], im.shape[1]])
    i = 1
    for ma in masks:
        ma = ma.astype(np.bool)
        fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[i, :3]   # np.array([0,0,255])/255.0
        i = i + 1
        ov[ma == 1] = fg[ma == 1]
        total_ma += ma

        # [-2:] is s trick to be compatible both with opencv 2 and 3
        contours = cv2.findContours(ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
        cv2.drawContours(ov, contours[0], -1, (0.0, 0.0, 0.0), 1)
    ov[total_ma == 0] = im[total_ma == 0]

    return ov 
開發者ID:scaelles,項目名稱:DEXTR-KerasTensorflow,代碼行數:27,代碼來源:helpers.py

示例7: overlay_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def overlay_mask(self, image, predictions):
        """
        Adds the instances contours for each predicted object.
        Each label has a different color.

        Arguments:
            image (np.ndarray): an image as returned by OpenCV
            predictions (BoxList): the result of the computation by the model.
                It should contain the field `mask` and `labels`.
        """
        masks = predictions.get_field("mask").numpy()
        labels = predictions.get_field("labels")

        colors = self.compute_colors_for_labels(labels).tolist()

        for mask, color in zip(masks, colors):
            thresh = mask[0, :, :, None]
            contours, hierarchy = cv2_util.findContours(
                thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
            )
            image = cv2.drawContours(image, contours, -1, color, 3)

        composite = image

        return composite 
開發者ID:Res2Net,項目名稱:Res2Net-maskrcnn,代碼行數:27,代碼來源:predictor.py

示例8: _custom_get

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def _custom_get(self, i, no, all_returns):

		for dataset_name, d in self.datasets_attr.items():
			if d['range'][0] <= i and d['range'][1] > i:
				image_root = d['image_root']
				d_name = dataset_name
				break

		image_new, link_new, target_new, weight_new, contour_i = self.aspect_resize(self.loader(image_root+'/'+self.images[i]), self.annots[i].copy(), self.remove_annots[i].copy())#, big_target_new
		image_new, target_new, link_new, contour_i = self.rotate(image_new, target_new, link_new, contour_i, 90)
		show = True
		if show:
			plt.imsave('img.png',image_new)
			num = np.array(image_new)
			cv2.drawContours(num, contour_i, -1, (0,255,0), 3)
			plt.imsave('contours.png',num)
			plt.imsave('target.png',target_new)
		img = self.transform(image_new).unsqueeze(0)
		target = self.target_transform(target_new).unsqueeze(0)
		link = self.target_transform(link_new).unsqueeze(0)
		weight = torch.FloatTensor(weight_new).unsqueeze(0).unsqueeze(0)
		all_returns[no] = [img, target, link, weight, contour_i, d_name] 
開發者ID:mayank-git-hub,項目名稱:Text-Recognition,代碼行數:24,代碼來源:scale_two.py

示例9: check_show_f

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def check_show_f(self, d_name, path, contour, data, target, link):

		import matplotlib.pyplot as plt
		import cv2

		print(d_name[0], path[0], contour[0].shape)

		show_t = np.zeros([data[0].shape[2], data[0].shape[3], 3])
		show_t[:, :, 0] = target[0][0].data.cpu().numpy().transpose(1, 2, 0)[:, :, 0]

		show_l = np.zeros([data[0].shape[2], data[0].shape[3], 3])
		show_l[:, :, 0] = link[0][0].data.cpu().numpy().transpose(1, 2, 0)[:, :, 0]
		image = (data[0][0].data.cpu().numpy().transpose(1, 2, 0)*255).astype(np.uint8).copy()
		cv2.drawContours(image, np.array(contour[0]).astype(np.int32), -1, (0, 255, 0), 3)

		plt.imshow(np.concatenate((data[0][0].data.cpu().numpy().transpose(1, 2, 0), show_t, show_l), axis=1))
		plt.show()
		plt.imshow(data[0][0].data.cpu().numpy().transpose(1, 2, 0)*show_t)
		plt.show()
		plt.imshow(image)
		plt.show() 
開發者ID:mayank-git-hub,項目名稱:Text-Recognition,代碼行數:23,代碼來源:TrainTestD.py

示例10: draw_debug_frame_for_object

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def draw_debug_frame_for_object(debug_frame, tracked_object: TrackedObject, color: Tuple[int, int, int] = (255, 255, 255)):
    # contour = tracked_object.last_object_contour
    bbox = tracked_object.last_bbox
    points = tracked_object.tracked_points

    # if contour is not None:
    #     cv2.drawContours(debug_frame, [contour], -1, (0, 255, 0), cv2.FILLED)

    if bbox is not None:
        x1, y1, x2, y2 = bbox
        cv2.rectangle(debug_frame, (x1, y1), (x2, y2), (255, 255, 255), 1)
        cv2.putText(debug_frame, "Id {0}".format(tracked_object.id), (x1, y1 - 5), cv2.FONT_HERSHEY_COMPLEX, 0.5,
                    (255, 255, 255))

    if points is not None and len(points) > 0:
        draw_tracker_points(points, debug_frame, color)
        cv2.circle(debug_frame, tuple(points[-1]), 3, (0, 0, 255), -1)

    return debug_frame 
開發者ID:gaborvecsei,項目名稱:Color-Tracker,代碼行數:21,代碼來源:visualize.py

示例11: vis_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=2):
    """Visualizes a single binary mask."""

    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    img[idx[0], idx[1], :] *= 1.0 - alpha
    img[idx[0], idx[1], :] += alpha * col

    if show_border:
        # How to use `cv2.findContours` in different OpenCV versions?
        # https://stackoverflow.com/questions/48291581/how-to-use-cv2-findcontours-in-different-opencv-versions/48292371#48292371
        contours = cv2.findContours(
            mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)[-2]
        cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
開發者ID:xingyizhou,項目名稱:ExtremeNet,代碼行數:19,代碼來源:visualize.py

示例12: remove_border

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def remove_border(contour, ary):
    """Remove everything outside a border contour."""
    # Use a rotated rectangle (should be a good approximation of a border).
    # If it's far from a right angle, it's probably two sides of a border and
    # we should use the bounding box instead.
    c_im = np.zeros(ary.shape)
    r = cv2.minAreaRect(contour)
    degs = r[2]
    if angle_from_right(degs) <= 10.0:
        box = cv2.cv.BoxPoints(r)
        box = np.int0(box)
        cv2.drawContours(c_im, [box], 0, 255, -1)
        cv2.drawContours(c_im, [box], 0, 0, 4)
    else:
        x1, y1, x2, y2 = cv2.boundingRect(contour)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4)

    return np.minimum(c_im, ary) 
開發者ID:danvk,項目名稱:oldnyc,代碼行數:21,代碼來源:crop_morphology.py

示例13: get_roi

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def get_roi(thermal_image, thermal_np, raw_thermal_np, Contours, index, area_rect = None ):
        raw_roi_values = []
        thermal_roi_values = []
        indices = []
        if area_rect is None:
            img2 = np.zeros( (thermal_image.shape[0], thermal_image.shape[1],1), np.uint8)
            cv.drawContours(img2 , Contours , index, 255 , -1 )
            x,y,w,h = cv.boundingRect(Contours[index])

            indices = np.arange(w*h)
            ind = np.where(img2[:, :, 0] == 255)
            indices = indices[np.where(img2[y:y+h,x:x+w,0].flatten() == 255)]
            raw_roi_values = raw_thermal_np[ind]
            thermal_roi_values = thermal_np[ind]

        else:
            x,y,w,h =  area_rect
            raw_roi_values = raw_thermal_np[y:y+h, x:x+w]
            thermal_roi_values = thermal_np[y:y+h, x:x+w]

        return raw_roi_values, thermal_roi_values, indices 
開發者ID:detecttechnologies,項目名稱:Thermal_Image_Analysis,代碼行數:23,代碼來源:CThermal.py

示例14: find_boxes

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def find_boxes(tiff_fl, blur=False):
    im = Image.open(tiff_fl).convert('L')
    a = np.asarray(im)
    if blur:
        a = cv.GaussianBlur(a, (5, 5), 0)
    contours, hierarchy = cv.findContours(a.copy(), mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)
    border_boxes = []
#     n = np.ones_like(a)
    for j,cnt in enumerate(contours):
        cnt_len = cv.arcLength(cnt, True)
        orig_cnt = cnt.copy()
        cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
        if len(cnt) == 4 and ((a.shape[0]-3) * (a.shape[1] -3)) > cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
            cnt = cnt.reshape(-1, 2)
            max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
            if max_cos < 0.1:
                b = cv.boundingRect(orig_cnt)
                x,y,w,h = b
                border_boxes.append(b)
#                 cv.rectangle(n, (x,y), (x+w, y+h), 0)
#                 cv.drawContours(n, [cnt], -1,0, thickness = 5)
#     Image.fromarray(n*255).show()
    return border_boxes 
開發者ID:zmr,項目名稱:namsel,代碼行數:25,代碼來源:detect_tables.py

示例15: visualize_contours

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import drawContours [as 別名]
def visualize_contours(name, small, cinfo_list):

    regions = np.zeros_like(small)

    for j, cinfo in enumerate(cinfo_list):

        cv2.drawContours(regions, [cinfo.contour], 0,
                         CCOLORS[j % len(CCOLORS)], -1)

    mask = (regions.max(axis=2) != 0)

    display = small.copy()
    display[mask] = (display[mask]/2) + (regions[mask]/2)

    for j, cinfo in enumerate(cinfo_list):
        color = CCOLORS[j % len(CCOLORS)]
        color = tuple([c/4 for c in color])

        cv2.circle(display, fltp(cinfo.center), 3,
                   (255, 255, 255), 1, cv2.LINE_AA)

        cv2.line(display, fltp(cinfo.point0), fltp(cinfo.point1),
                 (255, 255, 255), 1, cv2.LINE_AA)

    debug_show(name, 1, 'contours', display) 
開發者ID:mzucker,項目名稱:page_dewarp,代碼行數:27,代碼來源:page_dewarp.py


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