deven96 abhishek-gola commited on
Commit
e293846
·
0 Parent(s):

Duplicate from opencv/face_detection_yunet

Browse files

Co-authored-by: Abhishek Gola <abhishek-gola@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Caffe
3
+ *.caffemodel filter=lfs diff=lfs merge=lfs -text
4
+
5
+ # Tensorflow
6
+ *.pb filter=lfs diff=lfs merge=lfs -text
7
+ *.pbtxt filter=lfs diff=lfs merge=lfs -text
8
+
9
+ # Torch
10
+ *.t7 filter=lfs diff=lfs merge=lfs -text
11
+ *.net filter=lfs diff=lfs merge=lfs -text
12
+
13
+ # Darknet
14
+ *.weights filter=lfs diff=lfs merge=lfs -text
15
+
16
+ # ONNX
17
+ *.onnx filter=lfs diff=lfs merge=lfs -text
18
+
19
+ # NPY
20
+ *.npy filter=lfs diff=lfs merge=lfs -text
21
+
22
+ # Images
23
+ *.jpg filter=lfs diff=lfs merge=lfs -text
24
+ *.gif filter=lfs diff=lfs merge=lfs -text
25
+ *.png filter=lfs diff=lfs merge=lfs -text
26
+ *.webp filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ *.pyc
2
+ **/__pycache__
3
+ **/__pycache__/**
4
+
5
+ .vscode
6
+
7
+ build/
8
+ **/build
9
+ **/build/**
CMakeLists.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cmake_minimum_required(VERSION 3.24.0)
2
+ project(opencv_zoo_face_detection_yunet)
3
+
4
+ set(OPENCV_VERSION "4.10.0")
5
+ set(OPENCV_INSTALLATION_PATH "" CACHE PATH "Where to look for OpenCV installation")
6
+
7
+ # Find OpenCV
8
+ find_package(OpenCV ${OPENCV_VERSION} REQUIRED HINTS ${OPENCV_INSTALLATION_PATH})
9
+
10
+ add_executable(demo demo.cpp)
11
+ target_link_libraries(demo ${OpenCV_LIBS})
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Shiqi Yu <shiqi.yu@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YuNet
2
+
3
+ YuNet is a light-weight, fast and accurate face detection model, which achieves 0.834(AP_easy), 0.824(AP_medium), 0.708(AP_hard) on the WIDER Face validation set.
4
+
5
+ Notes:
6
+
7
+ - Model source: [here](https://github.com/ShiqiYu/libfacedetection.train/blob/a61a428929148171b488f024b5d6774f93cdbc13/tasks/task1/onnx/yunet.onnx).
8
+ - This model can detect **faces of pixels between around 10x10 to 300x300** due to the training scheme.
9
+ - For details on training this model, please visit https://github.com/ShiqiYu/libfacedetection.train.
10
+ - This ONNX model has fixed input shape, but OpenCV DNN infers on the exact shape of input image. See https://github.com/opencv/opencv_zoo/issues/44 for more information.
11
+ - `face_detection_yunet_2023mar_int8bq.onnx` represents the block-quantized version in int8 precision and is generated using [block_quantize.py](../../tools/quantize/block_quantize.py) with `block_size=64`.
12
+ - Paper source: [Yunet: A tiny millisecond-level face detector](https://link.springer.com/article/10.1007/s11633-023-1423-y).
13
+
14
+ Results of accuracy evaluation with [tools/eval](../../tools/eval).
15
+
16
+ | Models | Easy AP | Medium AP | Hard AP |
17
+ | ----------- | ------- | --------- | ------- |
18
+ | YuNet | 0.8844 | 0.8656 | 0.7503 |
19
+ | YuNet block | 0.8845 | 0.8652 | 0.7504 |
20
+ | YuNet quant | 0.8810 | 0.8629 | 0.7503 |
21
+
22
+
23
+ \*: 'quant' stands for 'quantized'.
24
+ \*\*: 'block' stands for 'blockwise quantized'.
25
+
26
+
27
+ ## Demo
28
+
29
+ ### Python
30
+
31
+ Run the following command to try the demo:
32
+
33
+ ```shell
34
+ # detect on camera input
35
+ python demo.py
36
+ # detect on an image
37
+ python demo.py --input /path/to/image -v
38
+
39
+ # get help regarding various parameters
40
+ python demo.py --help
41
+ ```
42
+
43
+ ### C++
44
+
45
+ Install latest OpenCV and CMake >= 3.24.0 to get started with:
46
+
47
+ ```shell
48
+ # A typical and default installation path of OpenCV is /usr/local
49
+ cmake -B build -D OPENCV_INSTALLATION_PATH=/path/to/opencv/installation .
50
+ cmake --build build
51
+
52
+ # detect on camera input
53
+ ./build/demo
54
+ # detect on an image
55
+ ./build/demo -i=/path/to/image -v
56
+ # get help messages
57
+ ./build/demo -h
58
+ ```
59
+
60
+ ### Example outputs
61
+
62
+ ![webcam demo](./example_outputs/yunet_demo.gif)
63
+
64
+ ![largest selfie](./example_outputs/largest_selfie.jpg)
65
+
66
+ ## License
67
+
68
+ All files in this directory are licensed under [MIT License](./LICENSE).
69
+
70
+ ## Reference
71
+
72
+ - https://github.com/ShiqiYu/libfacedetection
73
+ - https://github.com/ShiqiYu/libfacedetection.train
74
+
75
+ ## Citation
76
+
77
+ If you use `YuNet` in your work, please use the following BibTeX entries:
78
+
79
+ ```
80
+ @article{wu2023yunet,
81
+ title={Yunet: A tiny millisecond-level face detector},
82
+ author={Wu, Wei and Peng, Hanyang and Yu, Shiqi},
83
+ journal={Machine Intelligence Research},
84
+ volume={20},
85
+ number={5},
86
+ pages={656--665},
87
+ year={2023},
88
+ publisher={Springer}
89
+ }
90
+ ```
demo.cpp ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "opencv2/opencv.hpp"
2
+
3
+ #include <map>
4
+ #include <vector>
5
+ #include <string>
6
+ #include <iostream>
7
+
8
+ const std::map<std::string, int> str2backend{
9
+ {"opencv", cv::dnn::DNN_BACKEND_OPENCV}, {"cuda", cv::dnn::DNN_BACKEND_CUDA},
10
+ {"timvx", cv::dnn::DNN_BACKEND_TIMVX}, {"cann", cv::dnn::DNN_BACKEND_CANN}
11
+ };
12
+ const std::map<std::string, int> str2target{
13
+ {"cpu", cv::dnn::DNN_TARGET_CPU}, {"cuda", cv::dnn::DNN_TARGET_CUDA},
14
+ {"npu", cv::dnn::DNN_TARGET_NPU}, {"cuda_fp16", cv::dnn::DNN_TARGET_CUDA_FP16}
15
+ };
16
+
17
+ class YuNet
18
+ {
19
+ public:
20
+ YuNet(const std::string& model_path,
21
+ const cv::Size& input_size = cv::Size(320, 320),
22
+ float conf_threshold = 0.6f,
23
+ float nms_threshold = 0.3f,
24
+ int top_k = 5000,
25
+ int backend_id = 0,
26
+ int target_id = 0)
27
+ : model_path_(model_path), input_size_(input_size),
28
+ conf_threshold_(conf_threshold), nms_threshold_(nms_threshold),
29
+ top_k_(top_k), backend_id_(backend_id), target_id_(target_id)
30
+ {
31
+ model = cv::FaceDetectorYN::create(model_path_, "", input_size_, conf_threshold_, nms_threshold_, top_k_, backend_id_, target_id_);
32
+ }
33
+
34
+ /* Overwrite the input size when creating the model. Size format: [Width, Height].
35
+ */
36
+ void setInputSize(const cv::Size& input_size)
37
+ {
38
+ input_size_ = input_size;
39
+ model->setInputSize(input_size_);
40
+ }
41
+
42
+ cv::Mat infer(const cv::Mat image)
43
+ {
44
+ cv::Mat res;
45
+ model->detect(image, res);
46
+ return res;
47
+ }
48
+
49
+ private:
50
+ cv::Ptr<cv::FaceDetectorYN> model;
51
+
52
+ std::string model_path_;
53
+ cv::Size input_size_;
54
+ float conf_threshold_;
55
+ float nms_threshold_;
56
+ int top_k_;
57
+ int backend_id_;
58
+ int target_id_;
59
+ };
60
+
61
+ cv::Mat visualize(const cv::Mat& image, const cv::Mat& faces, float fps = -1.f)
62
+ {
63
+ static cv::Scalar box_color{0, 255, 0};
64
+ static std::vector<cv::Scalar> landmark_color{
65
+ cv::Scalar(255, 0, 0), // right eye
66
+ cv::Scalar( 0, 0, 255), // left eye
67
+ cv::Scalar( 0, 255, 0), // nose tip
68
+ cv::Scalar(255, 0, 255), // right mouth corner
69
+ cv::Scalar( 0, 255, 255) // left mouth corner
70
+ };
71
+ static cv::Scalar text_color{0, 255, 0};
72
+
73
+ auto output_image = image.clone();
74
+
75
+ if (fps >= 0)
76
+ {
77
+ cv::putText(output_image, cv::format("FPS: %.2f", fps), cv::Point(0, 15), cv::FONT_HERSHEY_SIMPLEX, 0.5, text_color, 2);
78
+ }
79
+
80
+ for (int i = 0; i < faces.rows; ++i)
81
+ {
82
+ // Draw bounding boxes
83
+ int x1 = static_cast<int>(faces.at<float>(i, 0));
84
+ int y1 = static_cast<int>(faces.at<float>(i, 1));
85
+ int w = static_cast<int>(faces.at<float>(i, 2));
86
+ int h = static_cast<int>(faces.at<float>(i, 3));
87
+ cv::rectangle(output_image, cv::Rect(x1, y1, w, h), box_color, 2);
88
+
89
+ // Confidence as text
90
+ float conf = faces.at<float>(i, 14);
91
+ cv::putText(output_image, cv::format("%.4f", conf), cv::Point(x1, y1+12), cv::FONT_HERSHEY_DUPLEX, 0.5, text_color);
92
+
93
+ // Draw landmarks
94
+ for (int j = 0; j < landmark_color.size(); ++j)
95
+ {
96
+ int x = static_cast<int>(faces.at<float>(i, 2*j+4)), y = static_cast<int>(faces.at<float>(i, 2*j+5));
97
+ cv::circle(output_image, cv::Point(x, y), 2, landmark_color[j], 2);
98
+ }
99
+ }
100
+ return output_image;
101
+ }
102
+
103
+ int main(int argc, char** argv)
104
+ {
105
+ cv::CommandLineParser parser(argc, argv,
106
+ "{help h | | Print this message}"
107
+ "{input i | | Set input to a certain image, omit if using camera}"
108
+ "{model m | face_detection_yunet_2023mar.onnx | Set path to the model}"
109
+ "{backend b | opencv | Set DNN backend}"
110
+ "{target t | cpu | Set DNN target}"
111
+ "{save s | false | Whether to save result image or not}"
112
+ "{vis v | false | Whether to visualize result image or not}"
113
+ /* model params below*/
114
+ "{conf_threshold | 0.9 | Set the minimum confidence for the model to identify a face. Filter out faces of conf < conf_threshold}"
115
+ "{nms_threshold | 0.3 | Set the threshold to suppress overlapped boxes. Suppress boxes if IoU(box1, box2) >= nms_threshold, the one of higher score is kept.}"
116
+ "{top_k | 5000 | Keep top_k bounding boxes before NMS. Set a lower value may help speed up postprocessing.}"
117
+ );
118
+ if (parser.has("help"))
119
+ {
120
+ parser.printMessage();
121
+ return 0;
122
+ }
123
+
124
+ std::string input_path = parser.get<std::string>("input");
125
+ std::string model_path = parser.get<std::string>("model");
126
+ std::string backend = parser.get<std::string>("backend");
127
+ std::string target = parser.get<std::string>("target");
128
+ bool save_flag = parser.get<bool>("save");
129
+ bool vis_flag = parser.get<bool>("vis");
130
+
131
+ // model params
132
+ float conf_threshold = parser.get<float>("conf_threshold");
133
+ float nms_threshold = parser.get<float>("nms_threshold");
134
+ int top_k = parser.get<int>("top_k");
135
+ const int backend_id = str2backend.at(backend);
136
+ const int target_id = str2target.at(target);
137
+
138
+ // Instantiate YuNet
139
+ YuNet model(model_path, cv::Size(320, 320), conf_threshold, nms_threshold, top_k, backend_id, target_id);
140
+
141
+ // If input is an image
142
+ if (!input_path.empty())
143
+ {
144
+ auto image = cv::imread(input_path);
145
+
146
+ // Inference
147
+ model.setInputSize(image.size());
148
+ auto faces = model.infer(image);
149
+
150
+ // Print faces
151
+ std::cout << cv::format("%d faces detected:\n", faces.rows);
152
+ for (int i = 0; i < faces.rows; ++i)
153
+ {
154
+ int x1 = static_cast<int>(faces.at<float>(i, 0));
155
+ int y1 = static_cast<int>(faces.at<float>(i, 1));
156
+ int w = static_cast<int>(faces.at<float>(i, 2));
157
+ int h = static_cast<int>(faces.at<float>(i, 3));
158
+ float conf = faces.at<float>(i, 14);
159
+ std::cout << cv::format("%d: x1=%d, y1=%d, w=%d, h=%d, conf=%.4f\n", i, x1, y1, w, h, conf);
160
+ }
161
+
162
+ // Draw reults on the input image
163
+ if (save_flag || vis_flag)
164
+ {
165
+ auto res_image = visualize(image, faces);
166
+ if (save_flag)
167
+ {
168
+ std::cout << "Results are saved to result.jpg\n";
169
+ cv::imwrite("result.jpg", res_image);
170
+ }
171
+ if (vis_flag)
172
+ {
173
+ cv::namedWindow(input_path, cv::WINDOW_AUTOSIZE);
174
+ cv::imshow(input_path, res_image);
175
+ cv::waitKey(0);
176
+ }
177
+ }
178
+ }
179
+ else // Call default camera
180
+ {
181
+ int device_id = 0;
182
+ auto cap = cv::VideoCapture(device_id);
183
+ int w = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
184
+ int h = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
185
+ model.setInputSize(cv::Size(w, h));
186
+
187
+ auto tick_meter = cv::TickMeter();
188
+ cv::Mat frame;
189
+ while (cv::waitKey(1) < 0)
190
+ {
191
+ bool has_frame = cap.read(frame);
192
+ if (!has_frame)
193
+ {
194
+ std::cout << "No frames grabbed! Exiting ...\n";
195
+ break;
196
+ }
197
+
198
+ // Inference
199
+ tick_meter.start();
200
+ cv::Mat faces = model.infer(frame);
201
+ tick_meter.stop();
202
+
203
+ // Draw results on the input image
204
+ auto res_image = visualize(frame, faces, (float)tick_meter.getFPS());
205
+ // Visualize in a new window
206
+ cv::imshow("YuNet Demo", res_image);
207
+
208
+ tick_meter.reset();
209
+ }
210
+ }
211
+
212
+ return 0;
213
+ }
demo.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Check OpenCV version
13
+ opencv_python_version = lambda str_version: tuple(map(int, (str_version.split("."))))
14
+ assert opencv_python_version(cv.__version__) >= opencv_python_version("4.10.0"), \
15
+ "Please install latest opencv-python for benchmark: python3 -m pip install --upgrade opencv-python"
16
+
17
+ from yunet import YuNet
18
+
19
+ # Valid combinations of backends and targets
20
+ backend_target_pairs = [
21
+ [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_CPU],
22
+ [cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA],
23
+ [cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16],
24
+ [cv.dnn.DNN_BACKEND_TIMVX, cv.dnn.DNN_TARGET_NPU],
25
+ [cv.dnn.DNN_BACKEND_CANN, cv.dnn.DNN_TARGET_NPU]
26
+ ]
27
+
28
+ parser = argparse.ArgumentParser(description='YuNet: A Fast and Accurate CNN-based Face Detector (https://github.com/ShiqiYu/libfacedetection).')
29
+ parser.add_argument('--input', '-i', type=str,
30
+ help='Usage: Set input to a certain image, omit if using camera.')
31
+ parser.add_argument('--model', '-m', type=str, default='face_detection_yunet_2023mar.onnx',
32
+ help="Usage: Set model type, defaults to 'face_detection_yunet_2023mar.onnx'.")
33
+ parser.add_argument('--backend_target', '-bt', type=int, default=0,
34
+ help='''Choose one of the backend-target pair to run this demo:
35
+ {:d}: (default) OpenCV implementation + CPU,
36
+ {:d}: CUDA + GPU (CUDA),
37
+ {:d}: CUDA + GPU (CUDA FP16),
38
+ {:d}: TIM-VX + NPU,
39
+ {:d}: CANN + NPU
40
+ '''.format(*[x for x in range(len(backend_target_pairs))]))
41
+ parser.add_argument('--conf_threshold', type=float, default=0.9,
42
+ help='Usage: Set the minimum needed confidence for the model to identify a face, defauts to 0.9. Smaller values may result in faster detection, but will limit accuracy. Filter out faces of confidence < conf_threshold.')
43
+ parser.add_argument('--nms_threshold', type=float, default=0.3,
44
+ help='Usage: Suppress bounding boxes of iou >= nms_threshold. Default = 0.3.')
45
+ parser.add_argument('--top_k', type=int, default=5000,
46
+ help='Usage: Keep top_k bounding boxes before NMS.')
47
+ parser.add_argument('--save', '-s', action='store_true',
48
+ help='Usage: Specify to save file with results (i.e. bounding box, confidence level). Invalid in case of camera input.')
49
+ parser.add_argument('--vis', '-v', action='store_true',
50
+ help='Usage: Specify to open a new window to show results. Invalid in case of camera input.')
51
+ args = parser.parse_args()
52
+
53
+ def visualize(image, results, box_color=(0, 255, 0), text_color=(0, 0, 255), fps=None):
54
+ output = image.copy()
55
+ landmark_color = [
56
+ (255, 0, 0), # right eye
57
+ ( 0, 0, 255), # left eye
58
+ ( 0, 255, 0), # nose tip
59
+ (255, 0, 255), # right mouth corner
60
+ ( 0, 255, 255) # left mouth corner
61
+ ]
62
+
63
+ if fps is not None:
64
+ cv.putText(output, 'FPS: {:.2f}'.format(fps), (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, text_color)
65
+
66
+ for det in results:
67
+ bbox = det[0:4].astype(np.int32)
68
+ cv.rectangle(output, (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3]), box_color, 2)
69
+
70
+ conf = det[-1]
71
+ cv.putText(output, '{:.4f}'.format(conf), (bbox[0], bbox[1]+12), cv.FONT_HERSHEY_DUPLEX, 0.5, text_color)
72
+
73
+ landmarks = det[4:14].astype(np.int32).reshape((5,2))
74
+ for idx, landmark in enumerate(landmarks):
75
+ cv.circle(output, landmark, 2, landmark_color[idx], 2)
76
+
77
+ return output
78
+
79
+ if __name__ == '__main__':
80
+ backend_id = backend_target_pairs[args.backend_target][0]
81
+ target_id = backend_target_pairs[args.backend_target][1]
82
+
83
+ # Instantiate YuNet
84
+ model = YuNet(modelPath=args.model,
85
+ inputSize=[320, 320],
86
+ confThreshold=args.conf_threshold,
87
+ nmsThreshold=args.nms_threshold,
88
+ topK=args.top_k,
89
+ backendId=backend_id,
90
+ targetId=target_id)
91
+
92
+ # If input is an image
93
+ if args.input is not None:
94
+ image = cv.imread(args.input)
95
+ h, w, _ = image.shape
96
+
97
+ # Inference
98
+ model.setInputSize([w, h])
99
+ results = model.infer(image)
100
+
101
+ # Print results
102
+ print('{} faces detected.'.format(results.shape[0]))
103
+ for idx, det in enumerate(results):
104
+ print('{}: {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f}'.format(
105
+ idx, *det[:-1])
106
+ )
107
+
108
+ # Draw results on the input image
109
+ image = visualize(image, results)
110
+
111
+ # Save results if save is true
112
+ if args.save:
113
+ print('Resutls saved to result.jpg\n')
114
+ cv.imwrite('result.jpg', image)
115
+
116
+ # Visualize results in a new window
117
+ if args.vis:
118
+ cv.namedWindow(args.input, cv.WINDOW_AUTOSIZE)
119
+ cv.imshow(args.input, image)
120
+ cv.waitKey(0)
121
+ else: # Omit input to call default camera
122
+ deviceId = 0
123
+ cap = cv.VideoCapture(deviceId)
124
+ w = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
125
+ h = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
126
+ model.setInputSize([w, h])
127
+
128
+ tm = cv.TickMeter()
129
+ while cv.waitKey(1) < 0:
130
+ hasFrame, frame = cap.read()
131
+ if not hasFrame:
132
+ print('No frames grabbed!')
133
+ break
134
+
135
+ # Inference
136
+ tm.start()
137
+ results = model.infer(frame) # results is a tuple
138
+ tm.stop()
139
+
140
+ # Draw results on the input image
141
+ frame = visualize(frame, results, fps=tm.getFPS())
142
+
143
+ # Visualize results in a new Window
144
+ cv.imshow('YuNet Demo', frame)
145
+
146
+ tm.reset()
example_outputs/largest_selfie.jpg ADDED

