JeVoisBase  1.18
JeVois Smart Embedded Machine Vision Toolkit Base Modules
Share this page:
demo.py
Go to the documentation of this file.
1 # This file is part of OpenCV Zoo project.
2 # It is subject to the license terms in the LICENSE file found in the same directory.
3 #
4 # Copyright (C) 2021, Shenzhen Institute of Artificial Intelligence and Robotics for Society, all rights reserved.
5 # Third party copyrights are property of their respective owners.
6 
7 import argparse
8 
9 import numpy as np
10 import cv2 as cv
11 
12 from pphumanseg import PPHumanSeg
13 
14 def str2bool(v):
15  if v.lower() in ['on', 'yes', 'true', 'y', 't']:
16  return True
17  elif v.lower() in ['off', 'no', 'false', 'n', 'f']:
18  return False
19  else:
20  raise NotImplementedError
21 
22 backends = [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_BACKEND_CUDA]
23 targets = [cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16]
24 help_msg_backends = "Choose one of the computation backends: {:d}: OpenCV implementation (default); {:d}: CUDA"
25 help_msg_targets = "Chose one of the target computation devices: {:d}: CPU (default); {:d}: CUDA; {:d}: CUDA fp16"
26 try:
27  backends += [cv.dnn.DNN_BACKEND_TIMVX]
28  targets += [cv.dnn.DNN_TARGET_NPU]
29  help_msg_backends += "; {:d}: TIMVX"
30  help_msg_targets += "; {:d}: NPU"
31 except:
32  print('This version of OpenCV does not support TIM-VX and NPU. Visit https://gist.github.com/fengyuentau/5a7a5ba36328f2b763aea026c43fa45f for more information.')
33 
34 parser = argparse.ArgumentParser(description='PPHumanSeg (https://github.com/PaddlePaddle/PaddleSeg/tree/release/2.2/contrib/PP-HumanSeg)')
35 parser.add_argument('--input', '-i', type=str, help='Path to the input image. Omit for using default camera.')
36 parser.add_argument('--model', '-m', type=str, default='human_segmentation_pphumanseg_2021oct.onnx', help='Path to the model.')
37 parser.add_argument('--backend', '-b', type=int, default=backends[0], help=help_msg_backends.format(*backends))
38 parser.add_argument('--target', '-t', type=int, default=targets[0], help=help_msg_targets.format(*targets))
39 parser.add_argument('--save', '-s', type=str, default=False, help='Set true to save results. This flag is invalid when using camera.')
40 parser.add_argument('--vis', '-v', type=str2bool, default=True, help='Set true to open a window for result visualization. This flag is invalid when using camera.')
41 args = parser.parse_args()
42 
43 def get_color_map_list(num_classes):
44  """
45  Returns the color map for visualizing the segmentation mask,
46  which can support arbitrary number of classes.
47 
48  Args:
49  num_classes (int): Number of classes.
50 
51  Returns:
52  (list). The color map.
53  """
54 
55  num_classes += 1
56  color_map = num_classes * [0, 0, 0]
57  for i in range(0, num_classes):
58  j = 0
59  lab = i
60  while lab:
61  color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
62  color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
63  color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
64  j += 1
65  lab >>= 3
66  color_map = color_map[3:]
67  return color_map
68 
69 def visualize(image, result, weight=0.6, fps=None):
70  """
71  Convert predict result to color image, and save added image.
72 
73  Args:
74  image (str): The input image.
75  result (np.ndarray): The predict result of image.
76  weight (float): The image weight of visual image, and the result weight is (1 - weight). Default: 0.6
77  fps (str): The FPS to be drawn on the input image.
78 
79  Returns:
80  vis_result (np.ndarray): The visualized result.
81  """
82  color_map = get_color_map_list(256)
83  color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
84  color_map = np.array(color_map).astype(np.uint8)
85  # Use OpenCV LUT for color mapping
86  c1 = cv.LUT(result, color_map[:, 0])
87  c2 = cv.LUT(result, color_map[:, 1])
88  c3 = cv.LUT(result, color_map[:, 2])
89  pseudo_img = np.dstack((c1, c2, c3))
90 
91  vis_result = cv.addWeighted(image, weight, pseudo_img, 1 - weight, 0)
92 
93  if fps is not None:
94  cv.putText(vis_result, 'FPS: {:.2f}'.format(fps), (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
95 
96  return vis_result
97 
98 
99 if __name__ == '__main__':
100  # Instantiate PPHumanSeg
101  model = PPHumanSeg(modelPath=args.model, backendId=args.backend, targetId=args.target)
102 
103  if args.input is not None:
104  # Read image and resize to 192x192
105  image = cv.imread(args.input)
106  h, w, _ = image.shape
107  image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
108  _image = cv.resize(image, dsize=(192, 192))
109 
110  # Inference
111  result = model.infer(_image)
112  result = cv.resize(result[0, :, :], dsize=(w, h), interpolation=cv.INTER_NEAREST)
113 
114  # Draw results on the input image
115  image = visualize(image, result)
116 
117  # Save results if save is true
118  if args.save:
119  print('Results saved to result.jpg\n')
120  cv.imwrite('result.jpg', image)
121 
122  # Visualize results in a new window
123  if args.vis:
124  cv.namedWindow(args.input, cv.WINDOW_AUTOSIZE)
125  cv.imshow(args.input, image)
126  cv.waitKey(0)
127  else: # Omit input to call default camera
128  deviceId = 0
129  cap = cv.VideoCapture(deviceId)
130  w = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
131  h = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
132 
133  tm = cv.TickMeter()
134  while cv.waitKey(1) < 0:
135  hasFrame, frame = cap.read()
136  if not hasFrame:
137  print('No frames grabbed!')
138  break
139 
140  _frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
141  _frame = cv.resize(_frame, dsize=(192, 192))
142 
143  # Inference
144  tm.start()
145  result = model.infer(_frame)
146  tm.stop()
147  result = cv.resize(result[0, :, :], dsize=(w, h), interpolation=cv.INTER_NEAREST)
148 
149  # Draw results on the input image
150  frame = visualize(frame, result, fps=tm.getFPS())
151 
152  # Visualize results in a new window
153  cv.imshow('PPHumanSeg Demo', frame)
154 
155  tm.reset()
156 
demo.str2bool
str2bool
Definition: demo.py:43
demo.int
int
Definition: demo.py:37
pphumanseg.PPHumanSeg
Definition: pphumanseg.py:10
demo.visualize
def visualize(image, results, box_color=(0, 255, 0), text_color=(0, 0, 255), fps=None)
Definition: demo.py:46
demo.get_color_map_list
def get_color_map_list(num_classes)
Definition: demo.py:43