当前位置: 首页>>代码示例>>Python>>正文


Python cv2.polylines方法代码示例

本文整理汇总了Python中cv2.polylines方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.polylines方法的具体用法?Python cv2.polylines怎么用?Python cv2.polylines使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cv2的用法示例。


在下文中一共展示了cv2.polylines方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: draw_box

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def draw_box(self, roi, img, linewidth, color, name=None):
        """
            roi: rectangle or polygon
            img: numpy array img
            linewith: line width of the bbox
        """
        if len(roi) > 6 and len(roi) % 2 == 0:
            pts = np.array(roi, np.int32).reshape(-1, 1, 2)
            color = tuple(map(int, color))
            img = cv2.polylines(img, [pts], True, color, linewidth)
            pt = (pts[0, 0, 0], pts[0, 0, 1]-5)
            if name:
                img = cv2.putText(img, name, pt, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, color, 1)
        elif len(roi) == 4:
            if not np.isnan(roi[0]):
                roi = list(map(int, roi))
                color = tuple(map(int, color))
                img = cv2.rectangle(img, (roi[0], roi[1]), (roi[0]+roi[2], roi[1]+roi[3]),
                         color, linewidth)
                if name:
                    img = cv2.putText(img, name, (roi[0], roi[1]-5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, color, 1)
        return img 
开发者ID:STVIR,项目名称:pysot,代码行数:24,代码来源:video.py

示例2: drawSplinesOnImage

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def drawSplinesOnImage(splines, color, im, pc, image_scale):
    for s in splines:
        # Get the shape of this spline and draw it on the image
        nds = []
        for wp in s["waypoints"]:
            nds.append(pc.tgcToCV2(wp["waypoint"]["x"], wp["waypoint"]["y"], image_scale))

        # Don't try to draw malformed splines
        if len(nds) == 0:
            continue

        # Uses points and not image pixels, so flip the x and y
        nds = np.array(nds)
        nds[:,[0, 1]] = nds[:,[1, 0]]
        nds = np.int32([nds]) # Bug with fillPoly, needs explict cast to 32bit

        thickness = int(s["width"])
        if(thickness < image_scale):
            thickness = int(image_scale)

        if s["isFilled"]:
            cv2.fillPoly(im, nds, color, lineType=cv2.LINE_AA)
        else:
            cv2.polylines(im, nds, s["isClosed"], color, thickness, lineType=cv2.LINE_AA) 
开发者ID:chadrockey,项目名称:TGC-Designer-Tools,代码行数:26,代码来源:tgc_visualizer.py

示例3: drawWayOnImage

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def drawWayOnImage(way, color, im, pc, image_scale, thickness=-1, x_offset=0.0, y_offset=0.0):
    # Get the shape of this way and draw it as a poly
    nds = []
    for node in way.get_nodes(resolve_missing=True): # Allow automatically resolving missing nodes, but this is VERY slow with the API requests, try to request them above instead
        nds.append(pc.latlonToCV2(node.lat, node.lon, image_scale, x_offset, y_offset))
    # Uses points and not image pixels, so flip the x and y
    nds = np.array(nds)
    nds[:,[0, 1]] = nds[:,[1, 0]]
    nds = np.int32([nds]) # Bug with fillPoly, needs explict cast to 32bit
    cv2.fillPoly(im, nds, color) 

    # Add option to draw shape again, but with thick line
    # Use this to automatically expand some shapes, for example water
    # For better masking
    if thickness > 0:
        # Need to draw again since fillPoly has no line thickness options that I've found
        cv2.polylines(im, nds, True, color, thickness, lineType=cv2.LINE_AA) 
开发者ID:chadrockey,项目名称:TGC-Designer-Tools,代码行数:19,代码来源:OSMTGC.py

示例4: annotate

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def annotate(self, img):
    # paint annotations on the image
    for i1 in range(len(self.kpus)):
      u1, v1 = int(round(self.kpus[i1][0])), int(round(self.kpus[i1][1]))
      if self.pts[i1] is not None:
        if len(self.pts[i1].frames) >= 5:
          cv2.circle(img, (u1, v1), color=(0,255,0), radius=3)
        else:
          cv2.circle(img, (u1, v1), color=(0,128,0), radius=3)
        # draw the trail
        pts = []
        lfid = None
        for f, idx in zip(self.pts[i1].frames[-9:][::-1], self.pts[i1].idxs[-9:][::-1]):
          if lfid is not None and lfid-1 != f.id:
            break
          pts.append(tuple(map(lambda x: int(round(x)), f.kpus[idx])))
          lfid = f.id
        if len(pts) >= 2:
          cv2.polylines(img, np.array([pts], dtype=np.int32), False, myjet[len(pts)]*255, thickness=1, lineType=16)
      else:
        cv2.circle(img, (u1, v1), color=(0,0,0), radius=3)
    return img


  # inverse of intrinsics matrix 
开发者ID:geohot,项目名称:twitchslam,代码行数:27,代码来源:frame.py

示例5: vis_octagon

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def vis_octagon(img, extreme_points, col, border_thick=2):
    """Visualizes a single binary mask."""

    img = img.astype(np.uint8)
    # COL = (col).astype(np.uint8).tolist()
    # print('col', COL)
    # octagon = get_octagon(extreme_points)
    # octagon = np.array(octagon).reshape(8, 1, 2).astype(np.int32)
    # cv2.polylines(img, [octagon], 
    #               True, COL, border_thick)
    mask = extreme_point_to_octagon_mask(
      extreme_points, img.shape[0], img.shape[1])

    img = vis_mask(img, mask, col)

    return img.astype(np.uint8) 
开发者ID:xingyizhou,项目名称:ExtremeNet,代码行数:18,代码来源:visualize.py

示例6: start

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def start(self):
        paused = False
        while True:
            if not paused or self.frame is None: 
                ret, frame = self.cap.read()
                scaling_factor = self.scaling_factor
                frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) 
                if not ret: break 
                self.frame = frame.copy() 
 
            img = self.frame.copy() 
            if not paused and self.rect is not None: 
                tracked = self.pose_tracker.track_target(self.frame) 
                for item in tracked: 
                    cv2.polylines(img, [np.int32(item.quad)], True, (255, 255, 255), 2) 
                    for (x, y) in np.int32(item.points_cur): 
                        cv2.circle(img, (x, y), 2, (255, 255, 255)) 
 
            self.roi_selector.draw_rect(img, self.rect) 
            cv2.imshow(self.win_name, img) 
            ch = cv2.waitKey(1) 
            if ch == ord(' '): paused = not paused 
            if ch == ord('c'): self.pose_tracker.clear_targets() 
            if ch == 27: break 
