Repository: yinguobing/facial-landmark-detection-hrnet
Branch: master
Commit: 597d48e86acb
Files: 34
Total size: 37.5 MB
Directory structure:
gitextract_1o3payh5/
├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── assets/
│ └── face_model/
│ ├── saved_model.pb
│ └── variables/
│ ├── variables.data-00000-of-00001
│ └── variables.index
├── callbacks.py
├── coreml_conversion.py
├── dataset.py
├── evaluate.py
├── fmd/
│ ├── __init__.py
│ ├── aflw2000_3d.py
│ ├── afw.py
│ ├── ds300vw.py
│ ├── ds300w.py
│ ├── ds300w_lp.py
│ ├── helen.py
│ ├── ibug.py
│ ├── lfpw.py
│ ├── mark_dataset/
│ │ ├── __init__.py
│ │ ├── data_pair.py
│ │ ├── dataset.py
│ │ └── util.py
│ ├── universal.py
│ └── wflw.py
├── mark_operator.py
├── network.py
├── postprocessing.py
├── predict.py
├── preprocessing.py
├── pruning.py
├── quantization.py
└── train.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# TensorFlow training files
logs
checkpoints
exported
tflite
optimized
================================================
FILE: .gitmodules
================================================
[submodule "models"]
path = models
url = https://github.com/yinguobing/models.git
[submodule "face_detector"]
path = face_detector
url = https://github.com/yinguobing/face_detector.git
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
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.
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.
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.
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.
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.
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.
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.
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.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"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.
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.
A "covered work" means either the unmodified Program or a work based
on the Program.
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.
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.
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.
1. Source Code.
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.
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.
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.
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.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
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.
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.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
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.
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.
4. Conveying Verbatim Copies.
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.
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.
5. Conveying Modified Source Versions.
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:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
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".
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.
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.
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.
6. Conveying Non-Source Forms.
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:
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.
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.
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.
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.
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.
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.
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.
"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.
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).
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.
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.
7. Additional Terms.
"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.
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.
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:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
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
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
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
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.
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.
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.
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.
8. Termination.
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).
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.
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.
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.
9. Acceptance Not Required for Having Copies.
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.
10. Automatic Licensing of Downstream Recipients.
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.
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.
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.
11. Patents.
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".
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.
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.
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.
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.
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.
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.
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.
12. No Surrender of Others' Freedom.
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.
13. Use with the GNU Affero General Public License.
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.
14. Revised Versions of this License.
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.
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.
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.
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.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
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.
17. Interpretation of Sections 15 and 16.
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.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
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.
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.
Copyright (C)
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.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
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".
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
.
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
.
================================================
FILE: README.md
================================================
# facial-landmark-detection-hrnet
A TensorFlow implementation of HRNet for facial landmark detection.

