Spaces:
Running
Running
Commit ·
53fe336
0
Parent(s):
initial commit
Browse files- .gitattributes +41 -0
- .gitignore +15 -0
- .pre-commit-config.yaml +30 -0
- LICENSES/GPL-3.0-or-later.txt +232 -0
- LICENSES/MIT.txt +18 -0
- README.md +11 -0
- REUSE.toml +13 -0
- app.py +498 -0
- lib/ModelWrappers.py +119 -0
- lib/__init__.py +0 -0
- lib/align.py +141 -0
- lib/face_alignment/README.md +8 -0
- lib/face_alignment/mtcnn.py +211 -0
- lib/face_alignment/mtcnn_pytorch/README.md +32 -0
- lib/face_alignment/mtcnn_pytorch/src/__init__.py +6 -0
- lib/face_alignment/mtcnn_pytorch/src/align_trans.py +307 -0
- lib/face_alignment/mtcnn_pytorch/src/box_utils.py +243 -0
- lib/face_alignment/mtcnn_pytorch/src/detector.py +141 -0
- lib/face_alignment/mtcnn_pytorch/src/first_stage.py +107 -0
- lib/face_alignment/mtcnn_pytorch/src/get_nets.py +169 -0
- lib/face_alignment/mtcnn_pytorch/src/matlab_cp2tform.py +338 -0
- lib/face_alignment/mtcnn_pytorch/src/visualization_utils.py +33 -0
- lib/face_alignment/mtcnn_pytorch/src/weights/onet.npy +3 -0
- lib/face_alignment/mtcnn_pytorch/src/weights/pnet.npy +3 -0
- lib/face_alignment/mtcnn_pytorch/src/weights/rnet.npy +3 -0
- lib/models.py +233 -0
- lib/utils.py +79 -0
- requirements.txt +26 -0
.gitattributes
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2026 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Samuel Michel <samuel.michel@idiap.ch>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2026 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Samuel Michel <samuel.michel@idiap.ch>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
.env
|
| 8 |
+
data/*
|
| 9 |
+
out/*
|
| 10 |
+
__pycache__/
|
| 11 |
+
models/
|
| 12 |
+
checkpoints/*
|
| 13 |
+
.gradio/*
|
| 14 |
+
models/*
|
| 15 |
+
venv/
|
.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2026 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Samuel Michel <samuel.michel@idiap.ch>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
repos:
|
| 8 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
| 9 |
+
rev: v0.14.0
|
| 10 |
+
hooks:
|
| 11 |
+
- id: ruff-check
|
| 12 |
+
args: [--fix, --exit-non-zero-on-fix,--exclude, lib/face_alignment/**]
|
| 13 |
+
- id: ruff-format
|
| 14 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 15 |
+
rev: v6.0.0
|
| 16 |
+
hooks:
|
| 17 |
+
- id: check-ast
|
| 18 |
+
- id: check-case-conflict
|
| 19 |
+
- id: trailing-whitespace
|
| 20 |
+
- id: end-of-file-fixer
|
| 21 |
+
- id: debug-statements
|
| 22 |
+
- id: check-added-large-files
|
| 23 |
+
- repo: https://github.com/jorisroovers/gitlint
|
| 24 |
+
rev: v0.19.1
|
| 25 |
+
hooks:
|
| 26 |
+
- id: gitlint
|
| 27 |
+
- repo: https://github.com/fsfe/reuse-tool
|
| 28 |
+
rev: v5.1.1
|
| 29 |
+
hooks:
|
| 30 |
+
- id: reuse-lint-file
|
LICENSES/GPL-3.0-or-later.txt
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
|
| 6 |
+
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
| 11 |
+
|
| 12 |
+
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
| 13 |
+
|
| 14 |
+
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
| 15 |
+
|
| 16 |
+
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
| 17 |
+
|
| 18 |
+
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
| 19 |
+
|
| 20 |
+
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
| 21 |
+
|
| 22 |
+
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
| 23 |
+
|
| 24 |
+
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
| 25 |
+
|
| 26 |
+
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
| 27 |
+
|
| 28 |
+
The precise terms and conditions for copying, distribution and modification follow.
|
| 29 |
+
|
| 30 |
+
TERMS AND CONDITIONS
|
| 31 |
+
|
| 32 |
+
0. Definitions.
|
| 33 |
+
|
| 34 |
+
“This License” refers to version 3 of the GNU General Public License.
|
| 35 |
+
|
| 36 |
+
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
| 37 |
+
|
| 38 |
+
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
| 39 |
+
|
| 40 |
+
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
| 41 |
+
|
| 42 |
+
A “covered work” means either the unmodified Program or a work based on the Program.
|
| 43 |
+
|
| 44 |
+
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
| 45 |
+
|
| 46 |
+
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
| 47 |
+
|
| 48 |
+
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
| 49 |
+
|
| 50 |
+
1. Source Code.
|
| 51 |
+
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
| 52 |
+
|
| 53 |
+
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
| 54 |
+
|
| 55 |
+
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
| 56 |
+
|
| 57 |
+
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
| 58 |
+
|
| 59 |
+
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
| 60 |
+
|
| 61 |
+
The Corresponding Source for a work in source code form is that same work.
|
| 62 |
+
|
| 63 |
+
2. Basic Permissions.
|
| 64 |
+
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
| 65 |
+
|
| 66 |
+
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
| 67 |
+
|
| 68 |
+
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
| 69 |
+
|
| 70 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 71 |
+
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
| 72 |
+
|
| 73 |
+
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
| 74 |
+
|
| 75 |
+
4. Conveying Verbatim Copies.
|
| 76 |
+
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
| 77 |
+
|
| 78 |
+
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
| 79 |
+
|
| 80 |
+
5. Conveying Modified Source Versions.
|
| 81 |
+
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
| 82 |
+
|
| 83 |
+
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
| 84 |
+
|
| 85 |
+
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
| 86 |
+
|
| 87 |
+
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
| 88 |
+
|
| 89 |
+
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
| 90 |
+
|
| 91 |
+
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
| 92 |
+
|
| 93 |
+
6. Conveying Non-Source Forms.
|
| 94 |
+
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
| 95 |
+
|
| 96 |
+
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
| 97 |
+
|
| 98 |
+
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
| 99 |
+
|
| 100 |
+
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
| 101 |
+
|
| 102 |
+
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
| 103 |
+
|
| 104 |
+
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
| 105 |
+
|
| 106 |
+
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
| 107 |
+
|
| 108 |
+
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
| 109 |
+
|
| 110 |
+
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
| 111 |
+
|
| 112 |
+
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
| 113 |
+
|
| 114 |
+
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
| 115 |
+
|
| 116 |
+
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
| 117 |
+
|
| 118 |
+
7. Additional Terms.
|
| 119 |
+
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
| 120 |
+
|
| 121 |
+
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
| 122 |
+
|
| 123 |
+
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
| 124 |
+
|
| 125 |
+
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
| 126 |
+
|
| 127 |
+
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
| 128 |
+
|
| 129 |
+
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
| 130 |
+
|
| 131 |
+
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
| 132 |
+
|
| 133 |
+
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
| 134 |
+
|
| 135 |
+
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
| 136 |
+
|
| 137 |
+
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
| 138 |
+
|
| 139 |
+
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
| 140 |
+
|
| 141 |
+
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
| 142 |
+
|
| 143 |
+
8. Termination.
|
| 144 |
+
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
| 145 |
+
|
| 146 |
+
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
| 147 |
+
|
| 148 |
+
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
| 149 |
+
|
| 150 |
+
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
| 151 |
+
|
| 152 |
+
9. Acceptance Not Required for Having Copies.
|
| 153 |
+
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
| 154 |
+
|
| 155 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 156 |
+
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
| 157 |
+
|
| 158 |
+
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
| 159 |
+
|
| 160 |
+
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
| 161 |
+
|
| 162 |
+
11. Patents.
|
| 163 |
+
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
| 164 |
+
|
| 165 |
+
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
| 166 |
+
|
| 167 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
| 168 |
+
|
| 169 |
+
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
| 170 |
+
|
| 171 |
+
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
| 172 |
+
|
| 173 |
+
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
| 174 |
+
|
| 175 |
+
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
| 176 |
+
|
| 177 |
+
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
| 178 |
+
|
| 179 |
+
12. No Surrender of Others' Freedom.
|
| 180 |
+
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
| 181 |
+
|
| 182 |
+
13. Use with the GNU Affero General Public License.
|
| 183 |
+
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
| 184 |
+
|
| 185 |
+
14. Revised Versions of this License.
|
| 186 |
+
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
| 187 |
+
|
| 188 |
+
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
| 189 |
+
|
| 190 |
+
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
| 191 |
+
|
| 192 |
+
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
| 193 |
+
|
| 194 |
+
15. Disclaimer of Warranty.
|
| 195 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 196 |
+
|
| 197 |
+
16. Limitation of Liability.
|
| 198 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
| 199 |
+
|
| 200 |
+
17. Interpretation of Sections 15 and 16.
|
| 201 |
+
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
| 202 |
+
|
| 203 |
+
END OF TERMS AND CONDITIONS
|
| 204 |
+
|
| 205 |
+
How to Apply These Terms to Your New Programs
|
| 206 |
+
|
| 207 |
+
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
| 208 |
+
|
| 209 |
+
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
| 210 |
+
|
| 211 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 212 |
+
Copyright (C) <year> <name of author>
|
| 213 |
+
|
| 214 |
+
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
| 215 |
+
|
| 216 |
+
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
| 217 |
+
|
| 218 |
+
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 219 |
+
|
| 220 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 221 |
+
|
| 222 |
+
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
| 223 |
+
|
| 224 |
+
<program> Copyright (C) <year> <name of author>
|
| 225 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 226 |
+
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
| 227 |
+
|
| 228 |
+
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
| 229 |
+
|
| 230 |
+
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
| 231 |
+
|
| 232 |
+
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
LICENSES/MIT.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) <year> <copyright holders>
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
| 6 |
+
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
| 7 |
+
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 8 |
+
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
| 9 |
+
following conditions:
|
| 10 |
+
|
| 11 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial
|
| 12 |
+
portions of the Software.
|
| 13 |
+
|
| 14 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
| 15 |
+
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
| 16 |
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
| 17 |
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
| 18 |
+
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: ArtFace
|
| 3 |
+
colorFrom: indigo
|
| 4 |
+
colorTo: red
|
| 5 |
+
sdk: gradio
|
| 6 |
+
sdk_version: 6.10.0
|
| 7 |
+
app_file: app.py
|
| 8 |
+
pinned: false
|
| 9 |
+
license: gpl-3.0
|
| 10 |
+
short_description: ArtFace Demo
|
| 11 |
+
---
|
REUSE.toml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = 1
|
| 2 |
+
|
| 3 |
+
[[annotations]]
|
| 4 |
+
path = ["lib/face_alignment/mtcnn_pytorch/src/weights/*"]
|
| 5 |
+
precedence = "aggregate"
|
| 6 |
+
SPDX-FileCopyrightText = "Copyright © 2017 Dan Antoshchenko"
|
| 7 |
+
SPDX-License-Identifier = "MIT"
|
| 8 |
+
|
| 9 |
+
[[annotations]]
|
| 10 |
+
path = ["README.md"]
|
| 11 |
+
precedence = "aggregate"
|
| 12 |
+
SPDX-FileCopyrightText = "Copyright © 2026 Idiap Research Institute <contact@idiap.ch>"
|
| 13 |
+
SPDX-License-Identifier = "GPL-3.0-or-later"
|
app.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2025 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Francois Poh <francois.poh22@imperial.ac.uk>
|
| 4 |
+
# SPDX-FileContributor: Samuel Michel <samuel.michel@idiap.ch>
|
| 5 |
+
|
| 6 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 7 |
+
#
|
| 8 |
+
# ArtFace Demo — Minimal, single-column professional UI
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import time
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import torch
|
| 16 |
+
import gradio as gr
|
| 17 |
+
|
| 18 |
+
import onnxruntime as ort
|
| 19 |
+
from lib.models import get_model
|
| 20 |
+
from lib.align import get_preprocessor
|
| 21 |
+
|
| 22 |
+
ort.set_default_logger_severity(3)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# =====================================================
|
| 26 |
+
# Configuration
|
| 27 |
+
# =====================================================
|
| 28 |
+
MODEL_VARIANTS = ["clip", "lora", "ires100", "ires100-tune"]
|
| 29 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 30 |
+
|
| 31 |
+
PROJECT_URL = "https://www.idiap.ch/paper/artface/"
|
| 32 |
+
ARXIV_URL = "https://arxiv.org/abs/2508.20626"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# =====================================================
|
| 36 |
+
# Minimal styling (clean, neutral, high-contrast)
|
| 37 |
+
# =====================================================
|
| 38 |
+
PRIMARY = "#F97316"
|
| 39 |
+
BG = "#FBFBFC"
|
| 40 |
+
CARD = "#FFFFFF"
|
| 41 |
+
BORDER = "#E7E7EA"
|
| 42 |
+
TEXT = "#0B1220"
|
| 43 |
+
MUTED = "#556070"
|
| 44 |
+
|
| 45 |
+
CSS = f"""
|
| 46 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');
|
| 47 |
+
|
| 48 |
+
body, .gradio-container {{
|
| 49 |
+
background: {BG};
|
| 50 |
+
font-family: 'Inter', sans-serif;
|
| 51 |
+
color: {TEXT};
|
| 52 |
+
}}
|
| 53 |
+
|
| 54 |
+
#wrap {{
|
| 55 |
+
max-width: 980px;
|
| 56 |
+
margin: 0 auto;
|
| 57 |
+
}}
|
| 58 |
+
|
| 59 |
+
.gr-block, .gr-box, .gr-panel {{
|
| 60 |
+
background: {CARD} !important;
|
| 61 |
+
border: 1px solid {BORDER} !important;
|
| 62 |
+
border-radius: 16px !important;
|
| 63 |
+
box-shadow: none !important;
|
| 64 |
+
}}
|
| 65 |
+
|
| 66 |
+
.gr-form, .gr-group {{
|
| 67 |
+
border-radius: 16px !important;
|
| 68 |
+
}}
|
| 69 |
+
|
| 70 |
+
.gr-input, .gr-text-input, .gr-dropdown, .gr-number, .gr-slider {{
|
| 71 |
+
border-radius: 12px !important;
|
| 72 |
+
}}
|
| 73 |
+
|
| 74 |
+
.gr-button-primary {{
|
| 75 |
+
background: {TEXT} !important;
|
| 76 |
+
border: 1px solid {TEXT} !important;
|
| 77 |
+
color: white !important;
|
| 78 |
+
font-weight: 800 !important;
|
| 79 |
+
border-radius: 12px !important;
|
| 80 |
+
}}
|
| 81 |
+
|
| 82 |
+
.gr-button-primary:hover {{
|
| 83 |
+
opacity: .92;
|
| 84 |
+
}}
|
| 85 |
+
|
| 86 |
+
.gr-button-secondary, .gr-button {{
|
| 87 |
+
border-radius: 12px !important;
|
| 88 |
+
}}
|
| 89 |
+
|
| 90 |
+
.kicker {{
|
| 91 |
+
display:flex;
|
| 92 |
+
align-items:center;
|
| 93 |
+
justify-content:space-between;
|
| 94 |
+
gap: 1rem;
|
| 95 |
+
padding: 1.1rem 1.2rem .7rem 1.2rem;
|
| 96 |
+
}}
|
| 97 |
+
|
| 98 |
+
.brand {{
|
| 99 |
+
display:flex;
|
| 100 |
+
flex-direction:column;
|
| 101 |
+
gap: .25rem;
|
| 102 |
+
}}
|
| 103 |
+
|
| 104 |
+
.title {{
|
| 105 |
+
font-size: 1.7rem;
|
| 106 |
+
font-weight: 900;
|
| 107 |
+
letter-spacing: -0.02em;
|
| 108 |
+
line-height: 1.1;
|
| 109 |
+
}}
|
| 110 |
+
|
| 111 |
+
.subtitle {{
|
| 112 |
+
color: {MUTED};
|
| 113 |
+
font-weight: 650;
|
| 114 |
+
font-size: .95rem;
|
| 115 |
+
}}
|
| 116 |
+
|
| 117 |
+
.chips {{
|
| 118 |
+
display:flex;
|
| 119 |
+
gap: .5rem;
|
| 120 |
+
flex-wrap:wrap;
|
| 121 |
+
justify-content:flex-end;
|
| 122 |
+
}}
|
| 123 |
+
|
| 124 |
+
.chip {{
|
| 125 |
+
border: 1px solid {BORDER};
|
| 126 |
+
border-radius: 999px;
|
| 127 |
+
padding: .25rem .6rem;
|
| 128 |
+
font-weight: 800;
|
| 129 |
+
font-size: .8rem;
|
| 130 |
+
color: {MUTED};
|
| 131 |
+
background: #fff;
|
| 132 |
+
}}
|
| 133 |
+
|
| 134 |
+
.links {{
|
| 135 |
+
padding: 0 1.2rem 1.1rem 1.2rem;
|
| 136 |
+
display:flex;
|
| 137 |
+
gap: 1rem;
|
| 138 |
+
flex-wrap:wrap;
|
| 139 |
+
}}
|
| 140 |
+
|
| 141 |
+
.links a {{
|
| 142 |
+
color: {TEXT};
|
| 143 |
+
text-decoration: none;
|
| 144 |
+
font-weight: 800;
|
| 145 |
+
border-bottom: 1px solid rgba(11,18,32,.15);
|
| 146 |
+
}}
|
| 147 |
+
|
| 148 |
+
.links a:hover {{
|
| 149 |
+
border-bottom-color: rgba(11,18,32,.5);
|
| 150 |
+
}}
|
| 151 |
+
|
| 152 |
+
.section {{
|
| 153 |
+
padding: 1.1rem 1.2rem 1.2rem 1.2rem;
|
| 154 |
+
}}
|
| 155 |
+
|
| 156 |
+
.section h3 {{
|
| 157 |
+
margin: 0 0 .35rem 0;
|
| 158 |
+
font-size: 1rem;
|
| 159 |
+
font-weight: 900;
|
| 160 |
+
}}
|
| 161 |
+
|
| 162 |
+
.hint {{
|
| 163 |
+
margin-top: -.15rem;
|
| 164 |
+
color: {MUTED};
|
| 165 |
+
font-weight: 650;
|
| 166 |
+
font-size: .92rem;
|
| 167 |
+
}}
|
| 168 |
+
|
| 169 |
+
.divider {{
|
| 170 |
+
height: 1px;
|
| 171 |
+
background: rgba(11,18,32,.08);
|
| 172 |
+
margin: 0 1.2rem;
|
| 173 |
+
}}
|
| 174 |
+
|
| 175 |
+
.alert {{
|
| 176 |
+
border-radius: 14px;
|
| 177 |
+
padding: .85rem 1rem;
|
| 178 |
+
border: 1px solid {BORDER};
|
| 179 |
+
background: #fff;
|
| 180 |
+
font-weight: 750;
|
| 181 |
+
}}
|
| 182 |
+
|
| 183 |
+
.alert-error {{
|
| 184 |
+
border-color: rgba(220,38,38,.25);
|
| 185 |
+
background: rgba(220,38,38,.05);
|
| 186 |
+
}}
|
| 187 |
+
|
| 188 |
+
.alert-info {{
|
| 189 |
+
border-color: rgba(59,130,246,.22);
|
| 190 |
+
background: rgba(59,130,246,.05);
|
| 191 |
+
}}
|
| 192 |
+
|
| 193 |
+
.fused {{
|
| 194 |
+
display:flex;
|
| 195 |
+
align-items:center;
|
| 196 |
+
justify-content:space-between;
|
| 197 |
+
gap: 1rem;
|
| 198 |
+
padding: 1rem;
|
| 199 |
+
border-radius: 16px;
|
| 200 |
+
border: 1px solid {BORDER};
|
| 201 |
+
background: #fff;
|
| 202 |
+
}}
|
| 203 |
+
|
| 204 |
+
.fused-left {{
|
| 205 |
+
display:flex;
|
| 206 |
+
flex-direction:column;
|
| 207 |
+
gap:.15rem;
|
| 208 |
+
}}
|
| 209 |
+
|
| 210 |
+
.fused-title {{
|
| 211 |
+
font-weight: 950;
|
| 212 |
+
font-size: 1.05rem;
|
| 213 |
+
}}
|
| 214 |
+
|
| 215 |
+
.fused-meta {{
|
| 216 |
+
color: {MUTED};
|
| 217 |
+
font-weight: 700;
|
| 218 |
+
font-size: .9rem;
|
| 219 |
+
}}
|
| 220 |
+
|
| 221 |
+
.big {{
|
| 222 |
+
font-size: 2.0rem;
|
| 223 |
+
font-weight: 950;
|
| 224 |
+
letter-spacing: -0.02em;
|
| 225 |
+
}}
|
| 226 |
+
|
| 227 |
+
.pill {{
|
| 228 |
+
border: 1px solid {BORDER};
|
| 229 |
+
border-radius: 999px;
|
| 230 |
+
padding: .25rem .65rem;
|
| 231 |
+
font-weight: 900;
|
| 232 |
+
font-size: .85rem;
|
| 233 |
+
color: {MUTED};
|
| 234 |
+
background: #fff;
|
| 235 |
+
width: fit-content;
|
| 236 |
+
}}
|
| 237 |
+
|
| 238 |
+
.pill-ok {{
|
| 239 |
+
color: #14532d;
|
| 240 |
+
border-color: rgba(21,128,61,.22);
|
| 241 |
+
background: rgba(21,128,61,.06);
|
| 242 |
+
}}
|
| 243 |
+
|
| 244 |
+
.pill-warn {{
|
| 245 |
+
color: #713f12;
|
| 246 |
+
border-color: rgba(202,138,4,.25);
|
| 247 |
+
background: rgba(202,138,4,.07);
|
| 248 |
+
}}
|
| 249 |
+
|
| 250 |
+
.pill-bad {{
|
| 251 |
+
color: #7f1d1d;
|
| 252 |
+
border-color: rgba(220,38,38,.22);
|
| 253 |
+
background: rgba(220,38,38,.06);
|
| 254 |
+
}}
|
| 255 |
+
|
| 256 |
+
.footer {{
|
| 257 |
+
text-align:center;
|
| 258 |
+
color: {MUTED};
|
| 259 |
+
font-weight: 650;
|
| 260 |
+
padding: .6rem 0 1.2rem 0;
|
| 261 |
+
font-size: .9rem;
|
| 262 |
+
}}
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
TITLE_HTML = f"""
|
| 267 |
+
<div id="wrap">
|
| 268 |
+
<div class="kicker">
|
| 269 |
+
<div class="brand">
|
| 270 |
+
<div class="title"><span style="color:{PRIMARY};">ArtFace</span> Demo</div>
|
| 271 |
+
<div class="subtitle">Historical portrait face identification via model adaptation</div>
|
| 272 |
+
</div>
|
| 273 |
+
<div class="chips">
|
| 274 |
+
<div class="chip">Single-page</div>
|
| 275 |
+
<div class="chip">Minimal UI</div>
|
| 276 |
+
<div class="chip">GPU: {"ON" if torch.cuda.is_available() else "OFF"}</div>
|
| 277 |
+
</div>
|
| 278 |
+
</div>
|
| 279 |
+
<div class="links">
|
| 280 |
+
<a href="{PROJECT_URL}" target="_blank" rel="noreferrer">Project / Code / Paper</a>
|
| 281 |
+
<a href="{ARXIV_URL}" target="_blank" rel="noreferrer">arXiv:2508.20626</a>
|
| 282 |
+
</div>
|
| 283 |
+
</div>
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# =====================================================
|
| 288 |
+
# Loading Models / Aligner
|
| 289 |
+
# =====================================================
|
| 290 |
+
aligner = get_preprocessor("align")
|
| 291 |
+
|
| 292 |
+
MODELS: dict[str, tuple[torch.nn.Module, callable]] = {}
|
| 293 |
+
for name in MODEL_VARIANTS:
|
| 294 |
+
model, preprocess = get_model(name).torch()
|
| 295 |
+
model.eval()
|
| 296 |
+
model.to(DEVICE)
|
| 297 |
+
MODELS[name] = (model, preprocess)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# =====================================================
|
| 301 |
+
# Helpers
|
| 302 |
+
# =====================================================
|
| 303 |
+
def render_alert(msg: str, kind: str = "error") -> str:
|
| 304 |
+
cls = "alert alert-error" if kind == "error" else "alert alert-info"
|
| 305 |
+
icon = "⚠️" if kind == "error" else "ℹ️"
|
| 306 |
+
return f"""<div class="{cls}">{icon} {msg}</div>"""
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def pill_class_for_score(s: float) -> str:
|
| 310 |
+
if s >= 0.80:
|
| 311 |
+
return "pill pill-ok"
|
| 312 |
+
if s >= 0.50:
|
| 313 |
+
return "pill pill-warn"
|
| 314 |
+
return "pill pill-bad"
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def fuse(scores: list[float], method: str) -> float:
|
| 318 |
+
if not scores:
|
| 319 |
+
return 0.0
|
| 320 |
+
arr = np.asarray(scores, dtype=np.float32)
|
| 321 |
+
if method == "median":
|
| 322 |
+
return float(np.median(arr))
|
| 323 |
+
if method == "max":
|
| 324 |
+
return float(np.max(arr))
|
| 325 |
+
return float(np.mean(arr))
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def scores_to_table(scores: dict[str, float]) -> pd.DataFrame:
|
| 329 |
+
rows = [
|
| 330 |
+
{
|
| 331 |
+
"Model": k,
|
| 332 |
+
"Similarity": round(float(v), 4),
|
| 333 |
+
"Percent": f"{int(round(v * 100))}%",
|
| 334 |
+
"Band": "High" if v >= 0.80 else ("Medium" if v >= 0.50 else "Low"),
|
| 335 |
+
}
|
| 336 |
+
for k, v in scores.items()
|
| 337 |
+
]
|
| 338 |
+
df = pd.DataFrame(rows)
|
| 339 |
+
if not df.empty:
|
| 340 |
+
df = df.sort_values("Similarity", ascending=False, ignore_index=True)
|
| 341 |
+
return df
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def render_fused_html(fused_score: float, elapsed: float, threshold: float) -> str:
|
| 345 |
+
pct = int(round(fused_score * 100))
|
| 346 |
+
verdict = "Likely match" if fused_score >= threshold else "Uncertain / no match"
|
| 347 |
+
pill_cls = pill_class_for_score(fused_score)
|
| 348 |
+
return f"""
|
| 349 |
+
<div class="fused">
|
| 350 |
+
<div class="fused-left">
|
| 351 |
+
<div class="fused-title">Fused Similarity</div>
|
| 352 |
+
<div class="fused-meta">Fusion threshold: <b>{threshold:.2f}</b> · ⏱ {elapsed:.3f}s</div>
|
| 353 |
+
<div class="{pill_cls}">{verdict}</div>
|
| 354 |
+
</div>
|
| 355 |
+
<div class="big">{pct}%</div>
|
| 356 |
+
</div>
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
# =====================================================
|
| 361 |
+
# Core compare
|
| 362 |
+
# =====================================================
|
| 363 |
+
def compare_faces(img1, img2, selected_models, fuse_method, threshold):
|
| 364 |
+
empty_df = pd.DataFrame(columns=["Model", "Similarity", "Percent", "Band"])
|
| 365 |
+
|
| 366 |
+
if img1 is None or img2 is None:
|
| 367 |
+
return None, None, render_alert("Upload both images to compare."), empty_df
|
| 368 |
+
|
| 369 |
+
selected_models = selected_models or []
|
| 370 |
+
if not selected_models:
|
| 371 |
+
return (
|
| 372 |
+
None,
|
| 373 |
+
None,
|
| 374 |
+
render_alert("Select at least one model in Advanced settings.", "info"),
|
| 375 |
+
empty_df,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
a1 = aligner(img1)
|
| 379 |
+
a2 = aligner(img2)
|
| 380 |
+
if a1 is None or a2 is None:
|
| 381 |
+
return (
|
| 382 |
+
None,
|
| 383 |
+
None,
|
| 384 |
+
render_alert("No face detected in one or both images. Try a clearer crop."),
|
| 385 |
+
empty_df,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
start = time.time()
|
| 389 |
+
scores: dict[str, float] = {}
|
| 390 |
+
|
| 391 |
+
for name in selected_models:
|
| 392 |
+
model, preprocess = MODELS[name]
|
| 393 |
+
|
| 394 |
+
x1 = preprocess(a1).unsqueeze(0).to(DEVICE)
|
| 395 |
+
x2 = preprocess(a2).unsqueeze(0).to(DEVICE)
|
| 396 |
+
|
| 397 |
+
with torch.no_grad():
|
| 398 |
+
e1 = model(x1)[0]
|
| 399 |
+
e2 = model(x2)[0]
|
| 400 |
+
|
| 401 |
+
e1 = e1.detach().cpu().numpy()
|
| 402 |
+
e2 = e2.detach().cpu().numpy()
|
| 403 |
+
denom = (np.linalg.norm(e1) * np.linalg.norm(e2)) + 1e-12
|
| 404 |
+
scores[name] = float(np.dot(e1, e2) / denom)
|
| 405 |
+
|
| 406 |
+
if torch.cuda.is_available():
|
| 407 |
+
torch.cuda.synchronize()
|
| 408 |
+
|
| 409 |
+
fused_score = fuse(list(scores.values()), fuse_method)
|
| 410 |
+
elapsed = time.time() - start
|
| 411 |
+
|
| 412 |
+
html = render_fused_html(fused_score, elapsed, threshold)
|
| 413 |
+
table = scores_to_table(scores)
|
| 414 |
+
return a1, a2, html, table
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# =====================================================
|
| 418 |
+
# UI (single column)
|
| 419 |
+
# =====================================================
|
| 420 |
+
theme = gr.themes.Soft(
|
| 421 |
+
primary_hue="orange",
|
| 422 |
+
neutral_hue="slate",
|
| 423 |
+
radius_size="lg",
|
| 424 |
+
font=["Inter", "ui-sans-serif", "system-ui"],
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
with gr.Blocks(css=CSS, title="ArtFace Demo", theme=theme) as demo:
|
| 428 |
+
gr.HTML(TITLE_HTML)
|
| 429 |
+
|
| 430 |
+
with gr.Group(elem_id="wrap"):
|
| 431 |
+
# --- Inputs ---
|
| 432 |
+
gr.HTML('<div class="divider"></div>')
|
| 433 |
+
with gr.Group():
|
| 434 |
+
gr.HTML(
|
| 435 |
+
'<div class="section"><h3>Inputs</h3><div class="hint">Upload two images. The demo aligns the largest detected face.</div></div>'
|
| 436 |
+
)
|
| 437 |
+
with gr.Row():
|
| 438 |
+
img1 = gr.Image(label="Image A", type="pil", height=320)
|
| 439 |
+
img2 = gr.Image(label="Image B", type="pil", height=320)
|
| 440 |
+
|
| 441 |
+
with gr.Row():
|
| 442 |
+
btn = gr.Button("Compare", variant="primary")
|
| 443 |
+
clear = gr.ClearButton([img1, img2], value="Clear")
|
| 444 |
+
|
| 445 |
+
# --- Advanced ---
|
| 446 |
+
with gr.Accordion("Advanced", open=False):
|
| 447 |
+
selected_models = gr.CheckboxGroup(
|
| 448 |
+
choices=MODEL_VARIANTS,
|
| 449 |
+
value=MODEL_VARIANTS,
|
| 450 |
+
label="Models",
|
| 451 |
+
)
|
| 452 |
+
fuse_method = gr.Radio(
|
| 453 |
+
["mean", "median", "max"],
|
| 454 |
+
value="mean",
|
| 455 |
+
label="Fusion",
|
| 456 |
+
)
|
| 457 |
+
threshold = gr.Slider(
|
| 458 |
+
minimum=0.0,
|
| 459 |
+
maximum=1.0,
|
| 460 |
+
value=0.75,
|
| 461 |
+
step=0.01,
|
| 462 |
+
label="Threshold",
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# --- Outputs ---
|
| 466 |
+
gr.HTML('<div class="divider"></div>')
|
| 467 |
+
gr.HTML(
|
| 468 |
+
'<div class="section"><h3>Outputs</h3><div class="hint">Aligned crops are shown for transparency. Scores are cosine similarity.</div></div>'
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
with gr.Row():
|
| 472 |
+
out1 = gr.Image(label="Aligned A", height=160)
|
| 473 |
+
out2 = gr.Image(label="Aligned B", height=160)
|
| 474 |
+
|
| 475 |
+
fused_html = gr.HTML(
|
| 476 |
+
render_alert("Upload two images, then click Compare.", "info")
|
| 477 |
+
)
|
| 478 |
+
scores_table = gr.Dataframe(
|
| 479 |
+
headers=["Model", "Similarity", "Percent", "Band"],
|
| 480 |
+
datatype=["str", "number", "str", "str"],
|
| 481 |
+
label="Per-model scores",
|
| 482 |
+
row_count=(0, "dynamic"),
|
| 483 |
+
col_count=(4, "fixed"),
|
| 484 |
+
wrap=True,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
gr.Markdown(
|
| 488 |
+
'<div class="footer"> Research demo · See links above for project page and paper</div>'
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
btn.click(
|
| 492 |
+
compare_faces,
|
| 493 |
+
inputs=[img1, img2, selected_models, fuse_method, threshold],
|
| 494 |
+
outputs=[out1, out2, fused_html, scores_table],
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
if __name__ == "__main__":
|
| 498 |
+
demo.launch(share=True)
|
lib/ModelWrappers.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2025 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Francois Poh <francois.poh22@imperial.ac.uk>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
# ArtFace contains the code for the paper: https://www.idiap.ch/paper/artface/
|
| 8 |
+
# It provides a facial recognition model for historical portraits, and scripts to reproduce the experiments in the paper.
|
| 9 |
+
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FaceLossHead(nn.Module):
|
| 18 |
+
def __init__(self, in_features, out_features, scale, margin, mode):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.mode = mode
|
| 21 |
+
if mode not in ("cosface", "arcface"):
|
| 22 |
+
raise ValueError(f"Unsupported mode: {mode}. Use 'cosface' or 'arcface'.")
|
| 23 |
+
self.scale = scale
|
| 24 |
+
self.margin = margin or (0.35 if mode == "cosface" else 0.5)
|
| 25 |
+
self.weight = nn.Parameter(torch.FloatTensor(out_features, in_features))
|
| 26 |
+
nn.init.xavier_uniform_(self.weight)
|
| 27 |
+
|
| 28 |
+
def forward(self, features, labels):
|
| 29 |
+
if self.mode == "cosface":
|
| 30 |
+
return self.cosface_forward(features, labels)
|
| 31 |
+
elif self.mode == "arcface":
|
| 32 |
+
return self.arcface_forward(features, labels)
|
| 33 |
+
|
| 34 |
+
def cosface_forward(self, features, labels):
|
| 35 |
+
cosine = F.linear(F.normalize(features), F.normalize(self.weight))
|
| 36 |
+
one_hot = torch.zeros_like(cosine)
|
| 37 |
+
one_hot.scatter_(1, labels.view(-1, 1), 1)
|
| 38 |
+
output = self.scale * (cosine - one_hot * self.margin)
|
| 39 |
+
return output
|
| 40 |
+
|
| 41 |
+
def arcface_forward(self, features, labels):
|
| 42 |
+
cosine = F.linear(F.normalize(features), F.normalize(self.weight))
|
| 43 |
+
one_hot = torch.zeros_like(cosine)
|
| 44 |
+
one_hot.scatter_(1, labels.view(-1, 1), 1)
|
| 45 |
+
theta = torch.acos(cosine.clamp(-1.0, 1.0))
|
| 46 |
+
target_theta = theta + self.margin
|
| 47 |
+
output = self.scale * torch.cos(target_theta) * one_hot + cosine * (1 - one_hot)
|
| 48 |
+
return output
|
| 49 |
+
|
| 50 |
+
def to(self, device):
|
| 51 |
+
super().to(device)
|
| 52 |
+
self.weight = self.weight.to(device)
|
| 53 |
+
return self
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class FaceLossWrapper(nn.Module):
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
backbone,
|
| 60 |
+
input_shape,
|
| 61 |
+
out_features,
|
| 62 |
+
scale=64.0,
|
| 63 |
+
margin=None,
|
| 64 |
+
mode="cosface",
|
| 65 |
+
):
|
| 66 |
+
super().__init__()
|
| 67 |
+
margin = margin or (0.35 if mode == "cosface" else 0.5)
|
| 68 |
+
self.backbone = backbone
|
| 69 |
+
self.device = backbone.device
|
| 70 |
+
dummy = torch.zeros(*input_shape).to(backbone.device)
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
feat = self.backbone(dummy)
|
| 73 |
+
if isinstance(feat, (tuple, list)):
|
| 74 |
+
feat = feat[0]
|
| 75 |
+
in_features = feat.shape[-1]
|
| 76 |
+
self.head = FaceLossHead(in_features, out_features, scale, margin, mode).to(
|
| 77 |
+
backbone.device
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def forward(self, x, labels=None):
|
| 81 |
+
features = self.backbone(x)
|
| 82 |
+
if self.training and labels is not None:
|
| 83 |
+
return self.head(features, labels)
|
| 84 |
+
return features
|
| 85 |
+
|
| 86 |
+
def save_pretrained(self, path):
|
| 87 |
+
self.backbone.save_pretrained(path)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class FusionModelWrapper(nn.Module):
|
| 91 |
+
def __init__(self, models, model_names, device="cuda"):
|
| 92 |
+
super().__init__(device)
|
| 93 |
+
counts = defaultdict(int)
|
| 94 |
+
self.model_names = []
|
| 95 |
+
for name in model_names:
|
| 96 |
+
self.model_names.append(f"{name}_{counts[name]}")
|
| 97 |
+
counts[name] += 1
|
| 98 |
+
for name, model in zip(self.model_names, models):
|
| 99 |
+
self.set_submodel(name, model.torch()[0])
|
| 100 |
+
|
| 101 |
+
def forward(self, xs):
|
| 102 |
+
models = (self.get_submodel(name) for name in self.model_names)
|
| 103 |
+
embeddings = [F.normalize((model(x)), dim=-1) for model, x in zip(models, xs)]
|
| 104 |
+
x = torch.cat(embeddings, dim=-1)
|
| 105 |
+
return F.normalize(x, dim=-1)
|
| 106 |
+
|
| 107 |
+
def named_submodels(self):
|
| 108 |
+
return [(name, self.get_submodel(name)) for name in self.model_names]
|
| 109 |
+
|
| 110 |
+
def save_pretrained(self, path):
|
| 111 |
+
for name, submodel in self.named_submodels():
|
| 112 |
+
Path(f"{path}/{name}").mkdir(parents=True, exist_ok=True)
|
| 113 |
+
submodel.save_pretrained(f"{path}/{name}")
|
| 114 |
+
|
| 115 |
+
def get_submodel(self, name):
|
| 116 |
+
return getattr(self, name)
|
| 117 |
+
|
| 118 |
+
def set_submodel(self, name, model):
|
| 119 |
+
return setattr(self, name, model)
|
lib/__init__.py
ADDED
|
File without changes
|
lib/align.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2025 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Francois Poh <francois.poh22@imperial.ac.uk>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
# ArtFace contains the code for the paper: https://www.idiap.ch/paper/artface/
|
| 8 |
+
# It provides a facial recognition model for historical portraits, and scripts to reproduce the experiments in the paper.
|
| 9 |
+
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import cv2
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ImagePreprocessor:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
def __call__(self, image):
|
| 21 |
+
# --------------------
|
| 22 |
+
# Accept path OR PIL image
|
| 23 |
+
# --------------------
|
| 24 |
+
if isinstance(image, str):
|
| 25 |
+
image = Image.open(image).convert("RGB")
|
| 26 |
+
elif isinstance(image, Image.Image):
|
| 27 |
+
image = image.convert("RGB")
|
| 28 |
+
else:
|
| 29 |
+
raise TypeError(
|
| 30 |
+
f"Unsupported input type {type(image)}. "
|
| 31 |
+
"Expected file path or PIL.Image."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
return self.process(image)
|
| 35 |
+
|
| 36 |
+
def process(self, image):
|
| 37 |
+
raise NotImplementedError("Subclasses should implement this method.")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class FaceAligner(ImagePreprocessor):
|
| 41 |
+
def __init__(self, detector="buffalo_l", crop_size=(112, 112), padding=0):
|
| 42 |
+
crop_size = tuple(map(int, crop_size))
|
| 43 |
+
super().__init__()
|
| 44 |
+
|
| 45 |
+
from lib.face_alignment import mtcnn
|
| 46 |
+
from insightface.app import FaceAnalysis
|
| 47 |
+
|
| 48 |
+
# --------------------
|
| 49 |
+
# Device selection
|
| 50 |
+
# --------------------
|
| 51 |
+
self.use_cuda = torch.cuda.is_available()
|
| 52 |
+
|
| 53 |
+
if self.use_cuda:
|
| 54 |
+
device = "cuda:0"
|
| 55 |
+
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 56 |
+
ctx_id = 0
|
| 57 |
+
else:
|
| 58 |
+
device = "cpu"
|
| 59 |
+
providers = ["CPUExecutionProvider"]
|
| 60 |
+
ctx_id = -1
|
| 61 |
+
|
| 62 |
+
# --------------------
|
| 63 |
+
# MTCNN (landmark warping)
|
| 64 |
+
# --------------------
|
| 65 |
+
self.mtcnn = mtcnn.MTCNN(
|
| 66 |
+
device=device,
|
| 67 |
+
crop_size=tuple(int(s) for s in crop_size),
|
| 68 |
+
padding=float(padding),
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# --------------------
|
| 72 |
+
# InsightFace detector
|
| 73 |
+
# --------------------
|
| 74 |
+
self.detector = FaceAnalysis(
|
| 75 |
+
name=detector,
|
| 76 |
+
root=".",
|
| 77 |
+
providers=providers,
|
| 78 |
+
)
|
| 79 |
+
self.detector.prepare(ctx_id=ctx_id)
|
| 80 |
+
|
| 81 |
+
print(
|
| 82 |
+
f"✅ FaceAligner initialized | "
|
| 83 |
+
f"CUDA: {self.use_cuda} | "
|
| 84 |
+
f"providers: {providers}"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def process(self, image):
|
| 88 |
+
from lib.face_alignment import mtcnn
|
| 89 |
+
|
| 90 |
+
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 91 |
+
|
| 92 |
+
# Detect face
|
| 93 |
+
_, kpss = self.detector.det_model.detect(image, max_num=1, metric="default")
|
| 94 |
+
|
| 95 |
+
if kpss is None or len(kpss) == 0:
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
# Convert landmarks
|
| 99 |
+
landmarks = np.array(
|
| 100 |
+
[np.concatenate([kpss[:, :, 0][0], kpss[:, :, 1][0]], axis=0)]
|
| 101 |
+
)
|
| 102 |
+
facial5points = [[landmarks[0][j], landmarks[0][j + 5]] for j in range(5)]
|
| 103 |
+
|
| 104 |
+
# Warp & crop
|
| 105 |
+
warped_face = mtcnn.warp_and_crop_face(
|
| 106 |
+
image,
|
| 107 |
+
facial5points,
|
| 108 |
+
self.mtcnn.refrence,
|
| 109 |
+
crop_size=self.mtcnn.crop_size,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
rgb_face = cv2.cvtColor(warped_face, cv2.COLOR_BGR2RGB)
|
| 113 |
+
return Image.fromarray(rgb_face)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
preprocessors = {
|
| 117 |
+
"align": (FaceAligner, {"crop_size": (112, 112)}),
|
| 118 |
+
"align-224": (FaceAligner, {"crop_size": (224, 224)}),
|
| 119 |
+
"align-pad": (FaceAligner, {"crop_size": (224, 224), "padding": 0.5}),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_preprocessor(name, args={}):
|
| 124 |
+
model_args = {}
|
| 125 |
+
if isinstance(args, list):
|
| 126 |
+
for arg in args:
|
| 127 |
+
if "=" not in arg:
|
| 128 |
+
raise ValueError(
|
| 129 |
+
f"Invalid argument format for model arguments. Expected 'key=value' pairs, got '{arg}'."
|
| 130 |
+
)
|
| 131 |
+
key, value = arg.split("=", 1)
|
| 132 |
+
value = value.strip("'")
|
| 133 |
+
if "," in value:
|
| 134 |
+
value = [v.strip("'") for v in value.split(",")]
|
| 135 |
+
model_args[key] = value
|
| 136 |
+
if name in preprocessors:
|
| 137 |
+
return preprocessors[name][0](**{**preprocessors[name][1], **model_args})
|
| 138 |
+
else:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
f"Unknown preprocessor: {name}\n Please choose from: {', '.join(preprocessors.keys())}"
|
| 141 |
+
)
|
lib/face_alignment/README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright © 2022 Minchul Kim
|
| 3 |
+
|
| 4 |
+
# SPDX-License-Identifier: MIT
|
| 5 |
+
-->
|
| 6 |
+
|
| 7 |
+
Face alignment script is from [AdaFace](https://github.com/mk-minchul/AdaFace)
|
| 8 |
+
repositpry: https://github.com/mk-minchul/AdaFace/tree/master/face_alignment
|
lib/face_alignment/mtcnn.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2022 Minchul Kim
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
from typing import Tuple
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 14 |
+
|
| 15 |
+
from mtcnn_pytorch.src.get_nets import PNet, RNet, ONet
|
| 16 |
+
from mtcnn_pytorch.src.box_utils import (
|
| 17 |
+
nms,
|
| 18 |
+
calibrate_box,
|
| 19 |
+
get_image_boxes,
|
| 20 |
+
convert_to_square,
|
| 21 |
+
)
|
| 22 |
+
from mtcnn_pytorch.src.first_stage import run_first_stage
|
| 23 |
+
from mtcnn_pytorch.src.align_trans import (
|
| 24 |
+
get_reference_facial_points,
|
| 25 |
+
warp_and_crop_face,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class MTCNN:
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
device: str = "cuda:0",
|
| 33 |
+
crop_size: Tuple[int, int] = (112, 112),
|
| 34 |
+
padding: int = 0,
|
| 35 |
+
):
|
| 36 |
+
assert device in ["cuda:0", "cpu"]
|
| 37 |
+
self.device = torch.device(device)
|
| 38 |
+
assert crop_size in [(112, 112), (96, 112), (224, 224), (336, 336)]
|
| 39 |
+
self.crop_size = crop_size
|
| 40 |
+
|
| 41 |
+
# change working dir to this file location to load npz files. Then switch back
|
| 42 |
+
cwd = os.getcwd()
|
| 43 |
+
os.chdir(os.path.dirname(__file__))
|
| 44 |
+
|
| 45 |
+
self.pnet = PNet().to(self.device)
|
| 46 |
+
self.rnet = RNet().to(self.device)
|
| 47 |
+
self.onet = ONet().to(self.device)
|
| 48 |
+
self.pnet.eval()
|
| 49 |
+
self.rnet.eval()
|
| 50 |
+
self.onet.eval()
|
| 51 |
+
self.refrence = get_reference_facial_points(
|
| 52 |
+
default_square=crop_size[0] == crop_size[1],
|
| 53 |
+
) * (crop_size[1] / 112.0)
|
| 54 |
+
self.refrence = (
|
| 55 |
+
np.array(self.refrence, dtype=np.float32)
|
| 56 |
+
- (crop_size[0] / 2, crop_size[1] / 2)
|
| 57 |
+
) / (1 + padding * 2) + (crop_size[0] / 2, crop_size[1] / 2)
|
| 58 |
+
|
| 59 |
+
self.min_face_size = 20
|
| 60 |
+
self.thresholds = [0.6, 0.7, 0.9]
|
| 61 |
+
self.nms_thresholds = [0.7, 0.7, 0.7]
|
| 62 |
+
self.factor = 0.85
|
| 63 |
+
|
| 64 |
+
os.chdir(cwd)
|
| 65 |
+
|
| 66 |
+
def align(self, img):
|
| 67 |
+
_, landmarks = self.detect_faces(
|
| 68 |
+
img, self.min_face_size, self.thresholds, self.nms_thresholds, self.factor
|
| 69 |
+
)
|
| 70 |
+
facial5points = [[landmarks[0][j], landmarks[0][j + 5]] for j in range(5)]
|
| 71 |
+
warped_face = warp_and_crop_face(
|
| 72 |
+
np.array(img), facial5points, self.refrence, crop_size=self.crop_size
|
| 73 |
+
)
|
| 74 |
+
return Image.fromarray(warped_face)
|
| 75 |
+
|
| 76 |
+
def align_multi(self, img, limit=None):
|
| 77 |
+
boxes, landmarks = self.detect_faces(
|
| 78 |
+
img, self.min_face_size, self.thresholds, self.nms_thresholds, self.factor
|
| 79 |
+
)
|
| 80 |
+
if limit:
|
| 81 |
+
boxes = boxes[:limit]
|
| 82 |
+
landmarks = landmarks[:limit]
|
| 83 |
+
faces = []
|
| 84 |
+
for landmark in landmarks:
|
| 85 |
+
facial5points = [[landmark[j], landmark[j + 5]] for j in range(5)]
|
| 86 |
+
warped_face = warp_and_crop_face(
|
| 87 |
+
np.array(img), facial5points, self.refrence, crop_size=self.crop_size
|
| 88 |
+
)
|
| 89 |
+
faces.append(Image.fromarray(warped_face))
|
| 90 |
+
return boxes, faces
|
| 91 |
+
|
| 92 |
+
def detect_faces(self, image, min_face_size, thresholds, nms_thresholds, factor):
|
| 93 |
+
"""
|
| 94 |
+
Arguments:
|
| 95 |
+
image: an instance of PIL.Image.
|
| 96 |
+
min_face_size: a float number.
|
| 97 |
+
thresholds: a list of length 3.
|
| 98 |
+
nms_thresholds: a list of length 3.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
two float numpy arrays of shapes [n_boxes, 4] and [n_boxes, 10],
|
| 102 |
+
bounding boxes and facial landmarks.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
# BUILD AN IMAGE PYRAMID
|
| 106 |
+
width, height = image.size
|
| 107 |
+
min_length = min(height, width)
|
| 108 |
+
|
| 109 |
+
min_detection_size = 12
|
| 110 |
+
# factor = 0.707 # sqrt(0.5)
|
| 111 |
+
|
| 112 |
+
# scales for scaling the image
|
| 113 |
+
scales = []
|
| 114 |
+
|
| 115 |
+
# scales the image so that
|
| 116 |
+
# minimum size that we can detect equals to
|
| 117 |
+
# minimum face size that we want to detect
|
| 118 |
+
m = min_detection_size / min_face_size
|
| 119 |
+
min_length *= m
|
| 120 |
+
|
| 121 |
+
factor_count = 0
|
| 122 |
+
while min_length > min_detection_size:
|
| 123 |
+
scales.append(m * factor**factor_count)
|
| 124 |
+
min_length *= factor
|
| 125 |
+
factor_count += 1
|
| 126 |
+
|
| 127 |
+
# STAGE 1
|
| 128 |
+
|
| 129 |
+
# it will be returned
|
| 130 |
+
bounding_boxes = []
|
| 131 |
+
|
| 132 |
+
with torch.no_grad():
|
| 133 |
+
# run P-Net on different scales
|
| 134 |
+
for s in scales:
|
| 135 |
+
boxes = run_first_stage(
|
| 136 |
+
image, self.pnet, scale=s, threshold=thresholds[0]
|
| 137 |
+
)
|
| 138 |
+
bounding_boxes.append(boxes)
|
| 139 |
+
|
| 140 |
+
# collect boxes (and offsets, and scores) from different scales
|
| 141 |
+
bounding_boxes = [i for i in bounding_boxes if i is not None]
|
| 142 |
+
if len(bounding_boxes) == 0:
|
| 143 |
+
return [], []
|
| 144 |
+
bounding_boxes = np.vstack(bounding_boxes)
|
| 145 |
+
|
| 146 |
+
keep = nms(bounding_boxes[:, 0:5], nms_thresholds[0])
|
| 147 |
+
bounding_boxes = bounding_boxes[keep]
|
| 148 |
+
|
| 149 |
+
# use offsets predicted by pnet to transform bounding boxes
|
| 150 |
+
bounding_boxes = calibrate_box(
|
| 151 |
+
bounding_boxes[:, 0:5], bounding_boxes[:, 5:]
|
| 152 |
+
)
|
| 153 |
+
# shape [n_boxes, 5]
|
| 154 |
+
|
| 155 |
+
bounding_boxes = convert_to_square(bounding_boxes)
|
| 156 |
+
bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
|
| 157 |
+
|
| 158 |
+
# STAGE 2
|
| 159 |
+
|
| 160 |
+
img_boxes = get_image_boxes(bounding_boxes, image, size=24)
|
| 161 |
+
img_boxes = torch.FloatTensor(img_boxes).to(self.device)
|
| 162 |
+
|
| 163 |
+
output = self.rnet(img_boxes)
|
| 164 |
+
offsets = output[0].cpu().data.numpy() # shape [n_boxes, 4]
|
| 165 |
+
probs = output[1].cpu().data.numpy() # shape [n_boxes, 2]
|
| 166 |
+
|
| 167 |
+
keep = np.where(probs[:, 1] > thresholds[1])[0]
|
| 168 |
+
bounding_boxes = bounding_boxes[keep]
|
| 169 |
+
bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
|
| 170 |
+
offsets = offsets[keep]
|
| 171 |
+
|
| 172 |
+
keep = nms(bounding_boxes, nms_thresholds[1])
|
| 173 |
+
bounding_boxes = bounding_boxes[keep]
|
| 174 |
+
bounding_boxes = calibrate_box(bounding_boxes, offsets[keep])
|
| 175 |
+
bounding_boxes = convert_to_square(bounding_boxes)
|
| 176 |
+
bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
|
| 177 |
+
|
| 178 |
+
# STAGE 3
|
| 179 |
+
|
| 180 |
+
img_boxes = get_image_boxes(bounding_boxes, image, size=48)
|
| 181 |
+
if len(img_boxes) == 0:
|
| 182 |
+
return [], []
|
| 183 |
+
img_boxes = torch.FloatTensor(img_boxes).to(self.device)
|
| 184 |
+
output = self.onet(img_boxes)
|
| 185 |
+
landmarks = output[0].cpu().data.numpy() # shape [n_boxes, 10]
|
| 186 |
+
offsets = output[1].cpu().data.numpy() # shape [n_boxes, 4]
|
| 187 |
+
probs = output[2].cpu().data.numpy() # shape [n_boxes, 2]
|
| 188 |
+
|
| 189 |
+
keep = np.where(probs[:, 1] > thresholds[2])[0]
|
| 190 |
+
bounding_boxes = bounding_boxes[keep]
|
| 191 |
+
bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
|
| 192 |
+
offsets = offsets[keep]
|
| 193 |
+
landmarks = landmarks[keep]
|
| 194 |
+
|
| 195 |
+
# compute landmark points
|
| 196 |
+
width = bounding_boxes[:, 2] - bounding_boxes[:, 0] + 1.0
|
| 197 |
+
height = bounding_boxes[:, 3] - bounding_boxes[:, 1] + 1.0
|
| 198 |
+
xmin, ymin = bounding_boxes[:, 0], bounding_boxes[:, 1]
|
| 199 |
+
landmarks[:, 0:5] = (
|
| 200 |
+
np.expand_dims(xmin, 1) + np.expand_dims(width, 1) * landmarks[:, 0:5]
|
| 201 |
+
)
|
| 202 |
+
landmarks[:, 5:10] = (
|
| 203 |
+
np.expand_dims(ymin, 1) + np.expand_dims(height, 1) * landmarks[:, 5:10]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
bounding_boxes = calibrate_box(bounding_boxes, offsets)
|
| 207 |
+
keep = nms(bounding_boxes, nms_thresholds[2], mode="min")
|
| 208 |
+
bounding_boxes = bounding_boxes[keep]
|
| 209 |
+
landmarks = landmarks[keep]
|
| 210 |
+
|
| 211 |
+
return bounding_boxes, landmarks
|
lib/face_alignment/mtcnn_pytorch/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 3 |
+
|
| 4 |
+
# SPDX-License-Identifier: MIT
|
| 5 |
+
-->
|
| 6 |
+
|
| 7 |
+
# MTCNN
|
| 8 |
+
|
| 9 |
+
`pytorch` implementation of **inference stage** of face detection algorithm described in
|
| 10 |
+
[Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks](https://arxiv.org/abs/1604.02878).
|
| 11 |
+
|
| 12 |
+
## Example
|
| 13 |
+

|
| 14 |
+
|
| 15 |
+
## How to use it
|
| 16 |
+
Just download the repository and then do this
|
| 17 |
+
```python
|
| 18 |
+
from src import detect_faces
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
image = Image.open('image.jpg')
|
| 22 |
+
bounding_boxes, landmarks = detect_faces(image)
|
| 23 |
+
```
|
| 24 |
+
For examples see `test_on_images.ipynb`.
|
| 25 |
+
|
| 26 |
+
## Requirements
|
| 27 |
+
* pytorch 0.2
|
| 28 |
+
* Pillow, numpy
|
| 29 |
+
|
| 30 |
+
## Credit
|
| 31 |
+
This implementation is heavily inspired by:
|
| 32 |
+
* [pangyupo/mxnet_mtcnn_face_detection](https://github.com/pangyupo/mxnet_mtcnn_face_detection)
|
lib/face_alignment/mtcnn_pytorch/src/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
from .visualization_utils import show_bboxes
|
| 6 |
+
from .detector import detect_faces
|
lib/face_alignment/mtcnn_pytorch/src/align_trans.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 3 |
+
|
| 4 |
+
# SPDX-License-Identifier: MIT
|
| 5 |
+
"""
|
| 6 |
+
Created on Mon Apr 24 15:43:29 2017
|
| 7 |
+
@author: zhaoy
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import cv2
|
| 12 |
+
|
| 13 |
+
# from scipy.linalg import lstsq
|
| 14 |
+
# from scipy.ndimage import geometric_transform # , map_coordinates
|
| 15 |
+
|
| 16 |
+
from mtcnn_pytorch.src.matlab_cp2tform import get_similarity_transform_for_cv2
|
| 17 |
+
|
| 18 |
+
# reference facial points, a list of coordinates (x,y)
|
| 19 |
+
REFERENCE_FACIAL_POINTS = [
|
| 20 |
+
[30.29459953, 51.69630051],
|
| 21 |
+
[65.53179932, 51.50139999],
|
| 22 |
+
[48.02519989, 71.73660278],
|
| 23 |
+
[33.54930115, 92.3655014],
|
| 24 |
+
[62.72990036, 92.20410156],
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
DEFAULT_CROP_SIZE = (96, 112)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class FaceWarpException(Exception):
|
| 31 |
+
def __str__(self):
|
| 32 |
+
return "In File {}:{}".format(__file__, super.__str__(self))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_reference_facial_points(
|
| 36 |
+
output_size=None,
|
| 37 |
+
inner_padding_factor=0.0,
|
| 38 |
+
outer_padding=(0, 0),
|
| 39 |
+
default_square=False,
|
| 40 |
+
):
|
| 41 |
+
"""
|
| 42 |
+
Function:
|
| 43 |
+
----------
|
| 44 |
+
get reference 5 key points according to crop settings:
|
| 45 |
+
0. Set default crop_size:
|
| 46 |
+
if default_square:
|
| 47 |
+
crop_size = (112, 112)
|
| 48 |
+
else:
|
| 49 |
+
crop_size = (96, 112)
|
| 50 |
+
1. Pad the crop_size by inner_padding_factor in each side;
|
| 51 |
+
2. Resize crop_size into (output_size - outer_padding*2),
|
| 52 |
+
pad into output_size with outer_padding;
|
| 53 |
+
3. Output reference_5point;
|
| 54 |
+
Parameters:
|
| 55 |
+
----------
|
| 56 |
+
@output_size: (w, h) or None
|
| 57 |
+
size of aligned face image
|
| 58 |
+
@inner_padding_factor: (w_factor, h_factor)
|
| 59 |
+
padding factor for inner (w, h)
|
| 60 |
+
@outer_padding: (w_pad, h_pad)
|
| 61 |
+
each row is a pair of coordinates (x, y)
|
| 62 |
+
@default_square: True or False
|
| 63 |
+
if True:
|
| 64 |
+
default crop_size = (112, 112)
|
| 65 |
+
else:
|
| 66 |
+
default crop_size = (96, 112);
|
| 67 |
+
!!! make sure, if output_size is not None:
|
| 68 |
+
(output_size - outer_padding)
|
| 69 |
+
= some_scale * (default crop_size * (1.0 + inner_padding_factor))
|
| 70 |
+
Returns:
|
| 71 |
+
----------
|
| 72 |
+
@reference_5point: 5x2 np.array
|
| 73 |
+
each row is a pair of transformed coordinates (x, y)
|
| 74 |
+
"""
|
| 75 |
+
# print('\n===> get_reference_facial_points():')
|
| 76 |
+
|
| 77 |
+
# print('---> Params:')
|
| 78 |
+
# print(' output_size: ', output_size)
|
| 79 |
+
# print(' inner_padding_factor: ', inner_padding_factor)
|
| 80 |
+
# print(' outer_padding:', outer_padding)
|
| 81 |
+
# print(' default_square: ', default_square)
|
| 82 |
+
|
| 83 |
+
tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)
|
| 84 |
+
tmp_crop_size = np.array(DEFAULT_CROP_SIZE)
|
| 85 |
+
|
| 86 |
+
# 0) make the inner region a square
|
| 87 |
+
if default_square:
|
| 88 |
+
size_diff = max(tmp_crop_size) - tmp_crop_size
|
| 89 |
+
tmp_5pts += size_diff / 2
|
| 90 |
+
tmp_crop_size += size_diff
|
| 91 |
+
|
| 92 |
+
# print('---> default:')
|
| 93 |
+
# print(' crop_size = ', tmp_crop_size)
|
| 94 |
+
# print(' reference_5pts = ', tmp_5pts)
|
| 95 |
+
|
| 96 |
+
if (
|
| 97 |
+
output_size
|
| 98 |
+
and output_size[0] == tmp_crop_size[0]
|
| 99 |
+
and output_size[1] == tmp_crop_size[1]
|
| 100 |
+
):
|
| 101 |
+
# print('output_size == DEFAULT_CROP_SIZE {}: return default reference points'.format(tmp_crop_size))
|
| 102 |
+
return tmp_5pts
|
| 103 |
+
|
| 104 |
+
if inner_padding_factor == 0 and outer_padding == (0, 0):
|
| 105 |
+
if output_size is None:
|
| 106 |
+
# print('No paddings to do: return default reference points')
|
| 107 |
+
return tmp_5pts
|
| 108 |
+
else:
|
| 109 |
+
raise FaceWarpException(
|
| 110 |
+
"No paddings to do, output_size must be None or {}".format(
|
| 111 |
+
tmp_crop_size
|
| 112 |
+
)
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# check output size
|
| 116 |
+
if not (0 <= inner_padding_factor <= 1.0):
|
| 117 |
+
raise FaceWarpException("Not (0 <= inner_padding_factor <= 1.0)")
|
| 118 |
+
|
| 119 |
+
if (
|
| 120 |
+
inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0
|
| 121 |
+
) and output_size is None:
|
| 122 |
+
output_size = tmp_crop_size * (1 + inner_padding_factor * 2).astype(np.int32)
|
| 123 |
+
output_size += np.array(outer_padding)
|
| 124 |
+
# print(' deduced from paddings, output_size = ', output_size)
|
| 125 |
+
|
| 126 |
+
if not (outer_padding[0] < output_size[0] and outer_padding[1] < output_size[1]):
|
| 127 |
+
raise FaceWarpException(
|
| 128 |
+
"Not (outer_padding[0] < output_size[0]"
|
| 129 |
+
"and outer_padding[1] < output_size[1])"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# 1) pad the inner region according inner_padding_factor
|
| 133 |
+
# print('---> STEP1: pad the inner region according inner_padding_factor')
|
| 134 |
+
if inner_padding_factor > 0:
|
| 135 |
+
size_diff = tmp_crop_size * inner_padding_factor * 2
|
| 136 |
+
tmp_5pts += size_diff / 2
|
| 137 |
+
tmp_crop_size += np.round(size_diff).astype(np.int32)
|
| 138 |
+
|
| 139 |
+
# print(' crop_size = ', tmp_crop_size)
|
| 140 |
+
# print(' reference_5pts = ', tmp_5pts)
|
| 141 |
+
|
| 142 |
+
# 2) resize the padded inner region
|
| 143 |
+
# print('---> STEP2: resize the padded inner region')
|
| 144 |
+
size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2
|
| 145 |
+
# print(' crop_size = ', tmp_crop_size)
|
| 146 |
+
# print(' size_bf_outer_pad = ', size_bf_outer_pad)
|
| 147 |
+
|
| 148 |
+
if (
|
| 149 |
+
size_bf_outer_pad[0] * tmp_crop_size[1]
|
| 150 |
+
!= size_bf_outer_pad[1] * tmp_crop_size[0]
|
| 151 |
+
):
|
| 152 |
+
raise FaceWarpException(
|
| 153 |
+
"Must have (output_size - outer_padding)"
|
| 154 |
+
"= some_scale * (crop_size * (1.0 + inner_padding_factor)"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0]
|
| 158 |
+
# print(' resize scale_factor = ', scale_factor)
|
| 159 |
+
tmp_5pts = tmp_5pts * scale_factor
|
| 160 |
+
# size_diff = tmp_crop_size * (scale_factor - min(scale_factor))
|
| 161 |
+
# tmp_5pts = tmp_5pts + size_diff / 2
|
| 162 |
+
tmp_crop_size = size_bf_outer_pad
|
| 163 |
+
# print(' crop_size = ', tmp_crop_size)
|
| 164 |
+
# print(' reference_5pts = ', tmp_5pts)
|
| 165 |
+
|
| 166 |
+
# 3) add outer_padding to make output_size
|
| 167 |
+
reference_5point = tmp_5pts + np.array(outer_padding)
|
| 168 |
+
tmp_crop_size = output_size
|
| 169 |
+
# print('---> STEP3: add outer_padding to make output_size')
|
| 170 |
+
# print(' crop_size = ', tmp_crop_size)
|
| 171 |
+
# print(' reference_5pts = ', tmp_5pts)
|
| 172 |
+
|
| 173 |
+
# print('===> end get_reference_facial_points\n')
|
| 174 |
+
|
| 175 |
+
return reference_5point
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def get_affine_transform_matrix(src_pts, dst_pts):
|
| 179 |
+
"""
|
| 180 |
+
Function:
|
| 181 |
+
----------
|
| 182 |
+
get affine transform matrix 'tfm' from src_pts to dst_pts
|
| 183 |
+
Parameters:
|
| 184 |
+
----------
|
| 185 |
+
@src_pts: Kx2 np.array
|
| 186 |
+
source points matrix, each row is a pair of coordinates (x, y)
|
| 187 |
+
@dst_pts: Kx2 np.array
|
| 188 |
+
destination points matrix, each row is a pair of coordinates (x, y)
|
| 189 |
+
Returns:
|
| 190 |
+
----------
|
| 191 |
+
@tfm: 2x3 np.array
|
| 192 |
+
transform matrix from src_pts to dst_pts
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
tfm = np.float32([[1, 0, 0], [0, 1, 0]])
|
| 196 |
+
n_pts = src_pts.shape[0]
|
| 197 |
+
ones = np.ones((n_pts, 1), src_pts.dtype)
|
| 198 |
+
src_pts_ = np.hstack([src_pts, ones])
|
| 199 |
+
dst_pts_ = np.hstack([dst_pts, ones])
|
| 200 |
+
|
| 201 |
+
# #print(('src_pts_:\n' + str(src_pts_))
|
| 202 |
+
# #print(('dst_pts_:\n' + str(dst_pts_))
|
| 203 |
+
|
| 204 |
+
A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_)
|
| 205 |
+
|
| 206 |
+
# #print(('np.linalg.lstsq return A: \n' + str(A))
|
| 207 |
+
# #print(('np.linalg.lstsq return res: \n' + str(res))
|
| 208 |
+
# #print(('np.linalg.lstsq return rank: \n' + str(rank))
|
| 209 |
+
# #print(('np.linalg.lstsq return s: \n' + str(s))
|
| 210 |
+
|
| 211 |
+
if rank == 3:
|
| 212 |
+
tfm = np.float32([[A[0, 0], A[1, 0], A[2, 0]], [A[0, 1], A[1, 1], A[2, 1]]])
|
| 213 |
+
elif rank == 2:
|
| 214 |
+
tfm = np.float32([[A[0, 0], A[1, 0], 0], [A[0, 1], A[1, 1], 0]])
|
| 215 |
+
|
| 216 |
+
return tfm
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def warp_and_crop_face(
|
| 220 |
+
src_img, facial_pts, reference_pts=None, crop_size=(96, 112), align_type="smilarity"
|
| 221 |
+
):
|
| 222 |
+
"""
|
| 223 |
+
Function:
|
| 224 |
+
----------
|
| 225 |
+
apply affine transform 'trans' to uv
|
| 226 |
+
Parameters:
|
| 227 |
+
----------
|
| 228 |
+
@src_img: 3x3 np.array
|
| 229 |
+
input image
|
| 230 |
+
@facial_pts: could be
|
| 231 |
+
1)a list of K coordinates (x,y)
|
| 232 |
+
or
|
| 233 |
+
2) Kx2 or 2xK np.array
|
| 234 |
+
each row or col is a pair of coordinates (x, y)
|
| 235 |
+
@reference_pts: could be
|
| 236 |
+
1) a list of K coordinates (x,y)
|
| 237 |
+
or
|
| 238 |
+
2) Kx2 or 2xK np.array
|
| 239 |
+
each row or col is a pair of coordinates (x, y)
|
| 240 |
+
or
|
| 241 |
+
3) None
|
| 242 |
+
if None, use default reference facial points
|
| 243 |
+
@crop_size: (w, h)
|
| 244 |
+
output face image size
|
| 245 |
+
@align_type: transform type, could be one of
|
| 246 |
+
1) 'similarity': use similarity transform
|
| 247 |
+
2) 'cv2_affine': use the first 3 points to do affine transform,
|
| 248 |
+
by calling cv2.getAffineTransform()
|
| 249 |
+
3) 'affine': use all points to do affine transform
|
| 250 |
+
Returns:
|
| 251 |
+
----------
|
| 252 |
+
@face_img: output face image with size (w, h) = @crop_size
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
if reference_pts is None:
|
| 256 |
+
if crop_size[0] == 96 and crop_size[1] == 112:
|
| 257 |
+
reference_pts = REFERENCE_FACIAL_POINTS
|
| 258 |
+
else:
|
| 259 |
+
default_square = False
|
| 260 |
+
inner_padding_factor = 0
|
| 261 |
+
outer_padding = (0, 0)
|
| 262 |
+
output_size = crop_size
|
| 263 |
+
|
| 264 |
+
reference_pts = get_reference_facial_points(
|
| 265 |
+
output_size, inner_padding_factor, outer_padding, default_square
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
ref_pts = np.float32(reference_pts)
|
| 269 |
+
ref_pts_shp = ref_pts.shape
|
| 270 |
+
if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2:
|
| 271 |
+
raise FaceWarpException("reference_pts.shape must be (K,2) or (2,K) and K>2")
|
| 272 |
+
|
| 273 |
+
if ref_pts_shp[0] == 2:
|
| 274 |
+
ref_pts = ref_pts.T
|
| 275 |
+
|
| 276 |
+
src_pts = np.float32(facial_pts)
|
| 277 |
+
src_pts_shp = src_pts.shape
|
| 278 |
+
if max(src_pts_shp) < 3 or min(src_pts_shp) != 2:
|
| 279 |
+
raise FaceWarpException("facial_pts.shape must be (K,2) or (2,K) and K>2")
|
| 280 |
+
|
| 281 |
+
if src_pts_shp[0] == 2:
|
| 282 |
+
src_pts = src_pts.T
|
| 283 |
+
|
| 284 |
+
# #print('--->src_pts:\n', src_pts
|
| 285 |
+
# #print('--->ref_pts\n', ref_pts
|
| 286 |
+
|
| 287 |
+
if src_pts.shape != ref_pts.shape:
|
| 288 |
+
raise FaceWarpException("facial_pts and reference_pts must have the same shape")
|
| 289 |
+
|
| 290 |
+
if align_type == "cv2_affine":
|
| 291 |
+
tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3])
|
| 292 |
+
# #print(('cv2.getAffineTransform() returns tfm=\n' + str(tfm))
|
| 293 |
+
elif align_type == "affine":
|
| 294 |
+
tfm = get_affine_transform_matrix(src_pts, ref_pts)
|
| 295 |
+
# #print(('get_affine_transform_matrix() returns tfm=\n' + str(tfm))
|
| 296 |
+
else:
|
| 297 |
+
tfm = get_similarity_transform_for_cv2(src_pts, ref_pts)
|
| 298 |
+
# #print(('get_similarity_transform_for_cv2() returns tfm=\n' + str(tfm))
|
| 299 |
+
|
| 300 |
+
# #print('--->Transform matrix: '
|
| 301 |
+
# #print(('type(tfm):' + str(type(tfm)))
|
| 302 |
+
# #print(('tfm.dtype:' + str(tfm.dtype))
|
| 303 |
+
# #print( tfm
|
| 304 |
+
|
| 305 |
+
face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]))
|
| 306 |
+
|
| 307 |
+
return face_img
|
lib/face_alignment/mtcnn_pytorch/src/box_utils.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def nms(boxes, overlap_threshold=0.5, mode="union"):
|
| 10 |
+
"""Non-maximum suppression.
|
| 11 |
+
|
| 12 |
+
Arguments:
|
| 13 |
+
boxes: a float numpy array of shape [n, 5],
|
| 14 |
+
where each row is (xmin, ymin, xmax, ymax, score).
|
| 15 |
+
overlap_threshold: a float number.
|
| 16 |
+
mode: 'union' or 'min'.
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
list with indices of the selected boxes
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
# if there are no boxes, return the empty list
|
| 23 |
+
if len(boxes) == 0:
|
| 24 |
+
return []
|
| 25 |
+
|
| 26 |
+
# list of picked indices
|
| 27 |
+
pick = []
|
| 28 |
+
|
| 29 |
+
# grab the coordinates of the bounding boxes
|
| 30 |
+
x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
|
| 31 |
+
|
| 32 |
+
area = (x2 - x1 + 1.0) * (y2 - y1 + 1.0)
|
| 33 |
+
ids = np.argsort(score) # in increasing order
|
| 34 |
+
|
| 35 |
+
while len(ids) > 0:
|
| 36 |
+
# grab index of the largest value
|
| 37 |
+
last = len(ids) - 1
|
| 38 |
+
i = ids[last]
|
| 39 |
+
pick.append(i)
|
| 40 |
+
|
| 41 |
+
# compute intersections
|
| 42 |
+
# of the box with the largest score
|
| 43 |
+
# with the rest of boxes
|
| 44 |
+
|
| 45 |
+
# left top corner of intersection boxes
|
| 46 |
+
ix1 = np.maximum(x1[i], x1[ids[:last]])
|
| 47 |
+
iy1 = np.maximum(y1[i], y1[ids[:last]])
|
| 48 |
+
|
| 49 |
+
# right bottom corner of intersection boxes
|
| 50 |
+
ix2 = np.minimum(x2[i], x2[ids[:last]])
|
| 51 |
+
iy2 = np.minimum(y2[i], y2[ids[:last]])
|
| 52 |
+
|
| 53 |
+
# width and height of intersection boxes
|
| 54 |
+
w = np.maximum(0.0, ix2 - ix1 + 1.0)
|
| 55 |
+
h = np.maximum(0.0, iy2 - iy1 + 1.0)
|
| 56 |
+
|
| 57 |
+
# intersections' areas
|
| 58 |
+
inter = w * h
|
| 59 |
+
if mode == "min":
|
| 60 |
+
overlap = inter / np.minimum(area[i], area[ids[:last]])
|
| 61 |
+
elif mode == "union":
|
| 62 |
+
# intersection over union (IoU)
|
| 63 |
+
overlap = inter / (area[i] + area[ids[:last]] - inter)
|
| 64 |
+
|
| 65 |
+
# delete all boxes where overlap is too big
|
| 66 |
+
ids = np.delete(
|
| 67 |
+
ids, np.concatenate([[last], np.where(overlap > overlap_threshold)[0]])
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
return pick
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def convert_to_square(bboxes):
|
| 74 |
+
"""Convert bounding boxes to a square form.
|
| 75 |
+
|
| 76 |
+
Arguments:
|
| 77 |
+
bboxes: a float numpy array of shape [n, 5].
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
a float numpy array of shape [n, 5],
|
| 81 |
+
squared bounding boxes.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
square_bboxes = np.zeros_like(bboxes)
|
| 85 |
+
x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
|
| 86 |
+
h = y2 - y1 + 1.0
|
| 87 |
+
w = x2 - x1 + 1.0
|
| 88 |
+
max_side = np.maximum(h, w)
|
| 89 |
+
square_bboxes[:, 0] = x1 + w * 0.5 - max_side * 0.5
|
| 90 |
+
square_bboxes[:, 1] = y1 + h * 0.5 - max_side * 0.5
|
| 91 |
+
square_bboxes[:, 2] = square_bboxes[:, 0] + max_side - 1.0
|
| 92 |
+
square_bboxes[:, 3] = square_bboxes[:, 1] + max_side - 1.0
|
| 93 |
+
return square_bboxes
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def calibrate_box(bboxes, offsets):
|
| 97 |
+
"""Transform bounding boxes to be more like true bounding boxes.
|
| 98 |
+
'offsets' is one of the outputs of the nets.
|
| 99 |
+
|
| 100 |
+
Arguments:
|
| 101 |
+
bboxes: a float numpy array of shape [n, 5].
|
| 102 |
+
offsets: a float numpy array of shape [n, 4].
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
a float numpy array of shape [n, 5].
|
| 106 |
+
"""
|
| 107 |
+
x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
|
| 108 |
+
w = x2 - x1 + 1.0
|
| 109 |
+
h = y2 - y1 + 1.0
|
| 110 |
+
w = np.expand_dims(w, 1)
|
| 111 |
+
h = np.expand_dims(h, 1)
|
| 112 |
+
|
| 113 |
+
# this is what happening here:
|
| 114 |
+
# tx1, ty1, tx2, ty2 = [offsets[:, i] for i in range(4)]
|
| 115 |
+
# x1_true = x1 + tx1*w
|
| 116 |
+
# y1_true = y1 + ty1*h
|
| 117 |
+
# x2_true = x2 + tx2*w
|
| 118 |
+
# y2_true = y2 + ty2*h
|
| 119 |
+
# below is just more compact form of this
|
| 120 |
+
|
| 121 |
+
# are offsets always such that
|
| 122 |
+
# x1 < x2 and y1 < y2 ?
|
| 123 |
+
|
| 124 |
+
translation = np.hstack([w, h, w, h]) * offsets
|
| 125 |
+
bboxes[:, 0:4] = bboxes[:, 0:4] + translation
|
| 126 |
+
return bboxes
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_image_boxes(bounding_boxes, img, size=24):
|
| 130 |
+
"""Cut out boxes from the image.
|
| 131 |
+
|
| 132 |
+
Arguments:
|
| 133 |
+
bounding_boxes: a float numpy array of shape [n, 5].
|
| 134 |
+
img: an instance of PIL.Image.
|
| 135 |
+
size: an integer, size of cutouts.
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
a float numpy array of shape [n, 3, size, size].
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
num_boxes = len(bounding_boxes)
|
| 142 |
+
width, height = img.size
|
| 143 |
+
|
| 144 |
+
[dy, edy, dx, edx, y, ey, x, ex, w, h] = correct_bboxes(
|
| 145 |
+
bounding_boxes, width, height
|
| 146 |
+
)
|
| 147 |
+
img_boxes = np.zeros((num_boxes, 3, size, size), "float32")
|
| 148 |
+
|
| 149 |
+
for i in range(num_boxes):
|
| 150 |
+
img_box = np.zeros((h[i], w[i], 3), "uint8")
|
| 151 |
+
|
| 152 |
+
img_array = np.asarray(img, "uint8")
|
| 153 |
+
img_box[dy[i] : (edy[i] + 1), dx[i] : (edx[i] + 1), :] = img_array[
|
| 154 |
+
y[i] : (ey[i] + 1), x[i] : (ex[i] + 1), :
|
| 155 |
+
]
|
| 156 |
+
|
| 157 |
+
# resize
|
| 158 |
+
img_box = Image.fromarray(img_box)
|
| 159 |
+
img_box = img_box.resize((size, size), Image.BILINEAR)
|
| 160 |
+
img_box = np.asarray(img_box, "float32")
|
| 161 |
+
|
| 162 |
+
img_boxes[i, :, :, :] = _preprocess(img_box)
|
| 163 |
+
|
| 164 |
+
return img_boxes
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def correct_bboxes(bboxes, width, height):
|
| 168 |
+
"""Crop boxes that are too big and get coordinates
|
| 169 |
+
with respect to cutouts.
|
| 170 |
+
|
| 171 |
+
Arguments:
|
| 172 |
+
bboxes: a float numpy array of shape [n, 5],
|
| 173 |
+
where each row is (xmin, ymin, xmax, ymax, score).
|
| 174 |
+
width: a float number.
|
| 175 |
+
height: a float number.
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
dy, dx, edy, edx: a int numpy arrays of shape [n],
|
| 179 |
+
coordinates of the boxes with respect to the cutouts.
|
| 180 |
+
y, x, ey, ex: a int numpy arrays of shape [n],
|
| 181 |
+
corrected ymin, xmin, ymax, xmax.
|
| 182 |
+
h, w: a int numpy arrays of shape [n],
|
| 183 |
+
just heights and widths of boxes.
|
| 184 |
+
|
| 185 |
+
in the following order:
|
| 186 |
+
[dy, edy, dx, edx, y, ey, x, ex, w, h].
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
|
| 190 |
+
w, h = x2 - x1 + 1.0, y2 - y1 + 1.0
|
| 191 |
+
num_boxes = bboxes.shape[0]
|
| 192 |
+
|
| 193 |
+
# 'e' stands for end
|
| 194 |
+
# (x, y) -> (ex, ey)
|
| 195 |
+
x, y, ex, ey = x1, y1, x2, y2
|
| 196 |
+
|
| 197 |
+
# we need to cut out a box from the image.
|
| 198 |
+
# (x, y, ex, ey) are corrected coordinates of the box
|
| 199 |
+
# in the image.
|
| 200 |
+
# (dx, dy, edx, edy) are coordinates of the box in the cutout
|
| 201 |
+
# from the image.
|
| 202 |
+
dx, dy = np.zeros((num_boxes,)), np.zeros((num_boxes,))
|
| 203 |
+
edx, edy = w.copy() - 1.0, h.copy() - 1.0
|
| 204 |
+
|
| 205 |
+
# if box's bottom right corner is too far right
|
| 206 |
+
ind = np.where(ex > width - 1.0)[0]
|
| 207 |
+
edx[ind] = w[ind] + width - 2.0 - ex[ind]
|
| 208 |
+
ex[ind] = width - 1.0
|
| 209 |
+
|
| 210 |
+
# if box's bottom right corner is too low
|
| 211 |
+
ind = np.where(ey > height - 1.0)[0]
|
| 212 |
+
edy[ind] = h[ind] + height - 2.0 - ey[ind]
|
| 213 |
+
ey[ind] = height - 1.0
|
| 214 |
+
|
| 215 |
+
# if box's top left corner is too far left
|
| 216 |
+
ind = np.where(x < 0.0)[0]
|
| 217 |
+
dx[ind] = 0.0 - x[ind]
|
| 218 |
+
x[ind] = 0.0
|
| 219 |
+
|
| 220 |
+
# if box's top left corner is too high
|
| 221 |
+
ind = np.where(y < 0.0)[0]
|
| 222 |
+
dy[ind] = 0.0 - y[ind]
|
| 223 |
+
y[ind] = 0.0
|
| 224 |
+
|
| 225 |
+
return_list = [dy, edy, dx, edx, y, ey, x, ex, w, h]
|
| 226 |
+
return_list = [i.astype("int32") for i in return_list]
|
| 227 |
+
|
| 228 |
+
return return_list
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _preprocess(img):
|
| 232 |
+
"""Preprocessing step before feeding the network.
|
| 233 |
+
|
| 234 |
+
Arguments:
|
| 235 |
+
img: a float numpy array of shape [h, w, c].
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
a float numpy array of shape [1, c, h, w].
|
| 239 |
+
"""
|
| 240 |
+
img = img.transpose((2, 0, 1))
|
| 241 |
+
img = np.expand_dims(img, 0)
|
| 242 |
+
img = (img - 127.5) * 0.0078125
|
| 243 |
+
return img
|
lib/face_alignment/mtcnn_pytorch/src/detector.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from .get_nets import PNet, RNet, ONet
|
| 8 |
+
from .box_utils import nms, calibrate_box, get_image_boxes, convert_to_square
|
| 9 |
+
from .first_stage import run_first_stage
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def detect_faces(
|
| 13 |
+
image,
|
| 14 |
+
min_face_size=20.0,
|
| 15 |
+
thresholds=[0.6, 0.7, 0.8],
|
| 16 |
+
nms_thresholds=[0.7, 0.7, 0.7],
|
| 17 |
+
):
|
| 18 |
+
"""
|
| 19 |
+
Arguments:
|
| 20 |
+
image: an instance of PIL.Image.
|
| 21 |
+
min_face_size: a float number.
|
| 22 |
+
thresholds: a list of length 3.
|
| 23 |
+
nms_thresholds: a list of length 3.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
two float numpy arrays of shapes [n_boxes, 4] and [n_boxes, 10],
|
| 27 |
+
bounding boxes and facial landmarks.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
# LOAD MODELS
|
| 31 |
+
pnet = PNet()
|
| 32 |
+
rnet = RNet()
|
| 33 |
+
onet = ONet()
|
| 34 |
+
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 35 |
+
device = "cpu"
|
| 36 |
+
pnet.to(device)
|
| 37 |
+
rnet.to(device)
|
| 38 |
+
onet.to(device)
|
| 39 |
+
onet.eval()
|
| 40 |
+
|
| 41 |
+
# BUILD AN IMAGE PYRAMID
|
| 42 |
+
width, height = image.size
|
| 43 |
+
min_length = min(height, width)
|
| 44 |
+
|
| 45 |
+
min_detection_size = 12
|
| 46 |
+
factor = 0.707 # sqrt(0.5)
|
| 47 |
+
|
| 48 |
+
# scales for scaling the image
|
| 49 |
+
scales = []
|
| 50 |
+
|
| 51 |
+
# scales the image so that
|
| 52 |
+
# minimum size that we can detect equals to
|
| 53 |
+
# minimum face size that we want to detect
|
| 54 |
+
m = min_detection_size / min_face_size
|
| 55 |
+
min_length *= m
|
| 56 |
+
|
| 57 |
+
factor_count = 0
|
| 58 |
+
while min_length > min_detection_size:
|
| 59 |
+
scales.append(m * factor**factor_count)
|
| 60 |
+
min_length *= factor
|
| 61 |
+
factor_count += 1
|
| 62 |
+
|
| 63 |
+
# STAGE 1
|
| 64 |
+
|
| 65 |
+
# it will be returned
|
| 66 |
+
bounding_boxes = []
|
| 67 |
+
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
# run P-Net on different scales
|
| 70 |
+
for s in scales:
|
| 71 |
+
boxes = run_first_stage(image, pnet, scale=s, threshold=thresholds[0])
|
| 72 |
+
bounding_boxes.append(boxes)
|
| 73 |
+
|
| 74 |
+
# collect boxes (and offsets, and scores) from different scales
|
| 75 |
+
bounding_boxes = [i for i in bounding_boxes if i is not None]
|
| 76 |
+
bounding_boxes = np.vstack(bounding_boxes)
|
| 77 |
+
|
| 78 |
+
keep = nms(bounding_boxes[:, 0:5], nms_thresholds[0])
|
| 79 |
+
bounding_boxes = bounding_boxes[keep]
|
| 80 |
+
|
| 81 |
+
# use offsets predicted by pnet to transform bounding boxes
|
| 82 |
+
bounding_boxes = calibrate_box(bounding_boxes[:, 0:5], bounding_boxes[:, 5:])
|
| 83 |
+
# shape [n_boxes, 5]
|
| 84 |
+
|
| 85 |
+
bounding_boxes = convert_to_square(bounding_boxes)
|
| 86 |
+
bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
|
| 87 |
+
|
| 88 |
+
# STAGE 2
|
| 89 |
+
|
| 90 |
+
img_boxes = get_image_boxes(bounding_boxes, image, size=24)
|
| 91 |
+
img_boxes = torch.FloatTensor(img_boxes).to(device)
|
| 92 |
+
|
| 93 |
+
output = rnet(img_boxes)
|
| 94 |
+
offsets = output[0].cpu().data.numpy() # shape [n_boxes, 4]
|
| 95 |
+
probs = output[1].cpu().data.numpy() # shape [n_boxes, 2]
|
| 96 |
+
|
| 97 |
+
keep = np.where(probs[:, 1] > thresholds[1])[0]
|
| 98 |
+
bounding_boxes = bounding_boxes[keep]
|
| 99 |
+
bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
|
| 100 |
+
offsets = offsets[keep]
|
| 101 |
+
|
| 102 |
+
keep = nms(bounding_boxes, nms_thresholds[1])
|
| 103 |
+
bounding_boxes = bounding_boxes[keep]
|
| 104 |
+
bounding_boxes = calibrate_box(bounding_boxes, offsets[keep])
|
| 105 |
+
bounding_boxes = convert_to_square(bounding_boxes)
|
| 106 |
+
bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
|
| 107 |
+
|
| 108 |
+
# STAGE 3
|
| 109 |
+
|
| 110 |
+
img_boxes = get_image_boxes(bounding_boxes, image, size=48)
|
| 111 |
+
if len(img_boxes) == 0:
|
| 112 |
+
return [], []
|
| 113 |
+
img_boxes = torch.FloatTensor(img_boxes).to(device)
|
| 114 |
+
output = onet(img_boxes)
|
| 115 |
+
landmarks = output[0].cpu().data.numpy() # shape [n_boxes, 10]
|
| 116 |
+
offsets = output[1].cpu().data.numpy() # shape [n_boxes, 4]
|
| 117 |
+
probs = output[2].cpu().data.numpy() # shape [n_boxes, 2]
|
| 118 |
+
|
| 119 |
+
keep = np.where(probs[:, 1] > thresholds[2])[0]
|
| 120 |
+
bounding_boxes = bounding_boxes[keep]
|
| 121 |
+
bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
|
| 122 |
+
offsets = offsets[keep]
|
| 123 |
+
landmarks = landmarks[keep]
|
| 124 |
+
|
| 125 |
+
# compute landmark points
|
| 126 |
+
width = bounding_boxes[:, 2] - bounding_boxes[:, 0] + 1.0
|
| 127 |
+
height = bounding_boxes[:, 3] - bounding_boxes[:, 1] + 1.0
|
| 128 |
+
xmin, ymin = bounding_boxes[:, 0], bounding_boxes[:, 1]
|
| 129 |
+
landmarks[:, 0:5] = (
|
| 130 |
+
np.expand_dims(xmin, 1) + np.expand_dims(width, 1) * landmarks[:, 0:5]
|
| 131 |
+
)
|
| 132 |
+
landmarks[:, 5:10] = (
|
| 133 |
+
np.expand_dims(ymin, 1) + np.expand_dims(height, 1) * landmarks[:, 5:10]
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
bounding_boxes = calibrate_box(bounding_boxes, offsets)
|
| 137 |
+
keep = nms(bounding_boxes, nms_thresholds[2], mode="min")
|
| 138 |
+
bounding_boxes = bounding_boxes[keep]
|
| 139 |
+
landmarks = landmarks[keep]
|
| 140 |
+
|
| 141 |
+
return bounding_boxes, landmarks
|
lib/face_alignment/mtcnn_pytorch/src/first_stage.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import math
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import numpy as np
|
| 9 |
+
from .box_utils import nms, _preprocess
|
| 10 |
+
|
| 11 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 12 |
+
# device = 'cpu'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def run_first_stage(image, net, scale, threshold):
|
| 16 |
+
"""Run P-Net, generate bounding boxes, and do NMS.
|
| 17 |
+
|
| 18 |
+
Arguments:
|
| 19 |
+
image: an instance of PIL.Image.
|
| 20 |
+
net: an instance of pytorch's nn.Module, P-Net.
|
| 21 |
+
scale: a float number,
|
| 22 |
+
scale width and height of the image by this number.
|
| 23 |
+
threshold: a float number,
|
| 24 |
+
threshold on the probability of a face when generating
|
| 25 |
+
bounding boxes from predictions of the net.
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
a float numpy array of shape [n_boxes, 9],
|
| 29 |
+
bounding boxes with scores and offsets (4 + 1 + 4).
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
# scale the image and convert it to a float array
|
| 33 |
+
width, height = image.size
|
| 34 |
+
sw, sh = math.ceil(width * scale), math.ceil(height * scale)
|
| 35 |
+
img = image.resize((sw, sh), Image.BILINEAR)
|
| 36 |
+
img = np.asarray(img, "float32")
|
| 37 |
+
|
| 38 |
+
img = torch.FloatTensor(_preprocess(img)).to(net.features.conv1.weight.device)
|
| 39 |
+
with torch.no_grad():
|
| 40 |
+
output = net(img)
|
| 41 |
+
probs = output[1].cpu().data.numpy()[0, 1, :, :]
|
| 42 |
+
offsets = output[0].cpu().data.numpy()
|
| 43 |
+
# probs: probability of a face at each sliding window
|
| 44 |
+
# offsets: transformations to true bounding boxes
|
| 45 |
+
|
| 46 |
+
boxes = _generate_bboxes(probs, offsets, scale, threshold)
|
| 47 |
+
if len(boxes) == 0:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
keep = nms(boxes[:, 0:5], overlap_threshold=0.5)
|
| 51 |
+
return boxes[keep]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _generate_bboxes(probs, offsets, scale, threshold):
|
| 55 |
+
"""Generate bounding boxes at places
|
| 56 |
+
where there is probably a face.
|
| 57 |
+
|
| 58 |
+
Arguments:
|
| 59 |
+
probs: a float numpy array of shape [n, m].
|
| 60 |
+
offsets: a float numpy array of shape [1, 4, n, m].
|
| 61 |
+
scale: a float number,
|
| 62 |
+
width and height of the image were scaled by this number.
|
| 63 |
+
threshold: a float number.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
a float numpy array of shape [n_boxes, 9]
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
# applying P-Net is equivalent, in some sense, to
|
| 70 |
+
# moving 12x12 window with stride 2
|
| 71 |
+
stride = 2
|
| 72 |
+
cell_size = 12
|
| 73 |
+
|
| 74 |
+
# indices of boxes where there is probably a face
|
| 75 |
+
inds = np.where(probs > threshold)
|
| 76 |
+
|
| 77 |
+
if inds[0].size == 0:
|
| 78 |
+
return np.array([])
|
| 79 |
+
|
| 80 |
+
# transformations of bounding boxes
|
| 81 |
+
tx1, ty1, tx2, ty2 = [offsets[0, i, inds[0], inds[1]] for i in range(4)]
|
| 82 |
+
# they are defined as:
|
| 83 |
+
# w = x2 - x1 + 1
|
| 84 |
+
# h = y2 - y1 + 1
|
| 85 |
+
# x1_true = x1 + tx1*w
|
| 86 |
+
# x2_true = x2 + tx2*w
|
| 87 |
+
# y1_true = y1 + ty1*h
|
| 88 |
+
# y2_true = y2 + ty2*h
|
| 89 |
+
|
| 90 |
+
offsets = np.array([tx1, ty1, tx2, ty2])
|
| 91 |
+
score = probs[inds[0], inds[1]]
|
| 92 |
+
|
| 93 |
+
# P-Net is applied to scaled images
|
| 94 |
+
# so we need to rescale bounding boxes back
|
| 95 |
+
bounding_boxes = np.vstack(
|
| 96 |
+
[
|
| 97 |
+
np.round((stride * inds[1] + 1.0) / scale),
|
| 98 |
+
np.round((stride * inds[0] + 1.0) / scale),
|
| 99 |
+
np.round((stride * inds[1] + 1.0 + cell_size) / scale),
|
| 100 |
+
np.round((stride * inds[0] + 1.0 + cell_size) / scale),
|
| 101 |
+
score,
|
| 102 |
+
offsets,
|
| 103 |
+
]
|
| 104 |
+
)
|
| 105 |
+
# why one is added?
|
| 106 |
+
|
| 107 |
+
return bounding_boxes.T
|
lib/face_alignment/mtcnn_pytorch/src/get_nets.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from collections import OrderedDict
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Flatten(nn.Module):
|
| 13 |
+
def __init__(self):
|
| 14 |
+
super(Flatten, self).__init__()
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
"""
|
| 18 |
+
Arguments:
|
| 19 |
+
x: a float tensor with shape [batch_size, c, h, w].
|
| 20 |
+
Returns:
|
| 21 |
+
a float tensor with shape [batch_size, c*h*w].
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
# without this pretrained model isn't working
|
| 25 |
+
x = x.transpose(3, 2).contiguous()
|
| 26 |
+
|
| 27 |
+
return x.view(x.size(0), -1)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class PNet(nn.Module):
|
| 31 |
+
def __init__(self):
|
| 32 |
+
super(PNet, self).__init__()
|
| 33 |
+
|
| 34 |
+
# suppose we have input with size HxW, then
|
| 35 |
+
# after first layer: H - 2,
|
| 36 |
+
# after pool: ceil((H - 2)/2),
|
| 37 |
+
# after second conv: ceil((H - 2)/2) - 2,
|
| 38 |
+
# after last conv: ceil((H - 2)/2) - 4,
|
| 39 |
+
# and the same for W
|
| 40 |
+
|
| 41 |
+
self.features = nn.Sequential(
|
| 42 |
+
OrderedDict(
|
| 43 |
+
[
|
| 44 |
+
("conv1", nn.Conv2d(3, 10, 3, 1)),
|
| 45 |
+
("prelu1", nn.PReLU(10)),
|
| 46 |
+
("pool1", nn.MaxPool2d(2, 2, ceil_mode=True)),
|
| 47 |
+
("conv2", nn.Conv2d(10, 16, 3, 1)),
|
| 48 |
+
("prelu2", nn.PReLU(16)),
|
| 49 |
+
("conv3", nn.Conv2d(16, 32, 3, 1)),
|
| 50 |
+
("prelu3", nn.PReLU(32)),
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
self.conv4_1 = nn.Conv2d(32, 2, 1, 1)
|
| 56 |
+
self.conv4_2 = nn.Conv2d(32, 4, 1, 1)
|
| 57 |
+
|
| 58 |
+
weights = np.load("mtcnn_pytorch/src/weights/pnet.npy", allow_pickle=True)[()]
|
| 59 |
+
for n, p in self.named_parameters():
|
| 60 |
+
p.data = torch.FloatTensor(weights[n])
|
| 61 |
+
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
"""
|
| 64 |
+
Arguments:
|
| 65 |
+
x: a float tensor with shape [batch_size, 3, h, w].
|
| 66 |
+
Returns:
|
| 67 |
+
b: a float tensor with shape [batch_size, 4, h', w'].
|
| 68 |
+
a: a float tensor with shape [batch_size, 2, h', w'].
|
| 69 |
+
"""
|
| 70 |
+
x = self.features(x)
|
| 71 |
+
a = self.conv4_1(x)
|
| 72 |
+
b = self.conv4_2(x)
|
| 73 |
+
a = F.softmax(a, dim=-1)
|
| 74 |
+
return b, a
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class RNet(nn.Module):
|
| 78 |
+
def __init__(self):
|
| 79 |
+
super(RNet, self).__init__()
|
| 80 |
+
|
| 81 |
+
self.features = nn.Sequential(
|
| 82 |
+
OrderedDict(
|
| 83 |
+
[
|
| 84 |
+
("conv1", nn.Conv2d(3, 28, 3, 1)),
|
| 85 |
+
("prelu1", nn.PReLU(28)),
|
| 86 |
+
("pool1", nn.MaxPool2d(3, 2, ceil_mode=True)),
|
| 87 |
+
("conv2", nn.Conv2d(28, 48, 3, 1)),
|
| 88 |
+
("prelu2", nn.PReLU(48)),
|
| 89 |
+
("pool2", nn.MaxPool2d(3, 2, ceil_mode=True)),
|
| 90 |
+
("conv3", nn.Conv2d(48, 64, 2, 1)),
|
| 91 |
+
("prelu3", nn.PReLU(64)),
|
| 92 |
+
("flatten", Flatten()),
|
| 93 |
+
("conv4", nn.Linear(576, 128)),
|
| 94 |
+
("prelu4", nn.PReLU(128)),
|
| 95 |
+
]
|
| 96 |
+
)
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
self.conv5_1 = nn.Linear(128, 2)
|
| 100 |
+
self.conv5_2 = nn.Linear(128, 4)
|
| 101 |
+
|
| 102 |
+
weights = np.load("mtcnn_pytorch/src/weights/rnet.npy", allow_pickle=True)[()]
|
| 103 |
+
for n, p in self.named_parameters():
|
| 104 |
+
p.data = torch.FloatTensor(weights[n])
|
| 105 |
+
|
| 106 |
+
def forward(self, x):
|
| 107 |
+
"""
|
| 108 |
+
Arguments:
|
| 109 |
+
x: a float tensor with shape [batch_size, 3, h, w].
|
| 110 |
+
Returns:
|
| 111 |
+
b: a float tensor with shape [batch_size, 4].
|
| 112 |
+
a: a float tensor with shape [batch_size, 2].
|
| 113 |
+
"""
|
| 114 |
+
x = self.features(x)
|
| 115 |
+
a = self.conv5_1(x)
|
| 116 |
+
b = self.conv5_2(x)
|
| 117 |
+
a = F.softmax(a, dim=-1)
|
| 118 |
+
return b, a
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class ONet(nn.Module):
|
| 122 |
+
def __init__(self):
|
| 123 |
+
super(ONet, self).__init__()
|
| 124 |
+
|
| 125 |
+
self.features = nn.Sequential(
|
| 126 |
+
OrderedDict(
|
| 127 |
+
[
|
| 128 |
+
("conv1", nn.Conv2d(3, 32, 3, 1)),
|
| 129 |
+
("prelu1", nn.PReLU(32)),
|
| 130 |
+
("pool1", nn.MaxPool2d(3, 2, ceil_mode=True)),
|
| 131 |
+
("conv2", nn.Conv2d(32, 64, 3, 1)),
|
| 132 |
+
("prelu2", nn.PReLU(64)),
|
| 133 |
+
("pool2", nn.MaxPool2d(3, 2, ceil_mode=True)),
|
| 134 |
+
("conv3", nn.Conv2d(64, 64, 3, 1)),
|
| 135 |
+
("prelu3", nn.PReLU(64)),
|
| 136 |
+
("pool3", nn.MaxPool2d(2, 2, ceil_mode=True)),
|
| 137 |
+
("conv4", nn.Conv2d(64, 128, 2, 1)),
|
| 138 |
+
("prelu4", nn.PReLU(128)),
|
| 139 |
+
("flatten", Flatten()),
|
| 140 |
+
("conv5", nn.Linear(1152, 256)),
|
| 141 |
+
("drop5", nn.Dropout(0.25)),
|
| 142 |
+
("prelu5", nn.PReLU(256)),
|
| 143 |
+
]
|
| 144 |
+
)
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
self.conv6_1 = nn.Linear(256, 2)
|
| 148 |
+
self.conv6_2 = nn.Linear(256, 4)
|
| 149 |
+
self.conv6_3 = nn.Linear(256, 10)
|
| 150 |
+
|
| 151 |
+
weights = np.load("mtcnn_pytorch/src/weights/onet.npy", allow_pickle=True)[()]
|
| 152 |
+
for n, p in self.named_parameters():
|
| 153 |
+
p.data = torch.FloatTensor(weights[n])
|
| 154 |
+
|
| 155 |
+
def forward(self, x):
|
| 156 |
+
"""
|
| 157 |
+
Arguments:
|
| 158 |
+
x: a float tensor with shape [batch_size, 3, h, w].
|
| 159 |
+
Returns:
|
| 160 |
+
c: a float tensor with shape [batch_size, 10].
|
| 161 |
+
b: a float tensor with shape [batch_size, 4].
|
| 162 |
+
a: a float tensor with shape [batch_size, 2].
|
| 163 |
+
"""
|
| 164 |
+
x = self.features(x)
|
| 165 |
+
a = self.conv6_1(x)
|
| 166 |
+
b = self.conv6_2(x)
|
| 167 |
+
c = self.conv6_3(x)
|
| 168 |
+
a = F.softmax(a, dim=-1)
|
| 169 |
+
return c, b, a
|
lib/face_alignment/mtcnn_pytorch/src/matlab_cp2tform.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 3 |
+
|
| 4 |
+
# SPDX-License-Identifier: MIT
|
| 5 |
+
"""
|
| 6 |
+
Created on Tue Jul 11 06:54:28 2017
|
| 7 |
+
|
| 8 |
+
@author: zhaoyafei
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from numpy.linalg import inv, norm, lstsq
|
| 13 |
+
from numpy.linalg import matrix_rank as rank
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MatlabCp2tormException(Exception):
|
| 17 |
+
def __str__(self):
|
| 18 |
+
return "In File {}:{}".format(__file__, super.__str__(self))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def tformfwd(trans, uv):
|
| 22 |
+
"""
|
| 23 |
+
Function:
|
| 24 |
+
----------
|
| 25 |
+
apply affine transform 'trans' to uv
|
| 26 |
+
|
| 27 |
+
Parameters:
|
| 28 |
+
----------
|
| 29 |
+
@trans: 3x3 np.array
|
| 30 |
+
transform matrix
|
| 31 |
+
@uv: Kx2 np.array
|
| 32 |
+
each row is a pair of coordinates (x, y)
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
----------
|
| 36 |
+
@xy: Kx2 np.array
|
| 37 |
+
each row is a pair of transformed coordinates (x, y)
|
| 38 |
+
"""
|
| 39 |
+
uv = np.hstack((uv, np.ones((uv.shape[0], 1))))
|
| 40 |
+
xy = np.dot(uv, trans)
|
| 41 |
+
xy = xy[:, 0:-1]
|
| 42 |
+
return xy
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def tforminv(trans, uv):
|
| 46 |
+
"""
|
| 47 |
+
Function:
|
| 48 |
+
----------
|
| 49 |
+
apply the inverse of affine transform 'trans' to uv
|
| 50 |
+
|
| 51 |
+
Parameters:
|
| 52 |
+
----------
|
| 53 |
+
@trans: 3x3 np.array
|
| 54 |
+
transform matrix
|
| 55 |
+
@uv: Kx2 np.array
|
| 56 |
+
each row is a pair of coordinates (x, y)
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
----------
|
| 60 |
+
@xy: Kx2 np.array
|
| 61 |
+
each row is a pair of inverse-transformed coordinates (x, y)
|
| 62 |
+
"""
|
| 63 |
+
Tinv = inv(trans)
|
| 64 |
+
xy = tformfwd(Tinv, uv)
|
| 65 |
+
return xy
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def findNonreflectiveSimilarity(uv, xy, options=None):
|
| 69 |
+
options = {"K": 2}
|
| 70 |
+
|
| 71 |
+
K = options["K"]
|
| 72 |
+
M = xy.shape[0]
|
| 73 |
+
x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
|
| 74 |
+
y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
|
| 75 |
+
# print('--->x, y:\n', x, y
|
| 76 |
+
|
| 77 |
+
tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
|
| 78 |
+
tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
|
| 79 |
+
X = np.vstack((tmp1, tmp2))
|
| 80 |
+
# print('--->X.shape: ', X.shape
|
| 81 |
+
# print('X:\n', X
|
| 82 |
+
|
| 83 |
+
u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
|
| 84 |
+
v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
|
| 85 |
+
U = np.vstack((u, v))
|
| 86 |
+
# print('--->U.shape: ', U.shape
|
| 87 |
+
# print('U:\n', U
|
| 88 |
+
|
| 89 |
+
# We know that X * r = U
|
| 90 |
+
if rank(X) >= 2 * K:
|
| 91 |
+
r, _, _, _ = lstsq(X, U)
|
| 92 |
+
r = np.squeeze(r)
|
| 93 |
+
else:
|
| 94 |
+
raise Exception("cp2tform:twoUniquePointsReq")
|
| 95 |
+
|
| 96 |
+
# print('--->r:\n', r
|
| 97 |
+
|
| 98 |
+
sc = r[0]
|
| 99 |
+
ss = r[1]
|
| 100 |
+
tx = r[2]
|
| 101 |
+
ty = r[3]
|
| 102 |
+
|
| 103 |
+
Tinv = np.array([[sc, -ss, 0], [ss, sc, 0], [tx, ty, 1]])
|
| 104 |
+
|
| 105 |
+
# print('--->Tinv:\n', Tinv
|
| 106 |
+
|
| 107 |
+
T = inv(Tinv)
|
| 108 |
+
# print('--->T:\n', T
|
| 109 |
+
|
| 110 |
+
T[:, 2] = np.array([0, 0, 1])
|
| 111 |
+
|
| 112 |
+
return T, Tinv
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def findSimilarity(uv, xy, options=None):
|
| 116 |
+
options = {"K": 2}
|
| 117 |
+
|
| 118 |
+
# uv = np.array(uv)
|
| 119 |
+
# xy = np.array(xy)
|
| 120 |
+
|
| 121 |
+
# Solve for trans1
|
| 122 |
+
trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options)
|
| 123 |
+
|
| 124 |
+
# Solve for trans2
|
| 125 |
+
|
| 126 |
+
# manually reflect the xy data across the Y-axis
|
| 127 |
+
xyR = xy
|
| 128 |
+
xyR[:, 0] = -1 * xyR[:, 0]
|
| 129 |
+
|
| 130 |
+
trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options)
|
| 131 |
+
|
| 132 |
+
# manually reflect the tform to undo the reflection done on xyR
|
| 133 |
+
TreflectY = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]])
|
| 134 |
+
|
| 135 |
+
trans2 = np.dot(trans2r, TreflectY)
|
| 136 |
+
|
| 137 |
+
# Figure out if trans1 or trans2 is better
|
| 138 |
+
xy1 = tformfwd(trans1, uv)
|
| 139 |
+
norm1 = norm(xy1 - xy)
|
| 140 |
+
|
| 141 |
+
xy2 = tformfwd(trans2, uv)
|
| 142 |
+
norm2 = norm(xy2 - xy)
|
| 143 |
+
|
| 144 |
+
if norm1 <= norm2:
|
| 145 |
+
return trans1, trans1_inv
|
| 146 |
+
else:
|
| 147 |
+
trans2_inv = inv(trans2)
|
| 148 |
+
return trans2, trans2_inv
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_similarity_transform(src_pts, dst_pts, reflective=True):
|
| 152 |
+
"""
|
| 153 |
+
Function:
|
| 154 |
+
----------
|
| 155 |
+
Find Similarity Transform Matrix 'trans':
|
| 156 |
+
u = src_pts[:, 0]
|
| 157 |
+
v = src_pts[:, 1]
|
| 158 |
+
x = dst_pts[:, 0]
|
| 159 |
+
y = dst_pts[:, 1]
|
| 160 |
+
[x, y, 1] = [u, v, 1] * trans
|
| 161 |
+
|
| 162 |
+
Parameters:
|
| 163 |
+
----------
|
| 164 |
+
@src_pts: Kx2 np.array
|
| 165 |
+
source points, each row is a pair of coordinates (x, y)
|
| 166 |
+
@dst_pts: Kx2 np.array
|
| 167 |
+
destination points, each row is a pair of transformed
|
| 168 |
+
coordinates (x, y)
|
| 169 |
+
@reflective: True or False
|
| 170 |
+
if True:
|
| 171 |
+
use reflective similarity transform
|
| 172 |
+
else:
|
| 173 |
+
use non-reflective similarity transform
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
----------
|
| 177 |
+
@trans: 3x3 np.array
|
| 178 |
+
transform matrix from uv to xy
|
| 179 |
+
trans_inv: 3x3 np.array
|
| 180 |
+
inverse of trans, transform matrix from xy to uv
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
if reflective:
|
| 184 |
+
trans, trans_inv = findSimilarity(src_pts, dst_pts)
|
| 185 |
+
else:
|
| 186 |
+
trans, trans_inv = findNonreflectiveSimilarity(src_pts, dst_pts)
|
| 187 |
+
|
| 188 |
+
return trans, trans_inv
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def cvt_tform_mat_for_cv2(trans):
|
| 192 |
+
"""
|
| 193 |
+
Function:
|
| 194 |
+
----------
|
| 195 |
+
Convert Transform Matrix 'trans' into 'cv2_trans' which could be
|
| 196 |
+
directly used by cv2.warpAffine():
|
| 197 |
+
u = src_pts[:, 0]
|
| 198 |
+
v = src_pts[:, 1]
|
| 199 |
+
x = dst_pts[:, 0]
|
| 200 |
+
y = dst_pts[:, 1]
|
| 201 |
+
[x, y].T = cv_trans * [u, v, 1].T
|
| 202 |
+
|
| 203 |
+
Parameters:
|
| 204 |
+
----------
|
| 205 |
+
@trans: 3x3 np.array
|
| 206 |
+
transform matrix from uv to xy
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
----------
|
| 210 |
+
@cv2_trans: 2x3 np.array
|
| 211 |
+
transform matrix from src_pts to dst_pts, could be directly used
|
| 212 |
+
for cv2.warpAffine()
|
| 213 |
+
"""
|
| 214 |
+
cv2_trans = trans[:, 0:2].T
|
| 215 |
+
|
| 216 |
+
return cv2_trans
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True):
|
| 220 |
+
"""
|
| 221 |
+
Function:
|
| 222 |
+
----------
|
| 223 |
+
Find Similarity Transform Matrix 'cv2_trans' which could be
|
| 224 |
+
directly used by cv2.warpAffine():
|
| 225 |
+
u = src_pts[:, 0]
|
| 226 |
+
v = src_pts[:, 1]
|
| 227 |
+
x = dst_pts[:, 0]
|
| 228 |
+
y = dst_pts[:, 1]
|
| 229 |
+
[x, y].T = cv_trans * [u, v, 1].T
|
| 230 |
+
|
| 231 |
+
Parameters:
|
| 232 |
+
----------
|
| 233 |
+
@src_pts: Kx2 np.array
|
| 234 |
+
source points, each row is a pair of coordinates (x, y)
|
| 235 |
+
@dst_pts: Kx2 np.array
|
| 236 |
+
destination points, each row is a pair of transformed
|
| 237 |
+
coordinates (x, y)
|
| 238 |
+
reflective: True or False
|
| 239 |
+
if True:
|
| 240 |
+
use reflective similarity transform
|
| 241 |
+
else:
|
| 242 |
+
use non-reflective similarity transform
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
----------
|
| 246 |
+
@cv2_trans: 2x3 np.array
|
| 247 |
+
transform matrix from src_pts to dst_pts, could be directly used
|
| 248 |
+
for cv2.warpAffine()
|
| 249 |
+
"""
|
| 250 |
+
trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective)
|
| 251 |
+
cv2_trans = cvt_tform_mat_for_cv2(trans)
|
| 252 |
+
|
| 253 |
+
return cv2_trans
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
"""
|
| 258 |
+
u = [0, 6, -2]
|
| 259 |
+
v = [0, 3, 5]
|
| 260 |
+
x = [-1, 0, 4]
|
| 261 |
+
y = [-1, -10, 4]
|
| 262 |
+
|
| 263 |
+
# In Matlab, run:
|
| 264 |
+
#
|
| 265 |
+
# uv = [u'; v'];
|
| 266 |
+
# xy = [x'; y'];
|
| 267 |
+
# tform_sim=cp2tform(uv,xy,'similarity');
|
| 268 |
+
#
|
| 269 |
+
# trans = tform_sim.tdata.T
|
| 270 |
+
# ans =
|
| 271 |
+
# -0.0764 -1.6190 0
|
| 272 |
+
# 1.6190 -0.0764 0
|
| 273 |
+
# -3.2156 0.0290 1.0000
|
| 274 |
+
# trans_inv = tform_sim.tdata.Tinv
|
| 275 |
+
# ans =
|
| 276 |
+
#
|
| 277 |
+
# -0.0291 0.6163 0
|
| 278 |
+
# -0.6163 -0.0291 0
|
| 279 |
+
# -0.0756 1.9826 1.0000
|
| 280 |
+
# xy_m=tformfwd(tform_sim, u,v)
|
| 281 |
+
#
|
| 282 |
+
# xy_m =
|
| 283 |
+
#
|
| 284 |
+
# -3.2156 0.0290
|
| 285 |
+
# 1.1833 -9.9143
|
| 286 |
+
# 5.0323 2.8853
|
| 287 |
+
# uv_m=tforminv(tform_sim, x,y)
|
| 288 |
+
#
|
| 289 |
+
# uv_m =
|
| 290 |
+
#
|
| 291 |
+
# 0.5698 1.3953
|
| 292 |
+
# 6.0872 2.2733
|
| 293 |
+
# -2.6570 4.3314
|
| 294 |
+
"""
|
| 295 |
+
u = [0, 6, -2]
|
| 296 |
+
v = [0, 3, 5]
|
| 297 |
+
x = [-1, 0, 4]
|
| 298 |
+
y = [-1, -10, 4]
|
| 299 |
+
|
| 300 |
+
uv = np.array((u, v)).T
|
| 301 |
+
xy = np.array((x, y)).T
|
| 302 |
+
|
| 303 |
+
print("\n--->uv:")
|
| 304 |
+
print(uv)
|
| 305 |
+
print("\n--->xy:")
|
| 306 |
+
print(xy)
|
| 307 |
+
|
| 308 |
+
trans, trans_inv = get_similarity_transform(uv, xy)
|
| 309 |
+
|
| 310 |
+
print("\n--->trans matrix:")
|
| 311 |
+
print(trans)
|
| 312 |
+
|
| 313 |
+
print("\n--->trans_inv matrix:")
|
| 314 |
+
print(trans_inv)
|
| 315 |
+
|
| 316 |
+
print("\n---> apply transform to uv")
|
| 317 |
+
print("\nxy_m = uv_augmented * trans")
|
| 318 |
+
uv_aug = np.hstack((uv, np.ones((uv.shape[0], 1))))
|
| 319 |
+
xy_m = np.dot(uv_aug, trans)
|
| 320 |
+
print(xy_m)
|
| 321 |
+
|
| 322 |
+
print("\nxy_m = tformfwd(trans, uv)")
|
| 323 |
+
xy_m = tformfwd(trans, uv)
|
| 324 |
+
print(xy_m)
|
| 325 |
+
|
| 326 |
+
print("\n---> apply inverse transform to xy")
|
| 327 |
+
print("\nuv_m = xy_augmented * trans_inv")
|
| 328 |
+
xy_aug = np.hstack((xy, np.ones((xy.shape[0], 1))))
|
| 329 |
+
uv_m = np.dot(xy_aug, trans_inv)
|
| 330 |
+
print(uv_m)
|
| 331 |
+
|
| 332 |
+
print("\nuv_m = tformfwd(trans_inv, xy)")
|
| 333 |
+
uv_m = tformfwd(trans_inv, xy)
|
| 334 |
+
print(uv_m)
|
| 335 |
+
|
| 336 |
+
uv_m = tforminv(trans, xy)
|
| 337 |
+
print("\nuv_m = tforminv(trans, xy)")
|
| 338 |
+
print(uv_m)
|
lib/face_alignment/mtcnn_pytorch/src/visualization_utils.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2017 Dan Antoshchenko
|
| 2 |
+
|
| 3 |
+
# SPDX-License-Identifier: MIT
|
| 4 |
+
|
| 5 |
+
from PIL import ImageDraw
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def show_bboxes(img, bounding_boxes, facial_landmarks=[]):
|
| 9 |
+
"""Draw bounding boxes and facial landmarks.
|
| 10 |
+
|
| 11 |
+
Arguments:
|
| 12 |
+
img: an instance of PIL.Image.
|
| 13 |
+
bounding_boxes: a float numpy array of shape [n, 5].
|
| 14 |
+
facial_landmarks: a float numpy array of shape [n, 10].
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
an instance of PIL.Image.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
img_copy = img.copy()
|
| 21 |
+
draw = ImageDraw.Draw(img_copy)
|
| 22 |
+
|
| 23 |
+
for b in bounding_boxes:
|
| 24 |
+
draw.rectangle([(b[0], b[1]), (b[2], b[3])], outline="white")
|
| 25 |
+
|
| 26 |
+
for p in facial_landmarks:
|
| 27 |
+
for i in range(5):
|
| 28 |
+
draw.ellipse(
|
| 29 |
+
[(p[i] - 1.0, p[i + 5] - 1.0), (p[i] + 1.0, p[i + 5] + 1.0)],
|
| 30 |
+
outline="blue",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
return img_copy
|
lib/face_alignment/mtcnn_pytorch/src/weights/onet.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:313141c3646bebb73cb8350a2d5fee4c7f044fb96304b46ccc21aeea8b818f83
|
| 3 |
+
size 2345483
|
lib/face_alignment/mtcnn_pytorch/src/weights/pnet.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03e19e5c473932ab38f5a6308fe6210624006994a687e858d1dcda53c66f18cb
|
| 3 |
+
size 41271
|
lib/face_alignment/mtcnn_pytorch/src/weights/rnet.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5660aad67688edc9e8a3dd4e47ed120932835e06a8a711a423252a6f2c747083
|
| 3 |
+
size 604651
|
lib/models.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2025 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Francois Poh <francois.poh22@imperial.ac.uk>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
# ArtFace contains the code for the paper: https://www.idiap.ch/paper/artface/
|
| 8 |
+
# It provides a facial recognition model for historical portraits, and scripts to reproduce the experiments in the paper.
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Model:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
+
|
| 21 |
+
def __call__(self, path):
|
| 22 |
+
image = Image.open(path).convert("RGB")
|
| 23 |
+
image.filename = path
|
| 24 |
+
embedding = self.get_embedding(image)
|
| 25 |
+
if embedding is None:
|
| 26 |
+
return None
|
| 27 |
+
if isinstance(embedding, torch.Tensor):
|
| 28 |
+
return embedding.cpu().detach().numpy().squeeze()
|
| 29 |
+
return embedding
|
| 30 |
+
|
| 31 |
+
def get_embedding(self, image):
|
| 32 |
+
raise NotImplementedError("Subclasses must implement get_embedding")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class CLIPModel(Model):
|
| 36 |
+
def __init__(self, checkpoint="openai/clip-vit-base-patch16"):
|
| 37 |
+
super().__init__()
|
| 38 |
+
from transformers import AutoProcessor, CLIPVisionModel
|
| 39 |
+
|
| 40 |
+
self.model = CLIPVisionModel.from_pretrained(
|
| 41 |
+
checkpoint, attn_implementation="eager"
|
| 42 |
+
).to(self.device)
|
| 43 |
+
self.processor = AutoProcessor.from_pretrained(checkpoint)
|
| 44 |
+
|
| 45 |
+
def get_embedding(self, image, output_attentions=False):
|
| 46 |
+
inputs = self.processor(images=image, return_tensors="pt").to(self.device)
|
| 47 |
+
image_features = self.model(**inputs, output_attentions=output_attentions)
|
| 48 |
+
|
| 49 |
+
if output_attentions:
|
| 50 |
+
return image_features.pooler_output, image_features.attentions
|
| 51 |
+
return image_features.pooler_output.squeeze(0)
|
| 52 |
+
|
| 53 |
+
def torch(self):
|
| 54 |
+
class CLIPVisionModelWrapper(torch.nn.Module):
|
| 55 |
+
def __init__(self, model):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.model = model
|
| 58 |
+
self.device = model.device
|
| 59 |
+
|
| 60 |
+
def forward(self, x, output_attentions=False):
|
| 61 |
+
output = self.model(pixel_values=x, output_attentions=output_attentions)
|
| 62 |
+
if output_attentions:
|
| 63 |
+
return output.pooler_output, output.attentions
|
| 64 |
+
return output.pooler_output
|
| 65 |
+
|
| 66 |
+
def preprocess(image):
|
| 67 |
+
inputs = self.processor(images=image, return_tensors="pt").to(self.device)
|
| 68 |
+
return inputs["pixel_values"].squeeze(0)
|
| 69 |
+
|
| 70 |
+
return CLIPVisionModelWrapper(self.model), preprocess
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class OnnxModel(Model):
|
| 74 |
+
def __init__(self, model_path, checkpoint=None):
|
| 75 |
+
super().__init__()
|
| 76 |
+
from onnx2torch import convert
|
| 77 |
+
|
| 78 |
+
self.transform = transforms.Compose(
|
| 79 |
+
[
|
| 80 |
+
transforms.Resize((112, 112)),
|
| 81 |
+
transforms.Lambda(
|
| 82 |
+
lambda x: x.float()
|
| 83 |
+
if isinstance(x, torch.Tensor)
|
| 84 |
+
else transforms.ToTensor()(x)
|
| 85 |
+
),
|
| 86 |
+
transforms.Normalize(
|
| 87 |
+
mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]
|
| 88 |
+
), # InsightFace uses [-1, 1] pixel range
|
| 89 |
+
]
|
| 90 |
+
)
|
| 91 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 92 |
+
if not os.path.exists(model_path):
|
| 93 |
+
import shutil
|
| 94 |
+
from insightface.utils import download
|
| 95 |
+
|
| 96 |
+
dirname = os.path.dirname(model_path)
|
| 97 |
+
download(sub_dir=".", name="antelopev2", root=dirname)
|
| 98 |
+
os.makedirs(dirname, exist_ok=True)
|
| 99 |
+
os.replace(f"{dirname}/antelopev2/antelopev2/glintr100.onnx", model_path)
|
| 100 |
+
shutil.rmtree(f"{dirname}/antelopev2")
|
| 101 |
+
os.remove(f"{dirname}/antelopev2.zip")
|
| 102 |
+
self.model = convert(model_path)
|
| 103 |
+
if checkpoint:
|
| 104 |
+
print(f"Loading weights from {checkpoint}")
|
| 105 |
+
self.model.load_state_dict(torch.load(checkpoint))
|
| 106 |
+
self.model.to(self.device)
|
| 107 |
+
self.model.eval()
|
| 108 |
+
|
| 109 |
+
def get_embedding(self, image):
|
| 110 |
+
image = self.transform(image).unsqueeze(0).to(self.device)
|
| 111 |
+
return self.model(image).squeeze(0)
|
| 112 |
+
|
| 113 |
+
def torch(self):
|
| 114 |
+
def preprocess(image):
|
| 115 |
+
return self.transform(image).to(self.device)
|
| 116 |
+
|
| 117 |
+
self.model.device = self.device
|
| 118 |
+
return self.model, preprocess
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class TrainedModel(Model):
|
| 122 |
+
def __init__(self, model_name, checkpoint, base_model_args={}):
|
| 123 |
+
from lib.utils import load_checkpoint
|
| 124 |
+
|
| 125 |
+
super().__init__()
|
| 126 |
+
base_model, self.processor = get_model(model_name, base_model_args).torch()
|
| 127 |
+
self.model = load_checkpoint(base_model, checkpoint)
|
| 128 |
+
self.model.to(self.device)
|
| 129 |
+
self.model.eval()
|
| 130 |
+
|
| 131 |
+
def get_embedding(self, image, output_attentions=False):
|
| 132 |
+
inputs = self.processor(image)
|
| 133 |
+
inputs = (
|
| 134 |
+
[x.to(self.device).unsqueeze(0) for x in inputs]
|
| 135 |
+
if isinstance(inputs, list)
|
| 136 |
+
else inputs.to(self.device).unsqueeze(0)
|
| 137 |
+
)
|
| 138 |
+
with torch.no_grad():
|
| 139 |
+
if output_attentions:
|
| 140 |
+
image_features = self.model(inputs, output_attentions=output_attentions)
|
| 141 |
+
return image_features[0].squeeze(0), image_features[1]
|
| 142 |
+
else:
|
| 143 |
+
image_features = self.model(inputs)
|
| 144 |
+
return image_features.squeeze(0)
|
| 145 |
+
|
| 146 |
+
def torch(self):
|
| 147 |
+
return self.model, self.processor
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class FusionInput(list):
|
| 151 |
+
def __init__(self, images):
|
| 152 |
+
super().__init__(images)
|
| 153 |
+
|
| 154 |
+
def unsqueeze(self, dim):
|
| 155 |
+
self[:] = [item.unsqueeze(dim) for item in self]
|
| 156 |
+
return self
|
| 157 |
+
|
| 158 |
+
def to(self, device):
|
| 159 |
+
self[:] = [item.to(device) for item in self]
|
| 160 |
+
return self
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class FusionModel(Model):
|
| 164 |
+
def __init__(self, models, head="none"):
|
| 165 |
+
super().__init__()
|
| 166 |
+
self.model_names = [name for name, _ in models]
|
| 167 |
+
self.models = [get_model(name, args) for name, args in models]
|
| 168 |
+
|
| 169 |
+
def get_embedding(self, image):
|
| 170 |
+
embeddings = [model.get_embedding(image) for model in self.models]
|
| 171 |
+
embeddings = [F.normalize(emb, dim=0) for emb in embeddings]
|
| 172 |
+
return F.normalize(torch.cat(embeddings, dim=0), dim=0)
|
| 173 |
+
|
| 174 |
+
def torch(self):
|
| 175 |
+
from lib.ModelWrappers import FusionModelWrapper
|
| 176 |
+
|
| 177 |
+
preprocessors = [model.torch()[1] for model in self.models]
|
| 178 |
+
|
| 179 |
+
def preprocess(image):
|
| 180 |
+
return FusionInput(preprocessor(image) for preprocessor in preprocessors)
|
| 181 |
+
|
| 182 |
+
return FusionModelWrapper(
|
| 183 |
+
self.models, self.model_names, self.device
|
| 184 |
+
), preprocess
|
| 185 |
+
|
| 186 |
+
def get_submodel(self, name):
|
| 187 |
+
return getattr(self, name)
|
| 188 |
+
|
| 189 |
+
def set_submodel(self, name, model):
|
| 190 |
+
return setattr(self, name, model)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
models = {
|
| 194 |
+
"clip": (CLIPModel, {"checkpoint": "openai/clip-vit-base-patch16"}),
|
| 195 |
+
"lora": (
|
| 196 |
+
TrainedModel,
|
| 197 |
+
{
|
| 198 |
+
"model_name": "clip",
|
| 199 |
+
"checkpoint": "Idiap/ArtFace-CLIP-LoRA",
|
| 200 |
+
},
|
| 201 |
+
),
|
| 202 |
+
"ires100": (OnnxModel, {"model_path": "checkpoints/antelopev2/glintr100.onnx"}),
|
| 203 |
+
"ires100-tune": (
|
| 204 |
+
TrainedModel,
|
| 205 |
+
{
|
| 206 |
+
"model_name": "ires100",
|
| 207 |
+
"checkpoint": "Idiap/ArtFace-IResNet100-Tuned",
|
| 208 |
+
},
|
| 209 |
+
),
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def get_model(name, args={}):
|
| 214 |
+
import ast
|
| 215 |
+
|
| 216 |
+
model_args = {}
|
| 217 |
+
if isinstance(args, list):
|
| 218 |
+
for arg in args:
|
| 219 |
+
if "=" not in arg:
|
| 220 |
+
raise ValueError(
|
| 221 |
+
f"Invalid argument format for model arguments. Expected 'key=value' pairs, got '{arg}'."
|
| 222 |
+
)
|
| 223 |
+
key, value = arg.split("=", 1)
|
| 224 |
+
try:
|
| 225 |
+
model_args[key] = ast.literal_eval(value)
|
| 226 |
+
except (ValueError, SyntaxError):
|
| 227 |
+
model_args[key] = value
|
| 228 |
+
elif isinstance(args, dict):
|
| 229 |
+
model_args = args
|
| 230 |
+
|
| 231 |
+
if name not in models:
|
| 232 |
+
raise ValueError("Unrecognised model name!")
|
| 233 |
+
return models[name][0](**dict(models[name][1], **model_args))
|
lib/utils.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2026 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Samuel Michel <samuel.michel@idiap.ch>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
# ArtFace contains the code for the paper: https://www.idiap.ch/paper/artface/
|
| 8 |
+
# It provides a facial recognition model for historical portraits, and scripts to reproduce the experiments in the paper.
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from lib.ModelWrappers import FusionModelWrapper
|
| 12 |
+
import glob
|
| 13 |
+
import zipfile
|
| 14 |
+
import torch
|
| 15 |
+
from huggingface_hub import snapshot_download, repo_info
|
| 16 |
+
from typing import Optional
|
| 17 |
+
from huggingface_hub.utils import RepositoryNotFoundError
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def repo_exists(
|
| 21 |
+
repo_id: str, repo_type: Optional[str] = None, token: Optional[str] = None
|
| 22 |
+
) -> bool:
|
| 23 |
+
try:
|
| 24 |
+
repo_info(repo_id, repo_type=repo_type, token=token)
|
| 25 |
+
return True
|
| 26 |
+
except RepositoryNotFoundError:
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def resolve_checkpoint(checkpoint):
|
| 31 |
+
if os.path.exists(checkpoint):
|
| 32 |
+
return checkpoint
|
| 33 |
+
if repo_exists(checkpoint):
|
| 34 |
+
local_dir = snapshot_download(repo_id=checkpoint)
|
| 35 |
+
for zip_path in glob.glob(os.path.join(local_dir, "*.zip")):
|
| 36 |
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
| 37 |
+
zf.extractall(local_dir)
|
| 38 |
+
return local_dir
|
| 39 |
+
return checkpoint
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_checkpoint(model, checkpoint):
|
| 43 |
+
checkpoint = resolve_checkpoint(checkpoint)
|
| 44 |
+
|
| 45 |
+
if isinstance(model, FusionModelWrapper):
|
| 46 |
+
for name, submodel in model.named_submodels():
|
| 47 |
+
ckpt = f"{checkpoint}/{name}"
|
| 48 |
+
submodel = load_checkpoint(submodel, ckpt)
|
| 49 |
+
model.set_submodel(name, submodel)
|
| 50 |
+
return model
|
| 51 |
+
|
| 52 |
+
# Extract zip files if present (for local checkpoints)
|
| 53 |
+
zips = glob.glob(f"{checkpoint}/*.zip") + glob.glob(
|
| 54 |
+
f"{os.path.dirname(checkpoint)}/*.zip"
|
| 55 |
+
)
|
| 56 |
+
if zips:
|
| 57 |
+
import zipfile
|
| 58 |
+
|
| 59 |
+
with zipfile.ZipFile(zips[0], "r") as zip_ref:
|
| 60 |
+
zip_ref.extractall(os.path.dirname(zips[0]))
|
| 61 |
+
|
| 62 |
+
# Look for .pth state-dict files (direct or in subdirectories)
|
| 63 |
+
ckpt = glob.glob(f"{checkpoint}/*.pth") or glob.glob(
|
| 64 |
+
f"{checkpoint}/**/*.pth", recursive=True
|
| 65 |
+
)
|
| 66 |
+
if ckpt:
|
| 67 |
+
model.load_state_dict(torch.load(ckpt[0], map_location="cpu"))
|
| 68 |
+
else:
|
| 69 |
+
from peft import PeftModel
|
| 70 |
+
|
| 71 |
+
# Adapter files may be in a subdirectory after zip extraction
|
| 72 |
+
adapter_configs = glob.glob(
|
| 73 |
+
f"{checkpoint}/**/adapter_config.json", recursive=True
|
| 74 |
+
)
|
| 75 |
+
adapter_dir = (
|
| 76 |
+
os.path.dirname(adapter_configs[0]) if adapter_configs else checkpoint
|
| 77 |
+
)
|
| 78 |
+
model = PeftModel.from_pretrained(model, adapter_dir, is_trainable=True)
|
| 79 |
+
return model
|
requirements.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: Copyright © 2026 Idiap Research Institute <contact@idiap.ch>
|
| 2 |
+
|
| 3 |
+
# SPDX-FileContributor: Samuel Michel <samuel.michel@idiap.ch>
|
| 4 |
+
|
| 5 |
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
| 6 |
+
|
| 7 |
+
caffe==0.1.0
|
| 8 |
+
huggingface_hub
|
| 9 |
+
insightface==0.7.3
|
| 10 |
+
matplotlib==3.10.5
|
| 11 |
+
natsort==8.4.0
|
| 12 |
+
numpy==2.3.2
|
| 13 |
+
onnx2torch==1.5.15
|
| 14 |
+
onnxruntime-gpu
|
| 15 |
+
opencv_python==4.11.0.86
|
| 16 |
+
opencv_python_headless==4.11.0.86
|
| 17 |
+
pandas==2.3.1
|
| 18 |
+
peft==0.15.2
|
| 19 |
+
Pillow==11.3.0
|
| 20 |
+
scikit_learn
|
| 21 |
+
seaborn==0.13.2
|
| 22 |
+
torch==2.7.1
|
| 23 |
+
torchvision==0.22.1
|
| 24 |
+
tqdm==4.67.1
|
| 25 |
+
transformers==4.51.3
|
| 26 |
+
gradio
|