开发者ID:PacktPublishing,项目名称:OpenCV-3-x-with-Python-By-Example,代码行数:26,代码来源:pose_estimation.py

示例7: draw_3dbbox_from_keypoints

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def draw_3dbbox_from_keypoints(img, keypoints):
    img = np.copy(img)

    color = [190, 0, 255] # (BGR)
    front_color = [255, 230, 0] # (BGR)
    lines = [[0, 3, 7, 4, 0], [1, 2, 6, 5, 1], [0, 1], [2, 3], [6, 7], [4, 5]] # (0 -> 3 -> 7 -> 4 -> 0, 1 -> 2 -> 6 -> 5 -> 1, etc.)
    colors = [front_color, color, color, color, color, color]

    for n, line in enumerate(lines):
        bg = colors[n]

        cv2.polylines(img, np.int32([keypoints[line]]), False, bg, lineType=cv2.LINE_AA, thickness=2)

    return img

# NOTE! NOTE! change this to not overwrite all log data when you train the model: 
开发者ID:fregu856,项目名称:3DOD_thesis,代码行数:18,代码来源:train_imgnet.py

示例8: add_bird_view

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def add_bird_view(self, dets, center_thresh=0.3, img_id='bird'):
    bird_view = np.ones((self.out_size, self.out_size, 3), dtype=np.uint8) * 230
    for cat in dets:
      cl = (self.colors[cat - 1, 0, 0]).tolist()
      lc = (250, 152, 12)
      for i in range(len(dets[cat])):
        if dets[cat][i, -1] > center_thresh:
          dim = dets[cat][i, 5:8]
          loc  = dets[cat][i, 8:11]
          rot_y = dets[cat][i, 11]
          rect = compute_box_3d(dim, loc, rot_y)[:4, [0, 2]]
          for k in range(4):
            rect[k] = self.project_3d_to_bird(rect[k])
            # cv2.circle(bird_view, (rect[k][0], rect[k][1]), 2, lc, -1)
          cv2.polylines(
              bird_view,[rect.reshape(-1, 1, 2).astype(np.int32)],
              True,lc,2,lineType=cv2.LINE_AA)
          for e in [[0, 1]]:
            t = 4 if e == [0, 1] else 1
            cv2.line(bird_view, (rect[e[0]][0], rect[e[0]][1]),
                    (rect[e[1]][0], rect[e[1]][1]), lc, t,
                    lineType=cv2.LINE_AA)
    self.imgs[img_id] = bird_view 
