当前位置: 首页>>代码示例>>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;未经允许,请勿转载。