本文整理匯總了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
示例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)
示例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)
示例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
示例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)
示例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
示例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:
示例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
示例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
示例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
示例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
示例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)
示例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)
示例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
示例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