开发者ID:Guanghan,项目名称:mxnet-centernet,代码行数:25,代码来源:debugger.py

示例9: draw_rect

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def draw_rect(img, r, angle = 0, color=(255,255,255), thickness = 4, alpha = 0.5):
    '''
    accepts:
    1. a (x,y,dx,dy) list
    4. a [(x,y,dx,dy),score] list, as returned by cv2.CascadeClassifier.detectMultiScaleWithScores()
    5. a CascadeResult object
    '''
    if type(r) == CascadeResult:
        color = tuple(list(color) + [alpha])
        cv2.polylines(img, pts = [r.points_int], isClosed = True, color = color, thickness = thickness)
        return
    elif len(r)==4 or len(r)==2: # [x,y,dx,dy]
        if len(r)==2:
            if len(r[0]) == 4:
                r = r[0]
            else: 
                raise Exception("bad input to draw_rect...")
        pt1 = int(round(r[0])), int(round(r[1]))
        pt2 = int(round(r[0]+r[2])), int(round(r[1]+r[3]))
        color = tuple(list(color) + [alpha])
        cv2.rectangle(img, pt1, pt2, color, thickness = thickness)
    else:
        raise Exception("bad input to draw_rect...")
    return 
开发者ID:eranid,项目名称:adience_align,代码行数:26,代码来源:drawing.py

