Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 1 | """ |
| 2 | SPDX-FileCopyrightText: 2020-present Open Networking Foundation <info@opennetworking.org> |
| 3 | SPDX-License-Identifier: LicenseRef-ONF-Member-1.01 |
| 4 | """ |
| 5 | |
| 6 | from __future__ import print_function |
| 7 | |
Shad Ansari | d365451 | 2021-09-29 10:31:53 -0700 | [diff] [blame^] | 8 | import cv2 |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 9 | import logging as log |
| 10 | import os |
| 11 | import sys |
| 12 | import time |
| 13 | from argparse import ArgumentParser, SUPPRESS |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 14 | from imutils import build_montages |
| 15 | from openvino.inference_engine import IECore |
| 16 | |
| 17 | |
| 18 | def build_argparser(): |
| 19 | parser = ArgumentParser(add_help=False) |
| 20 | args = parser.add_argument_group('Options') |
| 21 | args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.') |
| 22 | args.add_argument("-m", "--model", help="Required. Path to an .xml file with a trained model.", |
| 23 | required=True, type=str) |
| 24 | args.add_argument("-i", "--input", |
| 25 | help="Required. Path to video file or image. 'cam' for capturing video stream from camera", |
| 26 | required=True, type=str) |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 27 | args.add_argument("-l", "--cpu_extension", |
| 28 | help="Optional. Required for CPU custom layers. Absolute path to a shared library with the " |
| 29 | "kernels implementations.", type=str, default=None) |
| 30 | args.add_argument("-pp", "--plugin_dir", help="Optional. Path to a plugin folder", type=str, default=None) |
| 31 | args.add_argument("-d", "--device", |
| 32 | help="Optional. Specify the target device to infer on; CPU, GPU, FPGA, HDDL or MYRIAD is " |
| 33 | "acceptable. The demo will look for a suitable plugin for device specified. " |
| 34 | "Default value is CPU", default="CPU", type=str) |
| 35 | args.add_argument("--labels", help="Optional. Path to labels mapping file", default=None, type=str) |
| 36 | args.add_argument("-pt", "--prob_threshold", help="Optional. Probability threshold for detections filtering", |
| 37 | default=0.5, type=float) |
| 38 | args.add_argument("-ns", help='No show output', action='store_true') |
| 39 | |
| 40 | return parser |
| 41 | |
| 42 | |
| 43 | def main(): |
| 44 | log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout) |
| 45 | args = build_argparser().parse_args() |
| 46 | model_xml = args.model |
| 47 | model_bin = os.path.splitext(model_xml)[0] + ".bin" |
Shad Ansari | d365451 | 2021-09-29 10:31:53 -0700 | [diff] [blame^] | 48 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 49 | # Read IR |
| 50 | log.info("Reading IR...") |
| 51 | net = IECore().read_network(model=model_xml, weights=model_bin) |
| 52 | |
| 53 | assert len(net.inputs.keys()) == 1, "Demo supports only single input topologies" |
| 54 | assert len(net.outputs) == 1, "Demo supports only single output topologies" |
| 55 | input_blob = next(iter(net.inputs)) |
| 56 | out_blob = next(iter(net.outputs)) |
| 57 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 58 | log.info("Loading IR to the plugin...") |
Shad Ansari | d365451 | 2021-09-29 10:31:53 -0700 | [diff] [blame^] | 59 | exec_net = IECore().load_network(network=net, device_name=args.device, num_requests=2) |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 60 | # Read and pre-process input image |
| 61 | n, c, h, w = net.inputs[input_blob].shape |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 62 | del net |
| 63 | if args.input == 'cam': |
| 64 | input_stream = 0 |
| 65 | elif args.input == 'gstreamer': |
| 66 | # gst rtp sink |
| 67 | input_stream = 'udpsrc port=5000 caps = " application/x-rtp, encoding-name=JPEG,payload=26" ! rtpjpegdepay ! decodebin ! videoconvert ! appsink' |
| 68 | #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' |
| 69 | else: |
| 70 | input_stream = args.input |
| 71 | assert os.path.isfile(args.input), "Specified input file doesn't exist" |
| 72 | |
| 73 | if input_stream == 'gstreamer': |
| 74 | cap = cv2.VideoCapture(input_stream, cv2.CAP_GSTREAMER) |
| 75 | else: |
| 76 | cap = cv2.VideoCapture(input_stream) |
| 77 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 78 | if args.labels: |
| 79 | with open(args.labels, 'r') as f: |
| 80 | labels_map = [x.strip() for x in f] |
| 81 | else: |
| 82 | labels_map = None |
| 83 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 84 | cur_request_id = 0 |
| 85 | next_request_id = 1 |
| 86 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 87 | log.info("Starting inference in async mode...") |
| 88 | log.info("To switch between sync and async modes press Tab button") |
| 89 | log.info("To stop the demo execution press Esc button") |
| 90 | |
| 91 | # Async doesn't work if True |
| 92 | # Request issues = Runtime Error: [REQUEST BUSY] |
| 93 | is_async_mode = False |
Shad Ansari | d365451 | 2021-09-29 10:31:53 -0700 | [diff] [blame^] | 94 | #is_async_mode = True |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 95 | render_time = 0 |
| 96 | ret, frame = cap.read() |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 97 | |
| 98 | frameList = [] |
| 99 | |
| 100 | print("To close the application, press 'CTRL+C' or any key with focus on the output window") |
Shad Ansari | d365451 | 2021-09-29 10:31:53 -0700 | [diff] [blame^] | 101 | |
| 102 | while True: |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 103 | if is_async_mode: |
| 104 | ret, next_frame = cap.read() |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 105 | else: |
| 106 | ret, frame = cap.read() |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 107 | if not ret: |
| 108 | break |
| 109 | initial_w = cap.get(3) |
| 110 | initial_h = cap.get(4) |
Shad Ansari | d365451 | 2021-09-29 10:31:53 -0700 | [diff] [blame^] | 111 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 112 | # Main sync point: |
| 113 | # in the truly Async mode we start the NEXT infer request, while waiting for the CURRENT to complete |
| 114 | # in the regular mode we start the CURRENT request and immediately wait for it's completion |
| 115 | inf_start = time.time() |
| 116 | if is_async_mode: |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 117 | if ret: |
| 118 | in_frame = cv2.resize(next_frame, (w, h)) |
| 119 | in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW |
| 120 | in_frame = in_frame.reshape((n, c, h, w)) |
| 121 | exec_net.start_async(request_id=next_request_id, inputs={input_blob: in_frame}) |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 122 | else: |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 123 | if ret: |
| 124 | in_frame = cv2.resize(frame, (w, h)) |
| 125 | in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW |
| 126 | in_frame = in_frame.reshape((n, c, h, w)) |
| 127 | exec_net.start_async(request_id=cur_request_id, inputs={input_blob: in_frame}) |
| 128 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 129 | if exec_net.requests[cur_request_id].wait(-1) == 0: |
| 130 | inf_end = time.time() |
| 131 | det_time = inf_end - inf_start |
| 132 | |
| 133 | # Parse detection results of the current request |
| 134 | res = exec_net.requests[cur_request_id].outputs[out_blob] |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 135 | |
| 136 | for obj in res[0][0]: |
| 137 | # Draw only objects when probability more than specified threshold |
| 138 | if obj[2] > args.prob_threshold: |
| 139 | xmin = int(obj[3] * initial_w) |
| 140 | ymin = int(obj[4] * initial_h) |
| 141 | xmax = int(obj[5] * initial_w) |
| 142 | ymax = int(obj[6] * initial_h) |
| 143 | class_id = int(obj[1]) |
| 144 | # Draw box and label\class_id |
| 145 | color = (min(class_id * 12.5, 255), min(class_id * 7, 255), min(class_id * 5, 255)) |
| 146 | cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color, 2) |
| 147 | det_label = labels_map[class_id] if labels_map else str(class_id) |
| 148 | cv2.putText(frame, det_label + ' ' + str(round(obj[2] * 100, 1)) + ' %', (xmin, ymin - 7), |
| 149 | cv2.FONT_HERSHEY_COMPLEX, 0.6, color, 1) |
| 150 | print('Object detected, class_id:', class_id, 'probability:', obj[2], 'xmin:', xmin, 'ymin:', ymin, |
| 151 | 'xmax:', xmax, 'ymax:', ymax) |
| 152 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 153 | # Draw performance stats |
| 154 | inf_time_message = "Inference time: Not applicable for async mode" if is_async_mode else \ |
| 155 | "Inference time: {:.3f} ms".format(det_time * 1000) |
| 156 | render_time_message = "OpenCV rendering time: {:.3f} ms".format(render_time * 1000) |
| 157 | if is_async_mode: |
| 158 | async_mode_message = "Async mode is on. Processing request {}".format(cur_request_id) |
| 159 | else: |
| 160 | async_mode_message = "Async mode is off. Processing request {}".format(cur_request_id) |
| 161 | |
| 162 | cv2.putText(frame, inf_time_message, (15, 15), cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 10, 10), 1) |
| 163 | cv2.putText(frame, render_time_message, (15, 30), cv2.FONT_HERSHEY_COMPLEX, 0.5, (10, 10, 200), 1) |
| 164 | cv2.putText(frame, async_mode_message, (10, int(initial_h - 20)), cv2.FONT_HERSHEY_COMPLEX, 0.5, |
| 165 | (10, 10, 200), 1) |
| 166 | |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 167 | render_start = time.time() |
| 168 | |
| 169 | if not args.ns: |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 170 | if ret: |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 171 | cv2.imshow("Detection results", frame) |
| 172 | render_end = time.time() |
| 173 | render_time = render_end - render_start |
| 174 | |
| 175 | if is_async_mode: |
| 176 | cur_request_id, next_request_id = next_request_id, cur_request_id |
| 177 | |
| 178 | frame = next_frame |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 179 | key = cv2.waitKey(1) |
| 180 | if key == 27: |
| 181 | break |
| 182 | if 9 == key: |
| 183 | is_async_mode = not is_async_mode |
| 184 | log.info("Switched to {} mode".format("async" if is_async_mode else "sync")) |
| 185 | |
| 186 | cap.release() |
Shad Ansari | 47432b6 | 2021-09-27 22:46:25 +0000 | [diff] [blame] | 187 | cv2.destroyAllWindows() |
| 188 | |
| 189 | |
| 190 | if __name__ == '__main__': |
| 191 | sys.exit(main() or 0) |