Watch this demo video: [HRNet Facial Landmark Detection (bilibili)](https://www.bilibili.com/video/BV1Vy4y1C79p/).
## Features
- Support multiple public dataset: WFLW, IBUG, etc.
- Advanced model architecture: HRNet v2
- Data augmentation: randomly scale/rotate/flip
- Model optimization: quantization, pruning
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Prerequisites




### Installing
#### Get the source code for training
```shell
# From your favorite development directory
git clone --recursive https://github.com/yinguobing/facial-landmark-detection-hrnet.git
```
#### Generate the training data
There are multiple public facial mark datasets available which can be used to generate training heatmaps we need. For this training process the images will be augmented. The first step is transforming the dataset into a more uniform distribution that is easier to process. You can do this yourself or, use this repo:
```shell
# From your favorite development directory
git clone https://github.com/yinguobing/face-mesh-generator.git
# Checkout the desired branch
git checkout features/export_for_mark_regression
```
Use the module `generate_mesh_dataset.py` to generate training data. Popular public datasets like IBUG, 300-W, WFLW are supported. Checkout the full list here: [facial-landmark-dataset](https://github.com/yinguobing/facial-landmark-dataset).
## Training
Deep neural network training can be complicated as you have to make sure everything is ready like datasets, checkpoints, logs, etc. But do not worry. Following these steps you should be fine.
### Setup the model.
In the module `train.py`, setup your model's name and the number of marks.
```python
# What is the model's name?
name = "hrnetv2"
# How many marks are there for a single face sample?
number_marks = 98
```
### Set the training and testing datasets
These files do not change frequently so set them in the source code. Take WFLW as an example.
```python
# Training data.
train_files_dir = "/path/to/wflw_train"
# Testing data.
test_files_dir = "/path/to/wflw_test"
```
### Set the validation datasets
The loss value from this dataset will be used to decide which checkpoint should be preserved. Set `None` if no files available. Then about 512 of the training files will be used as validation samples.
```python
# Validation data.
val_files_dir = None
```
### Provide a sanity check image
This sample image will be logged into TensorBoard with detected marks drawing on it. In this way you can check the model's behavior visually during training.
```python
sample_image = "docs/face.jpg"
```
### Start training
Set the hyper parameters in the command line.
```Shell
python3 train.py --epochs=80 --batch_size=32
```
Training checkpoints can be found in directory `checkpoints`. Before training started, this directory will be checked and the model will be restored if any checkpoint is available. Only the best model (smallest validation loss) will be saved.
### Resume training
If training was interrupted, resume it by providing `--initial_epoch` argument.
```bash
python3 train.py --epochs=80 --initial_epoch=61
```
### Monitor the training process
Use TensorBoard. The log and profiling files are in directory `logs`
```shell
tensorboard --logdir /path/to/facial-landmark-detection-hrnet/logs
```
### Training speedup
You can download this checkpoint file to speedup the training process.
- [GoogleDrive](https://drive.google.com/file/d/1cQKrYdX0O7DsBodjTufzVzm70gXwsyaP/view?usp=sharing)
- [百度云盘](https://pan.baidu.com/s/1XDp6hDx_aXYTV5_OF1cc6g) (提取码 b3vm)
## Evaluation
A quick evaluation on validation datasets will be performed automatically after training. For a full evaluation, please run the `evaluate.py` file. The NME value will be printed after evaluation.
```
python3 evaluate.py
```
## Export
Even though the model wights are saved in the checkpoint, it is better to save the entire model so you won't need the source code to restore it. This is useful for inference and model optimization later.
### For cloud/PC applications
Exported model will be saved in `saved_model` format in directory `exported`. You can restore the model with `Keras` directly. Loading the model in OpenCV is also [supported](https://github.com/yinguobing/facial-landmark-detection-hrnet/issues/3).
```shell
python3 train.py --export_only=True
```
### For Android phones, embedded and IoT devices
TensorFlow lite and TensorFlow Model Optimization Toolkit will help you to get a optimized model for these applications. Please follow the instructions of the later section *Optimization*.
### For iPhone
Apple has developed a conversion tool named [coremltools](https://github.com/apple/coremltools) which can convert and quantize the TensorFlow model into the native model format supported and accelrated by iPhone's Neural Engine.
```bash
# Install the package
pip install --upgrade coremltools
# Do the conversion.
python3 coreml_conversion.py
```
## Inference
Check out module `predict.py` for details.
A pre-trained model is provided in case you want to try it in no time, or do not have adequate equipments to train it yourself.
URL: https://pan.baidu.com/s/1EQsB0LnSkfvoNjMvkFV5dQ
Access code: qg5e
## Optimization
Optimize the model so it can run on mobile, embedded, and IoT devices. TensorFlow supports post-training quantization, quantization aware training, pruning, and clustering.
### Post training quantization
There are multiple means for post training quantization: dynamic range, integer only, float16. To quantize the model, run:
```bash
python3 quantization.py
```
Quantized tflite file will be find in the `optimized` directory.
### Pruning
Model pruning could dramatically reduce the model size while minimize the side effects on model accuracy. There is a demo video showing the performance of a pruned model with 80% of weights pruned (set to zero): [TensorFlow model pruning (bilibili)](https://www.bilibili.com/video/BV1Uz4y1o7Fb/)
To prune the model in this repo, run:
```bash
python3 pruning.py
```
Pruned model file will be find in the `optimized` directory.
### Quantization aware training
Due to the conflict between pruning and quantization aware training, please checkout the other branch for details.
```bash
git checkout features/quantization-aware-training
python3 train.py --quantization=True
```
## Authors
Yin Guobing (尹国冰) - yinguobing

## License

## Acknowledgments
The HRNet authors and the dataset authors who made their work public.
================================================
FILE: assets/face_model/saved_model.pb
================================================
[File too large to display: 15.9 MB]
================================================
FILE: assets/face_model/variables/variables.data-00000-of-00001
================================================
[File too large to display: 21.5 MB]
================================================
FILE: callbacks.py
================================================
"""A module containing custom callbacks."""
import cv2
import tensorflow as tf
from tensorflow import keras
from preprocessing import normalize
from postprocessing import parse_heatmaps
class EpochBasedLearningRateSchedule(keras.callbacks.Callback):
"""Sets the learning rate according to epoch schedule."""
def __init__(self, schedule):
"""
Args:
schedule: a tuple that takes an epoch index (integer, indexed from 0)
and current learning rate.
"""
super(EpochBasedLearningRateSchedule, self).__init__()
self.schedule = schedule
def on_epoch_begin(self, epoch, logs=None):
if not hasattr(self.model.optimizer, "lr"):
raise ValueError('Optimizer must have a "lr" attribute.')
# Get the current learning rate from model's optimizer.
lr = float(tf.keras.backend.get_value(
self.model.optimizer.learning_rate))
# Get the scheduled learning rate.
def _lr_schedule(epoch, lr, schedule):
"""Helper function to retrieve the scheduled learning rate based on
epoch."""
if epoch < schedule[0][0] or epoch > schedule[-1][0]:
return lr
for i in range(len(schedule)):
if epoch == schedule[i][0]:
return schedule[i][1]
return lr
scheduled_lr = _lr_schedule(epoch, lr, self.schedule)
# Set the value back to the optimizer before this epoch starts
tf.keras.backend.set_value(self.model.optimizer.lr, scheduled_lr)
print("\nEpoch %05d: Learning rate is %6.6f." % (epoch, scheduled_lr))
class LogImages(keras.callbacks.Callback):
def __init__(self, logdir, sample_image):
super().__init__()
self.file_writer = tf.summary.create_file_writer(logdir)
self.sample_image = sample_image
def on_epoch_end(self, epoch, logs={}):
# Read in the image file.
image = cv2.imread(self.sample_image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
img = cv2.resize(image, (256, 256))
img = normalize(img)
# Do prediction.
heatmaps = self.model.predict(tf.expand_dims(img, 0))[0]
# Parse the heatmaps to get mark locations.
marks, _ = parse_heatmaps(heatmaps, image.shape[:2])
for mark in marks:
cv2.circle(image, tuple(mark.astype(int)), 2, (0, 255, 0), -1)
with self.file_writer.as_default():
# tf.summary needs a 4D tensor
img_tensor = tf.expand_dims(image, 0)
tf.summary.image("test-sample", img_tensor, step=epoch)
================================================
FILE: coreml_conversion.py
================================================
"""Convert the TensorFlow model to CoreML model supported by Apple devices.
MacOS is REQUIRED for quantization.
"""
import os
import coremltools as ct
import tensorflow as tf
from coremltools.models.neural_network import quantization_utils
if __name__ == "__main__":
# Converted model will be exported here.
export_dir = "./mlmodels"
if not os.path.exists(export_dir):
os.mkdir(export_dir)
# Restore the model.
model = tf.keras.models.load_model("./exported")
# Do the conversion.
mlmodel = ct.convert(model)
mlmodel.save("./mlmodels/hrnetv2_fp32.mlmodel")
# Quantization: FP16
model_fp16 = quantization_utils.quantize_weights(mlmodel, nbits=16)
model_fp16.save("./mlmodels/hrnetv2_fp16.mlmodel")
# Quantization: INT8
model_int8 = quantization_utils.quantize_weights(mlmodel, nbits=8)
model_int8.save("./mlmodels/model_int8.mlmodel")
================================================
FILE: dataset.py
================================================
"""This module provides the training and testing datasets."""
import cv2
import numpy as np
import tensorflow as tf
from fmd.universal import Universal
from preprocessing import (flip_randomly, generate_heatmaps, normalize,
rotate_randomly, scale_randomly)
def data_generator(data_dir, name, image_size, number_marks, training):
"""A generator function used to make TensorFlow dataset.
Currently only `universal` dataset (image + json) of FMD is supported.
Args:
data_dir: the direcotry of the raw image and json files.
name: the name of the dataset.
image_size: the width and height of the input images for the network.
number_marks: how many marks/points does one sample contains.
training: generated data will be used for training or not.
Yields:
preprocessed image and heatmaps.
"""
# Initialize the dataset with files.
dataset = Universal(name.decode("utf-8"))
dataset.populate_dataset(data_dir.decode("utf-8"), key_marks_indices=None)
dataset.meta.update({"num_marks": number_marks})
image_size = tuple(image_size)
width, _ = image_size
for sample in dataset:
# Follow the official preprocessing implementation.
image = sample.read_image("RGB")
marks = sample.marks
if training:
# Rotate the image randomly.
image, marks = rotate_randomly(image, marks, (-30, 30))
# Scale the image randomly.
image, marks = scale_randomly(image, marks, output_size=image_size)
# Flip the image randomly.
image, marks = flip_randomly(image, marks)
else:
# Scale the image to output size.
marks = marks / image.shape[0] * width
image = cv2.resize(image, image_size)
# Normalize the image.
image_float = normalize(image.astype(float))
# Generate heatmaps.
heatmaps = generate_heatmaps(marks, width, (64, 64))
heatmaps = np.transpose(heatmaps, (1, 2, 0))
yield image_float, heatmaps
class WFLWSequence(tf.keras.utils.Sequence):
"""A Sequence implementation for WFLW dataset generation.
This class is not used in training. It simply demonstrates how to generate
a TensorFlow dataset by using Keras `Sequence`.
"""
def __init__(self, data_dir, name, training, batch_size):
self.training = training
self.batch_size = batch_size
self.filenames = []
self.marks = []
# Initialize the dataset with files.
dataset = Universal(name)
dataset.populate_dataset(data_dir, key_marks_indices=[
60, 64, 68, 72, 76, 82])
for sample in dataset:
self.filenames.append(sample.image_file)
self.marks.append(sample.marks)
def __len__(self):
return int(np.ceil(len(self.filenames) / float(self.batch_size)))
def __getitem__(self, index):
batch_files = self.filenames[index *
self.batch_size:(index + 1) * self.batch_size]
batch_marks = self.marks[index *
self.batch_size:(index + 1) * self.batch_size]
batch_x = []
batch_y = []
for filename, marks in zip(batch_files, batch_marks):
# Follow the official preprocessing implementation.
image = cv2.imread(filename)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
if self.training:
# Rotate the image randomly.
image, marks = rotate_randomly(image, marks, (-30, 30))
# Scale the image randomly.
image, marks = scale_randomly(image, marks)
# Flip the image randomly.
image, marks = flip_randomly(image, marks)
else:
# Scale the image to output size.
marks = marks / image.shape[0] * 256
image = cv2.resize(image, (256, 256))
# Normalize the image.
image_float = normalize(image.astype(float))
# Generate heatmaps.
_, img_width, _ = image.shape
heatmaps = generate_heatmaps(marks, img_width, (64, 64))
heatmaps = np.transpose(heatmaps, (1, 2, 0))
# Generate the batch data.
batch_x.append(image_float)
batch_y.append(heatmaps)
return np.array(batch_x), np.array(batch_y)
def build_dataset(data_dir,
name,
number_marks,
image_shape=(256, 256, 3),
training=True,
batch_size=None,
shuffle=True,
prefetch=None):
"""Generate TensorFlow dataset from image and json files.
Args:
data_dir: the directory of the images and json files.
name: dataset name.
image_shape: the shape of the target output image of the dataset.
number_marks: how many marks/points does one sample contains.
training: True if dataset is for training.
batch_size: batch size.
shuffle: True if data should be shuffled.
prefetch: Set to True to prefetch data.
Returns:
a tf.data.dataset.
"""
dataset = tf.data.Dataset.from_generator(
data_generator,
output_types=(tf.float32, tf.float32),
output_shapes=(image_shape, (64, 64, number_marks)),
args=[data_dir, name, image_shape[:2], number_marks, training])
print("Dataset built from generator: {}".format(name))
# Shuffle the data.
if shuffle:
dataset = dataset.shuffle(1024)
# Batch the data.
dataset = dataset.batch(batch_size)
# Prefetch the data.
if prefetch is not None:
dataset = dataset.prefetch(prefetch)
return dataset
if __name__ == "__main__":
def top_k_indices(x, k):
"""Returns the k largest element indices from a numpy array. You can find
the original code here: https://stackoverflow.com/q/6910641
"""
flat = x.flatten()
indices = np.argpartition(flat, -k)[-k:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, x.shape)
def get_peak_location(heatmap, image_size=(256, 256)):
"""Return the interpreted location of the top 2 predictions."""
h_height, h_width = heatmap.shape
[y1, y2], [x1, x2] = top_k_indices(heatmap, 2)
x = (x1 + (x2 - x1)/4) / h_width * image_size[0]
y = (y1 + (y2 - y1)/4) / h_height * image_size[1]
return int(x), int(y)
def _parse_heatmaps(img, heatmaps):
# Parse the heatmaps to get mark locations.
heatmaps = np.transpose(heatmaps, (2, 0, 1))
for heatmap in heatmaps:
mark = get_peak_location(heatmap)
cv2.circle(img, mark, 2, (0, 255, 0), -1)
# Show individual heatmaps stacked.
heatmap_idvs = np.hstack(heatmaps[:8])
for row in range(1, 12, 1):
heatmap_idvs = np.vstack(
[heatmap_idvs, np.hstack(heatmaps[row:row+8])])
return img, heatmap_idvs
data_dir = "/home/robin/data/facial-marks/wflw_cropped/train"
batch_size = 1
# Build a sequence dataset.
dataset_sequence = make_wflw_dataset(data_dir, "wflw_sequence",
training=True,
batch_size=batch_size,
mode="sequence")
# Build dataset from generator.
dataset_from_generator = make_wflw_dataset(data_dir, "wflw_generator",
training=True,
batch_size=batch_size,
mode="generator")
if not isinstance(dataset_from_generator, tf.keras.utils.Sequence):
dataset_from_generator = dataset_from_generator.batch(batch_size)
for sample_s, sample_g in zip(dataset_sequence, dataset_from_generator):
img_s, heatmap_s = sample_s
img_g, heatmap_g = sample_g
img_s, heatmaps_s = _parse_heatmaps(img_s[0], heatmap_s[0])
img_g, heatmaps_g = _parse_heatmaps(
img_g[0].numpy(), heatmap_g[0].numpy())
# Show the result in windows.
cv2.imshow("images", np.hstack((img_s, img_g)))
cv2.imshow("heatmaps", np.hstack((heatmaps_s, heatmaps_g)))
if cv2.waitKey() == 27:
break
================================================
FILE: evaluate.py
================================================
"""Evaluation of the HRNet model on public facial mark datasets."""
import cv2
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import fmd
from postprocessing import parse_heatmaps
from preprocessing import crop_face, normalize
from quantization import TFLiteModelPredictor
def compute_nme(prediction, ground_truth):
"""This function is based on the official HRNet implementation."""
interocular = np.linalg.norm(ground_truth[60, ] - ground_truth[72, ])
rmse = np.sum(np.linalg.norm(
prediction - ground_truth, axis=1)) / (interocular)
return rmse
def evaluate(dataset: fmd.mark_dataset.dataset, model):
"""Evaluate the model on the dataset. The evaluation method should be the
same with the official code.
Args:
dataset: a FMD dataset
model: any model having `predict` method.
"""
# For NME
nme_count = 0
nme_sum = 0
count_failure_008 = 0
count_failure_010 = 0
# Loop though the dataset samples.
for sample in tqdm(dataset):
# Get image and marks.
image = sample.read_image()
marks = sample.marks
# Crop the face out of the image.
image_cropped, border, bbox = crop_face(image, marks, scale=1.2)
image_size = image_cropped.shape[:2]
# Get the prediction from the model.
image_cropped = cv2.resize(image_cropped, (256, 256))
img_rgb = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2RGB)
img_input = normalize(np.array(img_rgb, dtype=np.float32))
# Do prediction.
heatmaps = model.predict(tf.expand_dims(img_input, 0))[0]
# Parse the heatmaps to get mark locations.
marks_prediction, _ = parse_heatmaps(heatmaps, image_size)
# Transform the marks back to the original image dimensions.
x0 = bbox[0] - border
y0 = bbox[1] - border
marks_prediction[:, 0] += x0
marks_prediction[:, 1] += y0
# Compute NME.
nme_temp = compute_nme(marks_prediction, marks[:, :2])
if nme_temp > 0.08:
count_failure_008 += 1
if nme_temp > 0.10:
count_failure_010 += 1
nme_sum += nme_temp
nme_count = nme_count + 1
# # Visualize the result.
# for mark in marks_prediction:
# cv2.circle(image, tuple(mark.astype(int)), 2, (0, 255, 0), -1)
# cv2.imshow("cropped", image_cropped)
# cv2.imshow("image", image)
# if cv2.waitKey(1) == 27:
# break
# NME
nme = nme_sum / nme_count
failure_008_rate = count_failure_008 / nme_count
failure_010_rate = count_failure_010 / nme_count
msg = "NME:{:.4f}, [008]:{:.4f}, [010]:{:.4f}".format(
nme, failure_008_rate, failure_010_rate)
return msg
def make_dataset():
wflw_dir = "/home/robin/data/facial-marks/wflw/WFLW_images"
ds_wflw = fmd.wflw.WFLW(False, "wflw_test")
ds_wflw.populate_dataset(wflw_dir)
return ds_wflw
if __name__ == "__main__":
# Evaluate with FP32 model.
model = tf.keras.models.load_model("exported/hrnetv2")
print("FP32: ", evaluate(make_dataset(), model))
# # Evaluate with FP16 model.
# model_qdr = TFLiteModelPredictor(
# "./optimized/hrnet_quant_fp16.tflite")
# print("FP16 quantized:", evaluate(make_dataset(), model_qdr))
================================================
FILE: fmd/__init__.py
================================================
"""Facial landmark dataset toolkit.
Useage: https://github.com/yinguobing/facial-landmark-dataset
"""
from .aflw2000_3d import AFLW2000_3D
from .afw import AFW
from .ds300vw import DS300VW
from .ds300w import DS300W
from .helen import HELEN
from .ibug import IBUG
from .lfpw import LFPW
from .wflw import WFLW
================================================
FILE: fmd/aflw2000_3d.py
================================================
import cv2
import numpy as np
from scipy.io import loadmat
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class AFLW2000_3D(MarkDataset):
# To use this class, there are two functions should be overridden.
def populate_dataset(self, image_dir):
"""Populate the AFLW2000_3D dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the AFLW2000_3D dataset had the mark file named
# after the image file but with different extention name `mat`. We will
# make use of this.
self.mark_files = [img_path.split(
".")[-2] + ".mat" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For AFLW2000_3D the indices
# are 36, 39, 42, 45, 48, 54. Most of the time you need to do this
# manually. Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Chinese Academy of Sciences",
"year": 2015,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
mat_data = loadmat(mark_file)
marks = mat_data['pt3d_68'].T
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/afw.py
================================================
"""Toolkit for dataset AFW
Useage: https://github.com/yinguobing/facial-landmark-dataset/issues/4
"""
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class AFW(MarkDataset):
# To use this class, there are two functions need to be overridden.
def populate_dataset(self, image_dir):
"""Populate the AFW dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the AFW dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".pts" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For AFW the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Imperial College London",
"year": 2013,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
for line in fid:
if "version" in line or "points" in line or "{" in line or "}" in line:
continue
else:
loc_x, loc_y = line.strip().split(sep=" ")
marks.append([float(loc_x), float(loc_y), 0.0])
marks = np.array(marks, dtype=np.float)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/ds300vw.py
================================================
"""Dataset tools for 300VW.
Read this issue on GitHub before using:
https://github.com/yinguobing/facial-landmark-dataset/issues/5"""
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class DS300VW(MarkDataset):
# To use this class, there are two functions should be overridden.
def populate_dataset(self, image_dir):
"""Populate the 300vW dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the 300VW dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".pts" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For 300VW the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Imperial College London",
"year": 2015,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
for line in fid:
if "version" in line or "points" in line or "{" in line or "}" in line:
continue
else:
loc_x, loc_y = line.strip().split(sep=" ")
marks.append([float(loc_x), float(loc_y), 0.0])
marks = np.array(marks, dtype=np.float)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/ds300w.py
================================================
"""Toolkit for dataset 300W
Useage: https://github.com/yinguobing/facial-landmark-dataset/issues/1
"""
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class DS300W(MarkDataset):
# To use this class, there are two functions should be overridden.
def populate_dataset(self, image_dir):
"""Populate the 300W dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the 300W dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".pts" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For 300W the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Imperial College London",
"year": 2013,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
for line in fid:
if "version" in line or "points" in line or "{" in line or "}" in line:
continue
else:
loc_x, loc_y = line.strip().split(sep=" ")
marks.append([float(loc_x), float(loc_y), 0.0])
marks = np.array(marks, dtype=np.float)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/ds300w_lp.py
================================================
import cv2
import numpy as np
from scipy.io import loadmat
from mark_dataset.dataset import MarkDataset
from mark_dataset.util import FileListGenerator
class DS300W_LP(MarkDataset):
# To use this class, there are two functions should be overridden.
def populate_dataset(self, image_dir):
"""Populate the 300W_LP dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the 300W_LP dataset had the mark file named
# after the image file but with different extention name `mat`. We will
# make use of this.
self.mark_files = [img_path.split(
".")[-2] + ".mat" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For 300W_LP the indices
# are 36, 39, 42, 45, 48, 54. Most of the time you need to do this
# manually. Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Chinese Academy of Sciences",
"year": 2015,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
mat_data = loadmat(mark_file)
marks = np.pad(mat_data['pt2d'].T, (0, 1))
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/helen.py
================================================
"""Dataset tookit for HELEN.
Useage: https://github.com/yinguobing/facial-landmark-dataset/issues/3
"""
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class HELEN(MarkDataset):
# To use this class, there are two functions need to be overridden.
def populate_dataset(self, image_dir):
"""Populate the HELEN dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the HELEN dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".pts" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For HELEN the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Imperial College London",
"year": 2013,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
for line in fid:
if "version" in line or "points" in line or "{" in line or "}" in line:
continue
else:
loc_x, loc_y = line.strip().split(sep=" ")
marks.append([float(loc_x), float(loc_y), 0.0])
marks = np.array(marks, dtype=np.float)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/ibug.py
================================================
"""Dataset toolkit for IBUG
Useage: https://github.com/yinguobing/facial-landmark-dataset/issues/3
"""
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class IBUG(MarkDataset):
# To use this class, there are two functions need to be overridden.
def populate_dataset(self, image_dir):
"""Populate the IBUG dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the IBUG dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".pts" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For IBUG the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Imperial College London",
"year": 2013,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
for line in fid:
if "version" in line or "points" in line or "{" in line or "}" in line:
continue
else:
loc_x, loc_y = line.strip().split(sep=" ")
marks.append([float(loc_x), float(loc_y), 0.0])
marks = np.array(marks, dtype=np.float)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/lfpw.py
================================================
"""Dataset tookit for LFPW.
Useage: https://github.com/yinguobing/facial-landmark-dataset/issues/2
"""
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class LFPW(MarkDataset):
# To use this class, there are two functions need to be overridden.
def populate_dataset(self, image_dir):
"""Populate the LFPW dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the LFPW dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".pts" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For LFPW the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = [36, 39, 42, 45, 48, 54]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Imperial College London",
"year": 2013,
"num_marks": 68,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
for line in fid:
if "version" in line or "points" in line or "{" in line or "}" in line:
continue
else:
loc_x, loc_y = line.strip().split(sep=" ")
marks.append([float(loc_x), float(loc_y), 0.0])
marks = np.array(marks, dtype=np.float)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/mark_dataset/__init__.py
================================================
================================================
FILE: fmd/mark_dataset/data_pair.py
================================================
"""This module constains the implimentation of class DataPair."""
import json
import cv2
import numpy as np
class DataPair(object):
"""A pair of data consists of a single image and coresponding marks."""
def __init__(self, image_file, marks, key_marks_indices):
"""Construct a facial mark data pair
Args:
image_file: a path to the image.
marks: facial marks stored in a numpy array, as [[x, y, z], [x, y, z]
...].
key_marks_indices: the indices of key marks. Key marks are: left eye
left corner, left eye right corner, right eye left corner, right eye
right corner, mouse left corner, mouse right corner.
Returns:
a DataPair object.
"""
self.image_file = image_file
self.marks = marks
self.key_marks_indices = key_marks_indices
def read_image(self, format="BGR"):
"""Read in the image as a Numpy array.
Args:
format: Color channel order, "BGR" as default. Set it to "RGB" if you
want to use it in matplotlib.
Returns:
an image as numpy array.
"""
image_bgr = cv2.imread(self.image_file, cv2.IMREAD_COLOR)
if format is "RGB":
return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
return image_bgr
def get_marks(self):
"""Return all the marks.
Args:
None
Returns:
The full marks as a numpy array.
"""
return self.marks
def get_key_marks(self):
"""Return the key marks of the current marks, in the order of: left eye
left corner, left eye right corner, right eye left corner, right eye
right corner, mouse left corner, mouse right corner.
Args:
None
Returns:
key marks in form of [[x, y, z],[x, y, z]] as a numpy array.
"""
key_marks = []
[key_marks.append(self.marks[i]) for i in self.key_marks_indices]
return np.array(key_marks)
def save_mark_to_json(self, file_name):
"""Save the marks to a json file.
Args:
file_name: the full path of the json file.
Returns:
None
"""
with open(file_name, "w") as fid:
json.dump(self.marks.tolist(), fid)
================================================
FILE: fmd/mark_dataset/dataset.py
================================================
from abc import ABC, abstractmethod
from .data_pair import DataPair
import numpy as np
class MarkDataset(ABC):
def __init__(self, dataset_name):
self.meta = {"name": dataset_name,
"authors": None,
"year": None,
"num_marks": None,
"num_samples": None}
self.image_files = None
self.mark_files = None
self.key_marks_indices = None
self.index = 0
super().__init__()
def __str__(self):
# This function overridden makes the instance printable.
description = "".join("{}: {}\n".format(k, v)
for k, v in self.meta.items())
return description
def __len__(self):
_len = self.meta['num_samples']
return 0 if _len is None else _len
def __iter__(self):
return self
def __next__(self):
if self.index == len(self.image_files):
raise StopIteration
dp = self._make_datapair(self.index)
self.index += 1
return dp
def _make_datapair(self, data_index):
# Get the coresponding marks.
marks = self.get_marks_from_file(
self.mark_files[data_index]).astype(float)
# Construct a datapair.
return DataPair(self.image_files[data_index], marks, self.key_marks_indices)
@abstractmethod
def populate_dataset(self):
"""An abstract method to be overridden. This function should populate
the dataset with essential data, including:
* `image_files` This is a list of dataset image file paths. It should
contain all the image samples.
* `mark_files`. This is a list of dataset mark file paths. It should
contain all the mark files. Note alignment of image and mark files is
**required**. For instance:
image_files: ["a.jpg", "b.jpg", "c.jpg"]
mark_files; ["a.json", "b.json", "c.json"]
* `key_mark_indices` This is a list of indices of specific marks.
Currently they are: left eye left corner, left eye right corner, right
eye left corner, right eye right corner, mouse left corner, mouse right
corner.
Remember to set the meta data, even this is optional.
"""
pass
@abstractmethod
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
pass
def pick_one(self):
"""Randomly pick a data pair."""
# Pick a number randomly.
straw = np.random.randint(0, len(self.image_files))
return self._make_datapair(straw)
def export(self, export_dir):
"""Export the dataset in the FMD format.
Args:
export_dir: the directory to save the dataset.
"""
pass
================================================
FILE: fmd/mark_dataset/util.py
================================================
"""
Some convenient tools for dataset parsing and construction.
"""
import csv
import os
import cv2
class FileListGenerator:
"""Generate a list of specific files in directory."""
def __init__(self):
"""Initialization"""
# The list to be populated.
self.file_list = []
def generate_list(self, target_dir, format_list=["jpg", "png"]):
"""Generate the file list of format_list in target_dir
Args:
target_dir: the directory in which files will be listed.
format_list: a list of file extention names.
Returns:
a list of file urls.
"""
self.file_list.clear()
# Walk through directories and list all files.
for file_path, _, current_files in os.walk(target_dir, followlinks=False):
for filename in current_files:
# First make sure the file is exactly of the format we need.
# Then process the file.
if filename.split('.')[-1] in format_list:
# Get file url.
file_url = os.path.join(file_path, filename)
self.file_list.append(file_url)
return self.file_list
def save_file_path_list(self, list_name='list.csv'):
"""Save the list in csv format.
Args:
list_name: the file name to be written.
"""
with open(list_name, 'w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=['file_url'])
# Write the header.
writer.writeheader()
# Write all the rows.
for each_record in self.file_list:
writer.writerow({'file_url': each_record})
def save_basename_list(self, list_name='basename.csv'):
basename_list = []
for each_record in self.file_list:
basename = os.path.basename(each_record)
print(basename)
basename_list.append(basename.split(".")[-2])
with open(list_name, 'w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=['file_basename'])
# Write the header.
writer.writeheader()
# Write all the rows.
for each_record in basename_list:
writer.writerow({'file_basename': each_record})
def draw_marks(image, marks, mark_size=3, color=(0, 255, 0), line_width=-1):
"""Draw the marks in image.
Args:
image: the image on which to be drawn.
marks: points coordinates in a numpy array.
mark_size: the size of the marks.
color: the color of the marks, in BGR format, ranges 0~255.
line_width: the width of the mark's outline. Set to -1 to fill it.
"""
# We are drawing in an image, this is a 2D situation.
for point in marks:
cv2.circle(image, (int(point[0]), int(point[1])),
mark_size, color, line_width, cv2.LINE_AA)
================================================
FILE: fmd/universal.py
================================================
"""Dataset toolkit for Universal data format.
In this format the marks are stored in a json file which has same basename of
the image file.
Example:
/path/to/sample.jpg
/path/to/sample.json
"""
import json
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class Universal(MarkDataset):
# To use this class, there are two functions need to be overridden.
def populate_dataset(self, image_dir, key_marks_indices):
"""Populate the IBUG dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. populate the image file list.
lg = FileListGenerator()
self.image_files = lg.generate_list(image_dir)
# 2. Populate the mark file list. Note the order should be same with the
# image file list. Since the IBUG dataset had the mark file named after
# the image file but with different extention name `pts`. We will make
# use of this.
self.mark_files = [img_path.split(
".")[-2] + ".json" for img_path in self.image_files]
# 3 Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner. For IBUG the indices are 36,
# 39, 42, 45, 48, 54. Most of the time you need to do this manually.
# Refer to the mark dataset for details.
self.key_marks_indices = key_marks_indices
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "YinGuobing",
"year": 2020,
"num_marks": 98,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]]."""
marks = []
with open(mark_file) as fid:
mark_list = json.load(fid)
marks = np.reshape(
mark_list, (self.meta['num_marks'], -1)).astype(float)
if marks.shape[1] == 2:
marks = np.pad(marks, ((0, 0), (0, 1)), constant_values=-1)
assert marks.shape[1] == 3, "Marks should be 3D, check z axis values."
return marks
================================================
FILE: fmd/wflw.py
================================================
"""Dataset tookit for WFLW.
Useage: https://github.com/yinguobing/facial-landmark-dataset/issues/6
"""
import os
import cv2
import numpy as np
from fmd.mark_dataset.dataset import MarkDataset
from fmd.mark_dataset.util import FileListGenerator
class WFLW(MarkDataset):
"""Please make sure the uncompressed files are in the same folder:
.
├── WFLW_annotations
└── WFLW_images
"""
def __init__(self, is_train, name):
"""Initialize a WFLW dataset.
Args:
is_train: construct the training set if set to True, else test set.
"""
super(WFLW, self).__init__(dataset_name=name)
self.is_train = is_train
def populate_dataset(self, image_dir):
"""Populate the WFLW dataset with essential data.
Args:
image_dir: the direcotry of the dataset images.
"""
# As required by the abstract method, we need to override this function.
# 1. Populate the mark file list. Note the order should be same with the
# image file list. Since WFLW was not using single mark file, a virtual
# mark file will be generated.
# First, parse all the marks and store them in memory.
self.dataset_root_folder = os.path.dirname(image_dir)
mark_file_test = os.path.join(self.dataset_root_folder,
"WFLW_annotations",
"list_98pt_rect_attr_train_test",
"list_98pt_rect_attr_test.txt")
mark_file_train = os.path.join(self.dataset_root_folder,
"WFLW_annotations",
"list_98pt_rect_attr_train_test",
"list_98pt_rect_attr_train.txt")
self.image_files = []
self.mark_group = []
def _read_mark_file(mark_file):
with open(mark_file) as fid:
for line in fid:
raw_data = line.strip().split(sep=" ")
marks = np.array(raw_data[:98*2], np.float).reshape(-1, 2)
marks = np.pad(marks, ((0, 0), (0, 1)),
mode='constant', constant_values=0)
image_path = os.path.join(image_dir, raw_data[-1])
self.image_files.append(image_path)
self.mark_group.append(marks)
if self.is_train:
_read_mark_file(mark_file_train)
else:
_read_mark_file(mark_file_test)
# This is the virtual mark files. It is actually a int number.
self.mark_files = range(len(self.image_files))
# 3. Set the key marks indices. Here key marks are: left eye left corner,
# left eye right corner, right eye left corner, right eye right corner,
# mouse left corner, mouse right corner.
self.key_marks_indices = [60, 64, 68, 72, 76, 82]
# Even optional, it is highly recommended to update the meta data.
self.meta.update({"authors": "Tsinghua National Laboratory",
"year": 2018,
"num_marks": 98,
"num_samples": len(self.image_files)
})
def get_marks_from_file(self, mark_file):
"""This function should read the mark file and return the marks as a
numpy array in form of [[x, y, z], [x, y, z]].
Be carefull we are using int numbers as virtual mark files"""
return self.mark_group[mark_file]
================================================
FILE: mark_operator.py
================================================
"""A module provids common operations for point marks.
All marks, or points are numpy arrays of format like:
mark = [x, y, z]
marks = [[x, y, z],
[x, y, z],
...,
[x, y, z]]
Vectors are also numpy arrays:
vector = [x, y, z]
vectors = [[x, y, z],
[x, y, z],
...,
[x, y, z]]
"""
import numpy as np
class MarkOperator(object):
"""Operator instances are used to transform the marks."""
def __init__(self):
pass
def get_distance(self, mark1, mark2):
"""Calculate the distance between two marks."""
return np.linalg.norm(mark2 - mark1)
def get_angle(self, vector1, vector2, in_radian=False):
"""Return the angel between two vectors."""
d = np.dot(vector1, vector2)
cos_angle = d / (np.linalg.norm(vector1) * np.linalg.norm(vector2))
if cos_angle > 1.0:
radian = 0
elif cos_angle < -1.0:
radian = np.pi
else:
radian = np.arccos(cos_angle)
c = np.cross(vector1, vector2)
if (c.ndim == 0 and c < 0) or (c.ndim == 1 and c[2] < 0):
radian = 2*np.pi - radian
return radian if in_radian is True else np.rad2deg(radian)
def pad_to_3d(self, marks_2d, pad_value=-1):
"""Pad the 2D marks with zeros in z axis."""
marks_3d = np.pad(marks_2d, ((0, 0), (0, 1)),
mode='constant', constant_values=pad_value)
return marks_3d
def get_center(self, marks):
"""Return the center point of the mark group."""
x, y, z = (np.amax(marks, 0) + np.amin(marks, 0)) / 2
return np.array([x, y, z])
def get_height_width_depth(self, marks):
"""Return the height and width of the marks bounding box."""
height, width, depth = np.amax(marks, 0) - np.amin(marks, 0)
return height, width, depth
def rotate(self, marks, radian, center=(0, 0)):
"""Rotate the marks around center by angle"""
_points = marks[:, :2] - np.array(center, np.float)
cos_angle = np.cos(-radian)
sin_angle = np.sin(-radian)
rotaion_matrix = np.array([[cos_angle, sin_angle],
[-sin_angle, cos_angle]])
marks[:, :2] = np.dot(_points, rotaion_matrix) + center
return marks
def flip_lr(self, marks, width):
"""Flip the marks in horizontal direction."""
marks[:, 0] = width - marks[:, 0]
# Reset the order of the marks. The HRNet authors had provided this
# information in the official repository.
num_marks = marks.shape[0]
if num_marks == 98: # WFLW
mirrored_pairs = np.array([
[0, 32], [1, 31], [2, 30], [3, 29], [4, 28], [5, 27],
[6, 26], [7, 25], [8, 24], [9, 23], [10, 22], [11, 21],
[12, 20], [13, 19], [14, 18], [15, 17], [33, 46], [34, 45],
[35, 44], [36, 43], [37, 42], [38, 50], [39, 49], [40, 48],
[41, 47], [60, 72], [61, 71], [62, 70], [63, 69], [64, 68],
[65, 75], [66, 74], [67, 73], [55, 59], [56, 58], [76, 82],
[77, 81], [78, 80], [87, 83], [86, 84], [88, 92], [89, 91],
[95, 93], [96, 97]
])
elif num_marks == 68: # IBUG, etc.
mirrored_pairs = np.array([
[1, 17], [2, 16], [3, 15], [4, 14], [5, 13], [6, 12],
[7, 11], [8, 10], [18, 27], [19, 26], [20, 25], [21, 24],
[22, 23], [32, 36], [33, 35], [37, 46], [38, 45], [39, 44],
[40, 43], [41, 48], [42, 47], [49, 55], [50, 54], [51, 53],
[62, 64], [61, 65], [68, 66], [59, 57], [60, 56]]) - 1
else:
raise ValueError(
"Number of points {} not supported, please check the dataset.".format(num_marks))
tmp = marks[mirrored_pairs[:, 0]]
marks[mirrored_pairs[:, 0]] = marks[mirrored_pairs[:, 1]]
marks[mirrored_pairs[:, 1]] = tmp
return marks
def _generate_heatmap(self, heatmap_size, center_point, sigma):
"""Generating a heatmap with Gaussian distribution.
Args:
heatmap_size: a tuple containing the size of the heatmap.
center_point: a tuple containing the center point of the distribution.
sigma: how large area the distribution covers.
Returns:
a heatmap
"""
def _generate_gaussian_map(sigma):
"""Generate gaussian distribution with center value equals to 1."""
heat_range = 2 * sigma * 3 + 1
xs = np.arange(0, heat_range, 1, np.float32)
ys = xs[:, np.newaxis]
x_core = y_core = heat_range // 2
gaussian = np.exp(-((xs - x_core) ** 2 + (ys - y_core)
** 2) / (2 * sigma ** 2))
return gaussian
# Check that any part of the gaussian is in-bounds
map_height, map_width = heatmap_size
x, y = int(center_point[0]), int(center_point[1])
radius = sigma * 3
x0, y0 = x - radius, y - radius
x1, y1 = x + radius + 1, y + radius + 1
# If the distribution is out of the map, return an empty map.
if (x0 >= map_width or y0 >= map_height or x1 < 0 or y1 < 0):
return np.zeros(heatmap_size)
# Generate a Gaussian map.
gaussian = _generate_gaussian_map(sigma)
# Get the intersection area of the Gaussian map.
x_gauss = max(0, -x0), min(x1, map_width) - x0
y_gauss = max(0, -y0), min(y1, map_height) - y0
gaussian = gaussian[y_gauss[0]: y_gauss[1], x_gauss[0]: x_gauss[1]]
# Pad the Gaussian with zeros to get the heatmap.
pad_width = np.max(
[[0, 0, 0, 0], [y0, map_height-y1, x0, map_width-x1, ]], axis=0).reshape([2, 2])
heatmap = np.pad(gaussian, pad_width, mode='constant')
return heatmap
def generate_heatmaps(self, norm_marks, map_size=(64, 64), sigma=3):
"""Generate heatmaps for all the marks."""
maps = []
width, height = map_size
for norm_mark in norm_marks:
x = width * norm_mark[0]
y = height * norm_mark[1]
heatmap = self._generate_heatmap(map_size, (x, y), sigma)
maps.append(heatmap)
return np.array(maps, dtype=np.float32)
================================================
FILE: network.py
================================================
import tensorflow as tf
import tensorflow_model_optimization as tfmot
from tensorflow import keras
from tensorflow.keras import Model, layers
from models.hrnet import HRNetBody, hrnet_body
def hrnet_stem(filters=64):
stem_layers = [layers.Conv2D(filters, 3, 2, 'same'),
layers.BatchNormalization(),
layers.Conv2D(filters, 3, 2, 'same'),
layers.BatchNormalization(),
layers.Activation('relu')]
def forward(x):
for layer in stem_layers:
x = layer(x)
return x
return forward
def hrnet_heads(input_channels=64, output_channels=17):
# Construct up sacling layers.
scales = [2, 4, 8]
up_scale_layers = [layers.UpSampling2D((s, s)) for s in scales]
concatenate_layer = layers.Concatenate(axis=3)
heads_layers = [layers.Conv2D(filters=input_channels, kernel_size=(1, 1),
strides=(1, 1), padding='same'),
layers.BatchNormalization(),
layers.Activation('relu'),
layers.Conv2D(filters=output_channels, kernel_size=(1, 1),
strides=(1, 1), padding='same')]
def forward(inputs):
scaled = [f(x) for f, x in zip(up_scale_layers, inputs[1:])]
x = concatenate_layer([inputs[0], scaled[0], scaled[1], scaled[2]])
for layer in heads_layers:
x = layer(x)
return x
return forward
class HRNetStem(layers.Layer, tfmot.sparsity.keras.PrunableLayer):
def __init__(self, filters=64, **kwargs):
super(HRNetStem, self).__init__(**kwargs)
self.filters = filters
def build(self, input_shape):
# The stem of the network.
self.conv_1 = layers.Conv2D(self.filters, 3, 2, 'same')
self.batch_norm_1 = layers.BatchNormalization()
self.conv_2 = layers.Conv2D(self.filters, 3, 2, 'same')
self.batch_norm_2 = layers.BatchNormalization()
self.activation = layers.Activation('relu')
self.built = True
def call(self, inputs):
x = self.conv_1(inputs)
x = self.batch_norm_1(x)
x = self.conv_2(x)
x = self.batch_norm_2(x)
x = self.activation(x)
return x
def get_config(self):
config = super(HRNetStem, self).get_config()
config.update({"filters": self.filters})
return config
def get_prunable_weights(self):
prunable_weights = [getattr(self.conv_1, 'kernel'),
getattr(self.conv_2, 'kernel')]
return prunable_weights
class HRNetHeads(layers.Layer):
def __init__(self, input_channels=64, output_channels=17, **kwargs):
super(HRNetHeads, self).__init__(**kwargs)
self.input_channels = input_channels
self.output_channels = output_channels
def build(self, input_shape):
# Up sampling layers.
scales = [2, 4, 8]
self.up_scale_layers = [layers.UpSampling2D((s, s)) for s in scales]
self.concatenate = layers.Concatenate(axis=3)
self.conv_1 = layers.Conv2D(filters=self.input_channels, kernel_size=(1, 1),
strides=(1, 1), padding='same')
self.batch_norm = layers.BatchNormalization()
self.activation = layers.Activation('relu')
self.conv_2 = layers.Conv2D(filters=self.output_channels, kernel_size=(1, 1),
strides=(1, 1), padding='same')
self.built = True
def call(self, inputs):
scaled = [f(x) for f, x in zip(self.up_scale_layers, inputs[1:])]
x = self.concatenate([inputs[0], scaled[0], scaled[1], scaled[2]])
x = self.conv_1(x)
x = self.batch_norm(x)
x = self.activation(x)
x = self.conv_2(x)
return x
def get_config(self):
config = super(HRNetHeads, self).get_config()
config.update({"input_channels": self.input_channels,
"output_channels": self.output_channels})
return config
def get_prunable_weights(self):
prunable_weights = [getattr(self.conv_1, 'kernel'),
getattr(self.conv_2, 'kernel')]
return prunable_weights
def hrnet_v2(input_shape, output_channels, width=18, name="hrnetv2"):
"""This function returns a functional model of HRNetV2.
Args:
width: the hyperparameter width.
output_channels: number of output channels.
Returns:
a functional model.
"""
# Get the output size of the HRNet body.
last_stage_width = sum([width * pow(2, n) for n in range(4)])
# Describe the model.
inputs = keras.Input(input_shape, dtype=tf.float32)
x = hrnet_stem(64)(inputs)
x = hrnet_body(width)(x)
outputs = hrnet_heads(input_channels=last_stage_width,
output_channels=output_channels)(x)
# Construct the model and return it.
model = keras.Model(inputs=inputs, outputs=outputs, name=name)
return model
if __name__ == "__main__":
model_2 = hrnet_v2((256, 256, 3), 18, 98)
model_2.summary()
================================================
FILE: postprocessing.py
================================================
"""The post processing module for HRNet facial landmark detection."""
import cv2
import numpy as np
def top_k_indices(x, k):
"""Returns the k largest element indices from a numpy array. You can find
the original code here: https://stackoverflow.com/q/6910641
"""
flat = x.flatten()
indices = np.argpartition(flat, -k)[-k:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, x.shape)
def get_peak_location(heatmap, image_size=(256, 256)):
"""Return the interpreted location of the top 2 predictions."""
h_height, h_width = heatmap.shape
[y1, y2], [x1, x2] = top_k_indices(heatmap, 2)
x = (x1 + (x2 - x1)/4) / h_width * image_size[0]
y = (y1 + (y2 - y1)/4) / h_height * image_size[1]
return int(x), int(y)
def parse_heatmaps(heatmaps, image_size):
# Parse the heatmaps to get mark locations.
marks = []
heatmaps = np.transpose(heatmaps, (2, 0, 1))
for heatmap in heatmaps:
marks.append(get_peak_location(heatmap, image_size))
# Show individual heatmaps stacked.
heatmap_grid = np.hstack(heatmaps[:8])
for row in range(1, 12, 1):
heatmap_grid = np.vstack(
[heatmap_grid, np.hstack(heatmaps[row:row+8])])
return np.array(marks), heatmap_grid
def draw_marks(image, marks):
for m in marks:
for mark in m:
cv2.circle(image, tuple(mark.astype(int)), 2, (0, 255, 0), -1)
================================================
FILE: predict.py
================================================
"""Sample module for predicting face marks with HRNetV2."""
from argparse import ArgumentParser
import cv2
import numpy as np
import tensorflow as tf
from postprocessing import parse_heatmaps, draw_marks
from preprocessing import normalize
from face_detector.detector import Detector
# Take arguments from user input.
parser = ArgumentParser()
parser.add_argument("--video", type=str, default=None,
help="Video file to be processed.")
parser.add_argument("--cam", type=int, default=None,
help="The webcam index.")
parser.add_argument("--write_video", type=bool, default=False,
help="Write output video.")
args = parser.parse_args()
# Allow GPU memory growth.
devices = tf.config.list_physical_devices('GPU')
for device in devices:
tf.config.experimental.set_memory_growth(device, True)
if __name__ == "__main__":
"""Run human head pose estimation from video files."""
# What is the threshold value for face detection.
threshold = 0.7
# Construct a face detector.
detector_face = Detector('assets/face_model')
# Restore the model.
model = tf.keras.models.load_model("./exported/hrnetv2")
# Setup the video source. If no video file provided, the default webcam will
# be used.
video_src = args.cam if args.cam is not None else args.video
if video_src is None:
print("Warning: video source not assigned, default webcam will be used.")
video_src = 0
cap = cv2.VideoCapture(video_src)
# If reading frames from a webcam, try setting the camera resolution.
if video_src == 0:
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
# Get the real frame resolution.
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_rate = cap.get(cv2.CAP_PROP_FPS)
# Video output by video writer.
if args.write_video:
video_writer = cv2.VideoWriter(
'output.avi', cv2.VideoWriter_fourcc(*'avc1'), frame_rate, (frame_width, frame_height))
# Introduce a metter to measure the FPS.
tm = cv2.TickMeter()
# Loop through the video frames.
while True:
tm.start()
# Read frame, crop it, flip it, suits your needs.
frame_got, frame = cap.read()
if frame_got is False:
break
# Crop it if frame is larger than expected.
# frame = frame[0:480, 300:940]
# If frame comes from webcam, flip it so it looks like a mirror.
if video_src == 0:
frame = cv2.flip(frame, 2)
# Preprocess the input image.
_image = detector_face.preprocess(frame)
# Run the model
boxes, scores, _ = detector_face.predict(_image, threshold)
# Transform the boxes into squares.
boxes = detector_face.transform_to_square(
boxes, scale=1.22, offset=(0, 0.13))
# Clip the boxes if they cross the image boundaries.
boxes, _ = detector_face.clip_boxes(
boxes, (0, 0, frame_height, frame_width))
boxes = boxes.astype(np.int32)
if boxes.size > 0:
faces = []
for facebox in boxes:
# Crop the face image
top, left, bottom, right = facebox
face_image = frame[top:bottom, left:right]
# Preprocess it.
face_image = cv2.resize(face_image, (256, 256))
face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
face_image = normalize(np.array(face_image, dtype=np.float32))
faces.append(face_image)
faces = np.array(faces, dtype=np.float32)
# Do prediction.
heatmap_group = model.predict(faces)
# Parse the heatmaps to get mark locations.
mark_group = []
heatmap_grids = []
for facebox, heatmaps in zip(boxes, heatmap_group):
top, left, bottom, right = facebox
width = height = (bottom - top)
marks, heatmap_grid = parse_heatmaps(heatmaps, (width, height))
# Convert the marks locations from local CNN to global image.
marks[:, 0] += left
marks[:, 1] += top
mark_group.append(marks)
heatmap_grids.append(heatmap_grid)
# Draw the marks and the facebox in the original frame.
draw_marks(frame, mark_group)
detector_face.draw_boxes(frame, boxes, scores)
# Show the first heatmap.
cv2.imshow("heatmap_grid", heatmap_grid[0])
# Show the result in windows.
cv2.imshow('image', frame)
# Write video file.
if args.write_video:
video_writer.write(frame)
if cv2.waitKey(1) == 27:
break
================================================
FILE: preprocessing.py
================================================
"""This module provides commonly used image preprocessing functions."""
import cv2
import numpy as np
from mark_operator import MarkOperator
MO = MarkOperator()
def crop_face(image, marks, scale=1.8, shift_ratios=(0, 0)):
"""Crop the face area from the input image.
Args:
image: input image.
marks: the facial marks of the face to be cropped.
scale: how much to scale the face box.
shift_ratios: shift the face box to (right, down) by facebox size * ratios
Returns:
Cropped image, new marks, padding_width and bounding box.
"""
# How large the bounding box is?
x_min, y_min, _ = np.amin(marks, 0)
x_max, y_max, _ = np.amax(marks, 0)
side_length = max((x_max - x_min, y_max - y_min)) * scale
# Where is the center point of the bounding box?
x_center = (x_min + x_max) / 2
y_center = (y_min + y_max) / 2
# Face box is scaled, get the new corners, shifted.
img_height, img_width, _ = image.shape
x_shift, y_shift = np.array(shift_ratios) * side_length
x_start = int(x_center - side_length / 2 + x_shift)
y_start = int(y_center - side_length / 2 + y_shift)
x_end = int(x_center + side_length / 2 + x_shift)
y_end = int(y_center + side_length / 2 + y_shift)
# In case the new bbox is out of image bounding.
border_width = 0
border_x = min(x_start, y_start)
border_y = max(x_end - img_width, y_end - img_height)
if border_x < 0 or border_y > 0:
border_width = max(abs(border_x), abs(border_y))
x_start += border_width
y_start += border_width
x_end += border_width
y_end += border_width
image_with_border = cv2.copyMakeBorder(image, border_width,
border_width,
border_width,
border_width,
cv2.BORDER_CONSTANT,
value=[0, 0, 0])
image_cropped = image_with_border[y_start:y_end,
x_start:x_end]
else:
image_cropped = image[y_start:y_end, x_start:x_end]
return image_cropped, border_width, (x_start, y_start, x_end, y_end)
def normalize(inputs):
"""Preprocess the inputs. This function follows the official implementation
of HRNet.
Args:
inputs: a TensorFlow tensor of image.
Returns:
a normalized image.
"""
img_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
img_std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
# Normalization
return ((inputs / 255.0) - img_mean)/img_std
def rotate_randomly(image, marks, degrees=(-30, 30)):
"""Rotate the image randomly in degree range (-degrees, degrees).
Args:
image: an image with face to be processed.
marks: face marks.
degrees: degree ranges to rotate.
Returns:
a same size image rotated, and the rotated marks.
"""
degree = np.random.random_sample() * (degrees[1] - degrees[0]) + degrees[0]
img_height, img_width, _ = image.shape
rotation_mat = cv2.getRotationMatrix2D(((img_width-1)/2.0,
(img_height-1)/2.0), degree, 1)
image_rotated = cv2.warpAffine(
image, rotation_mat, (img_width, img_height))
marks_rotated = MO.rotate(marks, np.deg2rad(degree),
(img_width/2, img_height/2))
return image_rotated, marks_rotated
def scale_randomly(image, marks, output_size=(256, 256), scale_range=(0, 1)):
"""Scale the image randomly in a valid range defined by factor.
This function automatically calculates the valid scale range so that the
marks will always be visible in the image.
Args:
image: an image fully covered the face area in which the face is also
centered.
marks: face marks as numpy array in pixels.
scale_range: a tuple (a, b) defines the min and max values of the scale
range from the valid range.
output_size: output image size.
Returns:
processed image with target output size and new marks.
"""
img_height, img_width, _ = image.shape
face_height, face_width, _ = MO.get_height_width_depth(marks)
# The input image may not be a square. Choose the min range as valid range.
valid_range = min(img_height - face_height, img_width - face_width) / 2
# Get the new range from user input.
low, high = (np.array(scale_range) * valid_range).astype(int)
margin = np.random.randint(low, high)
# Cut the margins to the new image bounding box.
x_start = y_start = margin
x_stop, y_stop = (img_width - margin, img_height - margin)
# Crop and resize the image.
image_cropped = image[y_start:y_stop, x_start:x_stop]
image_resized = cv2.resize(image_cropped, output_size)
# Get the new mark locations.
marks -= [margin, margin, 0]
marks = (marks / (img_width - margin * 2) * output_size[0]).astype(int)
return image_resized, marks
def flip_randomly(image, marks, probability=0.5):
"""Flip the image in horizontal direction.
Args:
image: input image.
marks: face marks.
Returns:
flipped image, flipped marks
"""
if np.random.random_sample() < probability:
image = cv2.flip(image, 1)
marks = MO.flip_lr(marks, image.shape[0])
return image, marks
def generate_heatmaps(marks, img_size, map_size):
"""A convenient function to generate heatmaps from marks."""
marks_norm = marks / img_size
heatmaps = MO.generate_heatmaps(marks_norm, map_size=map_size)
return heatmaps
================================================
FILE: pruning.py
================================================
"""Optimize the model with pruning."""
import os
from argparse import ArgumentParser
import tensorflow as tf
import tensorflow_model_optimization as tfmot
from tensorflow import keras
from dataset import build_dataset_from_wflw
from network import hrnet_v2
parser = ArgumentParser()
parser.add_argument("--epochs", default=60, type=int,
help="Number of training epochs.")
parser.add_argument("--batch_size", default=32, type=int,
help="Training batch size.")
args = parser.parse_args()
if __name__ == "__main__":
# There are 3 steps for model pruning.
# 1. Load the model with pretrained weights.
# 2. Prune the model during training.
# 3. Export the model.
# Where are the pretrained weights.
checkpoint_dir = "./checkpoints"
# Where the pruned model will be exported
pruned_model_path = "./optimized/pruned"
if not os.path.exists(pruned_model_path):
os.makedirs(pruned_model_path)
# First, create the model and restore it with pretrained weights.
model = hrnet_v2((256, 256, 3), width=18, output_channels=98)
# Restore the latest model from checkpoint.
latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
model.load_weights(latest_checkpoint)
print("Checkpoint restored: {}".format(latest_checkpoint))
# Second, Setup the pruning.
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(
initial_sparsity=0.5,
final_sparsity=0.8,
begin_step=0,
end_step=500
)
}
model_pruned = tfmot.sparsity.keras.prune_low_magnitude(
model, **pruning_params)
# Hyper parameters for training.
epochs = args.epochs
batch_size = args.batch_size
callbacks = [
tfmot.sparsity.keras.UpdatePruningStep(),
tfmot.sparsity.keras.PruningSummaries(log_dir="./logs"),
]
# Construct training datasets.
train_files_dir = "/home/robin/data/facial-marks/wflw_cropped/train"
dataset_train = build_dataset_from_wflw(train_files_dir, "wflw_train",
training=True,
batch_size=batch_size,
shuffle=True,
prefetch=tf.data.experimental.AUTOTUNE,
mode="generator")
# Construct dataset for validation & testing.
test_files_dir = "/home/robin/data/facial-marks/wflw_cropped/test"
dataset_val = build_dataset_from_wflw(test_files_dir, "wflw_test",
training=False,
batch_size=batch_size,
shuffle=False,
prefetch=tf.data.experimental.AUTOTUNE,
mode="generator")
# Compile the model for pruning.
model_pruned.compile(optimizer=keras.optimizers.Adam(0.0001),
loss=keras.losses.MeanSquaredError(),
metrics=[keras.metrics.MeanSquaredError()])
model_pruned.summary()
# Start training loop.
model_pruned.fit(dataset_train, validation_data=dataset_val,
epochs=epochs, callbacks=callbacks,
initial_epoch=args.initial_epoch)
# At last, Export the pruned model.
model_for_export = tfmot.sparsity.keras.strip_pruning(model_pruned)
model_for_export.save(pruned_model_path, include_optimizer=False)
print("Pruned model saved to: {}".format(pruned_model_path))
================================================
FILE: quantization.py
================================================
import os
import cv2
import numpy as np
import tensorflow as tf
import fmd
from mark_operator import MarkOperator
from preprocessing import crop_face, normalize
MODE = {"DynamicRangeQuantization": None,
"IntegerWithFloatFallback": None,
"IntergerOnly": None,
"FP16": None,
"16x8": None}
def representative_dataset_gen():
wflw_dir = "/home/robin/data/facial-marks/wflw/WFLW_images"
ds_wflw = fmd.wflw.WFLW(False, "wflw_test")
ds_wflw.populate_dataset(wflw_dir)
for _ in range(100):
sample = ds_wflw.pick_one()
# Get image and marks.
image = sample.read_image()
marks = sample.marks
# Crop the face out of the image.
image_cropped, _, _ = crop_face(image, marks, scale=1.2)
# Get the prediction from the model.
image_cropped = cv2.resize(image_cropped, (256, 256))
img_rgb = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2RGB)
img_input = normalize(np.array(img_rgb, dtype=np.float32))
yield [np.expand_dims(img_input, axis=0)]
def quantize(saved_model, mode=None, representative_dataset=None):
"""TensorFlow model quantization by TFLite.
Args:
saved_model: the model's directory.
mode: the quantization mode.
Returns:
a tflite model quantized.
"""
converter = tf.lite.TFLiteConverter.from_saved_model("./exported")
# By default, do Dynamic Range Quantization.
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# Integer With Float Fallback
if mode["IntegerWithFloatFallback"]:
converter.representative_dataset = representative_dataset
# Integer only.
if mode["IntergerOnly"]:
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8 # or tf.uint8
converter.inference_output_type = tf.int8 # or tf.uint8
# Float16 only.
if mode["FP16"]:
converter.target_spec.supported_types = [tf.float16]
# [experimental] 16-bit activations with 8-bit weights
if mode["16x8"]:
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [
tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8]
# Finally, convert the model.
tflite_model = converter.convert()
return tflite_model
class TFLiteModelPredictor(object):
"""A light weight class for TFLite model prediction."""
def __init__(self, model_path):
self.interpreter = tf.lite.Interpreter(model_path)
self.interpreter.allocate_tensors()
self.input_index = self.interpreter.get_input_details()[0]["index"]
self.output_index = self.interpreter.get_output_details()[0]["index"]
def predict(self, inputs):
self.interpreter.set_tensor(self.input_index, inputs)
self.interpreter.invoke()
predictions = self.interpreter.get_tensor(self.output_index)
return predictions
if __name__ == "__main__":
# The directory to save quantized models.
export_dir = "./optimized"
if not os.path.exists(export_dir):
os.makedirs(export_dir)
# The model to be quantized.
saved_model = "./exported"
# Dynamic range quantization
mode = MODE.copy()
mode.update({"DynamicRangeQuantization": True})
tflite_model = quantize(saved_model, mode)
open("./optimized/hrnet_quant_dynamic_range.tflite", "wb").write(tflite_model)
# Full integer quantization - Integer with float fallback.
mode = MODE.copy()
mode.update({"IntegerWithFloatFallback": True})
tflite_model = quantize(saved_model, mode, representative_dataset_gen)
open("./optimized/hrnet_quant_int_fp_fallback.tflite", "wb").write(tflite_model)
# Full integer quantization - Integer only
mode = MODE.copy()
mode.update({"IntegerOnly": True})
tflite_model = quantize(saved_model, mode, representative_dataset_gen)
open("./optimized/hrnet_quant_int_only.tflite", "wb").write(tflite_model)
# Float16 quantization
mode = MODE.copy()
mode.update({"FP16": True})
tflite_model = quantize(saved_model, mode)
open("./optimized/hrnet_quant_fp16.tflite", "wb").write(tflite_model)
# 16x8 quantization
mode = MODE.copy()
mode.update({"16x8": True})
tflite_model = quantize(saved_model, mode)
open("./optimized/hrnet_quant_16x8.tflite", "wb").write(tflite_model)
================================================
FILE: train.py
================================================
"""The training script for HRNet facial landmark detection.
"""
import os
from argparse import ArgumentParser
import tensorflow as tf
from tensorflow import keras
from callbacks import EpochBasedLearningRateSchedule, LogImages
from dataset import build_dataset
from network import hrnet_v2
parser = ArgumentParser()
parser.add_argument("--epochs", default=60, type=int,
help="Number of training epochs.")
parser.add_argument("--initial_epoch", default=0, type=int,
help="From which epochs to resume training.")
parser.add_argument("--batch_size", default=32, type=int,
help="Training batch size.")
parser.add_argument("--export_only", default=False, type=bool,
help="Save the model without training.")
parser.add_argument("--eval_only", default=False, type=bool,
help="Evaluate the model without training.")
args = parser.parse_args()
if __name__ == "__main__":
# Deep neural network training is complicated. The first thing is making
# sure you have everything ready for training, like datasets, checkpoints,
# logs, etc. Modify these paths to suit your needs.
# What is the model's name?
name = "hrnetv2"
# How many marks are there for a single face sample?
number_marks = 98
# Where are the training files?
train_files_dir = "/home/robin/data/facial-marks/wflw_cropped/train"
# Where are the testing files?
test_files_dir = "/home/robin/data/facial-marks/wflw_cropped/test"
# Where are the validation files? Set `None` if no files available. Then 10%
# of the training files will be used as validation samples.
val_files_dir = None
# Do you have a sample image which will be logged into tensorboard for
# testing purpose?
sample_image = "docs/face.jpg"
# That should be sufficient for training. However if you want more
# customization, please keep going.
# Checkpoint is used to resume training.
checkpoint_dir = os.path.join("checkpoints", name)
# Save the model for inference later.
export_dir = os.path.join("exported", name)
# Log directory will keep training logs like loss/accuracy curves.
log_dir = os.path.join("logs", name)
# All sets. Now it's time to build the model. This model is defined in the
# `network` module with TensorFlow's functional API.
input_shape = (256, 256, 3)
model = hrnet_v2(input_shape=input_shape, output_channels=number_marks,
width=18, name=name)
# Model built. Restore the latest model if checkpoints are available.
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
print("Checkpoint directory created: {}".format(checkpoint_dir))
latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
if latest_checkpoint:
print("Checkpoint found: {}, restoring...".format(latest_checkpoint))
model.load_weights(latest_checkpoint)
print("Checkpoint restored: {}".format(latest_checkpoint))
else:
print("Checkpoint not found. Model weights will be initialized randomly.")
# If the restored model is ready for inference, save it and quit training.
if args.export_only:
if latest_checkpoint is None:
print("Warning: Model not restored from any checkpoint.")
print("Saving model to {} ...".format(export_dir))
model.save(export_dir)
print("Model saved at: {}".format(export_dir))
quit()
# Construct a dataset for evaluation.
dataset_test = build_dataset(test_files_dir, "test",
number_marks=number_marks,
image_shape=input_shape,
training=False,
batch_size=args.batch_size,
shuffle=False,
prefetch=tf.data.experimental.AUTOTUNE)
# If only evaluation is required.
if args.eval_only:
model.evaluate(dataset_test)
quit()
# Finally, it's time to train the model.
# Compile the model and print the model summary.
model.compile(optimizer=keras.optimizers.Adam(0.001, amsgrad=True, epsilon=0.001),
loss=keras.losses.MeanSquaredError(),
metrics=[keras.metrics.MeanSquaredError()])
# model.summary()
# Schedule the learning rate with (epoch to start, learning rate) tuples
schedule = [(1, 0.001),
(30, 0.0001),
(50, 0.00001)]
# All done. The following code will setup and start the trainign.
# Save a checkpoint. This could be used to resume training.
callback_checkpoint = keras.callbacks.ModelCheckpoint(
filepath=os.path.join(checkpoint_dir, name),
save_weights_only=True,
verbose=1,
save_best_only=True)
# Visualization in TensorBoard
callback_tensorboard = keras.callbacks.TensorBoard(log_dir=log_dir,
histogram_freq=1024,
write_graph=True,
update_freq='epoch')
# Learning rate decay.
callback_lr = EpochBasedLearningRateSchedule(schedule)
# Log a sample image to tensorboard.
callback_image = LogImages(log_dir, sample_image)
# List all the callbacks.
callbacks = [callback_checkpoint, callback_tensorboard, #callback_lr,
callback_image]
# Construct training datasets.
dataset_train = build_dataset(train_files_dir, "train",
number_marks=number_marks,
image_shape=input_shape,
training=True,
batch_size=args.batch_size,
shuffle=True,
prefetch=tf.data.experimental.AUTOTUNE)
# Construct dataset for validation. The loss value from this dataset will be
# used to decide which checkpoint should be preserved.
if val_files_dir:
dataset_val = build_dataset(val_files_dir, "validation",
number_marks=number_marks,
image_shape=input_shape,
training=False,
batch_size=args.batch_size,
shuffle=False,
prefetch=tf.data.experimental.AUTOTUNE)
else:
dataset_val = dataset_train.take(int(512/args.batch_size))
dataset_train = dataset_train.skip(int(512/args.batch_size))
# Start training loop.
model.fit(dataset_train,
validation_data=dataset_val,
epochs=args.epochs,
callbacks=callbacks,
initial_epoch=args.initial_epoch)
# Run a full evaluation after training.
model.evaluate(dataset_test)