Git LFS Details

  • SHA256: ab8413ad9bb4f53068f4fb63c6747e5989991dd02241c923d5595b614ecf2bf6
  • Pointer size: 132 Bytes
  • Size of remote file: 1.15 MB
example_outputs/yunet_demo.gif ADDED

Git LFS Details

  • SHA256: db90459c308b14dd423014eabf3253f5f6147fbe7906e81429a7a88c8dbe7b8c
  • Pointer size: 131 Bytes
  • Size of remote file: 661 kB
face_detection_yunet_2023mar.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4
3
+ size 232589
face_detection_yunet_2023mar_int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:321aa5a6afabf7ecc46a3d06bfab2b579dc96eb5c3be7edd365fa04502ad9294
3
+ size 100416
face_detection_yunet_2023mar_int8bq.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49f000ec501fef24739071fc7e68267d32209045b6822c0c72dce1da25726f10
3
+ size 122489
yunet.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from itertools import product
8
+
9
+ import numpy as np
10
+ import cv2 as cv
11
+
12
+ class YuNet:
13
+ def __init__(self, modelPath, inputSize=[320, 320], confThreshold=0.6, nmsThreshold=0.3, topK=5000, backendId=0, targetId=0):
14
+ self._modelPath = modelPath
15
+ self._inputSize = tuple(inputSize) # [w, h]
16
+ self._confThreshold = confThreshold
17
+ self._nmsThreshold = nmsThreshold
18
+ self._topK = topK
19
+ self._backendId = backendId
20
+ self._targetId = targetId
21
+
22
+ self._model = cv.FaceDetectorYN.create(
23
+ model=self._modelPath,
24
+ config="",
25
+ input_size=self._inputSize,
26
+ score_threshold=self._confThreshold,
27
+ nms_threshold=self._nmsThreshold,
28
+ top_k=self._topK,
29
+ backend_id=self._backendId,
30
+ target_id=self._targetId)
31
+
32
+ @property
33
+ def name(self):
34
+ return self.__class__.__name__
35
+
36
+ def setBackendAndTarget(self, backendId, targetId):
37
+ self._backendId = backendId
38
+ self._targetId = targetId
39
+ self._model = cv.FaceDetectorYN.create(
40
+ model=self._modelPath,
41
+ config="",
42
+ input_size=self._inputSize,
43
+ score_threshold=self._confThreshold,
44
+ nms_threshold=self._nmsThreshold,
45
+ top_k=self._topK,
46
+ backend_id=self._backendId,
47
+ target_id=self._targetId)
48
+
49
+ def setInputSize(self, input_size):
50
+ self._model.setInputSize(tuple(input_size))
51
+
52
+ def infer(self, image):
53
+ # Forward
54
+ faces = self._model.detect(image)
55
+ return np.empty(shape=(0, 5)) if faces[1] is None else faces[1]