示例10: get_bev

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def get_bev(velo_array, label_list = None, scores = None):
    map_height = velo_array.shape[0]
    intensity = np.zeros((velo_array.shape[0], velo_array.shape[1], 3), dtype=np.uint8)   
     # val = 1 - velo_array[::-1, :, -1]
    val = (1 - velo_array[::-1, :, :-1].max(axis=2)) * 255
    intensity[:, :, 0] = val
    intensity[:, :, 1] = val
    intensity[:, :, 2] = val
    # FLip in the x direction

    if label_list is not None:
        for corners in label_list:
            plot_corners = corners / 0.1
            plot_corners[:, 1] += int(map_height // 2)
            plot_corners[:, 1] = map_height - plot_corners[:, 1]
            plot_corners = plot_corners.astype(int).reshape((-1, 1, 2))
            cv2.polylines(intensity, [plot_corners], True, (255, 0, 0), 2)
            cv2.line(intensity, tuple(plot_corners[2, 0]), tuple(plot_corners[3, 0]), (0, 0, 255), 3)

    return intensity 
开发者ID:philip-huang,项目名称:PIXOR,代码行数:22,代码来源:utils.py

示例11: draw_skel_and_kp

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def draw_skel_and_kp(
        img, instance_scores, keypoint_scores, keypoint_coords,
        min_pose_score=0.5, min_part_score=0.5):
    out_img = img
    adjacent_keypoints = []
    cv_keypoints = []
    for ii, score in enumerate(instance_scores):
        if score < min_pose_score:
            continue

        new_keypoints = get_adjacent_keypoints(
            keypoint_scores[ii, :], keypoint_coords[ii, :, :], min_part_score)
        adjacent_keypoints.extend(new_keypoints)

        for ks, kc in zip(keypoint_scores[ii, :], keypoint_coords[ii, :, :]):
            if ks < min_part_score:
                continue
            cv_keypoints.append(cv2.KeyPoint(kc[1], kc[0], 10. * ks))

    out_img = cv2.drawKeypoints(
        out_img, cv_keypoints, outImage=np.array([]), color=(255, 255, 0),
        flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    out_img = cv2.polylines(out_img, adjacent_keypoints, isClosed=False, color=(255, 255, 0))
    return out_img 
开发者ID:rwightman,项目名称:posenet-python,代码行数:26,代码来源:utils.py

示例12: draw_extract_box

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def draw_extract_box(self, color_id=2, thickness=1):
        """ Draw the extracted face box """
        if not self.roi:
            return
        color = self.colors[color_id]
        for idx, roi in enumerate(self.roi):
            logger.trace("Drawing Extract Box: (idx: %s, roi: %s)", idx, roi)
            top_left = [point for point in roi.squeeze()[0]]
            top_left = (top_left[0], top_left[1] - 10)
            cv2.putText(self.image,
                        str(idx),
                        top_left,
                        cv2.FONT_HERSHEY_DUPLEX,
                        1.0,
                        color,
                        thickness)
            cv2.polylines(self.image, [roi], True, color, thickness) 
开发者ID:deepfakes,项目名称:faceswap,代码行数:19,代码来源:annotate.py

示例13: draw_landmarks_mesh

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def draw_landmarks_mesh(self, color_id=4, thickness=1):
        """ Draw the facial landmarks """
        color = self.colors[color_id]
        facial_landmarks_idxs = OrderedDict([("mouth", (48, 68)),
                                             ("right_eyebrow", (17, 22)),
                                             ("left_eyebrow", (22, 27)),
                                             ("right_eye", (36, 42)),
                                             ("left_eye", (42, 48)),
                                             ("nose", (27, 36)),
                                             ("jaw", (0, 17)),
                                             ("chin", (8, 11))])
        for alignment in self.alignments:
            landmarks = alignment["landmarks_xy"]
            logger.trace("Drawing Landmarks Mesh: (landmarks: %s, color: %s, thickness: %s)",
                         landmarks, color, thickness)
            for key, val in facial_landmarks_idxs.items():
                points = np.array([landmarks[val[0]:val[1]]], np.int32)
                fill_poly = bool(key in ("right_eye", "left_eye", "mouth"))
                cv2.polylines(self.image, points, fill_poly, color, thickness) 
开发者ID:deepfakes,项目名称:faceswap,代码行数:21,代码来源:annotate.py

示例14: build_baseline_mask

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def build_baseline_mask(self, out_size, color, line_width):
        """
        Builds a "image" mask of Baselines on XML-PAGE
        """
        size = self.get_size()[::-1]
        # --- Although NNLLoss requires an Long Tensor (np.int -> torch.LongTensor)
        # --- is better to keep mask as np.uint8 to save disk space, then change it
        # --- to np.int @ dataloader only if NNLLoss is going to be used.
        mask = np.zeros((out_size[0], out_size[1]), np.uint8)
        scale_factor = out_size / size
        for element in self.root.findall("".join([".//", self.base, "Baseline"])):
            # --- get element coords
            str_coords = element.attrib.get("points").split()
            coords = np.array([i.split(",") for i in str_coords]).astype(np.int)
            coords = (coords * np.flip(scale_factor, 0)).astype(np.int)
            cv2.polylines(mask, [coords.reshape(-1, 1, 2)], False, color, line_width)
        if not mask.any():
            self.logger.warning(
                    "File {} do not contains baselines".format(self.name)
                    )
        return mask 
开发者ID:lquirosd,项目名称:P2PaLA,代码行数:23,代码来源:xmlPAGE.py

示例15: getFrame

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import polylines [as 别名]
def getFrame(self):
        if self.frame==None:
            return None
        self.mutex.acquire()
        try:
            vis_frame = self.frame.copy()
        finally:
            self.mutex.release()

        rows,cols = vis_frame.shape[:2]        
        #M = cv2.getRotationMatrix2D((cols/2,rows/2),45,1)
        #vis_frame = cv2.warpAffine(vis_frame,M,(cols,rows))

        #draw_str(vis_frame, (20, 20), 'track count: %d' % len(tracker.tracks))
        if self.draw_trails:
            cv2.polylines(vis_frame, [np.int32(tr) for tr in [[t[:2] for t in tr]  for tr in self.tracks]], False, (0, 255, 0))

        for tr in self.tracks:
            cv2.circle(vis_frame, (tr[-1][0], tr[-1][1]), 2, (0, 255, 0), -1)

        return vis_frame 
开发者ID:tobykurien,项目名称:pi-tracking-telescope,代码行数:23,代码来源:tracking.py


注:本文中的cv2.polylines方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。