Commit ·
ce64435
0
Parent(s):
Duplicate from opencv/face_recognition_sface
Browse filesCo-authored-by: Abhishek Gola <abhishek-gola@users.noreply.huggingface.co>
- .gitattributes +26 -0
- .gitignore +9 -0
- CMakeLists.txt +11 -0
- LICENSE +202 -0
- README.md +68 -0
- demo.cpp +322 -0
- demo.py +157 -0
- example_outputs/demo.jpg +3 -0
- face_recognition_sface_2021dec.onnx +3 -0
- face_recognition_sface_2021dec_int8.onnx +3 -0
- face_recognition_sface_2021dec_int8bq.onnx +3 -0
- sface.py +63 -0
- yunet.py +55 -0
.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_recognition_sface)
|
| 3 |
+
|
| 4 |
+
set(OPENCV_VERSION "4.9.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,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SFace
|
| 2 |
+
|
| 3 |
+
SFace: Sigmoid-Constrained Hypersphere Loss for Robust Face Recognition
|
| 4 |
+
|
| 5 |
+
Note:
|
| 6 |
+
|
| 7 |
+
- SFace is contributed by [Yaoyao Zhong](https://github.com/zhongyy).
|
| 8 |
+
- Model files encode MobileFaceNet instances trained on the SFace loss function, see the [SFace paper](https://arxiv.org/abs/2205.12010) for reference.
|
| 9 |
+
- ONNX file conversions from [original code base](https://github.com/zhongyy/SFace) thanks to [Chengrui Wang](https://github.com/crywang).
|
| 10 |
+
- (As of Sep 2021) Supporting 5-landmark warping for now, see below for details.
|
| 11 |
+
- `face_recognition_sface_2021dec_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 |
+
|
| 13 |
+
Results of accuracy evaluation with [tools/eval](../../tools/eval).
|
| 14 |
+
|
| 15 |
+
| Models | Accuracy |
|
| 16 |
+
| ----------- | -------- |
|
| 17 |
+
| SFace | 0.9940 |
|
| 18 |
+
| SFace block | 0.9942 |
|
| 19 |
+
| SFace quant | 0.9932 |
|
| 20 |
+
|
| 21 |
+
\*: 'quant' stands for 'quantized'.
|
| 22 |
+
\*\*: 'block' stands for 'blockwise quantized'.
|
| 23 |
+
|
| 24 |
+
## Demo
|
| 25 |
+
|
| 26 |
+
***NOTE***: This demo uses [../face_detection_yunet](../face_detection_yunet) as face detector, which supports 5-landmark detection for now (2021sep).
|
| 27 |
+
|
| 28 |
+
Run the following command to try the demo:
|
| 29 |
+
|
| 30 |
+
### Python
|
| 31 |
+
```shell
|
| 32 |
+
# recognize on images
|
| 33 |
+
python demo.py --target /path/to/image1 --query /path/to/image2
|
| 34 |
+
|
| 35 |
+
# get help regarding various parameters
|
| 36 |
+
python demo.py --help
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
### C++
|
| 40 |
+
Install latest OpenCV and CMake >= 3.24.0 to get started with:
|
| 41 |
+
|
| 42 |
+
```shell
|
| 43 |
+
# A typical and default installation path of OpenCV is /usr/local
|
| 44 |
+
cmake -B build -D OPENCV_INSTALLATION_PATH=/path/to/opencv/installation .
|
| 45 |
+
cmake --build build
|
| 46 |
+
|
| 47 |
+
# detect on camera input
|
| 48 |
+
./build/demo -t=/path/to/target_face
|
| 49 |
+
# detect on an image
|
| 50 |
+
./build/demo -t=/path/to/target_face -q=/path/to/query_face -v
|
| 51 |
+
# get help messages
|
| 52 |
+
./build/demo -h
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### Example outputs
|
| 56 |
+
|
| 57 |
+

|
| 58 |
+
|
| 59 |
+
Note: Left part of the image is the target identity, the right part is the query. Green boxes are the same identity, red boxes are different identities compared to the left.
|
| 60 |
+
|
| 61 |
+
## License
|
| 62 |
+
|
| 63 |
+
All files in this directory are licensed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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "opencv2/opencv.hpp"
|
| 2 |
+
#include "opencv2/core/types.hpp"
|
| 3 |
+
|
| 4 |
+
#include <string>
|
| 5 |
+
#include <vector>
|
| 6 |
+
|
| 7 |
+
const std::vector<std::pair<int, int>> backend_target_pairs = {
|
| 8 |
+
{cv::dnn::DNN_BACKEND_OPENCV, cv::dnn::DNN_TARGET_CPU},
|
| 9 |
+
{cv::dnn::DNN_BACKEND_CUDA, cv::dnn::DNN_TARGET_CUDA},
|
| 10 |
+
{cv::dnn::DNN_BACKEND_CUDA, cv::dnn::DNN_TARGET_CUDA_FP16},
|
| 11 |
+
{cv::dnn::DNN_BACKEND_TIMVX, cv::dnn::DNN_TARGET_NPU},
|
| 12 |
+
{cv::dnn::DNN_BACKEND_CANN, cv::dnn::DNN_TARGET_NPU}
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
class YuNet
|
| 16 |
+
{
|
| 17 |
+
public:
|
| 18 |
+
YuNet(const std::string& model_path,
|
| 19 |
+
const cv::Size& input_size,
|
| 20 |
+
const float conf_threshold,
|
| 21 |
+
const float nms_threshold,
|
| 22 |
+
const int top_k,
|
| 23 |
+
const int backend_id,
|
| 24 |
+
const int target_id)
|
| 25 |
+
{
|
| 26 |
+
_detector = cv::FaceDetectorYN::create(
|
| 27 |
+
model_path, "", input_size, conf_threshold, nms_threshold, top_k, backend_id, target_id);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
void setInputSize(const cv::Size& input_size)
|
| 31 |
+
{
|
| 32 |
+
_detector->setInputSize(input_size);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
void setTopK(const int top_k)
|
| 36 |
+
{
|
| 37 |
+
_detector->setTopK(top_k);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
cv::Mat infer(const cv::Mat& image)
|
| 41 |
+
{
|
| 42 |
+
cv::Mat result;
|
| 43 |
+
_detector->detect(image, result);
|
| 44 |
+
return result;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
private:
|
| 48 |
+
cv::Ptr<cv::FaceDetectorYN> _detector;
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
class SFace
|
| 52 |
+
{
|
| 53 |
+
public:
|
| 54 |
+
SFace(const std::string& model_path,
|
| 55 |
+
const int backend_id,
|
| 56 |
+
const int target_id,
|
| 57 |
+
const int distance_type)
|
| 58 |
+
: _distance_type(static_cast<cv::FaceRecognizerSF::DisType>(distance_type))
|
| 59 |
+
{
|
| 60 |
+
_recognizer = cv::FaceRecognizerSF::create(model_path, "", backend_id, target_id);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
cv::Mat extractFeatures(const cv::Mat& orig_image, const cv::Mat& face_image)
|
| 64 |
+
{
|
| 65 |
+
// Align and crop detected face from original image
|
| 66 |
+
cv::Mat target_aligned;
|
| 67 |
+
_recognizer->alignCrop(orig_image, face_image, target_aligned);
|
| 68 |
+
// Extract features from cropped detected face
|
| 69 |
+
cv::Mat target_features;
|
| 70 |
+
_recognizer->feature(target_aligned, target_features);
|
| 71 |
+
return target_features.clone();
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
std::pair<double, bool> matchFeatures(const cv::Mat& target_features, const cv::Mat& query_features)
|
| 75 |
+
{
|
| 76 |
+
const double score = _recognizer->match(target_features, query_features, _distance_type);
|
| 77 |
+
if (_distance_type == cv::FaceRecognizerSF::DisType::FR_COSINE)
|
| 78 |
+
{
|
| 79 |
+
return {score, score >= _threshold_cosine};
|
| 80 |
+
}
|
| 81 |
+
return {score, score <= _threshold_norml2};
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
private:
|
| 85 |
+
cv::Ptr<cv::FaceRecognizerSF> _recognizer;
|
| 86 |
+
cv::FaceRecognizerSF::DisType _distance_type;
|
| 87 |
+
double _threshold_cosine = 0.363;
|
| 88 |
+
double _threshold_norml2 = 1.128;
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
cv::Mat visualize(const cv::Mat& image,
|
| 92 |
+
const cv::Mat& faces,
|
| 93 |
+
const std::vector<std::pair<double, bool>>& matches,
|
| 94 |
+
const float fps = -0.1F,
|
| 95 |
+
const cv::Size& target_size = cv::Size(512, 512))
|
| 96 |
+
{
|
| 97 |
+
static const cv::Scalar matched_box_color{0, 255, 0};
|
| 98 |
+
static const cv::Scalar mismatched_box_color{0, 0, 255};
|
| 99 |
+
|
| 100 |
+
if (fps >= 0)
|
| 101 |
+
{
|
| 102 |
+
cv::Mat output_image = image.clone();
|
| 103 |
+
|
| 104 |
+
const int x1 = static_cast<int>(faces.at<float>(0, 0));
|
| 105 |
+
const int y1 = static_cast<int>(faces.at<float>(0, 1));
|
| 106 |
+
const int w = static_cast<int>(faces.at<float>(0, 2));
|
| 107 |
+
const int h = static_cast<int>(faces.at<float>(0, 3));
|
| 108 |
+
const auto match = matches.at(0);
|
| 109 |
+
|
| 110 |
+
cv::Scalar box_color = match.second ? matched_box_color : mismatched_box_color;
|
| 111 |
+
// Draw bounding box
|
| 112 |
+
cv::rectangle(output_image, cv::Rect(x1, y1, w, h), box_color, 2);
|
| 113 |
+
// Draw match score
|
| 114 |
+
cv::putText(output_image, cv::format("%.4f", match.first), cv::Point(x1, y1+12), cv::FONT_HERSHEY_DUPLEX, 0.30, box_color);
|
| 115 |
+
// Draw FPS
|
| 116 |
+
cv::putText(output_image, cv::format("FPS: %.2f", fps), cv::Point(0, 15), cv::FONT_HERSHEY_SIMPLEX, 0.5, box_color, 2);
|
| 117 |
+
|
| 118 |
+
return output_image;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
cv::Mat output_image = cv::Mat::zeros(target_size, CV_8UC3);
|
| 122 |
+
|
| 123 |
+
// Determine new height and width of image with aspect ratio of original image
|
| 124 |
+
const double ratio = std::min(static_cast<double>(target_size.height) / image.rows,
|
| 125 |
+
static_cast<double>(target_size.width) / image.cols);
|
| 126 |
+
const int new_height = static_cast<int>(image.rows * ratio);
|
| 127 |
+
const int new_width = static_cast<int>(image.cols * ratio);
|
| 128 |
+
|
| 129 |
+
// Resize the original image, maintaining aspect ratio
|
| 130 |
+
cv::Mat resize_out;
|
| 131 |
+
cv::resize(image, resize_out, cv::Size(new_width, new_height), cv::INTER_LINEAR);
|
| 132 |
+
|
| 133 |
+
// Determine top left corner in resized dimensions
|
| 134 |
+
const int top = std::max(0, target_size.height - new_height) / 2;
|
| 135 |
+
const int left = std::max(0, target_size.width - new_width) / 2;
|
| 136 |
+
|
| 137 |
+
// Copy resized image into target output image
|
| 138 |
+
const cv::Rect roi = cv::Rect(cv::Point(left, top), cv::Size(new_width, new_height));
|
| 139 |
+
cv::Mat out_sub_image = output_image(roi);
|
| 140 |
+
resize_out.copyTo(out_sub_image);
|
| 141 |
+
|
| 142 |
+
for (int i = 0; i < faces.rows; ++i)
|
| 143 |
+
{
|
| 144 |
+
const int x1 = static_cast<int>(faces.at<float>(i, 0) * ratio) + left;
|
| 145 |
+
const int y1 = static_cast<int>(faces.at<float>(i, 1) * ratio) + top;
|
| 146 |
+
const int w = static_cast<int>(faces.at<float>(i, 2) * ratio);
|
| 147 |
+
const int h = static_cast<int>(faces.at<float>(i, 3) * ratio);
|
| 148 |
+
const auto match = matches.at(i);
|
| 149 |
+
|
| 150 |
+
cv::Scalar box_color = match.second ? matched_box_color : mismatched_box_color;
|
| 151 |
+
// Draw bounding box
|
| 152 |
+
cv::rectangle(output_image, cv::Rect(x1, y1, w, h), box_color, 2);
|
| 153 |
+
// Draw match score
|
| 154 |
+
cv::putText(output_image, cv::format("%.4f", match.first), cv::Point(x1, y1+12), cv::FONT_HERSHEY_DUPLEX, 0.30, box_color);
|
| 155 |
+
}
|
| 156 |
+
return output_image;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
int main(int argc, char** argv)
|
| 160 |
+
{
|
| 161 |
+
cv::CommandLineParser parser(argc, argv,
|
| 162 |
+
// General options
|
| 163 |
+
"{help h | | Print this message}"
|
| 164 |
+
"{backend_target b | 0 | Set DNN backend target pair:\n"
|
| 165 |
+
"0: (default) OpenCV implementation + CPU,\n"
|
| 166 |
+
"1: CUDA + GPU (CUDA),\n"
|
| 167 |
+
"2: CUDA + GPU (CUDA FP16),\n"
|
| 168 |
+
"3: TIM-VX + NPU,\n"
|
| 169 |
+
"4: CANN + NPU}"
|
| 170 |
+
"{save s | false | Whether to save result image or not}"
|
| 171 |
+
"{vis v | false | Whether to visualize result image or not}"
|
| 172 |
+
// SFace options
|
| 173 |
+
"{target_face t | | Set path to input image 1 (target face)}"
|
| 174 |
+
"{query_face q | | Set path to input image 2 (query face), omit if using camera}"
|
| 175 |
+
"{model m | face_recognition_sface_2021dec.onnx | Set path to the model}"
|
| 176 |
+
"{distance_type d | 0 | 0 = cosine, 1 = norm_l1}"
|
| 177 |
+
// YuNet options
|
| 178 |
+
"{yunet_model | ../face_detection_yunet/face_detection_yunet_2023mar.onnx | Set path to the YuNet model}"
|
| 179 |
+
"{detect_threshold | 0.9 | Set the minimum confidence for the model\n"
|
| 180 |
+
"to identify a face. Filter out faces of\n"
|
| 181 |
+
"conf < conf_threshold}"
|
| 182 |
+
"{nms_threshold | 0.3 | Set the threshold to suppress overlapped boxes.\n"
|
| 183 |
+
"Suppress boxes if IoU(box1, box2) >= nms_threshold\n"
|
| 184 |
+
", the one of higher score is kept.}"
|
| 185 |
+
"{top_k | 5000 | Keep top_k bounding boxes before NMS}"
|
| 186 |
+
);
|
| 187 |
+
|
| 188 |
+
if (parser.has("help"))
|
| 189 |
+
{
|
| 190 |
+
parser.printMessage();
|
| 191 |
+
return 0;
|
| 192 |
+
}
|
| 193 |
+
// General CLI options
|
| 194 |
+
const int backend = parser.get<int>("backend_target");
|
| 195 |
+
const bool save_flag = parser.get<bool>("save");
|
| 196 |
+
const bool vis_flag = parser.get<bool>("vis");
|
| 197 |
+
const int backend_id = backend_target_pairs.at(backend).first;
|
| 198 |
+
const int target_id = backend_target_pairs.at(backend).second;
|
| 199 |
+
|
| 200 |
+
// YuNet CLI options
|
| 201 |
+
const std::string detector_model_path = parser.get<std::string>("yunet_model");
|
| 202 |
+
const float detect_threshold = parser.get<float>("detect_threshold");
|
| 203 |
+
const float nms_threshold = parser.get<float>("nms_threshold");
|
| 204 |
+
const int top_k = parser.get<int>("top_k");
|
| 205 |
+
|
| 206 |
+
// Use YuNet as the detector backend
|
| 207 |
+
auto face_detector = YuNet(
|
| 208 |
+
detector_model_path, cv::Size(320, 320), detect_threshold, nms_threshold, top_k, backend_id, target_id);
|
| 209 |
+
|
| 210 |
+
// SFace CLI options
|
| 211 |
+
const std::string target_path = parser.get<std::string>("target_face");
|
| 212 |
+
const std::string query_path = parser.get<std::string>("query_face");
|
| 213 |
+
const std::string model_path = parser.get<std::string>("model");
|
| 214 |
+
const int distance_type = parser.get<int>("distance_type");
|
| 215 |
+
|
| 216 |
+
auto face_recognizer = SFace(model_path, backend_id, target_id, distance_type);
|
| 217 |
+
|
| 218 |
+
if (target_path.empty())
|
| 219 |
+
{
|
| 220 |
+
CV_Error(cv::Error::StsError, "Path to target image " + target_path + " not found");
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
cv::Mat target_image = cv::imread(target_path);
|
| 224 |
+
// Detect single face in target image
|
| 225 |
+
face_detector.setInputSize(target_image.size());
|
| 226 |
+
face_detector.setTopK(1);
|
| 227 |
+
cv::Mat target_face = face_detector.infer(target_image);
|
| 228 |
+
// Extract features from target face
|
| 229 |
+
cv::Mat target_features = face_recognizer.extractFeatures(target_image, target_face.row(0));
|
| 230 |
+
|
| 231 |
+
if (!query_path.empty()) // use image
|
| 232 |
+
{
|
| 233 |
+
// Detect any faces in query image
|
| 234 |
+
cv::Mat query_image = cv::imread(query_path);
|
| 235 |
+
face_detector.setInputSize(query_image.size());
|
| 236 |
+
face_detector.setTopK(5000);
|
| 237 |
+
cv::Mat query_faces = face_detector.infer(query_image);
|
| 238 |
+
|
| 239 |
+
// Store match scores for visualization
|
| 240 |
+
std::vector<std::pair<double, bool>> matches;
|
| 241 |
+
|
| 242 |
+
for (int i = 0; i < query_faces.rows; ++i)
|
| 243 |
+
{
|
| 244 |
+
// Extract features from query face
|
| 245 |
+
cv::Mat query_features = face_recognizer.extractFeatures(query_image, query_faces.row(i));
|
| 246 |
+
// Measure similarity of target face to query face
|
| 247 |
+
const auto match = face_recognizer.matchFeatures(target_features, query_features);
|
| 248 |
+
matches.push_back(match);
|
| 249 |
+
|
| 250 |
+
const int x1 = static_cast<int>(query_faces.at<float>(i, 0));
|
| 251 |
+
const int y1 = static_cast<int>(query_faces.at<float>(i, 1));
|
| 252 |
+
const int w = static_cast<int>(query_faces.at<float>(i, 2));
|
| 253 |
+
const int h = static_cast<int>(query_faces.at<float>(i, 3));
|
| 254 |
+
const float conf = query_faces.at<float>(i, 14);
|
| 255 |
+
|
| 256 |
+
std::cout << cv::format("%d: x1=%d, y1=%d, w=%d, h=%d, conf=%.4f, match=%.4f\n", i, x1, y1, w, h, conf, match.first);
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
if (save_flag || vis_flag)
|
| 260 |
+
{
|
| 261 |
+
auto vis_target = visualize(target_image, target_face, {{1.0, true}});
|
| 262 |
+
auto vis_query = visualize(query_image, query_faces, matches);
|
| 263 |
+
cv::Mat output_image;
|
| 264 |
+
cv::hconcat(vis_target, vis_query, output_image);
|
| 265 |
+
|
| 266 |
+
if (save_flag)
|
| 267 |
+
{
|
| 268 |
+
std::cout << "Results are saved to result.jpg\n";
|
| 269 |
+
cv::imwrite("result.jpg", output_image);
|
| 270 |
+
}
|
| 271 |
+
if (vis_flag)
|
| 272 |
+
{
|
| 273 |
+
cv::namedWindow(query_path, cv::WINDOW_AUTOSIZE);
|
| 274 |
+
cv::imshow(query_path, output_image);
|
| 275 |
+
cv::waitKey(0);
|
| 276 |
+
}
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
else // use video capture
|
| 280 |
+
{
|
| 281 |
+
const int device_id = 0;
|
| 282 |
+
auto cap = cv::VideoCapture(device_id);
|
| 283 |
+
const int w = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
|
| 284 |
+
const int h = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
|
| 285 |
+
face_detector.setInputSize(cv::Size(w, h));
|
| 286 |
+
|
| 287 |
+
auto tick_meter = cv::TickMeter();
|
| 288 |
+
cv::Mat query_frame;
|
| 289 |
+
|
| 290 |
+
while (cv::waitKey(1) < 0)
|
| 291 |
+
{
|
| 292 |
+
bool has_frame = cap.read(query_frame);
|
| 293 |
+
if (!has_frame)
|
| 294 |
+
{
|
| 295 |
+
std::cout << "No frames grabbed! Exiting ...\n";
|
| 296 |
+
break;
|
| 297 |
+
}
|
| 298 |
+
tick_meter.start();
|
| 299 |
+
// Detect faces from webcam image
|
| 300 |
+
cv::Mat query_faces = face_detector.infer(query_frame);
|
| 301 |
+
tick_meter.stop();
|
| 302 |
+
|
| 303 |
+
// Extract features from query face
|
| 304 |
+
cv::Mat query_features = face_recognizer.extractFeatures(query_frame, query_faces.row(0));
|
| 305 |
+
// Measure similarity of target face to query face
|
| 306 |
+
const auto match = face_recognizer.matchFeatures(target_features, query_features);
|
| 307 |
+
|
| 308 |
+
const auto fps = static_cast<float>(tick_meter.getFPS());
|
| 309 |
+
|
| 310 |
+
auto vis_target = visualize(target_image, target_face, {{1.0, true}}, -0.1F, cv::Size(w, h));
|
| 311 |
+
auto vis_query = visualize(query_frame, query_faces, {match}, fps);
|
| 312 |
+
cv::Mat output_image;
|
| 313 |
+
cv::hconcat(vis_target, vis_query, output_image);
|
| 314 |
+
|
| 315 |
+
// Visualize in a new window
|
| 316 |
+
cv::imshow("SFace Demo", output_image);
|
| 317 |
+
|
| 318 |
+
tick_meter.reset();
|
| 319 |
+
}
|
| 320 |
+
}
|
| 321 |
+
return 0;
|
| 322 |
+
}
|
demo.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 sys
|
| 8 |
+
import argparse
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import cv2 as cv
|
| 12 |
+
from huggingface_hub import hf_hub_download
|
| 13 |
+
|
| 14 |
+
# Check OpenCV version
|
| 15 |
+
opencv_python_version = lambda str_version: tuple(map(int, (str_version.split("."))))
|
| 16 |
+
assert opencv_python_version(cv.__version__) >= opencv_python_version("4.10.0"), \
|
| 17 |
+
"Please install latest opencv-python for benchmark: python3 -m pip install --upgrade opencv-python"
|
| 18 |
+
|
| 19 |
+
from sface import SFace
|
| 20 |
+
from yunet import YuNet
|
| 21 |
+
|
| 22 |
+
yunet_model_path = hf_hub_download(repo_id="opencv/face_detection_yunet", filename="face_detection_yunet_2023mar.onnx")
|
| 23 |
+
|
| 24 |
+
# Valid combinations of backends and targets
|
| 25 |
+
backend_target_pairs = [
|
| 26 |
+
[cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_CPU],
|
| 27 |
+
[cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA],
|
| 28 |
+
[cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16],
|
| 29 |
+
[cv.dnn.DNN_BACKEND_TIMVX, cv.dnn.DNN_TARGET_NPU],
|
| 30 |
+
[cv.dnn.DNN_BACKEND_CANN, cv.dnn.DNN_TARGET_NPU]
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
parser = argparse.ArgumentParser(
|
| 34 |
+
description="SFace: Sigmoid-Constrained Hypersphere Loss for Robust Face Recognition (https://ieeexplore.ieee.org/document/9318547)")
|
| 35 |
+
parser.add_argument('--target', '-t', type=str,
|
| 36 |
+
help='Usage: Set path to the input image 1 (target face).')
|
| 37 |
+
parser.add_argument('--query', '-q', type=str,
|
| 38 |
+
help='Usage: Set path to the input image 2 (query).')
|
| 39 |
+
parser.add_argument('--model', '-m', type=str, default='face_recognition_sface_2021dec.onnx',
|
| 40 |
+
help='Usage: Set model path, defaults to face_recognition_sface_2021dec.onnx.')
|
| 41 |
+
parser.add_argument('--backend_target', '-bt', type=int, default=0,
|
| 42 |
+
help='''Choose one of the backend-target pair to run this demo:
|
| 43 |
+
{:d}: (default) OpenCV implementation + CPU,
|
| 44 |
+
{:d}: CUDA + GPU (CUDA),
|
| 45 |
+
{:d}: CUDA + GPU (CUDA FP16),
|
| 46 |
+
{:d}: TIM-VX + NPU,
|
| 47 |
+
{:d}: CANN + NPU
|
| 48 |
+
'''.format(*[x for x in range(len(backend_target_pairs))]))
|
| 49 |
+
parser.add_argument('--dis_type', type=int, choices=[0, 1], default=0,
|
| 50 |
+
help='Usage: Distance type. \'0\': cosine, \'1\': norm_l1. Defaults to \'0\'')
|
| 51 |
+
parser.add_argument('--save', '-s', action='store_true',
|
| 52 |
+
help='Usage: Specify to save file with results (i.e. bounding box, confidence level). Invalid in case of camera input.')
|
| 53 |
+
parser.add_argument('--vis', '-v', action='store_true',
|
| 54 |
+
help='Usage: Specify to open a new window to show results. Invalid in case of camera input.')
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
def visualize(img1, faces1, img2, faces2, matches, scores, target_size=[512, 512]): # target_size: (h, w)
|
| 58 |
+
out1 = img1.copy()
|
| 59 |
+
out2 = img2.copy()
|
| 60 |
+
matched_box_color = (0, 255, 0) # BGR
|
| 61 |
+
mismatched_box_color = (0, 0, 255) # BGR
|
| 62 |
+
|
| 63 |
+
# Resize to 256x256 with the same aspect ratio
|
| 64 |
+
padded_out1 = np.zeros((target_size[0], target_size[1], 3)).astype(np.uint8)
|
| 65 |
+
h1, w1, _ = out1.shape
|
| 66 |
+
ratio1 = min(target_size[0] / out1.shape[0], target_size[1] / out1.shape[1])
|
| 67 |
+
new_h1 = int(h1 * ratio1)
|
| 68 |
+
new_w1 = int(w1 * ratio1)
|
| 69 |
+
resized_out1 = cv.resize(out1, (new_w1, new_h1), interpolation=cv.INTER_LINEAR).astype(np.float32)
|
| 70 |
+
top = max(0, target_size[0] - new_h1) // 2
|
| 71 |
+
bottom = top + new_h1
|
| 72 |
+
left = max(0, target_size[1] - new_w1) // 2
|
| 73 |
+
right = left + new_w1
|
| 74 |
+
padded_out1[top : bottom, left : right] = resized_out1
|
| 75 |
+
|
| 76 |
+
# Draw bbox
|
| 77 |
+
bbox1 = faces1[0][:4] * ratio1
|
| 78 |
+
x, y, w, h = bbox1.astype(np.int32)
|
| 79 |
+
cv.rectangle(padded_out1, (x + left, y + top), (x + left + w, y + top + h), matched_box_color, 2)
|
| 80 |
+
|
| 81 |
+
# Resize to 256x256 with the same aspect ratio
|
| 82 |
+
padded_out2 = np.zeros((target_size[0], target_size[1], 3)).astype(np.uint8)
|
| 83 |
+
h2, w2, _ = out2.shape
|
| 84 |
+
ratio2 = min(target_size[0] / out2.shape[0], target_size[1] / out2.shape[1])
|
| 85 |
+
new_h2 = int(h2 * ratio2)
|
| 86 |
+
new_w2 = int(w2 * ratio2)
|
| 87 |
+
resized_out2 = cv.resize(out2, (new_w2, new_h2), interpolation=cv.INTER_LINEAR).astype(np.float32)
|
| 88 |
+
top = max(0, target_size[0] - new_h2) // 2
|
| 89 |
+
bottom = top + new_h2
|
| 90 |
+
left = max(0, target_size[1] - new_w2) // 2
|
| 91 |
+
right = left + new_w2
|
| 92 |
+
padded_out2[top : bottom, left : right] = resized_out2
|
| 93 |
+
|
| 94 |
+
# Draw bbox
|
| 95 |
+
assert faces2.shape[0] == len(matches), "number of faces2 needs to match matches"
|
| 96 |
+
assert len(matches) == len(scores), "number of matches needs to match number of scores"
|
| 97 |
+
for index, match in enumerate(matches):
|
| 98 |
+
bbox2 = faces2[index][:4] * ratio2
|
| 99 |
+
x, y, w, h = bbox2.astype(np.int32)
|
| 100 |
+
box_color = matched_box_color if match else mismatched_box_color
|
| 101 |
+
cv.rectangle(padded_out2, (x + left, y + top), (x + left + w, y + top + h), box_color, 2)
|
| 102 |
+
|
| 103 |
+
score = scores[index]
|
| 104 |
+
text_color = matched_box_color if match else mismatched_box_color
|
| 105 |
+
cv.putText(padded_out2, "{:.2f}".format(score), (x + left, y + top - 5), cv.FONT_HERSHEY_DUPLEX, 0.4, text_color)
|
| 106 |
+
|
| 107 |
+
return np.concatenate([padded_out1, padded_out2], axis=1)
|
| 108 |
+
|
| 109 |
+
if __name__ == '__main__':
|
| 110 |
+
backend_id = backend_target_pairs[args.backend_target][0]
|
| 111 |
+
target_id = backend_target_pairs[args.backend_target][1]
|
| 112 |
+
# Instantiate SFace for face recognition
|
| 113 |
+
recognizer = SFace(modelPath=args.model,
|
| 114 |
+
disType=args.dis_type,
|
| 115 |
+
backendId=backend_id,
|
| 116 |
+
targetId=target_id)
|
| 117 |
+
# Instantiate YuNet for face detection
|
| 118 |
+
detector = YuNet(modelPath=yunet_model_path,
|
| 119 |
+
inputSize=[320, 320],
|
| 120 |
+
confThreshold=0.9,
|
| 121 |
+
nmsThreshold=0.3,
|
| 122 |
+
topK=5000,
|
| 123 |
+
backendId=backend_id,
|
| 124 |
+
targetId=target_id)
|
| 125 |
+
|
| 126 |
+
img1 = cv.imread(args.target)
|
| 127 |
+
img2 = cv.imread(args.query)
|
| 128 |
+
|
| 129 |
+
# Detect faces
|
| 130 |
+
detector.setInputSize([img1.shape[1], img1.shape[0]])
|
| 131 |
+
faces1 = detector.infer(img1)
|
| 132 |
+
assert faces1.shape[0] > 0, 'Cannot find a face in {}'.format(args.target)
|
| 133 |
+
detector.setInputSize([img2.shape[1], img2.shape[0]])
|
| 134 |
+
faces2 = detector.infer(img2)
|
| 135 |
+
assert faces2.shape[0] > 0, 'Cannot find a face in {}'.format(args.query)
|
| 136 |
+
|
| 137 |
+
# Match
|
| 138 |
+
scores = []
|
| 139 |
+
matches = []
|
| 140 |
+
for face in faces2:
|
| 141 |
+
result = recognizer.match(img1, faces1[0][:-1], img2, face[:-1])
|
| 142 |
+
scores.append(result[0])
|
| 143 |
+
matches.append(result[1])
|
| 144 |
+
|
| 145 |
+
# Draw results
|
| 146 |
+
image = visualize(img1, faces1, img2, faces2, matches, scores)
|
| 147 |
+
|
| 148 |
+
# Save results if save is true
|
| 149 |
+
if args.save:
|
| 150 |
+
print('Resutls saved to result.jpg\n')
|
| 151 |
+
cv.imwrite('result.jpg', image)
|
| 152 |
+
|
| 153 |
+
# Visualize results in a new window
|
| 154 |
+
if args.vis:
|
| 155 |
+
cv.namedWindow("SFace Demo", cv.WINDOW_AUTOSIZE)
|
| 156 |
+
cv.imshow("SFace Demo", image)
|
| 157 |
+
cv.waitKey(0)
|
example_outputs/demo.jpg
ADDED
|
Git LFS Details
|
face_recognition_sface_2021dec.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79
|
| 3 |
+
size 38696353
|
face_recognition_sface_2021dec_int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b0e941e6f16cc048c20aee0c8e31f569118f65d702914540f7bfdc14048d78a
|
| 3 |
+
size 9896933
|
face_recognition_sface_2021dec_int8bq.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb143eea07838aa532d1c95df5f69899974ea0140e1fba05e94204be13ed74ee
|
| 3 |
+
size 10667852
|
sface.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 numpy as np
|
| 8 |
+
import cv2 as cv
|
| 9 |
+
|
| 10 |
+
class SFace:
|
| 11 |
+
def __init__(self, modelPath, disType=0, backendId=0, targetId=0):
|
| 12 |
+
self._modelPath = modelPath
|
| 13 |
+
self._backendId = backendId
|
| 14 |
+
self._targetId = targetId
|
| 15 |
+
self._model = cv.FaceRecognizerSF.create(
|
| 16 |
+
model=self._modelPath,
|
| 17 |
+
config="",
|
| 18 |
+
backend_id=self._backendId,
|
| 19 |
+
target_id=self._targetId)
|
| 20 |
+
|
| 21 |
+
self._disType = disType # 0: cosine similarity, 1: Norm-L2 distance
|
| 22 |
+
assert self._disType in [0, 1], "0: Cosine similarity, 1: norm-L2 distance, others: invalid"
|
| 23 |
+
|
| 24 |
+
self._threshold_cosine = 0.363
|
| 25 |
+
self._threshold_norml2 = 1.128
|
| 26 |
+
|
| 27 |
+
@property
|
| 28 |
+
def name(self):
|
| 29 |
+
return self.__class__.__name__
|
| 30 |
+
|
| 31 |
+
def setBackendAndTarget(self, backendId, targetId):
|
| 32 |
+
self._backendId = backendId
|
| 33 |
+
self._targetId = targetId
|
| 34 |
+
self._model = cv.FaceRecognizerSF.create(
|
| 35 |
+
model=self._modelPath,
|
| 36 |
+
config="",
|
| 37 |
+
backend_id=self._backendId,
|
| 38 |
+
target_id=self._targetId)
|
| 39 |
+
|
| 40 |
+
def _preprocess(self, image, bbox):
|
| 41 |
+
if bbox is None:
|
| 42 |
+
return image
|
| 43 |
+
else:
|
| 44 |
+
return self._model.alignCrop(image, bbox)
|
| 45 |
+
|
| 46 |
+
def infer(self, image, bbox=None):
|
| 47 |
+
# Preprocess
|
| 48 |
+
inputBlob = self._preprocess(image, bbox)
|
| 49 |
+
|
| 50 |
+
# Forward
|
| 51 |
+
features = self._model.feature(inputBlob)
|
| 52 |
+
return features
|
| 53 |
+
|
| 54 |
+
def match(self, image1, face1, image2, face2):
|
| 55 |
+
feature1 = self.infer(image1, face1)
|
| 56 |
+
feature2 = self.infer(image2, face2)
|
| 57 |
+
|
| 58 |
+
if self._disType == 0: # COSINE
|
| 59 |
+
cosine_score = self._model.match(feature1, feature2, self._disType)
|
| 60 |
+
return cosine_score, 1 if cosine_score >= self._threshold_cosine else 0
|
| 61 |
+
else: # NORM_L2
|
| 62 |
+
norml2_distance = self._model.match(feature1, feature2, self._disType)
|
| 63 |
+
return norml2_distance, 1 if norml2_distance <= self._threshold_norml2 else 0
|
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]
|