JeVoisBase  1.22
JeVois Smart Embedded Machine Vision Toolkit Base Modules
Share this page:
Loading...
Searching...
No Matches
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
7import argparse
8
9import numpy as np
10import cv2 as cv
11
12from yunet import YuNet
13
14def 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
22backends = [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_BACKEND_CUDA]
23targets = [cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16]
24help_msg_backends = "Choose one of the computation backends: {:d}: OpenCV implementation (default); {:d}: CUDA"
25help_msg_targets = "Chose one of the target computation devices: {:d}: CPU (default); {:d}: CUDA; {:d}: CUDA fp16"
26try:
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"
31except:
32 print('This version of OpenCV does not support TIM-VX and NPU. Visit https://gist.github.com/fengyuentau/5a7a5ba36328f2b763aea026c43fa45f for more information.')
33
34parser = argparse.ArgumentParser(description='YuNet: A Fast and Accurate CNN-based Face Detector (https://github.com/ShiqiYu/libfacedetection).')
35parser.add_argument('--input', '-i', type=str, help='Path to the input image. Omit for using default camera.')
36parser.add_argument('--model', '-m', type=str, default='face_detection_yunet_2022mar.onnx', help='Path to the model.')
37parser.add_argument('--backend', '-b', type=int, default=backends[0], help=help_msg_backends.format(*backends))
38parser.add_argument('--target', '-t', type=int, default=targets[0], help=help_msg_targets.format(*targets))
39parser.add_argument('--conf_threshold', type=float, default=0.9, help='Filter out faces of confidence < conf_threshold.')
40parser.add_argument('--nms_threshold', type=float, default=0.3, help='Suppress bounding boxes of iou >= nms_threshold.')
41parser.add_argument('--top_k', type=int, default=5000, help='Keep top_k bounding boxes before NMS.')
42parser.add_argument('--save', '-s', type=str, default=False, help='Set true to save results. This flag is invalid when using camera.')
43parser.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.')
44args = parser.parse_args()
45
46def visualize(image, results, box_color=(0, 255, 0), text_color=(0, 0, 255), fps=None):
47 output = image.copy()
48 landmark_color = [
49 (255, 0, 0), # right eye
50 ( 0, 0, 255), # left eye
51 ( 0, 255, 0), # nose tip
52 (255, 0, 255), # right mouth corner
53 ( 0, 255, 255) # left mouth corner
54 ]
55
56 if fps is not None:
57 cv.putText(output, 'FPS: {:.2f}'.format(fps), (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, text_color)
58
59 for det in (results if results is not None else []):
60 bbox = det[0:4].astype(np.int32)
61 cv.rectangle(output, (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3]), box_color, 2)
62
63 conf = det[-1]
64 cv.putText(output, '{:.4f}'.format(conf), (bbox[0], bbox[1]+12), cv.FONT_HERSHEY_DUPLEX, 0.5, text_color)
65
66 landmarks = det[4:14].astype(np.int32).reshape((5,2))
67 for idx, landmark in enumerate(landmarks):
68 cv.circle(output, landmark, 2, landmark_color[idx], 2)
69
70 return output
71
72if __name__ == '__main__':
73 # Instantiate YuNet
74 model = YuNet(modelPath=args.model,
75 inputSize=[320, 320],
76 confThreshold=args.conf_threshold,
77 nmsThreshold=args.nms_threshold,
78 topK=args.top_k,
79 backendId=args.backend,
80 targetId=args.target)
81
82 # If input is an image
83 if args.input is not None:
84 image = cv.imread(args.input)
85 h, w, _ = image.shape
86
87 # Inference
88 model.setInputSize([w, h])
89 results = model.infer(image)
90
91 # Print results
92 print('{} faces detected.'.format(results.shape[0]))
93 for idx, det in enumerate(results):
94 print('{}: {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f}'.format(
95 idx, *det[:-1])
96 )
97
98 # Draw results on the input image
99 image = visualize(image, results)
100
101 # Save results if save is true
102 if args.save:
103 print('Resutls saved to result.jpg\n')
104 cv.imwrite('result.jpg', image)
105
106 # Visualize results in a new window
107 if args.vis:
108 cv.namedWindow(args.input, cv.WINDOW_AUTOSIZE)
109 cv.imshow(args.input, image)
110 cv.waitKey(0)
111 else: # Omit input to call default camera
112 deviceId = 0
113 cap = cv.VideoCapture(deviceId)
114 w = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
115 h = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
116 model.setInputSize([w, h])
117
118 tm = cv.TickMeter()
119 while cv.waitKey(1) < 0:
120 hasFrame, frame = cap.read()
121 if not hasFrame:
122 print('No frames grabbed!')
123 break
124
125 # Inference
126 tm.start()
127 results = model.infer(frame) # results is a tuple
128 tm.stop()
129
130 # Draw results on the input image
131 frame = visualize(frame, results, fps=tm.getFPS())
132
133 # Visualize results in a new Window
134 cv.imshow('YuNet Demo', frame)
135
136 tm.reset()
137
visualize(image, results, box_color=(0, 255, 0), text_color=(0, 0, 255), fps=None)
Definition demo.py:46
str2bool
Definition demo.py:43
int
Definition demo.py:37