blob: f5963fb8b9295c87861970c8d3e3e39e7579da4e [file] [log] [blame]
Shad Ansari47432b62021-09-27 22:46:25 +00001"""
2SPDX-FileCopyrightText: 2020-present Open Networking Foundation <info@opennetworking.org>
3SPDX-License-Identifier: LicenseRef-ONF-Member-1.01
4"""
5
6from __future__ import print_function
7
Shad Ansarid3654512021-09-29 10:31:53 -07008import cv2
Shad Ansari47432b62021-09-27 22:46:25 +00009import logging as log
10import os
11import sys
12import time
13from argparse import ArgumentParser, SUPPRESS
Shad Ansari47432b62021-09-27 22:46:25 +000014from imutils import build_montages
15from openvino.inference_engine import IECore
Shad Ansari30a23732021-09-29 23:07:21 -070016from base_camera import BaseCamera
Shad Ansari47432b62021-09-27 22:46:25 +000017
18
19def build_argparser():
20 parser = ArgumentParser(add_help=False)
21 args = parser.add_argument_group('Options')
22 args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')
23 args.add_argument("-m", "--model", help="Required. Path to an .xml file with a trained model.",
24 required=True, type=str)
25 args.add_argument("-i", "--input",
26 help="Required. Path to video file or image. 'cam' for capturing video stream from camera",
27 required=True, type=str)
Shad Ansari47432b62021-09-27 22:46:25 +000028 args.add_argument("-l", "--cpu_extension",
29 help="Optional. Required for CPU custom layers. Absolute path to a shared library with the "
30 "kernels implementations.", type=str, default=None)
31 args.add_argument("-pp", "--plugin_dir", help="Optional. Path to a plugin folder", type=str, default=None)
32 args.add_argument("-d", "--device",
33 help="Optional. Specify the target device to infer on; CPU, GPU, FPGA, HDDL or MYRIAD is "
34 "acceptable. The demo will look for a suitable plugin for device specified. "
35 "Default value is CPU", default="CPU", type=str)
36 args.add_argument("--labels", help="Optional. Path to labels mapping file", default=None, type=str)
37 args.add_argument("-pt", "--prob_threshold", help="Optional. Probability threshold for detections filtering",
38 default=0.5, type=float)
39 args.add_argument("-ns", help='No show output', action='store_true')
40
41 return parser
42
43
Shad Ansari30a23732021-09-29 23:07:21 -070044class Camera(BaseCamera):
Shad Ansarid3654512021-09-29 10:31:53 -070045
Shad Ansari30a23732021-09-29 23:07:21 -070046 def __init__(self, args):
47 log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout)
48 model_xml = args.model
49 model_bin = os.path.splitext(model_xml)[0] + ".bin"
Shad Ansari47432b62021-09-27 22:46:25 +000050
Shad Ansari30a23732021-09-29 23:07:21 -070051 # Read IR
52 log.info("Reading IR...")
53 net = IECore().read_network(model=model_xml, weights=model_bin)
Shad Ansari47432b62021-09-27 22:46:25 +000054
Shad Ansari30a23732021-09-29 23:07:21 -070055 assert len(net.inputs.keys()) == 1, "Demo supports only single input topologies"
56 assert len(net.outputs) == 1, "Demo supports only single output topologies"
57 self.input_blob = next(iter(net.inputs))
58 self.out_blob = next(iter(net.outputs))
Shad Ansari47432b62021-09-27 22:46:25 +000059
Shad Ansari30a23732021-09-29 23:07:21 -070060 log.info("Loading IR to the plugin...")
61 self.exec_net = IECore().load_network(network=net, device_name=args.device, num_requests=2)
62 # Read and pre-process input image
63 self.n, self.c, self.h, self.w = net.inputs[self.input_blob].shape
64 del net
65 if args.input == 'cam':
Shad Ansari79615b92021-09-30 11:15:41 -070066 self.input_stream = 0
Shad Ansari30a23732021-09-29 23:07:21 -070067 elif args.input == 'gstreamer':
68 # gst rtp sink
Shad Ansari79615b92021-09-30 11:15:41 -070069 self.input_stream = 'udpsrc port=5000 caps = " application/x-rtp, encoding-name=JPEG,payload=26" ! rtpjpegdepay ! decodebin ! videoconvert ! appsink'
Shad Ansari341ca3a2021-09-30 12:10:00 -070070 #input_stream = 'udpsrc port=5000 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, payload=(int)96" ! rtph264depay ! decodebin ! videoconvert ! appsink'
Shad Ansari47432b62021-09-27 22:46:25 +000071 else:
Shad Ansari341ca3a2021-09-30 12:10:00 -070072 self.input_stream = args.input
Shad Ansari30a23732021-09-29 23:07:21 -070073 assert os.path.isfile(args.input), "Specified input file doesn't exist"
Shad Ansarid3654512021-09-29 10:31:53 -070074
Shad Ansari30a23732021-09-29 23:07:21 -070075 if args.labels:
76 with open(args.labels, 'r') as f:
77 self.labels_map = [x.strip() for x in f]
78 else:
79 self.labels_map = None
Shad Ansari47432b62021-09-27 22:46:25 +000080
Shad Ansari30a23732021-09-29 23:07:21 -070081 self.args = args
Shad Ansari47432b62021-09-27 22:46:25 +000082
Shad Ansari30a23732021-09-29 23:07:21 -070083 super(Camera, self).__init__()
Shad Ansari47432b62021-09-27 22:46:25 +000084
Shad Ansari30a23732021-09-29 23:07:21 -070085 def __del__(self):
86 self.cap.release()
87 cv2.destroyAllWindows()
88
89 def frames(self):
Shad Ansari79615b92021-09-30 11:15:41 -070090
91 if self.input_stream == 'gstreamer':
92 self.cap = cv2.VideoCapture(self.input_stream, cv2.CAP_GSTREAMER)
93 else:
94 self.cap = cv2.VideoCapture(self.input_stream)
95
Shad Ansari30a23732021-09-29 23:07:21 -070096 cur_request_id = 0
97 next_request_id = 1
98
99 log.info("Starting inference in async mode...")
100 log.info("To switch between sync and async modes press Tab button")
101 log.info("To stop the demo execution press Esc button")
102
103 # Async doesn't work if True
104 # Request issues = Runtime Error: [REQUEST BUSY]
105 self.is_async_mode = False
106 #is_async_mode = True
107 render_time = 0
108 ret, frame = self.cap.read()
109
Shad Ansari30a23732021-09-29 23:07:21 -0700110 print("To close the application, press 'CTRL+C' or any key with focus on the output window")
111
112 while True:
113 if self.is_async_mode:
114 ret, next_frame = self.cap.read()
Shad Ansari47432b62021-09-27 22:46:25 +0000115 else:
Shad Ansari30a23732021-09-29 23:07:21 -0700116 ret, frame = self.cap.read()
117 if not ret:
118 break
119 initial_w = self.cap.get(3)
120 initial_h = self.cap.get(4)
Shad Ansari47432b62021-09-27 22:46:25 +0000121
Shad Ansari30a23732021-09-29 23:07:21 -0700122 # Main sync point:
123 # in the truly Async mode we start the NEXT infer request, while waiting for the CURRENT to complete
124 # in the regular mode we start the CURRENT request and immediately wait for it's completion
125 inf_start = time.time()
126 if self.is_async_mode:
Shad Ansari341ca3a2021-09-30 12:10:00 -0700127 in_frame = cv2.resize(next_frame, (self.w, self.h))
128 in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW
129 in_frame = in_frame.reshape((self.n, self.c, self.h, self.w))
130 self.exec_net.start_async(request_id=next_request_id, inputs={self.input_blob: in_frame})
Shad Ansari30a23732021-09-29 23:07:21 -0700131 else:
Shad Ansari341ca3a2021-09-30 12:10:00 -0700132 in_frame = cv2.resize(frame, (self.w, self.h))
133 in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW
134 in_frame = in_frame.reshape((self.n, self.c, self.h, self.w))
135 self.exec_net.start_async(request_id=cur_request_id, inputs={self.input_blob: in_frame})
Shad Ansari47432b62021-09-27 22:46:25 +0000136
Shad Ansari30a23732021-09-29 23:07:21 -0700137 if self.exec_net.requests[cur_request_id].wait(-1) == 0:
138 inf_end = time.time()
139 det_time = inf_end - inf_start
Shad Ansari47432b62021-09-27 22:46:25 +0000140
Shad Ansari30a23732021-09-29 23:07:21 -0700141 # Parse detection results of the current request
142 res = self.exec_net.requests[cur_request_id].outputs[self.out_blob]
Shad Ansari47432b62021-09-27 22:46:25 +0000143
Shad Ansari30a23732021-09-29 23:07:21 -0700144 for obj in res[0][0]:
145 # Draw only objects when probability more than specified threshold
146 if obj[2] > self.args.prob_threshold:
147 xmin = int(obj[3] * initial_w)
148 ymin = int(obj[4] * initial_h)
149 xmax = int(obj[5] * initial_w)
150 ymax = int(obj[6] * initial_h)
151 class_id = int(obj[1])
152 # Draw box and label\class_id
153 color = (min(class_id * 12.5, 255), min(class_id * 7, 255), min(class_id * 5, 255))
154 cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color, 2)
155 det_label = self.labels_map[class_id] if self.labels_map else str(class_id)
156 cv2.putText(frame, det_label + ' ' + str(round(obj[2] * 100, 1)) + ' %', (xmin, ymin - 7),
157 cv2.FONT_HERSHEY_COMPLEX, 0.6, color, 1)
Shad Ansari341ca3a2021-09-30 12:10:00 -0700158 # print('Object detected, class_id:', class_id, 'probability:', obj[2], 'xmin:', xmin, 'ymin:', ymin,
159 # 'xmax:', xmax, 'ymax:', ymax)
Shad Ansari47432b62021-09-27 22:46:25 +0000160
Shad Ansari30a23732021-09-29 23:07:21 -0700161 # Draw performance stats
162 inf_time_message = "Inference time: Not applicable for async mode" if self.is_async_mode else \
163 "Inference time: {:.3f} ms".format(det_time * 1000)
164 render_time_message = "OpenCV rendering time: {:.3f} ms".format(render_time * 1000)
165 if self.is_async_mode:
166 async_mode_message = "Async mode is on. Processing request {}".format(cur_request_id)
167 else:
168 async_mode_message = "Async mode is off. Processing request {}".format(cur_request_id)
Shad Ansari47432b62021-09-27 22:46:25 +0000169
Shad Ansari30a23732021-09-29 23:07:21 -0700170 cv2.putText(frame, inf_time_message, (15, 15), cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 10, 10), 1)
171 cv2.putText(frame, render_time_message, (15, 30), cv2.FONT_HERSHEY_COMPLEX, 0.5, (10, 10, 200), 1)
172 cv2.putText(frame, async_mode_message, (10, int(initial_h - 20)), cv2.FONT_HERSHEY_COMPLEX, 0.5,
173 (10, 10, 200), 1)
174
175 render_start = time.time()
176
177 yield cv2.imencode('.jpg', frame)[1].tobytes()
178
Shad Ansari341ca3a2021-09-30 12:10:00 -0700179 render_end = time.time()
180 render_time = render_end - render_start
Shad Ansari30a23732021-09-29 23:07:21 -0700181
182 if self.is_async_mode:
183 cur_request_id, next_request_id = next_request_id, cur_request_id
Shad Ansari30a23732021-09-29 23:07:21 -0700184 frame = next_frame
Shad Ansari47432b62021-09-27 22:46:25 +0000185
186
187if __name__ == '__main__':
Shad Ansari30a23732021-09-29 23:07:21 -0700188 args = build_argparser().parse_args()
189 camera = Camera(args)
190 camera.frames()
191 del camera