Repository: luigivieira/Facial-Landmarks-Annotation-Tool
Branch: master
Commit: b66fb09c7ecc
Files: 41
Total size: 340.7 KB
Directory structure:
gitextract_91x_51e_/
├── .gitignore
├── CMakeLists.txt
├── LICENSE
├── README.md
├── example/
│ └── example.fad
├── src/
│ ├── aboutwindow.cpp
│ ├── aboutwindow.h
│ ├── aboutwindow.ui
│ ├── application.cpp
│ ├── application.h
│ ├── childwindow.cpp
│ ├── childwindow.h
│ ├── facedataset.cpp
│ ├── facedataset.h
│ ├── facedatasetmodel.cpp
│ ├── facedatasetmodel.h
│ ├── facefeature.cpp
│ ├── facefeature.h
│ ├── facefeatureedge.cpp
│ ├── facefeatureedge.h
│ ├── facefeaturenode.cpp
│ ├── facefeaturenode.h
│ ├── facefitconfig.cpp
│ ├── facefitconfig.h
│ ├── facefitconfig.ui
│ ├── faceimage.cpp
│ ├── faceimage.h
│ ├── facewidget.cpp
│ ├── facewidget.h
│ ├── facewidgetscene.cpp
│ ├── facewidgetscene.h
│ ├── main.cpp
│ ├── mainwindow.cpp
│ ├── mainwindow.h
│ ├── mainwindow.ui
│ ├── resources/
│ │ └── images/
│ │ ├── brokenimage.xcf
│ │ └── noface.xcf
│ ├── resources.qrc
│ ├── utils.cpp
│ └── utils.h
└── version.h.in
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Ignore the build directory
**/build/
================================================
FILE: CMakeLists.txt
================================================
# Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
#
# This file is part of FLAT.
#
# FLAT 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.
#
# FLAT 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 .
# Minimum CMake version required
cmake_minimum_required(VERSION 2.8.11)
# Project information
project (FLAT)
# Version data and header file
set (CT_VERSION_MAJOR 1)
set (CT_VERSION_MINOR 0)
set (CT_VERSION_PATCH 0)
set (CT_VERSION "${CT_VERSION_MAJOR}.${CT_VERSION_MINOR}.${CT_VERSION_PATCH}")
configure_file (
"${PROJECT_SOURCE_DIR}/version.h.in"
"${PROJECT_BINARY_DIR}/version.h"
)
include_directories("${PROJECT_BINARY_DIR}")
# Default build type if none was specified
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
# Set the possible values of build type for cmake-gui
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
"MinSizeRel" "RelWithDebInfo")
endif()
# Qt configuration
set(CMAKE_INCLUDE_CURRENT_DIR ON) # Find includes in corresponding build directories
set(CMAKE_AUTOMOC ON) # Instruct CMake to run moc automatically when needed
set(CMAKE_AUTORCC ON) # Instruct CMake to run rcc automatically when needed
set(CMAKE_AUTOUIC ON) # Instruct CMake to run uic automatically when needed
find_package(Qt5Core REQUIRED)
find_package(Qt5Widgets REQUIRED)
find_package(Qt5Xml REQUIRED)
# Add all source and resource files
file(GLOB SRC src/*.cpp src/*.h)
file(GLOB RSC src/*.qrc)
# Add the executable
if(WIN32)
add_executable(FLAT WIN32 ${SRC} ${RSC})
else()
add_executable(FLAT ${SRC} ${RSC})
endif()
set_target_properties(FLAT PROPERTIES OUTPUT_NAME flat)
set_target_properties(FLAT PROPERTIES OUTPUT_NAME_DEBUG flatd)
# Set up the required libraries
target_link_libraries(FLAT Qt5::Core Qt5::Widgets Qt5::Xml)
================================================
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
================================================
# FLAT - Facial Landmarks Annotation Tool
A visual editor for manually annotating facial landmarks in images of human faces.

## Usage
Create a new face annotation dataset (files with extension `.fad`) and add the face images. Then, add the facial features and connect then as desired using either the program menus or the context menu. The zoom level can be controlled either from the widget control on the image properties tool window or by holding CTRL and scrolling the mouse wheel. While zoomed, an image can also be side scrolled by holding SHIFT and scrolling the mouse wheel. All images in the same face annotation dataset share the same model, that is they have the same amount of face landmarks (even though they can be differently positioned for each image). Automatically fitting of 66 face landmarks can be performed via the "Fit Landmarks" option if the utility is available (see details bellow). If the automatic fitting succeeds, the 66 landmarks will be positioned as best as possible in the face image. Otherwise, a status bar message will indicate the error.
## Dependences
The application has been developed and tested with:
- [CMake](https://cmake.org/) 3.5.0-rc3
- [Qt](http://www.qt.io/) 5.5.1 32-bit
The "Fit Landmarks" menu option (in "Tools/CSIRO Face Analysis SDK" menu) requires an external executable called `fit-fit(.exe)` - even though its absence does not prevent the FLAT tool from being compiled and used. Please check the [SDK web site](http://face.ci2cv.net/) and [the source code of my port to Windows/Linux](https://github.com/luigivieira/face-analysis-sdk). The option for an external dependence (instead of source code integration) is only to make the compilation of this project simpler and its usage broader.
## Building
1. Use CMake to configure and generate the environment. I suggest using the folder `build`, since it is the one ignored by gitignore.
2. In Windows, open the Visual Studio solution and build with the desired build type (*debug*, *release*, etc).
3. In Linux, use type `make` to let the Makefile produce the binary in the build type configured by CMake.
4. The code produces only a single executable named `flat(.exe)`, that depends only on Qt. If you want to use the "Fit Landmarks" option mentioned before, go to the CSIRO Face Analysis SDK page, download and build its libraries and executables. Then, configure in FLAT the path for the `face-fit(.exe)` executable.
## Credits
Copyright (C) 2016 [Luiz Carlos Vieira](http://www.luiz.vieira.nom.br). Available under GPL (see details in the license file).
The application icons and images are either from or based on the Oxygen Icons Set, downloaded as [PNGs from Felipe Azevedo (pasnox)](https://github.com/pasnox/oxygen-icons-png) and [licensed under LGPL from KDE](https://techbase.kde.org/Projects/Oxygen/Licensing), and the [Farm-Fresh Web Icons Set](http://www.fatcow.com/free-icons), licensed under [Creative Commons (CC BY 4.0)](http://creativecommons.org/licenses/by/4.0/).
================================================
FILE: example/example.fad
================================================
================================================
FILE: src/aboutwindow.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "aboutwindow.h"
#include "ui_aboutwindow.h"
#include "version.h"
#include
#include
// +-----------------------------------------------------------
ft::AboutWindow::AboutWindow(QWidget *pParent) :
QDialog(pParent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint),
ui(new Ui::AboutWindow)
{
ui->setupUi(this);
ui->label->setText(ui->label->text().arg(FLAT_VERSION));
ui->label->setOpenExternalLinks(true);
setFixedSize(425, 268);
}
// +-----------------------------------------------------------
ft::AboutWindow::~AboutWindow()
{
delete ui;
}
================================================
FILE: src/aboutwindow.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef ABOUTWINDOW_H
#define ABOUTWINDOW_H
#include
namespace Ui
{
class AboutWindow;
}
namespace ft
{
/**
* Form class used to display the about dialog box.
*/
class AboutWindow : public QDialog
{
Q_OBJECT
public:
/**
* Class constructor.
* @param pParent QWidget with the window parent.
*/
explicit AboutWindow(QWidget *pParent = 0);
/**
* Class destructor
*/
virtual ~AboutWindow();
private:
/** Instance of the ui for GUI element access. */
Ui::AboutWindow *ui;
};
}
#endif // ABOUTWINDOW_H
================================================
FILE: src/aboutwindow.ui
================================================
AboutWindow
Qt::ApplicationModal
0
0
425
268
About...
true
5
5
5
5
5
-
10
-
true
0
0
394
331
0
0
0
0
0
-
<html><head/><body><p><span style=" font-weight:600;">FLAT - Facial Landmarks Annotation Tool (version %1)</span></p><p>Copyright (C) 2016 <a href="http://www.luiz.vieira.nom.br/"><span style=" text-decoration: underline; color:#0000ff;">Luiz Carlos Vieira</span></a></p><p>This is a visual editor to help annotating face images with facial landmarks required for the implementation of deformable fit algorithms or avatar transposition. The source code is available <a href="https://github.com/luigivieira/Facial-Landmarks-Annotation-Tool"><span style=" text-decoration: underline; color:#0000ff;">at Github</span></a>.</p><p>The application icons and images are either from or based on the Oxygen Icons Set, downloaded as <a href="https://github.com/pasnox/oxygen-icons-png"><span style=" text-decoration: underline; color:#0000ff;">PNGs from Felipe Azevedo (pasnox)</span></a> and <a href="https://techbase.kde.org/Projects/Oxygen/Licensing"><span style=" text-decoration: underline; color:#0000ff;">licensed under LGPL from KDE</span></a>, and the <a href="http://www.fatcow.com/free-icons"><span style=" text-decoration: underline; color:#0000ff;">Farm-Fresh Web Icons Set</span></a>, licensed under <a href="http://creativecommons.org/licenses/by/4.0/"><span style=" text-decoration: underline; color:#0000ff;">Creative Commons (CC BY 4.0)</span></a>.</p><p>LICENSE</p><p>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.</p><p>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.</p><p>You should have received a copy of the GNU General Public License along with this program. If not, see <a href="http://www.gnu.org/licenses/"><span style=" text-decoration: underline; color:#0000ff;">http://www.gnu.org/licenses/</span></a>.</p></body></html>
Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop
true
true
-
0
-
Qt::Horizontal
40
20
-
80
16777215
&Close
true
closeButton
clicked()
AboutWindow
accept()
380
249
212
133
================================================
FILE: src/application.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "application.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
// +-----------------------------------------------------------
ft::FtApplication::FtApplication(int argc, char* argv[]): QApplication(argc, argv)
{
m_pMainWindow = NULL;
// Information used to store the program settings
QCoreApplication::setOrganizationName("Flat");
QCoreApplication::setOrganizationDomain("https://github.com/luigivieira/Facial-Landmarks-Annotation-Tool.git");
QCoreApplication::setApplicationName("Data");
QString sAppFile = QCoreApplication::applicationFilePath();
QString sDocPath = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)) + QDir::separator();
QFileInfo oFile = QFileInfo(sAppFile);
QString sLogFile = QString("%1%2.log").arg(sDocPath).arg(oFile.baseName());
m_oLogFile.open(qPrintable(sLogFile), ios::app);
if (!m_oLogFile.is_open())
{
cerr << QString("Could not open the file [%1] for writing. No log will be created.").arg(sLogFile).toStdString();
exit(-1);
}
qInstallMessageHandler(&ft::FtApplication::handleLogOutput);
qDebug() << QCoreApplication::applicationFilePath().toStdString().c_str() << "started.";
}
// +-----------------------------------------------------------
ft::FtApplication::~FtApplication()
{
qDebug() << QCoreApplication::applicationFilePath().toStdString().c_str() << "ended.";
if (m_oLogFile.is_open())
{
m_oLogFile.flush();
m_oLogFile.close();
}
}
// +-----------------------------------------------------------
bool ft::FtApplication::notify(QObject* pReceiver, QEvent* pEvent)
{
try
{
// Retransmit the event notification
return QApplication::notify(pReceiver, pEvent);
}
catch (std::exception &e)
{
qFatal("Exception %s sending event [%s] to object [%s] (%s)",
e.what(), typeid(*pEvent).name(), qPrintable(pReceiver->objectName()), typeid(*pReceiver).name());
}
catch (...)
{
qFatal("Exception sending event [%s] to object [%s] (%s)",
typeid(*pEvent).name(), qPrintable(pReceiver->objectName()), typeid(*pReceiver).name());
}
return false;
}
// +-----------------------------------------------------------
void ft::FtApplication::handleLogOutput(QtMsgType eType, const QMessageLogContext &oContext, const QString &sMsg) {
QString sNow = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
// Only include context information if it exists (when compiled in debug)
QString sDebugInfo;
if(oContext.line != 0)
{
QString sSource = QFileInfo(QFile(oContext.file).fileName()).fileName();
sDebugInfo = QString(" [%1:%2, %3] ").arg(sSource).arg(oContext.line).arg(oContext.function);
}
else
sDebugInfo = " ";
switch (eType)
{
case QtDebugMsg:
FtApplication::instance()->m_oLogFile << qPrintable(sNow) << qPrintable(sDebugInfo) << "DEBUG: " << qPrintable(sMsg) << endl;
FtApplication::instance()->m_oLogFile.flush();
break;
case QtWarningMsg:
FtApplication::instance()->m_oLogFile << qPrintable(sNow) << qPrintable(sDebugInfo) << "WARNING: " << qPrintable(sMsg) << endl;
FtApplication::instance()->m_oLogFile.flush();
break;
case QtCriticalMsg:
FtApplication::instance()->m_oLogFile << qPrintable(sNow) << qPrintable(sDebugInfo) << "CRITICAL: " << qPrintable(sMsg) << endl;
FtApplication::instance()->m_oLogFile.flush();
break;
case QtFatalMsg:
QApplication::beep();
QMessageBox::critical(NULL, qApp->translate("Main", "Runtime Error"), qApp->translate("Main", "A severe exception happened and the application must terminate."), QMessageBox::Ok);
cerr << qPrintable(sNow) << qPrintable(sDebugInfo) << "FATAL: " << qPrintable(sMsg) << endl;
FtApplication::instance()->m_oLogFile << qPrintable(sNow) << qPrintable(sDebugInfo) << "FATAL:" << qPrintable(sMsg) << endl;
exit(-2);
}
}
// +-----------------------------------------------------------
ft::FtApplication* ft::FtApplication::instance()
{
return (FtApplication *) qApp;
}
// +-----------------------------------------------------------
void ft::FtApplication::showStatusMessage(const QString &sMsg, const int iTimeout)
{
FtApplication::instance()->emit statusMessageShown(sMsg, iTimeout);
}
================================================
FILE: src/application.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include
#include
#include
#include
namespace ft
{
/**
* Custom application class, used to intercept message notifications in the project applications.
*/
class FtApplication: public QApplication
{
Q_OBJECT
public:
/**
* Class constructor.
* @param argc Number of arguments received from the command line.
* @param argv Array of char pointers with the arguments received from the command line.
*/
FtApplication(int argc, char* argv[]);
/**
* Class destructor.
*/
virtual ~FtApplication();
/**
* Displays a text message in the main window status bar.
* @param sMsg QString with the message to be displayed.
* @param iTimeout Integer with the number of miliseconds
* by which the message will be displayed. The default is 5000
* (i.e. 5 seconds).
*/
static void showStatusMessage(const QString &sMsg, const int iTimeout = 5000);
/**
* Handles the notification of messages in the application event loop.
* @param pReceiver Pointer to the QObject that shall receive the message.
* @param pEvent Pointer to the QEvent with the message information.
*/
bool notify(QObject* pReceiver, QEvent* pEvent);
/**
* Gets the default instance for this application (from the qApp variable simply type-casted).
* @return Pointer to the default instance of the FtApplication.
*/
static FtApplication* instance();
signals:
/**
* Signal indicating that a status message was requested to be displayed on the
* application main window.
* @param sMsg QString with the message to be displayed.
* @param iTimeout Integer with the number of miliseconds
* by which the message will be displayed.
*/
void statusMessageShown(const QString &sMsg, const int iTimeout);
protected:
/**
* Log and exception message handler for application events.
* @param eType QtMsgType enum value with the type of the log event.
* @param oContext QMessageLogContext instance with information on where the event happened (function, line, etc)
* @param sMsg QString instance with the event message.
*/
static void handleLogOutput(QtMsgType eType, const QMessageLogContext& oContext, const QString& sMsg);
private:
/** File stream used to log application messages. */
std::ofstream m_oLogFile;
/** Instance of the main window used with this application. */
QMainWindow *m_pMainWindow;
};
}
#endif // APPLICATION_H
================================================
FILE: src/childwindow.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "childwindow.h"
#include "mainwindow.h"
#include "application.h"
#include
#include
#include
#include
#include
#include
using namespace std;
// +-----------------------------------------------------------
ft::ChildWindow::ChildWindow(QWidget *pParent) :
QWidget(pParent)
{
setAutoFillBackground(true);
setBackgroundRole(QPalette::Dark);
setAttribute(Qt::WA_DeleteOnClose);
QGridLayout *pLayout = new QGridLayout(this);
pLayout->setMargin(0);
setLayout(pLayout);
m_pFaceWidget = new FaceWidget(this);
pLayout->addWidget(m_pFaceWidget);
m_pFaceWidget->setPixmap(QPixmap(":/images/noface"));
m_pFaceDatasetModel = new FaceDatasetModel();
m_pFaceSelectionModel = new QItemSelectionModel(m_pFaceDatasetModel);
// Capture of relevant signals
connect(m_pFaceWidget, SIGNAL(onScaleFactorChanged(const double)), this, SLOT(onScaleFactorChanged(const double)));
connect(m_pFaceWidget, SIGNAL(onFaceFeaturesSelectionChanged()), this, SLOT(onFaceFeaturesSelectionChanged()));
connect(m_pFaceWidget, SIGNAL(onFaceFeaturesChanged()), this, SLOT(onDataChanged()));
connect(m_pFaceDatasetModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&, const QVector&)), this, SLOT(onDataChanged()));
connect(m_pFaceSelectionModel, SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(onCurrentChanged(const QModelIndex &, const QModelIndex &)));
// Indicate that it is a brand new dataset (i.e. not yet saved to a file)
setProperty("new", true);
m_iCurrentImage = -1;
}
// +-----------------------------------------------------------
ft::ChildWindow::~ChildWindow()
{
delete m_pFaceSelectionModel;
delete m_pFaceDatasetModel;
}
// +-----------------------------------------------------------
ft::FaceDatasetModel* ft::ChildWindow::dataModel() const
{
return m_pFaceDatasetModel;
}
// +-----------------------------------------------------------
QItemSelectionModel* ft::ChildWindow::selectionModel() const
{
return m_pFaceSelectionModel;
}
// +-----------------------------------------------------------
bool ft::ChildWindow::save(QString &sMsgError)
{
if(!m_pFaceDatasetModel->saveToFile(windowFilePath(), sMsgError))
return false;
onDataChanged(false);
setProperty("new", QVariant()); // No longer a new dataset
return true;
}
// +-----------------------------------------------------------
bool ft::ChildWindow::saveToFile(const QString &sFileName, QString &sMsgError)
{
if(!m_pFaceDatasetModel->saveToFile(sFileName, sMsgError))
return false;
setWindowFilePath(sFileName);
onDataChanged(false);
setProperty("new", QVariant()); // No longer a new dataset
return true;
}
// +-----------------------------------------------------------
bool ft::ChildWindow::loadFromFile(const QString &sFileName, QString &sMsgError)
{
if(!m_pFaceDatasetModel->loadFromFile(qPrintable(sFileName), sMsgError))
return false;
setWindowFilePath(sFileName);
onDataChanged(false);
setProperty("new", QVariant()); // No longer a new dataset
return true;
}
// +-----------------------------------------------------------
void ft::ChildWindow::setZoomLevel(const int iLevel)
{
int iSteps = iLevel - 11; // Because 11 is the middle slider value, equivalent to the scale of 1.0 (100%)
double dBase = iSteps < 0 ? FaceWidget::ZOOM_OUT_STEP : FaceWidget::ZOOM_IN_STEP;
double dFactor = 1.0 * qPow(dBase, abs(iSteps));
m_pFaceWidget->setScaleFactor(dFactor);
}
// +-----------------------------------------------------------
int ft::ChildWindow::getZoomLevel() const
{
double dFactor = m_pFaceWidget->getScaleFactor();
double dBase = dFactor < 1.0 ? FaceWidget::ZOOM_OUT_STEP : FaceWidget::ZOOM_IN_STEP;
int iSteps = qCeil(qLn(abs(dFactor)) / qLn(dBase));
if(dFactor > 1.0)
return iSteps + 11;
else
return 11 - iSteps;
}
// +-----------------------------------------------------------
void ft::ChildWindow::zoomIn()
{
m_pFaceWidget->zoomIn();
}
// +-----------------------------------------------------------
void ft::ChildWindow::zoomOut()
{
m_pFaceWidget->zoomOut();
}
// +-----------------------------------------------------------
void ft::ChildWindow::onScaleFactorChanged(const double dScaleFactor)
{
Q_UNUSED(dScaleFactor);
QModelIndex oCurrent = m_pFaceSelectionModel->currentIndex();
QString sImageName = m_pFaceDatasetModel->data(m_pFaceDatasetModel->index(oCurrent.row(), 0), Qt::UserRole).toString();
emit onUIUpdated(sImageName, getZoomLevel());
}
// +-----------------------------------------------------------
void ft::ChildWindow::onDataChanged(const bool bModified)
{
if(bModified)
updateFeaturesInDataset();
setWindowModified(bModified);
emit onDataModified();
}
// +-----------------------------------------------------------
void ft::ChildWindow::onCurrentChanged(const QModelIndex &oCurrent, const QModelIndex &oPrevious)
{
Q_UNUSED(oPrevious);
if(!oCurrent.isValid())
{
m_iCurrentImage = -1;
m_pFaceWidget->setPixmap(QPixmap(":/images/noface"));
emit onUIUpdated("", 0);
}
else
{
m_iCurrentImage = oCurrent.row();
QVariant oData = m_pFaceDatasetModel->data(m_pFaceDatasetModel->index(m_iCurrentImage, 2), Qt::UserRole);
if(oData.isValid())
m_pFaceWidget->setPixmap(oData.value());
else
m_pFaceWidget->setPixmap(QPixmap(":/images/brokenimage"));
QString sImageName = oCurrent.data(Qt::UserRole).toString();
emit onUIUpdated(sImageName, getZoomLevel());
refreshFeaturesInWidget();
}
}
// +-----------------------------------------------------------
void ft::ChildWindow::refreshFeaturesInWidget()
{
vector vFeats = m_pFaceDatasetModel->getFeatures(m_iCurrentImage);
QList lsNodes = m_pFaceWidget->getFaceFeatures(m_pFaceDatasetModel->numFeatures()); // This call automatically guarantees that there are "m_pFaceDatasetModel->numFeatures()" features in the editor
for(int i = 0; i < (int) vFeats.size(); i++)
{
lsNodes[i]->setData(0, true); // Indication to avoid emitting position change event
// Refresh the feature visual in the widget:
// - (re)position the feature
// - (re)do any connections
lsNodes[i]->setPos(vFeats[i]->x(), vFeats[i]->y());
foreach(int iID, vFeats[i]->getConnections())
m_pFaceWidget->connectFaceFeatures(vFeats[i]->getID(), iID);
lsNodes[i]->setData(0, false);
}
}
// +-----------------------------------------------------------
void ft::ChildWindow::updateFeaturesInDataset()
{
QList lsNodes = m_pFaceWidget->getFaceFeatures();
vector vFeats = m_pFaceDatasetModel->getFeatures(m_iCurrentImage);
FaceFeatureNode* pNode;
for(int i = 0; i < (int) vFeats.size(); i++)
{
if(i >= lsNodes.size()) // Sanity check (vFeats and lsNodes are supposed to have the same size, but who knows?)
{
qCritical() << tr("An update of face features in dataset was not performed due to inconsistences.");
continue;
}
pNode = lsNodes.at(i);
vFeats[i]->setID(pNode->getID());
vFeats[i]->setX(pNode->x());
vFeats[i]->setY(pNode->y());
}
}
// +-----------------------------------------------------------
void ft::ChildWindow::onFaceFeaturesSelectionChanged()
{
emit onFeaturesSelectionChanged();
}
// +-----------------------------------------------------------
bool ft::ChildWindow::displayFaceFeatures() const
{
return m_pFaceWidget->displayFaceFeatures();
}
// +-----------------------------------------------------------
void ft::ChildWindow::setDisplayFaceFeatures(const bool bValue)
{
m_pFaceWidget->setDisplayFaceFeatures(bValue);
}
// +-----------------------------------------------------------
bool ft::ChildWindow::displayConnections() const
{
return m_pFaceWidget->displayConnections();
}
// +-----------------------------------------------------------
void ft::ChildWindow::setDisplayConnections(const bool bValue)
{
m_pFaceWidget->setDisplayConnections(bValue);
}
// +-----------------------------------------------------------
bool ft::ChildWindow::displayFeatureIDs() const
{
return m_pFaceWidget->displayFeatureIDs();
}
// +-----------------------------------------------------------
void ft::ChildWindow::setDisplayFeatureIDs(const bool bValue)
{
m_pFaceWidget->setDisplayFeatureIDs(bValue);
}
// +-----------------------------------------------------------
const QList& ft::ChildWindow::getFaceFeatures() const
{
return m_pFaceWidget->getFaceFeatures();
}
// +-----------------------------------------------------------
QList ft::ChildWindow::getSelectedFeatures() const
{
return m_pFaceWidget->getSelectedFeatures();
}
// +-----------------------------------------------------------
QList ft::ChildWindow::getSelectedConnections() const
{
return m_pFaceWidget->getSelectedConnections();
}
// +-----------------------------------------------------------
void ft::ChildWindow::setContextMenu(QMenu *pMenu)
{
m_pFaceWidget->setContextMenu(pMenu);
}
// +-----------------------------------------------------------
void ft::ChildWindow::addFeature(const QPoint &oPos)
{
FaceFeatureNode *pNode = m_pFaceWidget->addFaceFeature(oPos, true);
m_pFaceDatasetModel->addFeature(pNode->getID(), pNode->x(), pNode->y());
onDataChanged();
}
// +-----------------------------------------------------------
void ft::ChildWindow::removeSelectedFeatures()
{
bool bUpdated = false;
QList lsFeats = m_pFaceWidget->getSelectedFeatures();
foreach(FaceFeatureNode *pNode, lsFeats)
{
m_pFaceDatasetModel->removeFeature(pNode->getID());
m_pFaceWidget->removeFaceFeature(pNode);
bUpdated = true;
}
if(bUpdated)
{
updateFeaturesInDataset();
onDataChanged();
}
}
// +-----------------------------------------------------------
void ft::ChildWindow::connectFeatures()
{
bool bUpdated = false;
QList lsFeats = m_pFaceWidget->getSelectedFeatures();
QList::iterator oFirst, oSecond;
for(oFirst = lsFeats.begin(); oFirst != lsFeats.end(); oFirst++)
{
for(oSecond = oFirst + 1; oSecond != lsFeats.end(); oSecond++)
{
m_pFaceWidget->connectFaceFeatures(*oFirst, *oSecond);
m_pFaceDatasetModel->connectFeatures((*oFirst)->getID(), (*oSecond)->getID());
bUpdated = true;
}
}
if(bUpdated)
onDataChanged();
}
// +-----------------------------------------------------------
void ft::ChildWindow::disconnectFeatures()
{
bool bUpdated = false;
QList lsFeats = m_pFaceWidget->getSelectedFeatures();
QList::iterator oFirst, oSecond;
for(oFirst = lsFeats.begin(); oFirst != lsFeats.end(); oFirst++)
{
for(oSecond = oFirst + 1; oSecond != lsFeats.end(); oSecond++)
{
m_pFaceWidget->disconnectFaceFeatures(*oFirst, *oSecond);
m_pFaceDatasetModel->disconnectFeatures((*oFirst)->getID(), (*oSecond)->getID());
bUpdated = true;
}
}
if(bUpdated)
onDataChanged();
}
// +-----------------------------------------------------------
bool ft::ChildWindow::positionFeatures(std::vector vPoints)
{
QList lFeats = m_pFaceWidget->getFaceFeatures(vPoints.size()); // this call automatically adds or removes features to match vPoints.size()
// Adjust the dataset so it has the same amount of features as the widget
vector vFeats = m_pFaceDatasetModel->getFeatures(m_iCurrentImage);
int iDiff = lFeats.size() - vFeats.size();
// If the widget has more features than the dataset, add the difference
if (iDiff > 0)
{
for (int i = 0; i < iDiff; i++)
m_pFaceDatasetModel->addFeature(lFeats.size() + i - 1, 0, 0);
}
// Else, if the widget has less features than the dataset, remove the difference
else if (iDiff < 0)
{
for (int i = 0; i < abs(iDiff); i++)
m_pFaceDatasetModel->removeFeature(lFeats.size() - i - 1);
}
// Move the features
FaceFeatureNode *pFeat;
for (unsigned int i = 0; i < vPoints.size(); i++)
{
pFeat = lFeats.at(i);
pFeat->setPos(vPoints[i]);
}
updateFeaturesInDataset();
setWindowModified(true);
emit onDataModified();
return true;
}
================================================
FILE: src/childwindow.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef CHILDWINDOW_H
#define CHILDWINDOW_H
#include "facedatasetmodel.h"
#include "facewidget.h"
#include
#include
namespace ft
{
/**
* MDI-child window class used to display and edit the face annotation datasets.
*/
class ChildWindow : public QWidget
{
Q_OBJECT
public:
/**
* Class constructor.
* @param pParent Instance of the widget that will be the parent of this window.
*/
explicit ChildWindow(QWidget* pParent = 0);
/**
* Class destructor.
*/
virtual ~ChildWindow();
/**
* Gets the list model used to display information about the contents of the
* face annotation dataset handled by this window.
* @return An instance of a QAbstractListModel that can be used with any subclass of QAbstractItemView
* to display lists, icons or trees with the face annotation dataset contents.
*/
FaceDatasetModel* dataModel() const;
/**
* Gets the list selection model used to display selection information about the contents of the
* face annotation dataset handled by this window.
* @return An instance of a QItemSelectionModel that can be used with any subclass of QAbstractItemView
* to display lists, icons or tress with the face annotation dataset contents.
*/
QItemSelectionModel* selectionModel() const;
/**
* Saves the contents of the face annotation dataset in this window to the current file
* (stored in the windowFilePath property). The file is saved in the YAML format, as defined
* in the FaceDataset class.
*/
bool save(QString &sMsgError);
/**
* Saves the contents of the face annotation dataset in this window to the given file.
* The file is saved in the YAML format, as defined in the FaceDataset class.
* @param sFileName QString with the path and name of the file to save the dataset to.
*/
bool saveToFile(const QString &sFileName, QString &sMsgError);
/**
* Loads the contents of the face annotation dataset from the given file into this window.
* The file must be in the YAML format, as defined in the FaceDataset class.
* @param sFileName QString with the path and name of the file to load the dataset from.
*/
bool loadFromFile(const QString &sFileName, QString &sMsgError);
/**
* Sets the zoom level of the image in display in terms of the steps defined in the zoom
* slider from 1 to 21, with 11 (the middle value) as "no zoom" (i.e. 100% view).
* @param iLevel Integer with the zoom level to set.
*/
void setZoomLevel(const int iLevel);
/**
* Gets the current zoom level of the image in display in terms of the steps defined in the zoom
* slider from 1 to 21, with 11 (the middle value) as "no zoom" (i.e. 100% view).
* @return Integer with the current zoom level.
*/
int getZoomLevel() const;
/**
* Performs one step of zoom in.
*/
void zoomIn();
/**
* Performs one step of zoom out.
*/
void zoomOut();
/**
* Indicates if the face feature nodes are on display.
* @return Boolean indicating if the face feature nodes are being displayed or not.
*/
bool displayFaceFeatures() const;
/**
* Updates the indication on if the face feature nodes shall be displayed or not.
* @param bValue Boolean with the new value (true means show, false means hide).
*/
void setDisplayFaceFeatures(const bool bValue);
/**
* Indicates if the face feature edges are on display.
* @return Boolean indicating if the face feature edges are being displayed or not.
*/
bool displayConnections() const;
/**
* Updates the indication on if the face feature edges shall be displayed or not.
* @param bValue Boolean with the new value (true means show, false means hide).
*/
void setDisplayConnections(const bool bValue);
/**
* Indicates if the identifiers of the face feature nodes are on display.
* @return Boolean indicating if the identifiers of the face feature nodes are being displayed or not.
*/
bool displayFeatureIDs() const;
/**
* Updates the indication on if the identifiers of the face feature nodes shall be displayed or not.
* @param bValue Boolean with the new value (true means show, false means hide).
*/
void setDisplayFeatureIDs(const bool bValue);
/**
* Queries the list of existing face feature nodes.
* @param Const reference to the QList of existing nodes.
*/
const QList& getFaceFeatures() const;
/**
* Queries the selected face feature nodes.
* @return QList with the pointers to the selected face feature nodes.
*/
QList getSelectedFeatures() const;
/**
* Queries the selected face feature edges.
* @return QList with the pointers to the selected face feature edges.
*/
QList getSelectedConnections() const;
/**
* Sets the menu to be displayed upon events of context menu on the face features editor.
* The actions used in the menu must be controlled by the caller.
* @param pMenu Instance of the QMenu to be used for the context of the editor.
*/
void setContextMenu(QMenu *pMenu);
/**
* Adds a new feature to the face feature editor, in the given position.
* @param oPos QPoint with the position (x, y) of the new feature.
*/
void addFeature(const QPoint &oPos);
/**
* Removes the selected features and all their connections.
*/
void removeSelectedFeatures();
/**
* Connects the selected features among themselves.
*/
void connectFeatures();
/**
* Disconnects the selected features.
*/
void disconnectFeatures();
/**
* Moves the face features in the image currently on display according to the given
* list of positions. If the number of face features is different than the number of
* points, the model is updated accordingly (with features added or removed to match
* the number of points).
* @param vPoints A std::vector with the list of QPoint instances with the new
* features' positions.
* @return Boolean indicating if the reposition was successfully done or not.
*/
bool positionFeatures(std::vector vPoints);
protected:
/**
* Refreshes the positions of face features in the editor based on the values in the dataset.
*/
void refreshFeaturesInWidget();
/**
* Updates the positions of face features in the dataset based on the values in the editor.
*/
void updateFeaturesInDataset();
protected slots:
/**
* Captures the indication of changes in the image scale factor (zoom).
* @param dScaleFactor Double with the new scale factor for the image.
*/
void onScaleFactorChanged(const double dScaleFactor);
/**
* Captures the indication that face features were selected or unselected in the editor.
*/
void onFaceFeaturesSelectionChanged();
/**
* Captures indications of changes in the data model or the face widget
* (so the UI can be updated accordingly).
* @param bModified Boolean indicating if the child window shall be marked as modified or not.
* The default is true.
*/
void onDataChanged(const bool bModified = true);
/**
* Captures indication of changes in the current selected image on the selection model.
*/
void onCurrentChanged(const QModelIndex &oCurrent, const QModelIndex &oPrevious);
signals:
/**
* Signal to indicate changes in the data model (so the UI can be updated accordingly).
*/
void onDataModified();
/**
* Signal to indicate that the selection of face features changed in the editor.
* The selection can be queried through getSelectedFeatures() and getSelectedConnections().
*/
void onFeaturesSelectionChanged();
/**
* Signal to indicate an update in the UI due to changes in the selection model.
* @param sImageName QString with the name of the current selected face image.
* @param iZoomLevel Current level of zoom in the face image widget.
*/
void onUIUpdated(const QString sImageName, const int iZoomLevel);
private:
/** Index of the current displayed face image. */
int m_iCurrentImage;
/** Widget used to display face images and edit facial features. */
FaceWidget *m_pFaceWidget;
/** Instance of the model used to encapsulate the access of the face dataset to Qt view components such as QListView. */
FaceDatasetModel *m_pFaceDatasetModel;
/** Selection model used to represent the selection of items in Qt view components such as QListView. */
QItemSelectionModel *m_pFaceSelectionModel;
};
}
#endif // CHILDWINDOW_H
================================================
FILE: src/facedataset.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facedataset.h"
#include
#include
#include
#include
using namespace std;
// +-----------------------------------------------------------
ft::FaceDataset::FaceDataset()
{
m_iNumFeatures = 0;
}
// +-----------------------------------------------------------
ft::FaceDataset::~FaceDataset()
{
clear();
}
// +-----------------------------------------------------------
int ft::FaceDataset::size() const
{
return m_vSamples.size();
}
// +-----------------------------------------------------------
bool ft::FaceDataset::loadFromFile(const QString &sFileName, QString &sMsgError)
{
/******************************************************
* Open and read the file
******************************************************/
QFile oFile(sFileName);
if (!oFile.open(QFile::ReadOnly))
{
sMsgError = QString(QApplication::translate("FaceDataset", "it was not possible to read from file [%1]")).arg(sFileName);
return false;
}
// Used to resolve the image file names relative to the saved file path
QDir oBase(QFileInfo(sFileName).absolutePath());
QTextStream oData(&oFile);
QString sData = oData.readAll();
oFile.close();
/******************************************************
* Parse the xml document
******************************************************/
QDomDocument oDoc;
QString sError;
int iLine, iColumn;
if(!oDoc.setContent(sData, true, &sError, &iLine, &iColumn))
{
sMsgError = QString(QApplication::translate("FaceDataset", "there is an error in the contents of the file [%1]: error [%2], line [%3], column [%4]")).arg(sFileName, sError, QString::number(iLine), QString::number(iColumn));
return false;
}
// Root node
QDomElement oRoot = oDoc.firstChildElement("FaceDataset");
if(oRoot.isNull())
{
sMsgError = QString(QApplication::translate("FaceDataset", "there is an error in the contents of the file [%1]: the node '%2' does not exist")).arg(sFileName, "FaceDataset");
return false;
}
int iNumFeats = oRoot.attribute("numberOfFeatures", "-1").toInt();
if(iNumFeats < 0)
{
sMsgError = QString(QApplication::translate("FaceDataset", "there is an error in the contents of the file [%1]: the attribute '%2' does not exist or it contains an invalid value")).arg(sFileName, "numberOfFeatures");
return false;
}
// Sample images
QDomElement oSamples = oRoot.firstChildElement("Samples");
if(oSamples.isNull())
{
sMsgError = QString(QApplication::translate("FaceDataset", "there is an error in the contents of the file [%1]: the node '%2' does not exist")).arg(sFileName, "Samples");
return false;
}
vector vSamples;
for(QDomElement oElement = oSamples.firstChildElement(); !oElement.isNull(); oElement = oElement.nextSiblingElement())
{
FaceImage *pSample = new FaceImage();
if(!pSample->loadFromXML(oElement, sError, iNumFeats))
{
foreach(FaceImage *pSamp, vSamples)
delete(pSamp);
delete pSample;
sMsgError = QString(QApplication::translate("FaceDataset", "there is an error in the contents of the file [%1]: %2")).arg(sFileName, sError);
return false;
}
pSample->setFileName(oBase.absoluteFilePath(pSample->fileName()));
vSamples.push_back(pSample);
}
clear();
m_iNumFeatures = iNumFeats;
m_vSamples = vSamples;
return true;
}
// +-----------------------------------------------------------
bool ft::FaceDataset::saveToFile(const QString &sFileName, QString &sMsgError) const
{
/******************************************************
* Create the xml document
******************************************************/
QDomDocument oDoc;
// Processing instruction
QDomProcessingInstruction oInstr = oDoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
oDoc.appendChild(oInstr);
// Root node
QDomElement oRoot = oDoc.createElementNS("https://github.com/luigivieira/Facial-Landmarks-Annotation-Tool", "FaceDataset");
oDoc.appendChild(oRoot);
oRoot.setAttribute("numberOfFeatures", m_iNumFeatures);
// Sample images
QDomElement oSamples = oDoc.createElement("Samples");
oRoot.appendChild(oSamples);
// Used to make the image file names relative to the saved file path
QDir oBase(QFileInfo(sFileName).absolutePath());
QString sSave;
foreach(FaceImage *pImage, m_vSamples)
{
sSave = pImage->fileName(); // Save the absolute path (it is still used in the editor)
pImage->setFileName(oBase.relativeFilePath(pImage->fileName()));
pImage->saveToXML(oSamples);
pImage->setFileName(sSave);
}
/******************************************************
* Save the file
******************************************************/
QFile oFile(sFileName);
if (!oFile.open(QFile::WriteOnly | QFile::Truncate))
{
sMsgError = QString(QApplication::translate("FaceDataset", "it was not possible to write to file [%1]")).arg(sFileName);
return false;
}
QTextStream oData(&oFile);
oDoc.save(oData, 4);
oFile.close();
return true;
}
// +-----------------------------------------------------------
void ft::FaceDataset::clear()
{
foreach(FaceImage *pImage, m_vSamples)
delete pImage;
m_vSamples.clear();
m_iNumFeatures = 0;
}
// +-----------------------------------------------------------
ft::FaceImage* ft::FaceDataset::getImage(const int iIndex) const
{
if(iIndex < 0 || iIndex >= size())
return NULL;
return m_vSamples[iIndex];
}
// +-----------------------------------------------------------
ft::FaceImage* ft::FaceDataset::addImage(const QString &sFileName)
{
foreach(FaceImage *pImage, m_vSamples)
if(pImage->fileName() == sFileName)
return pImage;
FaceImage *pRet = new FaceImage(sFileName);
m_vSamples.push_back(pRet);
return pRet;
}
// +-----------------------------------------------------------
bool ft::FaceDataset::removeImage(const int iIndex)
{
if(iIndex < 0 || iIndex >= size())
return false;
FaceImage *pImage = m_vSamples[iIndex];
m_vSamples.erase(m_vSamples.begin() + iIndex);
delete pImage;
return true;
}
// +-----------------------------------------------------------
int ft::FaceDataset::numFeatures() const
{
return m_iNumFeatures;
}
// +-----------------------------------------------------------
void ft::FaceDataset::setNumFeatures(int iNumFeats)
{
m_iNumFeatures = iNumFeats;
}
// +-----------------------------------------------------------
void ft::FaceDataset::addFeature(int iID, float x, float y)
{
FaceFeature *pFeat;
foreach(FaceImage *pSample, m_vSamples)
pFeat = pSample->addFeature(iID, x, y);
m_iNumFeatures++;
}
// +-----------------------------------------------------------
bool ft::FaceDataset::removeFeature(const int iIndex)
{
if(iIndex < 0 || iIndex >= m_iNumFeatures)
return false;
foreach(FaceImage *pSample, m_vSamples)
pSample->removeFeature(iIndex);
m_iNumFeatures--;
return true;
}
// +-----------------------------------------------------------
bool ft::FaceDataset::connectFeatures(int iIDSource, int iIDTarget)
{
foreach(FaceImage *pSample, m_vSamples)
pSample->connectFeatures(iIDSource, iIDTarget);
return true;
}
// +-----------------------------------------------------------
bool ft::FaceDataset::disconnectFeatures(int iIDSource, int iIDTarget)
{
foreach(FaceImage *pSample, m_vSamples)
pSample->disconnectFeatures(iIDSource, iIDTarget);
return true;
}
// +-----------------------------------------------------------
vector ft::FaceDataset::getImageFeatures(const int iIndex)
{
if(iIndex < 0 || iIndex >= (int) m_vSamples.size())
return vector();
return m_vSamples[iIndex]->getFeatures();
}
================================================
FILE: src/facedataset.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEDATASET_H
#define FACEDATASET_H
#include "faceimage.h"
#include "facefeature.h"
#include
#include
namespace ft
{
/**
* Represents a dataset of facial images that can be annotated with facial landmarks and
* prototypical emotional labels.
*/
class FaceDataset
{
public:
/**
* Class constructor.
*/
FaceDataset();
/**
* Class destructor.
*/
virtual ~FaceDataset();
/**
* Returns the number of face samples in the dataset.
* @return Integer with the number of face samples in this dataset.
*/
int size() const;
/**
* Loads (unserializes) the instance from the given text file in the YAML format
* (YAML Ain't Markup Language - http://en.wikipedia.org/wiki/YAML).
* @param sFileName QString with the name of the file to read the data from.
* @param sMsgError QString to receive the error message in case the method fails.
* @return Boolean indicating if the loading was successful (true) of failed (false).
*/
bool loadFromFile(const QString &sFileName, QString &sMsgError);
/**
* Saves (serializes) the instance to the given file in the YAML format
* (YAML Ain't Markup Language - http://en.wikipedia.org/wiki/YAML).
* @param sFileName QString with the name of the file to write the data to.
* @param sMsgError QString to receive the error message in case the method fails.
* @return Boolean indicating if the saving was successful (true) of failed (false).
*/
bool saveToFile(const QString &sFileName, QString &sMsgError) const;
/**
* Clear the face annotation dataset.
*/
void clear();
/**
* Gets the face image for the given index. The index must be in the range [0, count - 1],
* where count is the number of face images in the dataset.
* @param iIndex Integer with the index of the image file to load.
* @return Pointer to a FaceImage with the face image data. If the method fails, NULL is returned.
*/
FaceImage* getImage(const int iIndex) const;
/**
* Adds a new image to the face annotation dataset. All other data (landmarks, connections, etc)
* are created with default values.
* @param sFileName QString with the path and filename of the image file to be added to the dataset.
* @return Pointer to a FaceImage with the new image added to the dataset or NULL if failed.
*/
FaceImage* addImage(const QString &sFileName);
/**
* Removes an image from the face annotation dataset. All other data (landmarks, connections, etc)
* are also removed.
* @param iIndex Integer with the index of the image to remove.
* @return Boolean indicating if the image was removed (true) or not (false, in case
* the given index is out of range).
*/
bool removeImage(const int iIndex);
/**
* Queries the number of facial features in the dataset (applicable to all images).
* @return Integer with the number of face features in the dataset.
*/
int numFeatures() const;
/**
* Updates the number of facial features in the dataset (applicable to all images).
* @param iNumFeats Integer with the new number of facial features for the dataset.
*/
void setNumFeatures(int iNumFeats);
/**
* Adds a new feature to the face dataset. A new feature is added to all
* face images in the dataset in the same coordinates.
* @param iID Integer with the identifier of the face feature.
* @param x Float with the x coordinate for the face features.
* @param y Float with the y coordinate for the face features.
*/
void addFeature(int iID, float x = 0.0f, float y = 0.0f);
/**
* Removes an existing feature from the face dataset. The feature is removed from all
* face images in the dataset.
* @param iIndex Integer with the index of the feature to remove.
* @return Boolean indicating if the feature was successfully removed (true) or not (false).
*/
bool removeFeature(const int iIndex);
/**
* Connects the two given features.
* @param iIDSource Integer with the ID of the source feature.
* @param iIDTarget Integer with the ID of the target feature.
* @return Boolean indicating if the connection was successfully created.
*/
bool connectFeatures(int iIDSource, int iIDTarget);
/**
* Disconnects the two given features.
* @param iIDSource Integer with the ID of the source feature.
* @param iIDTarget Integer with the ID of the target feature.
* @return Boolean indicating if the connection was successfully removed.
*/
bool disconnectFeatures(int iIDSource, int iIDTarget);
/**
* Gets the list of face features in the given image index.
* @param iIndex Integer with the index of the image to query the face features.
* @param A vector of FaceFeature instances with the face features in the image. It returns
* an empty vector if the given index is invalid.
*/
std::vector getImageFeatures(const int iIndex);
private:
/** Vector of sample face images. */
std::vector m_vSamples;
/** Number of face features in the dataset (i.e. applicable to all images). */
int m_iNumFeatures;
};
}
#endif // FACEDATASET_H
================================================
FILE: src/facedatasetmodel.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facedatasetmodel.h"
#include
#include
#include
#include
// +-----------------------------------------------------------
ft::FaceDatasetModel::FaceDatasetModel(QObject *pParent):
QAbstractListModel(pParent)
{
m_pFaceDataset = new FaceDataset();
}
// +-----------------------------------------------------------
ft::FaceDatasetModel::~FaceDatasetModel()
{
delete m_pFaceDataset;
}
// +-----------------------------------------------------------
int ft::FaceDatasetModel::rowCount(const QModelIndex &oParent) const
{
Q_UNUSED(oParent);
return m_pFaceDataset->size();
}
// +-----------------------------------------------------------
int ft::FaceDatasetModel::columnCount(const QModelIndex &oParent) const
{
Q_UNUSED(oParent);
return 4; // There are four columns of data: [Image Name]
}
// +-----------------------------------------------------------
QVariant ft::FaceDatasetModel::headerData(int iSection, Qt::Orientation eOrientation, int iRole) const
{
Q_UNUSED(eOrientation);
switch(iRole)
{
// Display data (the dataset contents)
case Qt::DisplayRole:
switch(iSection)
{
case 0: // [Image Name]
return QApplication::translate("FaceDatasetModel", "Image Name");
case 1: // [File Path]
return QApplication::translate("FaceDatasetModel", "File Path");
default:
return QVariant();
}
case Qt::DecorationRole:
if(iSection == 0)
return QApplication::translate("FaceDatasetModel", "Thumbnail");
else
return QVariant();
default:
return QVariant();
}
}
// +-----------------------------------------------------------
QVariant ft::FaceDatasetModel::data(const QModelIndex &oIndex, int iRole) const
{
FaceImage *pImage = m_pFaceDataset->getImage(oIndex.row());
if(!pImage)
return QVariant();
QPixmap oPixmap;
switch(iRole)
{
// Data to be displayed on ModelViews
case Qt::DisplayRole:
switch(oIndex.column())
{
case 0: // [Image Name]
return QFileInfo(pImage->fileName()).baseName();
case 1: // [File Path]
return pImage->fileName();
default:
return QVariant();
}
// Decoration data (image thumbnails for the first column)
case Qt::DecorationRole:
if(oIndex.column() == 0)
return m_lCachedThumbnails[oIndex.row()];
else
return QVariant();
// Raw data from the face dataset
case Qt::UserRole:
switch(oIndex.column())
{
case 0: // The complete image file name+path
return pImage->fileName();
case 2: // The image data
oPixmap = pImage->pixMap();
if(oPixmap.isNull())
oPixmap = QPixmap(":/images/brokenimage");
return oPixmap;
default:
return QVariant();
}
// Any other role, return invalid
default:
return QVariant();
}
}
// +-----------------------------------------------------------
bool ft::FaceDatasetModel::setData(const QModelIndex &oIndex, const QVariant &oValue, int iRole)
{
FaceImage *pImage = m_pFaceDataset->getImage(oIndex.row());
if(!pImage)
return false;
if(iRole == Qt::UserRole)
{
switch(oIndex.column())
{
case 0: // [Image Name]
return false;
default:
return false;
}
}
else
return false;
}
// +-----------------------------------------------------------
bool ft::FaceDatasetModel::loadFromFile(const QString &sFileName, QString &sMsgError)
{
beginResetModel();
bool bRet = m_pFaceDataset->loadFromFile(sFileName, sMsgError);
// Rebuild the thumbnails cache
if(bRet)
{
m_lCachedThumbnails.clear();
for(int i = 0; i < m_pFaceDataset->size(); i++)
m_lCachedThumbnails.append(buildThumbnail(i));
}
endResetModel();
return bRet;
}
// +-----------------------------------------------------------
bool ft::FaceDatasetModel::saveToFile(const QString &sFileName, QString &sMsgError) const
{
return m_pFaceDataset->saveToFile(sFileName, sMsgError);
}
// +-----------------------------------------------------------
bool ft::FaceDatasetModel::addImages(const QStringList &lImageFiles)
{
int iFirst = m_pFaceDataset->size();
int iLast = iFirst + lImageFiles.size() - 1;
beginInsertRows(QModelIndex(), iFirst, iLast);
for(int i = 0; i < lImageFiles.size(); i++)
{
m_pFaceDataset->addImage(lImageFiles[i]);
m_lCachedThumbnails.append(buildThumbnail(m_pFaceDataset->size() - 1));
}
endInsertRows();
emit dataChanged(index(iFirst), index(iLast));
return true;
}
// +-----------------------------------------------------------
bool ft::FaceDatasetModel::removeImages(const QList &lImageIndexes)
{
int iFirst = lImageIndexes.first();
int iLast = lImageIndexes.last();
beginRemoveRows(QModelIndex(), iFirst, iLast);
for(int i = lImageIndexes.size() - 1; i >= 0; i--)
{
m_pFaceDataset->removeImage(lImageIndexes[i]);
m_lCachedThumbnails.removeAt(lImageIndexes[i]);
}
endRemoveRows();
emit dataChanged(index(0), index(lImageIndexes.size() - 1));
return true;
}
// +-----------------------------------------------------------
void ft::FaceDatasetModel::addFeature(int iID, float x, float y)
{
m_pFaceDataset->addFeature(iID, x, y);
}
// +-----------------------------------------------------------
void ft::FaceDatasetModel::removeFeature(const int iIndex)
{
m_pFaceDataset->removeFeature(iIndex);
}
// +-----------------------------------------------------------
void ft::FaceDatasetModel::connectFeatures(int iIDSource, int iIDTarget)
{
m_pFaceDataset->connectFeatures(iIDSource, iIDTarget);
}
// +-----------------------------------------------------------
void ft::FaceDatasetModel::disconnectFeatures(int iIDSource, int iIDTarget)
{
m_pFaceDataset->disconnectFeatures(iIDSource, iIDTarget);
}
// +-----------------------------------------------------------
std::vector ft::FaceDatasetModel::getFeatures(const int iIndex)
{
return m_pFaceDataset->getImageFeatures(iIndex);
}
// +-----------------------------------------------------------
int ft::FaceDatasetModel::numFeatures() const
{
return m_pFaceDataset->numFeatures();
}
// +-----------------------------------------------------------
QPixmap ft::FaceDatasetModel::buildThumbnail(const int iIndex)
{
QPixmap oImage;
FaceImage *pImage = m_pFaceDataset->getImage(iIndex);
if(!pImage)
oImage = QPixmap(":/images/imagemissing");
else
{
oImage = pImage->pixMap();
if(oImage.isNull())
oImage = QPixmap(":/images/imagemissing");
}
oImage = oImage.scaled(50, 50, Qt::IgnoreAspectRatio);
return oImage;
}
// +-----------------------------------------------------------
Qt::ItemFlags ft::FaceDatasetModel::flags(const QModelIndex &oIndex) const
{
switch(oIndex.column())
{
case 0: // [Image Name]
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
default:
return Qt::NoItemFlags;
}
}
================================================
FILE: src/facedatasetmodel.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEDATASETMODEL_H
#define FACEDATASETMODEL_H
#include "facedataset.h"
#include
#include
#include
namespace ft
{
/**
* Model class that encapsulates the access to the FaceDataset in order to provide data for
* the view classes in Qt (such as QListView).
*/
class FaceDatasetModel : public QAbstractListModel
{
public:
/**
* Class constructor.
* @param pParent Instance of a QObject with the parent of the model. Default is NULL.
*/
FaceDatasetModel(QObject *pParent = NULL);
/**
* Virtual class destructor.
*/
virtual ~FaceDatasetModel();
/**
* Returns the number of rows under the given parent. When the parent is valid
* it means that rowCount is returning the number of children of parent.
* @param oParent A QModelIndex with the parent to be used in the query.
* @return Integer with the number of rows under the given parent.
*/
int rowCount(const QModelIndex &oParent = QModelIndex()) const;
/**
* Returns the number of columns for the children of the given parent.
* @param oParent A QModelIndex with the parent to be used in the query.
* @return Integer with the number of columns for the children of the given parent.
*/
int columnCount(const QModelIndex &oParent = QModelIndex()) const;
/**
* Returns the data stored under the given role for the item referred to by the index.
* @param oIndex A QModelIndex with the index of the data requested.
* @param iRole A DispleyRole identifying the role of the data requested (the default is DisplayRole).
* @return A QVariant with the data requested.
*/
QVariant data(const QModelIndex &oIndex, int iRole = Qt::DisplayRole) const;
/**
* Returns the header data stored under the given section (column), for the given role.
* @param iSection Integer with the section (column) to retrieve the header data.
* @param eOrientation The orientation of the header (not used).
* @param iRole A DispleyRole identifying the role of the header data requested (the default is DisplayRole).
* @return A QVariant with the header data requested.
*/
QVariant headerData(int iSection, Qt::Orientation eOrientation, int iRole = Qt::DisplayRole) const;
/**
* Updates the face data stored under the given role for the item referred by the index.
* @param oIndex A QModelIndex with the index of the data to be updated.
* param oValue A QVariant with the new value for the data under the index.
* @param iRole A DisplayRole identifying the role of the data to be updated.
* @return A boolean indicating if the update was successful (true) or not (false).
*/
bool setData(const QModelIndex &oIndex, const QVariant &oValue, int iRole = Qt::EditRole);
/**
* Loads the data from the given text file in the YAML format
* (YAML Ain't Markup Language - http://en.wikipedia.org/wiki/YAML).
* @param sFileName QString with the name of the file to read the data from.
* @param sMsgError QString to receive the error message in case the method fails.
* @return Boolean indicating if the loading was successful (true) of failed (false).
*/
bool loadFromFile(const QString &sFileName, QString &sMsgError);
/**
* Saves the data to the given file in the YAML format
* (YAML Ain't Markup Language - http://en.wikipedia.org/wiki/YAML).
* @param sFileName QString with the name of the file to write the data to.
* @param sMsgError QString to receive the error message in case the method fails.
* @return Boolean indicating if the saving was successful (true) of failed (false).
*/
bool saveToFile(const QString &sFileName, QString &sMsgError) const;
/**
* Adds the given images to the dataset.
* @param lImageFiles QStringList with the list of image file names to add.
* @return Boolean indicating if the operation was successful or not.
*/
bool addImages(const QStringList &lImageFiles);
/**
* Removes the given images to the dataset.
* @param lImageFiles QList with the list of image indexes to remove.
* @return Boolean indicating if the operation was successful or not.
*/
bool removeImages(const QList &lImageIndexes);
/**
* Adds a new feature to the face dataset. A new feature is added to all
* face images in the dataset in the same coordinates.
* @param iID Integer with the identifier of the face feature.
* @param x Float with the x coordinate for the face features.
* @param y Float with the y coordinate for the face features.
*/
void addFeature(int iID, float x = 0.0f, float y = 0.0f);
/**
* Removes the feature of given index in all face images.
* @param iIndex Index of the feature to remove.
*/
void removeFeature(const int iIndex);
/**
* Connects the two given features in the face dataset.
* @param iIDSource Integer with the ID of the source feature.
* @param iIDTarget Integer with the ID of the target feature.
*/
void connectFeatures(int iIDSource, int iIDTarget);
/**
* Disconnects the two given features in the face dataset.
* @param iIDSource Integer with the ID of the source feature.
* @param iIDTarget Integer with the ID of the target feature.
*/
void disconnectFeatures(int iIDSource, int iIDTarget);
/**
* Gets all features in the given face image index.
* @param iIndex Integer with the index of the face image to query.
* @return Vector of FaceFeature instances with the face features in the image.
*/
std::vector getFeatures(const int iIndex);
/**
* Queries the number of facial features in the dataset (applicable to all images).
* @return Integer with the number of face features in the dataset.
*/
int numFeatures() const;
protected:
/**
* Build a thumbnail for the given image index.
* @param iIndex Integer with the index of the image to build the thumbnail for.
* @return A QPixmap with the thumbmail. If the image could not be read,
* a thumbnail of the 'image missing' is returned instead.
*/
QPixmap buildThumbnail(const int iIndex);
/**
* Queries the display/edit flags for the given index.
* @param oIndex A QModelIndex with the index to be queried.
* @return A Qt::ItemFlags with the flags to be applied to the given index.
*/
Qt::ItemFlags flags(const QModelIndex &oIndex) const;
private:
/** Instance of the face annotation dataset for data access. */
FaceDataset *m_pFaceDataset;
/**
* List of thumbnails for the existing images to improve access performance.
* The thumbnails are related to the images in the facedataset according to their
* indexed position.
*/
QList m_lCachedThumbnails;
};
}
#endif //FACEDATASETMODEL_H
================================================
FILE: src/facefeature.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facefeature.h"
#include
#include
using namespace std;
// +-----------------------------------------------------------
ft::FaceFeature::FaceFeature(): QPoint()
{
setID(-1);
}
// +-----------------------------------------------------------
ft::FaceFeature::FaceFeature(int iID, float x, float y): QPoint(x, y)
{
setID(iID);
}
// +-----------------------------------------------------------
int ft::FaceFeature::getID() const
{
return m_iID;
}
// +-----------------------------------------------------------
void ft::FaceFeature::setID(int iID)
{
m_iID = iID;
}
// +-----------------------------------------------------------
void ft::FaceFeature::connectTo(FaceFeature *pOther)
{
vector::iterator it = find(m_vConnections.begin(), m_vConnections.end(), pOther->getID());
if (it == m_vConnections.end())
m_vConnections.push_back(pOther->getID());
}
// +-----------------------------------------------------------
void ft::FaceFeature::disconnectFrom(FaceFeature *pOther)
{
vector::iterator it = find(m_vConnections.begin(), m_vConnections.end(), pOther->getID());
if (it != m_vConnections.end())
m_vConnections.erase(it);
}
// +-----------------------------------------------------------
std::vector ft::FaceFeature::getConnections()
{
return m_vConnections;
}
// +-----------------------------------------------------------
bool ft::FaceFeature::loadFromXML(const QDomElement &oElement, QString &sMsgError)
{
// Check the element name
if(oElement.tagName() != "Feature")
{
sMsgError = QString(QApplication::translate("FaceFeature", "invalid node name [%1] - expected node '%2'").arg(oElement.tagName(), "Feature"));
return false;
}
QString sID = oElement.attribute("id");
if(sID == "")
{
sMsgError = QString(QApplication::translate("FaceFeature", "the attribute '%1' does not exist or it contains an invalid value").arg("id"));
return false;
}
QString sValueX = oElement.attribute("x");
if(sValueX == "")
{
sMsgError = QString(QApplication::translate("FaceFeature", "the attribute '%1' does not exist or it contains an invalid value").arg("x"));
return false;
}
QString sValueY = oElement.attribute("y");
if(sValueY == "")
{
sMsgError = QString(QApplication::translate("FaceFeature", "the attribute '%1' does not exist or it contains an invalid value").arg("y"));
return false;
}
// Connetions
QDomElement oConnections = oElement.firstChildElement("Connections");
if (oConnections.isNull())
{
sMsgError = QString(QApplication::translate("FaceFeature", "the node '%1' does not exist")).arg("Connections");
return false;
}
vector vConnections;
for (QDomElement oConn = oConnections.firstChildElement(); !oConn.isNull(); oConn = oConn.nextSiblingElement())
{
QString sValue = oConn.attribute("id");
if (sValue == "")
{
sMsgError = QString(QApplication::translate("FaceFeature", "the attribute '%1' does not exist or it contains an invalid value").arg("id"));
return false;
}
vConnections.push_back(sValue.toInt());
}
m_iID = sID.toInt();
setX(sValueX.toFloat());
setY(sValueY.toFloat());
m_vConnections = vConnections;
return true;
}
// +-----------------------------------------------------------
void ft::FaceFeature::saveToXML(QDomElement &oParent) const
{
QDomElement oFeature = oParent.ownerDocument().createElement("Feature");
oParent.appendChild(oFeature);
// Save the feature attributes
oFeature.setAttribute("id", m_iID);
oFeature.setAttribute("x", x());
oFeature.setAttribute("y", y());
// Add the "Connections" subnode
QDomElement oConnections = oParent.ownerDocument().createElement("Connections");
oFeature.appendChild(oConnections);
// Save all the connections
QDomElement oTarget;
foreach(int iID, m_vConnections)
{
oTarget = oParent.ownerDocument().createElement("Target");
oConnections.appendChild(oTarget);
oTarget.setAttribute("id", iID);
}
}
================================================
FILE: src/facefeature.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACE_FEATURE_H
#define FACE_FEATURE_H
#include
#include
#include
namespace ft
{
/**
* Represents the data of a facial feature in the image dataset.
*/
class FaceFeature : public QPoint
{
public:
/**
* Class constructor.
*/
FaceFeature();
/**
* Class constructor.
* @param iID Integer with the feature identifier.
* @param x Float with the x coordinate of the face feature.
* @param y Float with the y coordinate of the face feature.
*/
FaceFeature(int iID, float x, float y);
/**
* Getter of the feature ID.
* @return Integer with the ID of the feature.
*/
int getID() const;
/**
* Setter of the feature ID.
* @param iID Integer with the new ID for the feature.
*/
void setID(int iID);
/**
* Connects this feature to the feature of given ID.
* @param *pOther Pointer to the other feature to connect to.
*/
void connectTo(FaceFeature *pOther);
/**
* Disconnects this feature from the feature of given ID.
* @param pOther Pointer to the other feature to disconnect from.
*/
void disconnectFrom(FaceFeature *pOther);
/**
* Gets the list of features (by their IDs) to which this feature is connected to.
* @return Std vector with a list of integers (the connected features' IDs).
*/
std::vector getConnections();
/**
* Loads (unserializes) the face feature data from the given xml element.
* @param oElement QDomElement from where to read the feature data (the feature node in the xml).
* @param sMsgError QString to receive the error message in case the method fails.
* @return Boolean indicating if the loading was successful (true) or if it failed (false).
*/
bool loadFromXML(const QDomElement &oElement, QString &sMsgError);
/**
* Saves the face feature data into the given xml element.
* @param oParent QDomElement to receive the node of the face feature data.
*/
void saveToXML(QDomElement &oParent) const;
private:
/** Identifier of the face feature. */
int m_iID;
/** List of other features to which this feature is connected to. */
std::vector m_vConnections;
};
}
#endif // FACE_FEATURE_H
================================================
FILE: src/facefeatureedge.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facefeatureedge.h"
#include "facewidget.h"
#include "facefeaturenode.h"
#include
#include
#include
#include
// +-----------------------------------------------------------
ft::FaceFeatureEdge::FaceFeatureEdge(FaceWidget *pFaceWidget, FaceFeatureNode *pSourceNode, FaceFeatureNode *pTargetNode)
{
m_pFaceWidget = pFaceWidget;
setAcceptedMouseButtons(0);
m_pSourceNode = pSourceNode;
m_pTargetNode = pTargetNode;
m_pTargetNode->addEdge(this);
m_pSourceNode->addEdge(this);
adjust();
}
// +-----------------------------------------------------------
ft::FaceFeatureNode* ft::FaceFeatureEdge::sourceNode() const
{
return m_pSourceNode;
}
// +-----------------------------------------------------------
ft::FaceFeatureNode* ft::FaceFeatureEdge::targetNode() const
{
return m_pTargetNode;
}
// +-----------------------------------------------------------
void ft::FaceFeatureEdge::adjust()
{
if (!m_pSourceNode || !m_pTargetNode)
return;
QLineF line(mapFromItem(m_pSourceNode, 0, 0), mapFromItem(m_pTargetNode, 0, 0));
qreal length = line.length();
prepareGeometryChange();
QPointF edgeOffset((line.dx() * FaceFeatureNode::RADIUS) / length, (line.dy() * FaceFeatureNode::RADIUS) / length);
m_oSourcePoint = line.p1() + edgeOffset;
m_oTargetPoint = line.p2() - edgeOffset;
}
// +-----------------------------------------------------------
QRectF ft::FaceFeatureEdge::boundingRect() const
{
if (!m_pSourceNode || !m_pTargetNode)
return QRectF();
QRectF oRet = QRectF(m_oSourcePoint, QSizeF(m_oTargetPoint.x() - m_oSourcePoint.x(), m_oTargetPoint.y() - m_oSourcePoint.y()));
return oRet.normalized();
}
// +-----------------------------------------------------------
void ft::FaceFeatureEdge::paint(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, QWidget *pWidget)
{
Q_UNUSED(pOption);
Q_UNUSED(pWidget);
if (!m_pSourceNode || !m_pTargetNode)
return;
QLineF oLine(m_oSourcePoint, m_oTargetPoint);
pPainter->setPen(QPen(Qt::yellow, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
pPainter->drawLine(oLine);
}
================================================
FILE: src/facefeatureedge.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEFEATUREEDGE_H
#define FACEFEATUREEDGE_H
#include
namespace ft
{
class FaceWidget;
class FaceFeatureNode;
/**
* Implements the edges connecting two FaceFeatures.
*/
class FaceFeatureEdge : public QGraphicsItem
{
public:
/**
* Class constructor.
* @param pFaceWidget Instance of the FaceWidget to be the parent of the face feature edge.
* @param pSourceFeat Instance of the FaceFeatureNode that acts as the first point of the edge.
* @param pTargetNode Instance of the FaceFeatureNode that acts as the second point of the edge.
*/
FaceFeatureEdge(FaceWidget *pFaceWidget, FaceFeatureNode *pSourceNode, FaceFeatureNode *pTargetNode);
/**
* Gets the first point of the edge.
* @return An instance of FaceFeatureNode with the first point of the edge.
*/
FaceFeatureNode *sourceNode() const;
/**
* Gets the second point of the edge.
* @return An instance of FaceFeatureNode with the second point of the edge.
*/
FaceFeatureNode *targetNode() const;
/**
* Forces the edge to adjust its coordinates based on the first (source) and second (target) face feature nodes.
*/
void adjust();
protected:
/**
* Queries the bounding rectangle of the face feature edge.
* @return A QRectF with the coordinates and size of the bounding rect of the edge.
*/
QRectF boundingRect() const Q_DECL_OVERRIDE;
/**
* Paint method for the face feature edge.
* @param pPainter Instance of a QPainter to allow drawing the edge.
* @param pOption Instance of a QStyleOptionGraphicsItem with information on the style and state of the edge.
* @param pWidget Instance of a QWidget with the widget that the edge is being painted on. Optional, and might be 0.
*/
void paint(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, QWidget *pWidget) Q_DECL_OVERRIDE;
private:
/** Reference to the parent face widget. */
FaceWidget *m_pFaceWidget;
/** The first (source) face feature node of the edge. */
FaceFeatureNode *m_pSourceNode;
/** The second (target) face feature node of the edge. */
FaceFeatureNode *m_pTargetNode;
/** Starting point for the face feature edge. */
QPointF m_oSourcePoint;
/** Ending point for the face feature edge. */
QPointF m_oTargetPoint;
};
};
#endif // FACEFEATUREEDGE_H
================================================
FILE: src/facefeaturenode.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facefeaturenode.h"
#include "facewidget.h"
#include "facefeatureedge.h"
#include "application.h"
#include
#include
#include
// Radius of the drawn node, in pixels
const int ft::FaceFeatureNode::RADIUS = 4;
// +-----------------------------------------------------------
ft::FaceFeatureNode::FaceFeatureNode(int iID, FaceWidget *pFaceWidget)
{
m_pFaceWidget = pFaceWidget;
setFlag(ItemIsMovable);
setFlag(ItemSendsGeometryChanges);
setFlag(ItemIsSelectable);
setCacheMode(DeviceCoordinateCache);
setSelected(false);
setAcceptHoverEvents(true);
m_iID = iID;
}
// +-----------------------------------------------------------
void ft::FaceFeatureNode::addEdge(FaceFeatureEdge *pEdge)
{
m_lEdges.append(pEdge);
pEdge->adjust();
}
// +-----------------------------------------------------------
void ft::FaceFeatureNode::removeEdge(FaceFeatureEdge *pEdge)
{
m_lEdges.removeOne(pEdge);
}
// +-----------------------------------------------------------
QList ft::FaceFeatureNode::edges() const
{
return m_lEdges;
}
// +-----------------------------------------------------------
ft::FaceFeatureEdge *ft::FaceFeatureNode::getEdgeTo(const FaceFeatureNode *pNode) const
{
foreach(FaceFeatureEdge *pEdge, m_lEdges)
{
if((pEdge->sourceNode() == this && pEdge->targetNode() == pNode) ||
(pEdge->sourceNode() == pNode && pEdge->targetNode() == this))
{
return pEdge;
}
}
return NULL;
}
// +-----------------------------------------------------------
QRectF ft::FaceFeatureNode::boundingRect() const
{
if(m_pFaceWidget->displayFeatureIDs())
{
QString sID = QString::number(m_iID);
int iHeight = m_pFaceWidget->fontMetrics().height();
int iWidth = m_pFaceWidget->fontMetrics().width(sID);
return QRectF(-(iWidth + RADIUS), -(iHeight + RADIUS), 2 * RADIUS + iWidth, 2 * RADIUS + iHeight);
}
else
return QRectF(-RADIUS, -RADIUS, 2 * RADIUS, 2 * RADIUS);
}
// +-----------------------------------------------------------
void ft::FaceFeatureNode::paint(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, QWidget *pWidget)
{
Q_UNUSED(pOption);
Q_UNUSED(pWidget);
QBrush oBrush;
oBrush.setStyle(Qt::SolidPattern);
if(isSelected())
{
pPainter->setPen(QPen(Qt::red, 0));
oBrush.setColor(QColor(Qt::red));
}
else
{
pPainter->setPen(QPen(Qt::yellow, 0));
oBrush.setColor(QColor(Qt::yellow));
}
QRectF oBounds;
if(m_pFaceWidget->displayFeatureIDs())
{
QString sID = QString::number(m_iID);
int iHeight = m_pFaceWidget->fontMetrics().height();
int iWidth = m_pFaceWidget->fontMetrics().width(sID);
oBounds = QRectF(-(iWidth + RADIUS), -(iHeight + RADIUS), iWidth, iHeight);
pPainter->drawText(oBounds, sID);
oBounds = QRectF(-RADIUS, -RADIUS, 2 * RADIUS, 2 * RADIUS);
}
else
oBounds = boundingRect();
pPainter->setBrush(oBrush);
pPainter->drawEllipse(oBounds);
}
// +-----------------------------------------------------------
QVariant ft::FaceFeatureNode::itemChange(GraphicsItemChange eChange, const QVariant &oValue)
{
QString sText;
switch(eChange)
{
case ItemPositionHasChanged:
foreach(FaceFeatureEdge *pEdge, m_lEdges)
pEdge->adjust();
sText = QApplication::translate("FaceFeatureNode", "Node: %1 Position: (%2, %3)").arg(m_iID).arg(QString::number(pos().x(), 'f', 2)).arg(QString::number(pos().y(), 'f', 2));
FtApplication::instance()->showStatusMessage(sText, 0);
if(!data(0).toBool()) // This flag is used in ChildWindow::refreshFeaturesInWidget
m_pFaceWidget->faceFeatureMoved(this);
break;
default:
break;
};
return QGraphicsItem::itemChange(eChange, oValue);
}
// +-----------------------------------------------------------
void ft::FaceFeatureNode::hoverEnterEvent(QGraphicsSceneHoverEvent *pEvent)
{
QString sText = QApplication::translate("FaceFeatureNode", "Node: %1 Position: (%2, %3)").arg(m_iID).arg(QString::number(pos().x(), 'f', 2)).arg(QString::number(pos().y(), 'f', 2));
FtApplication::instance()->showStatusMessage(sText, 0);
QGraphicsItem::hoverEnterEvent(pEvent);
}
// +-----------------------------------------------------------
void ft::FaceFeatureNode::hoverLeaveEvent(QGraphicsSceneHoverEvent *pEvent)
{
FtApplication::instance()->showStatusMessage("");
QGraphicsItem::hoverLeaveEvent(pEvent);
}
// +-----------------------------------------------------------
int ft::FaceFeatureNode::getID() const
{
return m_iID;
}
// +-----------------------------------------------------------
void ft::FaceFeatureNode::setID(int iID)
{
m_iID = iID;
}
================================================
FILE: src/facefeaturenode.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEFEATURENODE_H
#define FACEFEATURENODE_H
#include
#include
namespace ft
{
class FaceWidget;
class FaceFeatureEdge;
/**
* Implements the visual manipulator of facial feature nodes to be used together with the FaceWidget.
*/
class FaceFeatureNode: public QGraphicsItem
{
public:
/**
* Class constructor.
* @param iID Integer with the ID of the feature node.
* @param pFaceWidget Instance of the FaceWidget to be the parent of the face feature node.
*/
FaceFeatureNode(int iID, FaceWidget *pFaceWidget);
/**
* Adds a new edge to the face feature node.
* @param pEdge Instance of the FaceFeatureEdge to be added to the face feature.
*/
void addEdge(FaceFeatureEdge *pEdge);
/**
* Removes an existing edge from the face feature node.
* @param pEdge Instance of the FaceFeatureEdge to be removed from the face feature.
*/
void removeEdge(FaceFeatureEdge *pEdge);
/**
* Queries the list of face feature edges connected to this node.
* @return Q QList with the list of edges connected to this node.
*/
QList edges() const;
/**
* Queries the edge that connects this node to the given node.
* @param pNode Instance of the other FaceFeatureNode that might be connected to this node.
* @return An instance of the FaceFeatureEdge with the edge connecting the two nodes, or NULL
* if there is no edge connecting the nodes.
*/
FaceFeatureEdge *getEdgeTo(const FaceFeatureNode *pNode) const;
/**
* Queries the bounding rectangle of the face feature node.
* @return A QRectF with the coordinates and size of the bounding rect of the node.
*/
QRectF boundingRect() const Q_DECL_OVERRIDE;
/**
* Gets the identifier of the feature node.
*/
int getID() const;
/**
* Updates the identifier of the feature node.
* @param iID Integer with the new identifier for the feature node.
*/
void setID(int iID);
public:
/** Constant with the radius of the node drawn, in pixels. */
const static int RADIUS;
protected:
/**
* Paint method for the face feature node.
* @param pPainter Instance of a QPainter to allow drawing the node.
* @param pOption Instance of a QStyleOptionGraphicsItem with information on the style and state of the node.
* @param pWidget Instance of a QWidget with the widget that the node is being painted on. Optional, and might be 0.
*/
void paint(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, QWidget *pWidget) Q_DECL_OVERRIDE;
/**
* Captures the event of changes in the node.
* @param eChange GraphicsItemChange enumeration value indicating what is the change.
* @param oValue QVariant const reference with the value that changed.
*/
QVariant itemChange(GraphicsItemChange eChange, const QVariant &oValue) Q_DECL_OVERRIDE;
/**
* Captures the mouse enter event on the feature node.
* @param pEvent Instance of a QGraphicsSceneHoverEvent with the event data.
*/
void hoverEnterEvent(QGraphicsSceneHoverEvent *pEvent) Q_DECL_OVERRIDE;
/**
* Captures the mouse exit event on the feature node.
* @param pEvent Instance of a QGraphicsSceneHoverEvent with the event data.
*/
void hoverLeaveEvent(QGraphicsSceneHoverEvent *pEvent) Q_DECL_OVERRIDE;
private:
/** Reference to the parent face widget. */
FaceWidget *m_pFaceWidget;
/** List of edges added to the node. */
QList m_lEdges;
/** Identifier of the face feature node. */
int m_iID;
};
};
#endif // FACEFEATURENODE_H
================================================
FILE: src/facefitconfig.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facefitconfig.h"
#include "ui_facefitconfig.h"
#include
#include
#include
#include
// +-----------------------------------------------------------
ft::FaceFitConfig::FaceFitConfig(QWidget *pParent) :
QDialog(pParent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint),
ui(new Ui::FaceFitConfig)
{
ui->setupUi(this);
setFixedSize(size());
connect(ui->pathButton, SIGNAL(clicked()), this, SLOT(on_actionSelectPath_triggered()));
connect(ui->pathEdit, SIGNAL(textChanged(QString)), this, SLOT(onPathChanged(QString)));
connect(ui->buttonBox, SIGNAL(helpRequested()), this, SLOT(onShowHelp()));
onPathChanged(ui->pathEdit->text());
}
// +-----------------------------------------------------------
ft::FaceFitConfig::~FaceFitConfig()
{
delete ui;
}
// +-----------------------------------------------------------
void ft::FaceFitConfig::onPathChanged(QString sFilePath)
{
bool bEnabled = sFilePath.length() > 0 && QFileInfo(sFilePath).exists();
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(bEnabled);
}
// +-----------------------------------------------------------
void ft::FaceFitConfig::onShowHelp()
{
QMessageBox::information(this, tr("Help on the face-fit utility"), tr("The face-fit utility is an external executable that can be used to automatically adjust facial landmarks to an image of a human face. It is part of the CSIRO Face Analysis SDK."), QMessageBox::Ok);
}
// +-----------------------------------------------------------
void ft::FaceFitConfig::on_actionSelectPath_triggered()
{
QString sFile = QFileDialog::getOpenFileName(this, tr("Select face-fit executable..."), NULL, tr("All files (*.*)"));
if (sFile.length())
ui->pathEdit->setText(sFile);
}
// +-----------------------------------------------------------
QString ft::FaceFitConfig::getFaceFitPath()
{
return ui->pathEdit->text();
}
================================================
FILE: src/facefitconfig.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEFITCONFIG_H
#define FACEFITCONFIG_H
#include
namespace Ui
{
class FaceFitConfig;
}
namespace ft
{
/**
* Form class used to display the configuration window for the face fit utility.
*/
class FaceFitConfig : public QDialog
{
Q_OBJECT
public:
/**
* Class constructor.
* @param pParent QWidget with the window parent.
*/
explicit FaceFitConfig(QWidget *pParent = 0);
/**
* Class destructor
*/
virtual ~FaceFitConfig();
/**
* Gets the configured path for the face-fit utility.
* @param QString with the path of the face-fit utility.
*/
QString getFaceFitPath();
private slots:
/**
* Slot for the Select Path event.
*/
void on_actionSelectPath_triggered();
/**
* Slot to handle changes in the path line editor.
* @param sFilePath QString with the newly editted utility path.
*/
void onPathChanged(QString sFilePath);
/**
* Slot to handle the request for help.
*/
void onShowHelp();
private:
/** Instance of the ui for GUI element access. */
Ui::FaceFitConfig *ui;
};
}
#endif // FACEFITCONFIG_H
================================================
FILE: src/facefitconfig.ui
================================================
FaceFitConfig
0
0
391
76
Configuration of the face-fit utility
-
QLayout::SetMinimumSize
-
Path to the face-fit utility:
-
0
QLayout::SetMinimumSize
-
-
...
-
Qt::Horizontal
QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok
buttonBox
accepted()
FaceFitConfig
accept()
248
254
157
274
buttonBox
rejected()
FaceFitConfig
reject()
195
55
195
37
================================================
FILE: src/faceimage.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "faceimage.h"
#include
using namespace std;
// +-----------------------------------------------------------
ft::FaceImage::FaceImage(const QString &sFileName)
{
m_sFileName = sFileName;
}
// +-----------------------------------------------------------
ft::FaceImage::~FaceImage()
{
clear();
}
// +-----------------------------------------------------------
void ft::FaceImage::clear()
{
foreach(FaceFeature *pFeature, m_vFeatures)
delete pFeature;
foreach(FaceFeatureEdge *pEdge, m_vConnections)
delete pEdge;
m_vFeatures.clear();
m_vConnections.clear();
}
// +-----------------------------------------------------------
QString ft::FaceImage::fileName() const
{
return m_sFileName;
}
// +-----------------------------------------------------------
void ft::FaceImage::setFileName(QString sFileName)
{
m_sFileName = sFileName;
}
// +-----------------------------------------------------------
bool ft::FaceImage::loadFromXML(const QDomElement &oElement, QString &sMsgError, int iNumExpectedFeatures)
{
// Check the element name
if(oElement.tagName() != "Sample")
{
sMsgError = QString(QApplication::translate("FaceImage", "invalid node name [%1] - expected node '%2'").arg(oElement.tagName(), "Sample"));
return false;
}
// Read the file name
QString sFile = oElement.attribute("fileName");
if(sFile == "")
{
sMsgError = QString(QApplication::translate("FaceImage", "the attribute '%1' does not exist or it contains an invalid value").arg("fileName"));
return false;
}
// Read the face features
// Sample images
QDomElement oFeatures = oElement.firstChildElement("Features");
if(oFeatures.isNull() || oFeatures.childNodes().count() != iNumExpectedFeatures)
{
sMsgError = QString(QApplication::translate("FaceImage", "the node '%1' does not exist or it contains less children nodes than expected").arg("Features"));
return false;
}
vector vFeatures;
for(QDomElement oElement = oFeatures.firstChildElement(); !oElement.isNull(); oElement = oElement.nextSiblingElement())
{
FaceFeature *pFeature = new FaceFeature();
if(!pFeature->loadFromXML(oElement, sMsgError))
{
foreach(FaceFeature *pFeat, vFeatures)
delete(pFeat);
delete pFeature;
return false;
}
vFeatures.push_back(pFeature);
}
clear();
m_sFileName = sFile;
m_vFeatures = vFeatures;
return true;
}
// +-----------------------------------------------------------
void ft::FaceImage::saveToXML(QDomElement &oParent) const
{
// Add the "Sample" node
QDomElement oSample = oParent.ownerDocument().createElement("Sample");
oParent.appendChild(oSample);
// Define it's attributes
oSample.setAttribute("fileName", m_sFileName);
// Add the "Features" subnode
QDomElement oFeatures = oParent.ownerDocument().createElement("Features");
oSample.appendChild(oFeatures);
// Add the nodes for the features
foreach(FaceFeature *pFeat, m_vFeatures)
pFeat->saveToXML(oFeatures);
}
// +-----------------------------------------------------------
QPixmap ft::FaceImage::pixMap() const
{
QPixmap oRet;
oRet.load(m_sFileName);
return oRet;
}
// +-----------------------------------------------------------
ft::FaceFeature* ft::FaceImage::addFeature(int iID, float x, float y)
{
FaceFeature *pFeat = new FaceFeature(iID, x, y);
m_vFeatures.push_back(pFeat);
return pFeat;
}
// +-----------------------------------------------------------
ft::FaceFeature* ft::FaceImage::getFeature(const int iIndex) const
{
if(iIndex < 0 || iIndex >= (int) m_vFeatures.size())
return NULL;
return m_vFeatures[iIndex];
}
// +-----------------------------------------------------------
std::vector ft::FaceImage::getFeatures() const
{
return m_vFeatures;
}
// +-----------------------------------------------------------
bool ft::FaceImage::removeFeature(const int iIndex)
{
if(iIndex < 0 || iIndex >= (int) m_vFeatures.size())
return false;
FaceFeature *pFeat = m_vFeatures[iIndex];
m_vFeatures.erase(m_vFeatures.begin() + iIndex);
delete pFeat;
return true;
}
// +-----------------------------------------------------------
bool ft::FaceImage::connectFeatures(int iIDSource, int iIDTarget)
{
if (iIDSource < 0 || iIDSource >= (int)m_vFeatures.size())
return false;
if (iIDTarget < 0 || iIDTarget >= (int)m_vFeatures.size())
return false;
FaceFeature *pSource = m_vFeatures[iIDSource];
FaceFeature *pTarget = m_vFeatures[iIDTarget];
pSource->connectTo(pTarget);
return true;
}
// +-----------------------------------------------------------
bool ft::FaceImage::disconnectFeatures(int iIDSource, int iIDTarget)
{
if (iIDSource < 0 || iIDSource >= (int)m_vFeatures.size())
return false;
if (iIDTarget < 0 || iIDTarget >= (int)m_vFeatures.size())
return false;
FaceFeature *pSource = m_vFeatures[iIDSource];
FaceFeature *pTarget = m_vFeatures[iIDTarget];
pSource->disconnectFrom(pTarget);
return true;
}
================================================
FILE: src/faceimage.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACE_IMAGE_H
#define FACE_IMAGE_H
#include "facefeature.h"
#include "facefeatureedge.h"
#include
#include
#include
#include
#include
namespace ft
{
/**
* Represents the data from one facial image sample in the image dataset, including its
* annotations (facial features, their connections, and the face emotional label).
*/
class FaceImage
{
public:
/**
* Class constructor.
* @param sFileName String with the file name of the face image. If defined as empty in the
* constructor, it can only be later updated by reading from a file.
*/
FaceImage(const QString &sFileName = QString());
/**
* Class destructor.
*/
virtual ~FaceImage();
/**
* Gets the file name of the face image.
* @return QString with the complete file name of the face image.
*/
QString fileName() const;
/**
* Sets the file name of the face image.
* @param sFileName QString with the new file name for the face image.
*/
void setFileName(QString sFileName);
/**
* Adds a new face feature to the face image.
* @param iID Integer with the ID of the face feature.
* @param x Float with the x coordinate of the face feature.
* @param y Float with the y coordinate of the face feature.
* @return Instance of a FaceFeature with the new feature created.
*/
FaceFeature *addFeature(int iID, float x = 0.0f, float y = 0.0f);
/**
* Gets the face feature at the given index.
* @param iIndex Integer with the index of the feature to be obtained.
* @return Instance of the face feature at the index or NULL if the index
* is out of bounds.
*/
FaceFeature *getFeature(const int iIndex) const;
/**
* Gets all face features in the image.
* @return Vector with all instances of face features in the image.
*/
std::vector getFeatures() const;
/**
* Removes the face feature at the given index.
* @param iIndex Integer with the index of the feature to be removed.
* @return Boolean indicating if the face feature was successfully
* removed (true) or not (false).
*/
bool removeFeature(const int iIndex);
/**
* Connects the two given features.
* @param iIDSource Integer with the ID (index) of the source feature.
* @param iIDTarget Integer with the ID (index) of the target feature.
* @return Boolean indicating if the connection was successfully created.
*/
bool connectFeatures(int iIDSource, int iIDTarget);
/**
* Disconnects the two given features.
* @param iIDSource Integer with the ID (index) of the source feature.
* @param iIDTarget Integer with the ID (index) of the target feature.
* @return Boolean indicating if the connection was successfully removed.
*/
bool disconnectFeatures(int iIDSource, int iIDTarget);
/**
* Loads (unserializes) the face image data from the given xml element.
* @param oElement QDomElement from where to read the image data (the image node in the xml).
* @param sMsgError QString to receive the error message in case the method fails.
* @param iNumExpectedFeatures Integer with the number of expected features.
* @return Boolean indicating if the loading was successful (true) or if it failed (false).
*/
bool loadFromXML(const QDomElement &oElement, QString &sMsgError, int iNumExpectedFeatures);
/**
* Saves the face image data into the given xml element.
* @param oParent Parent QDomElement to receive the new node of the face image data.
*/
void saveToXML(QDomElement &oParent) const;
/**
* Loads and returns the image data as a Qt's QPixmap. If an error occur during the loading of
* the file, an empty QPixmap is returned instead (that can be checked with QPixmap::isNull()).
* @return A QPixmap with the image data, or an empty QPixmap if an error ocurred.
*/
QPixmap pixMap() const;
protected:
/**
* Clears the internal data (like face features).
*/
void clear();
private:
/** Name of the file with the face image. */
QString m_sFileName;
/** Vector of the face features in this face image. */
std::vector m_vFeatures;
/** Vector of the connections between face features in this face image. */
std::vector m_vConnections;
};
}
#endif // FACE_IMAGE_H
================================================
FILE: src/facewidget.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facewidget.h"
#include "facewidgetscene.h"
#include
#include
#include
#include
#include
#include
// Scale values for zoom in and out steps
const double ft::FaceWidget::ZOOM_IN_STEP = 1.25;
const double ft::FaceWidget::ZOOM_OUT_STEP = 0.80;
// Number of face features edited by the widget
const int ft::FaceWidget::NUM_FACE_FEATURES = 68;
// +-----------------------------------------------------------
ft::FaceWidget::FaceWidget(QWidget *pParent) : QGraphicsView(pParent)
{
setDragMode(RubberBandDrag);
m_pScene = (QGraphicsScene*) new FaceWidgetScene(this);
m_pScene->setItemIndexMethod(QGraphicsScene::NoIndex);
setScene(m_pScene);
connect(m_pScene, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
setCacheMode(CacheBackground);
setViewportUpdateMode(BoundingRectViewportUpdate);
setRenderHint(QPainter::Antialiasing);
setTransformationAnchor(AnchorUnderMouse);
scale(1.0, 1.0);
m_dScaleFactor = 1.0;
setBackgroundBrush(QApplication::palette().dark());
// Add the image item
QPixmap oPixmap(":/images/noface");
m_pPixmapItem = m_pScene->addPixmap(oPixmap);
m_pPixmapItem->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
m_pScene->setSceneRect(0, 0, oPixmap.width(), oPixmap.height());
// Setup the face features editor
m_bDisplayFaceFeatures = true;
m_bDisplayConnections = true;
m_bDisplayFeatureIDs = false;
m_pContextMenu = NULL;
//createFaceFeatures();
m_bFeaturesMoved = false;
m_bSelectionChanged = false;
}
// +-----------------------------------------------------------
ft::FaceWidget::~FaceWidget()
{
delete m_pScene;
}
// +-----------------------------------------------------------
void ft::FaceWidget::setPixmap(const QPixmap &oPixmap)
{
m_pPixmapItem->setPixmap(oPixmap);
m_pScene->setSceneRect(0, 0, oPixmap.width(), oPixmap.height());
}
// +-----------------------------------------------------------
double ft::FaceWidget::getScaleFactor() const
{
return qFloor(m_dScaleFactor * 100000.0) / 100000.0; // Returns it with precision of 5 decimals
}
// +-----------------------------------------------------------
void ft::FaceWidget::setScaleFactor(const double dScaleFactor)
{
if(dScaleFactor == m_dScaleFactor)
return;
if(dScaleFactor >= 0.10 && dScaleFactor <= 10.0)
{
// First, go back to the base scale (1.0 or 100%)
double dAdjust = 1.0 / m_dScaleFactor;
scale(dAdjust, dAdjust);
// Then, apply the requested factor.
m_dScaleFactor = dScaleFactor;
if(m_dScaleFactor != 1.0)
scale(dScaleFactor, dScaleFactor);
}
}
// +-----------------------------------------------------------
void ft::FaceWidget::scaleViewBy(double dFactorBy)
{
double dFactor = m_dScaleFactor * dFactorBy;
if(dFactor >= 0.10 && dFactor <= 10.0)
{
m_dScaleFactor = dFactor;
scale(dFactorBy, dFactorBy);
// Emit the signal that the scale factor has changed
emit onScaleFactorChanged(getScaleFactor());
}
}
#ifndef QT_NO_WHEELEVENT
// +-----------------------------------------------------------
void ft::FaceWidget::wheelEvent(QWheelEvent *pEvent)
{
bool bCtrl = QApplication::keyboardModifiers() & Qt::ControlModifier;
bool bAlt = QApplication::keyboardModifiers() & Qt::AltModifier;
bool bShift = QApplication::keyboardModifiers() & Qt::ShiftModifier;
int iDelta = pEvent->angleDelta().x() + pEvent->angleDelta().y();
double dBase = iDelta < 0 ? ZOOM_OUT_STEP : ZOOM_IN_STEP;
int iSteps = abs(iDelta / 120);
if(!(bCtrl || bAlt || bShift)) // No special key pressed => scroll vertically
verticalScrollBar()->setValue(verticalScrollBar()->value() - iDelta);
else if(bShift && !(bCtrl || bAlt)) // Only shift key pressed => scroll horizontally
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - iDelta);
else if(bCtrl && !(bAlt || bShift)) // Only ctrl key pressed => zoom in and out
scaleViewBy(qPow(dBase, iSteps));
}
#endif
// +-----------------------------------------------------------
void ft::FaceWidget::mousePressEvent(QMouseEvent* pEvent)
{
QPointF oPos = pEvent->pos();
oPos = mapToScene(pEvent->pos());
QTransform oTrf;
QGraphicsItem* pItem = scene()->itemAt(oPos, oTrf);
if (pItem && pItem->isEnabled() && (pItem->flags() & QGraphicsItem::ItemIsSelectable) &&
(pEvent->modifiers() & Qt::ShiftModifier))
{
int iFirst, iLast;
QList lsSelected = getSelectedFeatures();
if(!lsSelected.size())
iFirst = 0;
else
{
iFirst = lsSelected.first()->getID();
foreach(FaceFeatureNode *pNode, lsSelected)
if(pNode->getID() < iFirst)
iFirst = pNode->getID();
}
iLast = ((FaceFeatureNode*) pItem)->getID();
if(iFirst != iLast)
{
QList lsFeats = getFaceFeatures();
foreach(FaceFeatureNode* pFeat, lsFeats)
pFeat->setSelected(false);
for(int i = qMin(iFirst, iLast); i <= qMax(iFirst, iLast); i++)
lsFeats[i]->setSelected(true);
}
pEvent->accept();
}
else
QGraphicsView::mousePressEvent((QMouseEvent*) pEvent);
}
// +-----------------------------------------------------------
void ft::FaceWidget::mouseReleaseEvent(QMouseEvent *pEvent)
{
if(m_bFeaturesMoved)
{
emit onFaceFeaturesChanged();
m_bFeaturesMoved = false;
}
if(m_bSelectionChanged)
{
emit onFaceFeaturesSelectionChanged();
m_bSelectionChanged = false;
}
QGraphicsView::mouseReleaseEvent(pEvent);
}
// +-----------------------------------------------------------
void ft::FaceWidget::zoomIn()
{
scaleViewBy(ZOOM_IN_STEP);
}
// +-----------------------------------------------------------
void ft::FaceWidget::zoomOut()
{
scaleViewBy(ZOOM_OUT_STEP);
}
// +-----------------------------------------------------------
void ft::FaceWidget::createFaceFeatures()
{
// These are the coordinates for the face features of a sample face model
double aFaceModel[NUM_FACE_FEATURES][2] =
{
{217.79878, 217.08728},
{216.89078, 254.86311},
{223.67206, 292.07462},
{238.23885, 326.79248},
{254.94789, 360.61587},
{279.53139, 388.90414},
{310.45043, 410.42450},
{345.37818, 425.29204},
{382.36266, 428.51270},
{418.06689, 424.13911},
{449.99561, 408.56366},
{477.42884, 385.63278},
{499.83194, 357.72590},
{509.49470, 323.37268},
{516.13174, 287.86876},
{518.15853, 252.06194},
{518.69634, 216.55158},
{247.62010, 180.34162},
{268.70792, 165.39026},
{293.56778, 158.93545},
{319.16937, 160.78699},
{343.48894, 169.15112},
{397.25624, 164.28431},
{420.26527, 156.48688},
{443.57508, 150.79923},
{467.19522, 154.84270},
{488.87233, 165.42594},
{372.77664, 199.50671},
{373.99586, 223.36618},
{375.57578, 246.90136},
{378.10595, 270.34028},
{345.61168, 293.24677},
{361.62731, 300.03883},
{378.63337, 301.76439},
{393.55789, 298.57543},
{406.85187, 291.64665},
{280.10863, 206.43671},
{300.22526, 197.40182},
{321.95062, 195.23294},
{339.75602, 206.97070},
{319.74604, 209.54150},
{299.69791, 210.59487},
{405.25688, 203.23706},
{420.24655, 189.68711},
{440.47753, 188.93026},
{459.57889, 196.31247},
{442.35281, 203.82019},
{423.65388, 206.10059},
{329.76923, 340.09600},
{344.93415, 328.45414},
{359.76855, 316.54668},
{377.56618, 319.87236},
{395.18127, 314.47085},
{411.21730, 325.09745},
{427.09559, 335.85024},
{415.75540, 349.79882},
{398.78054, 356.02983},
{380.76123, 358.75053},
{361.44337, 358.76781},
{343.08983, 353.52445},
{341.63086, 335.00864},
{353.49249, 334.72611},
{377.56554, 336.91333},
{402.31187, 331.58481},
{414.70373, 331.84948},
{401.78216, 332.11416},
{377.03251, 337.44653},
{353.00775, 335.29117},
};
// Add the face feature nodes
FaceFeatureNode *pPrevFeat = NULL;
FaceFeatureNode *pCurFeat = NULL;
for(int i = 0; i < NUM_FACE_FEATURES; i++)
{
pCurFeat = addFaceFeature(QPoint(aFaceModel[i][0], aFaceModel[i][1]));
if(!pPrevFeat)
pPrevFeat = pCurFeat;
else
{
connectFaceFeatures(pPrevFeat, pCurFeat);
pPrevFeat = pCurFeat;
}
}
}
// +-----------------------------------------------------------
const QList& ft::FaceWidget::getFaceFeatures(int iNumFeats)
{
if(iNumFeats != -1)
{
int iDiff = m_lFaceFeatures.size() - iNumFeats;
if(iDiff > 0)
{
while(iDiff-- > 0)
removeFaceFeature(m_lFaceFeatures.last());
}
else if(iDiff < 0)
{
while(iDiff++ < 0)
addFaceFeature();
}
}
return m_lFaceFeatures;
}
// +-----------------------------------------------------------
QList ft::FaceWidget::getSelectedFeatures() const
{
QList lSelected;
foreach(QGraphicsItem *pItem, m_pScene->selectedItems())
lSelected.append((FaceFeatureNode*) pItem);
return lSelected;
}
// +-----------------------------------------------------------
QList ft::FaceWidget::getSelectedConnections() const
{
QList lFeatures = getSelectedFeatures();
QList lSelected;
QList::iterator oFirst, oSecond;
FaceFeatureEdge *pEdge;
for(oFirst = lFeatures.begin(); oFirst != lFeatures.end(); ++oFirst)
{
for(oSecond = oFirst + 1; oSecond != lFeatures.end(); ++oSecond)
{
pEdge = (*oFirst)->getEdgeTo(*oSecond);
if(pEdge)
{
lSelected.append(pEdge);
break;
}
}
}
return lSelected;
}
// +-----------------------------------------------------------
ft::FaceFeatureNode* ft::FaceWidget::addFaceFeature(const QPoint &oPos, bool bGlobal)
{
int iID = m_lFaceFeatures.size();
FaceFeatureNode *pNode = new FaceFeatureNode(iID, this);
m_pScene->addItem(pNode);
m_lFaceFeatures.append(pNode);
if(bGlobal)
pNode->setPos(mapToScene(mapFromGlobal(oPos)));
else
pNode->setPos(oPos);
return pNode;
}
// +-----------------------------------------------------------
void ft::FaceWidget::removeFaceFeature(FaceFeatureNode* pNode)
{
// First, remove all edges connected to the node
QList lEdges = pNode->edges();
for(int i = 0; i < lEdges.size(); i++)
removeConnection(lEdges[i]);
// Then, remove the node
m_lFaceFeatures.removeOne(pNode);
m_pScene->removeItem(pNode);
delete pNode;
// And adjust the IDs of the remaining features
int iID = 0;
foreach(FaceFeatureNode *pNode, m_lFaceFeatures)
pNode->setID(iID++);
}
// +-----------------------------------------------------------
ft::FaceFeatureEdge* ft::FaceWidget::connectFaceFeatures(FaceFeatureNode* pSource, FaceFeatureNode* pTarget)
{
FaceFeatureEdge* pEdge = pSource->getEdgeTo(pTarget);
if(pEdge)
return pEdge;
pEdge = new FaceFeatureEdge(this, pSource, pTarget);
m_pScene->addItem(pEdge);
m_lConnections.append(pEdge);
return pEdge;
}
// +-----------------------------------------------------------
ft::FaceFeatureEdge* ft::FaceWidget::connectFaceFeatures(int iSource, int iTarget)
{
FaceFeatureNode *pSource = NULL, *pTarget = NULL;
QList lFeats = getFaceFeatures();
foreach(FaceFeatureNode *pFeat, lFeats)
{
if (pFeat->getID() == iSource)
pSource = pFeat;
else if (pFeat->getID() == iTarget)
pTarget = pFeat;
if (pSource && pTarget)
break;
}
if (pSource && pTarget)
return connectFaceFeatures(pSource, pTarget);
else
return NULL;
}
// +-----------------------------------------------------------
void ft::FaceWidget::disconnectFaceFeatures(FaceFeatureNode* pSource, FaceFeatureNode* pTarget)
{
FaceFeatureEdge *pEdge = pSource->getEdgeTo(pTarget);
if(pEdge)
removeConnection(pEdge);
}
// +-----------------------------------------------------------
void ft::FaceWidget::removeConnection(FaceFeatureEdge* pEdge)
{
pEdge->sourceNode()->removeEdge(pEdge);
pEdge->targetNode()->removeEdge(pEdge);
m_lConnections.removeOne(pEdge);
m_pScene->removeItem(pEdge);
delete pEdge;
}
// +-----------------------------------------------------------
void ft::FaceWidget::faceFeatureMoved(FaceFeatureNode *pNode)
{
Q_UNUSED(pNode);
m_bFeaturesMoved = true;
}
// +-----------------------------------------------------------
void ft::FaceWidget::onSelectionChanged()
{
m_bSelectionChanged = true;
}
// +-----------------------------------------------------------
bool ft::FaceWidget::displayFaceFeatures() const
{
return m_bDisplayFaceFeatures;
}
// +-----------------------------------------------------------
void ft::FaceWidget::setDisplayFaceFeatures(const bool bValue)
{
if(bValue == m_bDisplayFaceFeatures)
return;
m_bDisplayFaceFeatures = bValue;
foreach(FaceFeatureNode *pNode, m_lFaceFeatures)
pNode->setVisible(bValue);
update();
}
// +-----------------------------------------------------------
bool ft::FaceWidget::displayConnections() const
{
return m_bDisplayConnections;
}
// +-----------------------------------------------------------
void ft::FaceWidget::setDisplayConnections(const bool bValue)
{
if(bValue == m_bDisplayConnections)
return;
m_bDisplayConnections = bValue;
foreach(FaceFeatureEdge *pEdge, m_lConnections)
pEdge->setVisible(bValue);
update();
}
// +-----------------------------------------------------------
bool ft::FaceWidget::displayFeatureIDs() const
{
return m_bDisplayFeatureIDs;
}
// +-----------------------------------------------------------
void ft::FaceWidget::setDisplayFeatureIDs(const bool bValue)
{
m_bDisplayFeatureIDs = bValue;
foreach(FaceFeatureNode *pNode, m_lFaceFeatures)
pNode->update();
update();
}
// +-----------------------------------------------------------
void ft::FaceWidget::contextMenuEvent(QContextMenuEvent *pEvent)
{
if(m_pContextMenu)
{
// Set the context menu mouse position as the user data of the
// first action (the 'add feature' action), so it can be used
// as the position of the new feature point
m_pContextMenu->actions()[0]->setData(pEvent->globalPos());
// call the context menu
m_pContextMenu->exec(pEvent->globalPos());
// After the menu is closed, empty the data to avoid using it wrongly in the future
m_pContextMenu->actions()[0]->setData(QVariant::Invalid);
}
}
// +-----------------------------------------------------------
void ft::FaceWidget::setContextMenu(QMenu *pMenu)
{
m_pContextMenu = pMenu;
}
================================================
FILE: src/facewidget.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEWIDGET_H
#define FACEWIDGET_H
#include
#include
#include
#include
#include
#include "facefeaturenode.h"
#include "facefeatureedge.h"
namespace Ui {
class MainWindow;
}
namespace ft
{
/**
* Implements the widget used to display face images and to edit facial features by dragging its points.
*/
class FaceWidget : public QGraphicsView
{
Q_OBJECT
public:
/** Scale value for the zoom in step. */
static const double ZOOM_IN_STEP;
/** Scale value for the zoom out step. */
static const double ZOOM_OUT_STEP;
/**
* Class constructor.
* @param pParent Instance of the parent widget.
*/
FaceWidget(QWidget *pParent = 0);
/**
* Class destructor.
*/
virtual ~FaceWidget();
/**
* Updates the pixmap displayed at the central area.
* @param oPixmap Reference for a QPixmap with the new pixmap to display.
*/
void setPixmap(const QPixmap &oPixmap);
/**
* Gets the currently applied scale factor on the image displayed.
* @return Double with the currently applied scale factor.
*/
double getScaleFactor() const;
/**
* Sets the scale factor of the image displayed.
* @param dScaleFactor Double with the new scale factor to be applied. It must be
* in the interval [0.10, 10.0].
*/
void setScaleFactor(const double dScaleFactor);
/**
* Performs one step of zoom in.
*/
void zoomIn();
/**
* Performs one step of zoom out.
*/
void zoomOut();
/**
* Queries the list of existing face feature nodes. Optionally, guarantee that the
* correct number of face features are available in the editor.
* @param iNumFeats Integer with the expected number of face features in the editor.
* If -1 is provided (the default), the method simply returns the current set of
* face features without performing any checking. If the value is different than -1,
* the method will create or remove face features to guarantee that given number of
* features.
* @param Const reference to the QList of existing nodes.
*/
const QList& getFaceFeatures(int iNumFeats = -1);
/**
* Queries the selected face feature nodes.
* @return QList with the pointers to the selected face feature nodes.
*/
QList getSelectedFeatures() const;
/**
* Queries the selected face feature edges.
* @return QList with the pointers to the selected face feature edges.
*/
QList getSelectedConnections() const;
/**
* Adds a new face feature node in the given position.
* @param oPos A QPoint with the coordinates for the new node. If not provided, (0, 0) is assumed.
* @param bGlobal Bool indicating if the coordinate of the position is referenced to the global
* coordinate system or to the scene coordinate system. The default is false (indicating that is related
* to the scene coordinate system).
* @return Pointer to the instance of the newly added face feature node.
*/
FaceFeatureNode* addFaceFeature(const QPoint &oPos = QPoint(), bool bGlobal = false);
/**
* Removes an existing face feature node.
* @param pNode Pointer to the instance of the face feature node to remove.
*/
void removeFaceFeature(FaceFeatureNode* pNode);
/**
* Adds a new face feature edge connecting two existing nodes.
* @param pSource Pointer to the instance of the first face feature node.
* @param pTarget Pointer to the instance of the second face feature node.
* @return Pointer to the instance of the newly added face feature edge connecting the two nodes.
*/
FaceFeatureEdge* connectFaceFeatures(FaceFeatureNode* pSource, FaceFeatureNode* pTarget);
/**
* Adds a new face feature edge connecting two existing nodes, based on their IDs.
* @param iSource Integer with the ID of the first face feature node.
* @param iTarget Integer with the ID of the second face feature node.
* @return Pointer to the instance of the newly added face feature edge connecting the two nodes.
*/
FaceFeatureEdge* connectFaceFeatures(int iSource, int iTarget);
/**
* Removes the face feature edge connecting two existing nodes.
* @param pSource Pointer to the instance of the first face feature node.
* @param pTarget Pointer to the instance of the second face feature node.
*/
void disconnectFaceFeatures(FaceFeatureNode* pSource, FaceFeatureNode* pTarget);
/**
* Removes an existing face feature edge.
* @param pEdge Pointer to the instance of the face feature edge to remove.
*/
void removeConnection(FaceFeatureEdge* pEdge);
/**
* Captures the indication that a face feature node has been moved by the user.
* @param pNode Instance of the Face Feature Node that has been moved.
*/
void faceFeatureMoved(FaceFeatureNode *pNode);
/**
* Indicates if the face feature nodes are on display.
* @return Boolean indicating if the face feature nodes are being displayed or not.
*/
bool displayFaceFeatures() const;
/**
* Updates the indication on if the face feature nodes shall be displayed or not.
* @param bValue Boolean with the new value (true means show, false means hide).
*/
void setDisplayFaceFeatures(const bool bValue);
/**
* Indicates if the face feature edges are on display.
* @return Boolean indicating if the face feature edges are being displayed or not.
*/
bool displayConnections() const;
/**
* Updates the indication on if the face feature edges shall be displayed or not.
* @param bValue Boolean with the new value (true means show, false means hide).
*/
void setDisplayConnections(const bool bValue);
/**
* Indicates if the identifiers of the face feature nodes are on display.
* @return Boolean indicating if the identifiers of the face feature nodes are being displayed or not.
*/
bool displayFeatureIDs() const;
/**
* Updates the indication on if the identifiers of the face feature nodes shall be displayed or not.
* @param bValue Boolean with the new value (true means show, false means hide).
*/
void setDisplayFeatureIDs(const bool bValue);
/**
* Sets the menu to be displayed upon events of context menu on the face features editor.
* The actions used in the menu must be controlled by the caller.
* @param pMenu Instance of the QMenu to be used for the context of the editor.
*/
void setContextMenu(QMenu *pMenu);
public:
/** Constant with the number of face features. */
const static int NUM_FACE_FEATURES;
signals:
/**
* Signal to indicate that the scale of the display image has changed from direct user interaction
* with the widget (that is, a call to setScaleFactor does not emit this signal).
* @param dScaleFactor Double with the new scale factor.
*/
void onScaleFactorChanged(const double dScaleFactor);
/**
* Signal to indicate that the face features changed somehow: a face feature node was added, removed or moved
* or a connection between two face feature nodes was created or removed.
*/
void onFaceFeaturesChanged();
/**
* Signal to indicate that face features were selected or unselected in the editor.
* The selection can be queried through getSelectedFeatures() and getSelectedConnections().
*/
void onFaceFeaturesSelectionChanged();
protected:
#ifndef QT_NO_WHEELEVENT
/**
* Captures and handles the mouse wheel events to automate user interactions.
* @param pEvent Pointer to a QWheelEvent with the mouse event.
*/
void wheelEvent(QWheelEvent *pEvent) Q_DECL_OVERRIDE;
#endif
/**
* Captures the press of the mouse button to notify changes in the face feature editor.
* @param pEvent Instance of the QMouseEvent with the event data.
*/
void mousePressEvent(QMouseEvent* pEvent);
/**
* Captures the release of the mouse button to notify changes in the face feature editor.
* @param pEvent Instance of the QMouseEvent with the event data.
*/
void mouseReleaseEvent(QMouseEvent *pEvent);
/**
* Scales the widget view to emulate a zoom behaviour by the given factor.
* @param dFactorBy Double with the scale to be added/removed.
*/
void scaleViewBy(double dFactorBy);
/**
* Creates the face feature nodes and edges to be used by the face features editor.
*/
void createFaceFeatures();
/**
* Captures the context menu event.
* @param pEvent Instance of a QContextMenuEvent with the event data.
*/
void contextMenuEvent(QContextMenuEvent *pEvent) Q_DECL_OVERRIDE;
protected slots:
/**
* Captures the signal of selection changed in the graphics scene.
*/
void onSelectionChanged();
private:
/** Indication about the feature nodes being moved. */
bool m_bFeaturesMoved;
/** Indication about the selection of feature nodes being changed. */
bool m_bSelectionChanged;
/** The scene used to render the widget contents. */
QGraphicsScene *m_pScene;
/** Pixmap item used to display the face image. */
QGraphicsPixmapItem *m_pPixmapItem;
/** The current applied scale factor. */
double m_dScaleFactor;
/** List of nodes used to edit the coordinates of facial features. */
QList m_lFaceFeatures;
/** List of edges connecting two feature nodes. */
QList m_lConnections;
/** Indicates if the face feature nodes should be displayed or not. */
bool m_bDisplayFaceFeatures;
/** Indicates if the face feature edges should be displayed or not. */
bool m_bDisplayConnections;
/** Indicates if the IDs of the face feature nodes should be displayed or not. */
bool m_bDisplayFeatureIDs;
/** Context menu for the face feature editor. */
QMenu *m_pContextMenu;
};
};
#endif //FACEWIDGET_H
================================================
FILE: src/facewidgetscene.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "facewidgetscene.h"
// +-----------------------------------------------------------
ft::FaceWidgetScene::FaceWidgetScene(QObject *pParent):
QGraphicsScene(pParent)
{
}
// +-----------------------------------------------------------
void ft::FaceWidgetScene::mousePressEvent(QGraphicsSceneMouseEvent *pEvent)
{
if(pEvent->button() != Qt::LeftButton)
{
pEvent->accept();
return;
}
QGraphicsScene::mousePressEvent(pEvent);
}
================================================
FILE: src/facewidgetscene.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef FACEWIDGETSCENE_H
#define FACEWIDGETSCENE_H
#include
#include
namespace ft
{
/**
* Inherits the base QGraphicsScene to implement specific interaction behaviours in the face features editor.
*/
class FaceWidgetScene: QGraphicsScene
{
public:
/**
* Class constructor.
* @param pParent Instance of a QObject with the parent for the scene.
*/
FaceWidgetScene(QObject *pParent = 0);
protected:
/**
* Captures the mouse press event.
* @param pEvent Instance of a QGraphicsSceneMouseEvent with the event data.
*/
void mousePressEvent(QGraphicsSceneMouseEvent *pEvent) Q_DECL_OVERRIDE;
};
};
#endif //FACEWIDGETSCENE_H
================================================
FILE: src/main.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "mainwindow.h"
#include "application.h"
using namespace ft;
// +-----------------------------------------------------------
int main(int argc, char *argv[])
{
FtApplication oApp(argc, argv);
MainWindow oMainWindow;
QObject::connect(FtApplication::instance(), SIGNAL(statusMessageShown(const QString &, const int)), &oMainWindow, SLOT(showStatusMessage(const QString &, const int)));
oMainWindow.show();
return oApp.exec();
}
================================================
FILE: src/mainwindow.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutwindow.h"
#include "facefitconfig.h"
#include "utils.h"
#include "application.h"
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
// +-----------------------------------------------------------
ft::MainWindow::MainWindow(QWidget *pParent) :
QMainWindow(pParent),
ui(new Ui::MainWindow)
{
// Setup the UI
ui->setupUi(this);
QPalette oROPalette = ui->textFileName->palette();
oROPalette.setColor(QPalette::Base, oROPalette.midlight().color());
ui->textFileName->setPalette(oROPalette);
setWindowState(Qt::WindowMaximized);
m_pAbout = NULL;
setWindowIcon(QIcon(":/icons/fat"));
ui->tabWidget->setAutoFillBackground(true);
ui->tabWidget->setBackgroundRole(QPalette::Midlight);
// Setup the TAB changing events
connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(on_tabCloseRequested(int)));
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(on_tabChanged(int)));
// Add the view dropdown button manually (because Qt designer does not allow it...)
m_pViewButton = new QMenu(ui->imagesToolbar);
ui->imagesToolbar->addSeparator();
ui->imagesToolbar->addAction(m_pViewButton->menuAction());
QAction *pViewDetails = new QAction(QIcon(":/icons/viewdetails"), tr("&Details"), this);
pViewDetails->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
m_pViewButton->addAction(pViewDetails);
QAction *pViewIcons = new QAction(QIcon(":/icons/viewicons"), tr("&Icons"), this);
pViewIcons->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_I));
m_pViewButton->addAction(pViewIcons);
QSignalMapper *pMap = new QSignalMapper(ui->imagesToolbar);
connect(pViewDetails, SIGNAL(triggered()), pMap, SLOT(map()));
connect(pViewIcons, SIGNAL(triggered()), pMap, SLOT(map()));
pMap->setMapping(pViewDetails, QString("details"));
pMap->setMapping(pViewIcons, QString("icons"));
connect(pMap, SIGNAL(mapped(QString)), this, SLOT(setImageListView(QString)));
connect(m_pViewButton->menuAction(), SIGNAL(triggered()), this, SLOT(toggleImageListView()));
m_pViewButton->setIcon(QIcon(":/icons/viewicons")); // By default display the image thumbnails
ui->treeImages->setVisible(false);
// Default path for file dialogs is the standard documents path
m_sLastPathUsed = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)) + QDir::separator();
// Default path for the face-fit utility
m_sFaceFitPath = "";
m_oFitProcess = new QProcess(this);
connect(m_oFitProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onFitError(::ProcessError)));
connect(m_oFitProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onFitFinished(int, QProcess::ExitStatus)));
// Add the action shortcuts to the tooltips (in order to make it easier for the user to know they exist)
// P.S.: I wonder why doesn't Qt do that automatically... :)
QObjectList lsObjects = children();
QAction *pAction;
for(int i = 0; i < lsObjects.size(); i++)
{
pAction = qobject_cast(lsObjects.at(i));
if(pAction && !pAction->shortcut().isEmpty())
pAction->setToolTip(QString("%1 (%2)").arg(pAction->toolTip()).arg(pAction->shortcut().toString()));
}
// Connect the zoom slider
connect(ui->zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged(int)));
}
// +-----------------------------------------------------------
ft::MainWindow::~MainWindow()
{
// Save the current window state and geometry
QSettings oSettings;
oSettings.setValue("geometry", saveGeometry());
oSettings.setValue("windowState", saveState());
oSettings.setValue("lastPathUsed", m_sLastPathUsed);
oSettings.setValue("faceFitPath", m_sFaceFitPath);
if(m_pAbout)
delete m_pAbout;
if(m_pViewButton)
delete m_pViewButton;
if (m_oFitProcess)
delete m_oFitProcess;
delete ui;
}
// +-----------------------------------------------------------
void ft::MainWindow::closeEvent(QCloseEvent *pEvent)
{
QList lModified;
ChildWindow *pChild;
// Get the list of modified child windows
for(int i = 0; i < ui->tabWidget->count(); i++)
{
pChild = (ChildWindow*) ui->tabWidget->widget(i);
if(pChild->isWindowModified())
lModified.append(pChild);
}
// Ask for saving the modifiled child windows
if(lModified.size() > 0)
{
QString sMsg;
if(lModified.size() == 1)
{
pChild = lModified[0];
sMsg = tr("There are pending changes in the face annotation dataset named [%1]. Do you wish to save it before closing?").arg(QFileInfo(pChild->windowFilePath()).baseName());
}
else
sMsg = tr("There are %1 face annotation datasets opened with pending changes. Do you wish to save them before closing?").arg(lModified.size());
QMessageBox::StandardButton oResp = QMessageBox::question(this, tr("Pending changes"), sMsg, QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
// Do not close the tab if the user has chosen "cancel" or if she has chosen "yes" but then
// cancelled the file save dialog in any of the modified tab
if(oResp == QMessageBox::Cancel)
{
pEvent->ignore();
return;
}
else if(oResp == QMessageBox::Yes)
{
for(int i = 0; i < lModified.size(); i++)
{
pChild = lModified[i];
ui->tabWidget->setCurrentWidget(pChild);
if(!saveCurrentFile())
{
pEvent->ignore();
return;
}
}
}
}
pEvent->accept();
}
// +-----------------------------------------------------------
void ft::MainWindow::showEvent(QShowEvent *pEvent)
{
// Restore the previous window state and geometry
QSettings oSettings;
restoreState(oSettings.value("windowState").toByteArray());
restoreGeometry(oSettings.value("geometry").toByteArray());
QVariant vValue = oSettings.value("lastPathUsed");
if (vValue.isValid())
m_sLastPathUsed = vValue.toString();
vValue = oSettings.value("faceFitPath");
if (vValue.isValid())
m_sFaceFitPath = vValue.toString();
// Update UI elements
updateUI();
ui->actionShowImagesList->setChecked(ui->dockImages->isVisible());
ui->actionShowImageProperties->setChecked(ui->dockProperties->isVisible());
pEvent->accept();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionNew_triggered()
{
createChildWindow();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionOpen_triggered()
{
QString sFile = QFileDialog::getOpenFileName(this, tr("Open face annotation dataset..."), m_sLastPathUsed, tr("Face Annotation Dataset files (*.fad);; All files (*.*)"));
if(sFile.length())
{
m_sLastPathUsed = QFileInfo(sFile).absolutePath();
sFile = QDir::toNativeSeparators(sFile);
int iPage = getFilePageIndex(sFile);
if(iPage != -1)
{
ui->tabWidget->setCurrentIndex(iPage);
showStatusMessage(QString(tr("The face annotation dataset [%1] is already opened in the editor.")).arg(Utils::shortenPath(sFile)));
}
else
{
ChildWindow *pChild = createChildWindow(sFile, false);
QString sMsg;
if(!pChild->loadFromFile(sFile, sMsg))
{
destroyChildWindow(pChild);
QMessageBox::warning(this, tr("Fail to load the face annotation dataset"), tr("It was not possible to open the face annotation dataset:\n%1").arg(sMsg), QMessageBox::Ok);
return;
}
if(pChild->dataModel()->rowCount() > 0)
pChild->selectionModel()->setCurrentIndex(pChild->dataModel()->index(0, 0), QItemSelectionModel::Select);
updateUI();
}
}
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionSave_triggered()
{
saveCurrentFile();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionSaveAs_triggered()
{
saveCurrentFile(true);
}
// +-----------------------------------------------------------
bool ft::MainWindow::saveCurrentFile(bool bAskForFileName)
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild || (!bAskForFileName && !pChild->isWindowModified()))
return false;
if(bAskForFileName)
{
QString sFileName = QFileDialog::getSaveFileName(this, tr("Save face annotation dataset..."), windowFilePath(), tr("Face Annotation Dataset files (*.fad);; All files (*.*)"));
if(sFileName.length())
{
QString sMsg;
if(!pChild->saveToFile(sFileName, sMsg))
{
QMessageBox::warning(this, tr("Fail to save the face annotation dataset"), tr("It was not possible to save the face annotation dataset:\n%1").arg(sMsg), QMessageBox::Ok);
return false;
}
m_sLastPathUsed = QFileInfo(sFileName).absolutePath();
return true;
}
else
return false;
}
else
{
// Force the user to chose a file name if the dataset has not yet been saved
if(pChild->property("new").toBool())
return saveCurrentFile(true);
else
{
QString sMsg;
if(!pChild->save(sMsg))
{
QMessageBox::warning(this, tr("Fail to save the face annotation dataset"), tr("It was not possible to save the face annotation dataset:\n%1").arg(sMsg), QMessageBox::Ok);
return false;
}
return true;
}
}
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionExit_triggered()
{
QApplication::exit(0);
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionConfigure_triggered()
{
FaceFitConfig oConfig;
if (oConfig.exec() == FaceFitConfig::Accepted)
m_sFaceFitPath = oConfig.getFaceFitPath();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionFitLandmarks_triggered()
{
// Only continue if the face-fit utilility is properly configured
if (m_sFaceFitPath.length() < 0 || !QFileInfo(m_sFaceFitPath).exists())
{
QMessageBox::critical(this, tr("Error running face-fit utility"), tr("The face-fit utility executable could not be executed. Please check its configuration."), QMessageBox::Ok);
return;
}
// Get the selected face annotation dataset
ChildWindow *pChild = (ChildWindow*)ui->tabWidget->currentWidget();
if (!pChild) // Sanity check
return;
// Get the path of the selected image in the dataset
QModelIndex oSelectedImage = pChild->selectionModel()->currentIndex();
QModelIndex oIdx = pChild->dataModel()->index(oSelectedImage.row(), 1);
QString sImageFile = pChild->dataModel()->data(oIdx, Qt::DisplayRole).toString();
// Build the arguments for the face-fit utility
QTemporaryFile oTemp("face-fit-results");
oTemp.open();
m_sFitTempFile = oTemp.fileName();
oTemp.close();
QStringList oArgs;
oArgs << sImageFile << m_sFitTempFile;
m_oFitProcess->start(m_sFaceFitPath, oArgs, QProcess::ReadOnly);
showStatusMessage(tr("Face fit started. Please wait..."), 0);
}
// +-----------------------------------------------------------
void ft::MainWindow::onFitError(QProcess::ProcessError eError)
{
Q_UNUSED(eError);
QFile::remove(m_sFitTempFile);
m_sFitTempFile = "";
showStatusMessage(tr("The face fit utility executable failed to execute. Please check its configuration."));
}
// +-----------------------------------------------------------
void ft::MainWindow::onFitFinished(int iExitCode, QProcess::ExitStatus eExitStatus)
{
QFileInfo oFileInfo(m_sFitTempFile);
if (!oFileInfo.exists())
{
showStatusMessage(tr("The face fit utility could not fit the landmarks to this image."));
QFile::remove(m_sFitTempFile);
m_sFitTempFile = "";
return;
}
vector vPoints = Utils::readFaceFitPointsFile(m_sFitTempFile);
if (vPoints.size() == 0)
{
showStatusMessage(tr("The face fit utility could not fit the landmarks to this image."));
QFile::remove(m_sFitTempFile);
m_sFitTempFile = "";
return;
}
QFile::remove(m_sFitTempFile);
m_sFitTempFile = "";
// Get the selected face annotation dataset
ChildWindow *pChild = (ChildWindow*)ui->tabWidget->currentWidget();
if (!pChild) // Sanity check
return;
// Reposition the features according to the face-fit results
pChild->positionFeatures(vPoints);
showStatusMessage(tr("Face fit completed successfully."));
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionExportPointsFile_triggered()
{
ChildWindow *pChild = (ChildWindow*)ui->tabWidget->currentWidget();
if (!pChild) // Sanity check
return;
QList lFeats = pChild->getFaceFeatures();
if(lFeats.size() == 0)
{
QMessageBox::critical(this, tr("Error exporting data"), tr("The exporting can not be done because there are no landmarks to export."), QMessageBox::Ok);
return;
}
QString sFileName = QFileDialog::getSaveFileName(this, tr("Export CSIRO points file..."), windowFilePath(), tr("CSIRO Face Analysis SDK points file (*.pts);; All files (*.*)"));
if (sFileName.length())
{
QFile oFile(sFileName);
if (!oFile.open(QFile::WriteOnly | QFile::Text))
{
QMessageBox::critical(this, tr("Error exporting data"), tr("The exporting failed because it was not possible to write to file [%1].").arg(sFileName), QMessageBox::Ok);
return;
}
QTextStream oStream(&oFile);
QString sData = QString("n_points: %1").arg(lFeats.size());
oStream << sData << endl;
oStream << "{" << endl;
foreach(FaceFeatureNode *pFeat, lFeats)
{
sData = QString("%1\t%2").arg(pFeat->x()).arg(pFeat->y());
oStream << sData << endl;
}
oStream << "}" << endl;
oFile.close();
}
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionProject_triggered()
{
QDesktopServices::openUrl(QUrl("https://github.com/luigivieira/Facial-Landmarks-Annotation-Tool.git"));
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionAbout_triggered()
{
(new AboutWindow(this))->show();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_tabCloseRequested(int iTabIndex)
{
ChildWindow* pChild = (ChildWindow*) ui->tabWidget->widget(iTabIndex);
if(pChild->isWindowModified())
{
QString sMsg = tr("There are pending changes in the face annotation dataset named [%1]. Do you wish to save it before closing?").arg(QFileInfo(pChild->windowFilePath()).baseName());
QMessageBox::StandardButton oResp = QMessageBox::question(this, tr("Pending changes"), sMsg, QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
// Do not close the tab if the user has chosen "cancel" or if she has chosen "yes" but then
// cancelled the file save dialog
ui->tabWidget->setCurrentIndex(iTabIndex);
if(oResp == QMessageBox::Cancel || (oResp == QMessageBox::Yes && !saveCurrentFile()))
return;
}
destroyChildWindow(pChild);
if(ui->tabWidget->count() == 0) // no more tabs
{
ui->textFileName->setText("");
ui->zoomSlider->blockSignals(true);
ui->zoomSlider->setValue((ui->zoomSlider->maximum() - ui->zoomSlider->minimum()) / 2 + 1);
ui->zoomSlider->blockSignals(false);
}
}
// +-----------------------------------------------------------
void ft::MainWindow::on_tabChanged(int iTabIndex)
{
Q_UNUSED(iTabIndex);
updateUI();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionAddImage_triggered()
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
return;
QStringList lsFiles = QFileDialog::getOpenFileNames(this, tr("Select face images..."), m_sLastPathUsed, tr("Common image files (*.bmp *.png *.jpg *.gif);; All files (*.*)"));
if(lsFiles.size())
{
m_sLastPathUsed = QFileInfo(lsFiles[0]).absolutePath();
pChild->dataModel()->addImages(lsFiles);
if(!pChild->selectionModel()->currentIndex().isValid())
pChild->selectionModel()->setCurrentIndex(pChild->dataModel()->index(0, 0), QItemSelectionModel::Select);
}
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionRemoveImage_triggered()
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
return;
QModelIndexList lsSelected = pChild->selectionModel()->selectedRows();
if(lsSelected.size() > 0)
{
QString sMsg;
if(lsSelected.size() == 1)
sMsg = tr("Do you confirm the removal of the selected image?");
else
sMsg = tr("Do you confirm the removal of %1 selected images?").arg(lsSelected.size());
if(QMessageBox::question(this, tr("Confirmation"), sMsg, QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes)
{
QList lIndexes;
for(int i = 0; i < lsSelected.size(); i++)
lIndexes.append(lsSelected[i].row());
pChild->dataModel()->removeImages(lIndexes);
}
}
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionShowImagesList_triggered(bool bChecked)
{
ui->dockImages->setVisible(bChecked);
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionShowImageProperties_triggered(bool bChecked)
{
ui->dockProperties->setVisible(bChecked);
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionShowFeatures_triggered(bool bChecked)
{
if(!bChecked)
{
ui->actionShowConnections->setChecked(false);
ui->actionShowFeatureIDs->setChecked(false);
}
updateUI();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionShowConnections_triggered(bool bChecked)
{
if(bChecked && !ui->actionShowFeatures->isChecked())
ui->actionShowFeatures->setChecked(true);
updateUI();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionShowFeatureIDs_triggered(bool bChecked)
{
if(bChecked && !ui->actionShowFeatures->isChecked())
ui->actionShowFeatures->setChecked(true);
updateUI();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionAddFeature_triggered()
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
return;
// The position of the mouse is stored in this action data
// if the action is called from a context menu in the face features
// editor (see method FaceWidget::contextMenuEvent)
QVariant vPos = ui->actionAddFeature->data();
QPoint oPos;
if(vPos.isValid())
oPos = vPos.value();
else
oPos = QCursor::pos();
pChild->addFeature(oPos);
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionRemoveFeature_triggered()
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
return;
QString sMsg = tr("Do you confirm the removal of the selected facial landmarks? This action can not be undone.");
QMessageBox::StandardButton oResp = QMessageBox::question(this, tr("Confirmation"), sMsg, QMessageBox::Yes|QMessageBox::No);
if(oResp == QMessageBox::Yes)
pChild->removeSelectedFeatures();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionConnectFeatures_triggered()
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
return;
pChild->connectFeatures();
}
// +-----------------------------------------------------------
void ft::MainWindow::on_actionDisconnectFeatures_triggered()
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
return;
pChild->disconnectFeatures();
}
// +-----------------------------------------------------------
void ft::MainWindow::showStatusMessage(const QString &sMsg, const int iTimeout)
{
ui->statusBar->showMessage(sMsg, iTimeout);
}
// +-----------------------------------------------------------
int ft::MainWindow::getFilePageIndex(const QString &sFile)
{
int iRet = -1;
for(int iPage = 0; iPage < ui->tabWidget->count(); iPage++)
{
ChildWindow* pChild = (ChildWindow*) ui->tabWidget->widget(iPage);
if(pChild->windowFilePath() == sFile)
{
iRet = iPage;
break;
}
}
return iRet;
}
// +-----------------------------------------------------------
void ft::MainWindow::setImageListView(QString sType)
{
if(sType == "details")
{
m_pViewButton->setIcon(QIcon(":/icons/viewdetails"));
ui->listImages->setVisible(false);
ui->treeImages->setVisible(true);
}
else if(sType == "icons")
{
m_pViewButton->setIcon(QIcon(":/icons/viewicons"));
ui->treeImages->setVisible(false);
ui->listImages->setVisible(true);
}
}
// +-----------------------------------------------------------
void ft::MainWindow::toggleImageListView()
{
if(ui->treeImages->isVisible())
setImageListView("icons");
else
setImageListView("details");
}
// +-----------------------------------------------------------
void ft::MainWindow::onChildUIUpdated(const QString sImageName, const int iZoomLevel)
{
// Image file name
ui->textFileName->setText(sImageName);
ui->textFileName->moveCursor(QTextCursor::End);
ui->textFileName->ensureCursorVisible();
// Zoom level
ui->zoomSlider->blockSignals(true);
ui->zoomSlider->setValue(iZoomLevel);
ui->zoomSlider->blockSignals(false);
updateUI();
}
// +-----------------------------------------------------------
void ft::MainWindow::updateUI()
{
// Setup the control variables
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
bool bFileOpened = pChild != NULL;
bool bFileChanged = bFileOpened ? pChild->isWindowModified() : false;
bool bItemsSelected = bFileOpened && (pChild->selectionModel()->currentIndex().isValid() || pChild->selectionModel()->selectedIndexes().size() > 0);
bool bFileNotNew = bFileOpened && !pChild->property("new").toBool();
QList lFeats;
QList lConns;
if(bFileOpened)
{
lFeats = pChild->getSelectedFeatures();
lConns = pChild->getSelectedConnections();
}
bool bFeaturesSelected = lFeats.size() > 0;
bool bConnectionsSelected = lConns.size() > 0;
bool bFeaturesConnectable = lFeats.size() == 2 && lConns.size() == 0;
// Update the data and selection models
if(bFileOpened)
{
ui->listImages->setModel(pChild->dataModel());
ui->listImages->setSelectionModel(pChild->selectionModel());
ui->treeImages->setModel(pChild->dataModel());
ui->treeImages->setSelectionModel(pChild->selectionModel());
}
else
{
ui->listImages->setModel(NULL);
ui->treeImages->setModel(NULL);
}
// Update the UI availability
ui->actionSave->setEnabled(bFileChanged);
ui->actionSaveAs->setEnabled(bFileNotNew);
ui->actionAddImage->setEnabled(bFileOpened);
ui->actionRemoveImage->setEnabled(bItemsSelected);
ui->actionAddFeature->setEnabled(bFileOpened);
ui->actionRemoveFeature->setEnabled(bFeaturesSelected);
ui->actionConnectFeatures->setEnabled(bFeaturesConnectable);
ui->actionDisconnectFeatures->setEnabled(bConnectionsSelected);
ui->actionFitLandmarks->setEnabled(bItemsSelected);
ui->actionExportPointsFile->setEnabled(bItemsSelected);
m_pViewButton->setEnabled(bFileOpened);
ui->zoomSlider->setEnabled(bFileOpened);
// Update the tab title and tooltip
if(bFileOpened)
{
QString sTitle = QFileInfo(pChild->windowFilePath()).baseName() + (pChild->isWindowModified() ? "*" : "");
ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), sTitle);
if(bFileNotNew) // Complete file path only if the file has been saved before
ui->tabWidget->setTabToolTip(ui->tabWidget->currentIndex(), pChild->windowFilePath());
}
// Display of face features
if(bFileOpened)
{
pChild->setDisplayFaceFeatures(ui->actionShowFeatures->isChecked());
pChild->setDisplayConnections(ui->actionShowFeatures->isChecked() && ui->actionShowConnections->isChecked());
pChild->setDisplayFeatureIDs(ui->actionShowFeatures->isChecked() && ui->actionShowFeatureIDs->isChecked());
}
}
// +-----------------------------------------------------------
void ft::MainWindow::onSliderValueChanged(int iValue)
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(pChild)
pChild->setZoomLevel(iValue);
}
// +-----------------------------------------------------------
void ft::MainWindow::onZoomLevelChanged(int iValue)
{
ui->zoomSlider->blockSignals(true);
ui->zoomSlider->setValue(iValue);
ui->zoomSlider->blockSignals(false);
}
// +-----------------------------------------------------------
void ft::MainWindow::onUpdateUI()
{
updateUI();
}
// +-----------------------------------------------------------
void ft::MainWindow::keyPressEvent(QKeyEvent *pEvent)
{
ChildWindow *pChild = (ChildWindow*) ui->tabWidget->currentWidget();
if(!pChild)
{
QMainWindow::keyPressEvent(pEvent);
return;
}
switch(pEvent->key())
{
case Qt::Key_Plus:
pChild->zoomIn();
pEvent->accept();
break;
case Qt::Key_Minus:
pChild->zoomOut();
pEvent->accept();
break;
default:
QMainWindow::keyPressEvent(pEvent);
}
}
// +-----------------------------------------------------------
ft::ChildWindow* ft::MainWindow::createChildWindow(QString sFileName, bool bModified)
{
ChildWindow *pChild = new ChildWindow(this);
// Define the window attributes
if(!sFileName.length())
{
sFileName = QString(tr("%1new face annotation dataset.fad")).arg(m_sLastPathUsed);
bModified = true;
}
pChild->setWindowIcon(QIcon(":/icons/face-dataset"));
pChild->setWindowFilePath(sFileName);
pChild->setWindowModified(bModified);
// Connect to its signals
connect(pChild, SIGNAL(onUIUpdated(const QString, const int)), this, SLOT(onChildUIUpdated(const QString, const int)));
connect(pChild, SIGNAL(onDataModified()), this, SLOT(onUpdateUI()));
connect(pChild, SIGNAL(onFeaturesSelectionChanged()), this, SLOT(onUpdateUI()));
// Create the context menu for the features editor, using the same actions from the main window
QMenu *pContextMenu = new QMenu(pChild);
pContextMenu->addAction(ui->actionAddFeature);
pContextMenu->addAction(ui->actionRemoveFeature);
pContextMenu->addAction(ui->actionConnectFeatures);
pContextMenu->addAction(ui->actionDisconnectFeatures);
pChild->setContextMenu(pContextMenu);
// Add the window to the tab widget
int iIndex = ui->tabWidget->addTab(pChild, pChild->windowIcon(), "");
ui->tabWidget->setCurrentIndex(iIndex);
return pChild;
}
// +-----------------------------------------------------------
void ft::MainWindow::destroyChildWindow(ChildWindow *pChild)
{
int iTabIndex = ui->tabWidget->indexOf(pChild);
ui->tabWidget->removeTab(iTabIndex);
disconnect(pChild, SIGNAL(onUIUpdated(const QString, const int)), this, SLOT(onChildUIUpdated(const QString, const int)));
disconnect(pChild, SIGNAL(onDataModified()), this, SLOT(onUpdateUI()));
disconnect(pChild, SIGNAL(onFeaturesSelectionChanged()), this, SLOT(onUpdateUI()));
delete pChild;
}
================================================
FILE: src/mainwindow.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include "aboutwindow.h"
#include "childwindow.h"
namespace Ui {
class MainWindow;
}
namespace ft
{
/**
* Main GUI window class.
*/
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
/**
* Class constructor.
* @param pParent QWidget with the window parent.
*/
explicit MainWindow(QWidget *pParent = 0);
/**
* Class destructor.
*/
virtual ~MainWindow();
protected:
/**
* Captures the close event of the main window.
* @param pEvent Instance of the QCloseEvent with the close event data.
*/
void closeEvent(QCloseEvent *pEvent);
/**
* Captures the show event of the main window.
* @param pEvent Instance of the QShowEvent with the show event data.
*/
void showEvent(QShowEvent *pEvent);
/**
* Helper method to request the saving of the current face annotation dataset opened
* to the user.
* @param bAskForFileName Boolean indicating if the UI should ask the user for a file
* name. If the value is true, the user is requested to choose a file name, otherwise
* (the default) the current file name is used. If the file has not yet been saved,
* a file name is requested despite the value on this parameter.
* @return Boolean indicating if the save was performed or false if the user cancelled
* the operation.
*/
bool saveCurrentFile(bool bAskForFileName=false);
/**
* Gets the page index of the file if already opened in the editor.
* @param sFile QString with the complete file name (path + name) of the file to be searched.
* @return Integer with the index (in range [0,...]) of the page where the file is opened
* or -1 if the file is not already opened in the editor.
*/
int getFilePageIndex(const QString &sFile);
/**
* Updates all the user interface components according to the current state of the application
* (i.e. disables action buttons when there is no opened face annotation dataset, etc).
*/
void updateUI();
/**
* Captures and handles the keyboard events to automate user interactions.
* @param pEvent Instance of the QKeyEvent with the parameters of the event that happened.
*/
void keyPressEvent(QKeyEvent *pEvent) Q_DECL_OVERRIDE;
/**
* Creates a new child window instance.
* @return Instance of the newly created ChildWindow.
*/
ChildWindow *createChildWindow(QString sFileName = QString(), bool bModified = true);
/**
* Destroys the given child window instance.
* @param pChild Instance of the ChildWindow to be destroyed.
*/
void destroyChildWindow(ChildWindow *pChild);
public slots:
/**
* Displays a text message in the main window status bar.
* @param sMsg QString with the message to be displayed.
* @param iTimeout Integer with the number of miliseconds
* by which the message will be displayed. The default is 5000
* (i.e. 5 seconds).
*/
void showStatusMessage(const QString &sMsg, const int iTimeout = 5000);
private slots:
/**
* Slot for the menu New trigger event.
*/
void on_actionNew_triggered();
/**
* Slot for the menu Open trigger event.
*/
void on_actionOpen_triggered();
/**
* Slot for the menu Save trigger event.
*/
void on_actionSave_triggered();
/**
* Slot for the menu Save As trigger event.
*/
void on_actionSaveAs_triggered();
/**
* Slot for the menu Exit trigger event.
*/
void on_actionExit_triggered();
/**
* Slot for the menu Configure trigger event.
*/
void on_actionConfigure_triggered();
/**
* Slot for the menu Fit Landmarks trigger event.
*/
void on_actionFitLandmarks_triggered();
/**
* Slot for the menu Export Points File trigger event.
*/
void on_actionExportPointsFile_triggered();
/**
* Slot for the menu Project trigger event.
*/
void on_actionProject_triggered();
/**
* Slot for the menu About trigger event.
*/
void on_actionAbout_triggered();
/**
* Slot for the tab (child window) closing request (by clicking in the close button).
* @param iTabIndex Integer with the index of the tab requested to close.
*/
void on_tabCloseRequested(int iTabIndex);
/**
* Slot for the tab (child window) change event (when a new tab is selected).
* @param iTabIndex Integer with the index of the tab now selected.
*/
void on_tabChanged(int iTabIndex);
/**
* Slot for the button Add Image trigger event.
*/
void on_actionAddImage_triggered();
/**
* Slot for the button Add Image trigger event.
*/
void on_actionRemoveImage_triggered();
/**
* Slot for the menu Show Image List trigger event.
*/
void on_actionShowImagesList_triggered(bool bChecked);
/**
* Slot for the menu Show Image Properties trigger event.
*/
void on_actionShowImageProperties_triggered(bool bChecked);
/**
* Slot for the menu Show Face Feature Nodes trigger event.
*/
void on_actionShowFeatures_triggered(bool bChecked);
/**
* Slot for the menu Show Face Feature Edges trigger event.
*/
void on_actionShowConnections_triggered(bool bChecked);
/**
* Slot for the menu Show Ids of Face Feature Nodes trigger event.
*/
void on_actionShowFeatureIDs_triggered(bool bChecked);
/**
* Slot for the menu Add Feature trigger event.
*/
void on_actionAddFeature_triggered();
/**
* Slot for the menu Remove Feature trigger event.
*/
void on_actionRemoveFeature_triggered();
/**
* Slot for the menu Connect Features trigger event.
*/
void on_actionConnectFeatures_triggered();
/**
* Slot for the menu Disconnect Features trigger event.
*/
void on_actionDisconnectFeatures_triggered();
/**
* Define the view to be used for the list of images (icons, a list view, or "details", a tree view).
* @param sType String with the type to be used (either "icons" or "details").
*/
void setImageListView(QString sType);
/**
* Helper method to toggle the current view for the list of images (used in the shortcut button).
*/
void toggleImageListView();
/**
* Slot to capture indications of update in the UI due to changes in the child window selection model.
* @param sImageName QString with the name of the current selected face image.
* @param iZoomLevel Current level of zoom in the face image displayed.
*/
void onChildUIUpdated(const QString sImageName, const int iZoomLevel);
/**
* Captures the updates in the zoom slider by user interaction.
* @param iValue Integer with the new value of the slider (in the range [1, 21]).
*/
void onSliderValueChanged(int iValue);
/**
* Captures the updates in the zoom by user interaction in other sources that not the slider.
* @param iValue Integer with the new value of the zoom (in the range [1, 21]).
*/
void onZoomLevelChanged(int iValue);
/**
* Captures indications that the UI needs to be updated due to changes in the data model
* or selection in the features editor.
*/
void onUpdateUI();
/**
* Captures the result (error) of the process executed for the face-fit utility.
* @param eError QProcess::ProcessError enumeration with the error type.
*/
void onFitError(QProcess::ProcessError eError);
/**
* Captures the conclusion of the process executed for the face-fit utility.
* @param eExitStatus QProcess::ExitStatus enumeration with the utility exit status.
*/
void onFitFinished(int iExitCode, QProcess::ExitStatus eExitStatus);
private:
/** Instance of the ui for GUI element access. */
Ui::MainWindow *ui;
/** Instance of the about dialog box. */
AboutWindow* m_pAbout;
/** Last path used in File Dialogs. */
QString m_sLastPathUsed;
/** Path to the face-fit utility. */
QString m_sFaceFitPath;
/** Instance of a dropdown button for the view mode of the image list. */
QMenu *m_pViewButton;
/** Process instance to execute the face-fit utility. */
QProcess *m_oFitProcess;
/** Name of the temporary file used for the face-fit utility. */
QString m_sFitTempFile;
};
};
#endif // MAINWINDOW_H
================================================
FILE: src/mainwindow.ui
================================================
MainWindow
0
0
912
548
FLAT - Facial Landmarks Annotation Tool
false
0
0
0
0
-
QTabWidget::North
QTabWidget::Triangular
24
24
Qt::ElideNone
true
true
true
false
File
32
32
TopToolBarArea
false
Image Properties
1
-
QLayout::SetMinimumSize
-
QLayout::SetMinimumSize
-
12
Path:
textFileName
-
16777215
25
Qt::ScrollBarAlwaysOff
Qt::ScrollBarAlwaysOff
false
QTextEdit::NoWrap
true
false
Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse
-
-
12
Zoom:
zoomSlider
-
-
12
Altera o zoom nas imagens (+/- ou Ctrl+Roda do Mouse)
1
21
1
1
11
11
Qt::Horizontal
QSlider::TicksBelow
0
-
QLayout::SetMinimumSize
-
45
0
45
16777215
10%
-
Qt::Horizontal
40
20
-
45
0
45
16777215
100%
Qt::AlignCenter
-
Qt::Horizontal
40
20
-
45
0
45
16777215
1000%
Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter
-
Qt::Vertical
20
40
Image List
1
3
3
3
3
3
6
-
24
24
false
-
QAbstractItemView::NoEditTriggers
QAbstractItemView::ExtendedSelection
QAbstractItemView::SelectRows
QListView::IconMode
false
-
QAbstractItemView::AllEditTriggers
QAbstractItemView::ExtendedSelection
150
Edit
32
32
TopToolBarArea
false
View
32
32
TopToolBarArea
false
Tools
32
32
TopToolBarArea
false
toolBar
32
32
TopToolBarArea
false
&Exit
Terminates the program
:/icons/resources/icons/information.png:/icons/resources/icons/information.png
&About...
Displays information on this program
:/icons/resources/icons/open.png:/icons/resources/icons/open.png
&Open...
Loads an existing face annotation dataset from a file
Ctrl+O
:/icons/resources/icons/new.png:/icons/resources/icons/new.png
&New
Creates a new face annotation dataset
Ctrl+N
:/icons/resources/icons/save.png:/icons/resources/icons/save.png
&Save
Saves the changes in the face annotation dataset
Ctrl+S
:/icons/resources/icons/saveas.png:/icons/resources/icons/saveas.png
Save &as...
Saves the changes in the face annotation dataset to a different file
:/icons/resources/icons/help.png:/icons/resources/icons/help.png
&Project Docs
Displays the project's documentation page on Github
F1
:/icons/resources/icons/add.png:/icons/resources/icons/add.png
Add...
Adds new images to the face annotation dataset
Ctrl+Ins
:/icons/resources/icons/delete.png:/icons/resources/icons/delete.png
Remove
Removes the selected images from the face annotation dataset
Ctrl+Del
true
true
:/icons/resources/icons/image-list.png:/icons/resources/icons/image-list.png
&List of Images
Displays or hides the window with the list of images in the face annotation dataset
F2
true
true
:/icons/resources/icons/image-properties.png:/icons/resources/icons/image-properties.png
&Image Properties
Displays/hides the window with the propriedades of the selected image
F3
true
true
:/icons/resources/icons/features.png:/icons/resources/icons/features.png
&Landmarks
Displays/hides the facial landmarks
F4
true
true
:/icons/resources/icons/links.png:/icons/resources/icons/links.png
&Links
Displays/hides the links between facial landmarks
F5
true
:/icons/resources/icons/feature-ids.png:/icons/resources/icons/feature-ids.png
&Labels
Shows/hides the labels of the facial landmarks
F6
:/icons/resources/icons/add-feature.png:/icons/resources/icons/add-feature.png
&Add
Add a new facial landmark to the face annotation dataset
Shift+A
:/icons/resources/icons/remove-feature.png:/icons/resources/icons/remove-feature.png
&Remove
Removes the selected facial landmarks (and their links) from the face annotation dataset
Shift+R
:/icons/resources/icons/connect.png:/icons/resources/icons/connect.png
&Link
Links two selected facial landmarks
Shift+L
:/icons/resources/icons/disconnect.png:/icons/resources/icons/disconnect.png
&Unlink
Unlinks the selected facial landmarks
Shift+U
:/icons/fat:/icons/fat
&Fit Landmarks
Attempts to automaticaly fit the face model (with 66 landmarks) to the currently selected face image using the face-fit utility from the CSIRO Face Analysis SDK
Ctrl+F
&Configure...
Configure the face-fit utility from the CSIRO Face Analysis SDK
:/icons/resources/icons/image-properties.png:/icons/resources/icons/image-properties.png
&Export points file...
Exports the annotation in current selected image to a CSIRO Face Analysis SDK points file
tabWidget
textFileName
listImages
treeImages
================================================
FILE: src/resources.qrc
================================================
resources/icons/fat.png
resources/icons/new.png
resources/icons/open.png
resources/icons/save.png
resources/icons/saveas.png
resources/icons/help.png
resources/icons/viewdetails.png
resources/icons/viewicons.png
resources/icons/add.png
resources/icons/database.png
resources/icons/delete.png
resources/icons/information.png
resources/icons/image-list.png
resources/icons/image-properties.png
resources/icons/remove-feature.png
resources/icons/add-feature.png
resources/icons/feature-ids.png
resources/icons/features.png
resources/icons/disconnect.png
resources/icons/connect.png
resources/icons/links.png
resources/images/noface.png
resources/images/brokenimage.png
resources/images/imagemissing.png
================================================
FILE: src/utils.cpp
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#include "utils.h"
#include
#include
#include
#include
#include
using namespace std;
// +-----------------------------------------------------------
ft::Utils::Utils()
{
}
// +-----------------------------------------------------------
QString ft::Utils::shortenPath(const QString &sPath, int iMaxLen)
{
// If the string is not long enough, simply return it
if(sPath.length() <= iMaxLen)
return QDir::toNativeSeparators(sPath);
QFileInfo oFile = QFileInfo(sPath);
QString sPathOnly = oFile.path();
QString sFileName = QDir::separator() + oFile.fileName();
QString sDriveLetter = ""; // In case it is running on a Windows OS
// Firstly, split the path (only) into parts (for the drive letter and/or each subfolder)
QRegExp oRegex("([\\\\\\/][\\w -\\.]*)");
QStringList lsParts;
QMultiMap mpSortedParts;
QString sPart;
bool bFirst = true;
int iPos = 0;
while((iPos = oRegex.indexIn(sPathOnly, iPos)) != -1)
{
if(bFirst)
{
sDriveLetter = sPathOnly.left(iPos);
bFirst = false;
}
sPart = oRegex.cap(1);
lsParts.push_back(sPart);
mpSortedParts.insert(sPart.length(), lsParts.count() - 1);
iPos += oRegex.matchedLength();
}
// Then, iteratively remove the larger parts while the path is bigger than
// the maximum number of characters desired
QString sNewPath;
do
{
sNewPath = "";
// Rebuild the path replacing the so far larger part for "..."
QMapIterator oSorted(mpSortedParts);
oSorted.toBack();
if(oSorted.hasPrevious())
{
int iLength = oSorted.peekPrevious().key();
int iIndex = oSorted.peekPrevious().value();
mpSortedParts.remove(iLength, iIndex);
lsParts.replace(iIndex, QDir::separator() + QString("..."));
for(QStringList::iterator it = lsParts.begin(); it != lsParts.end(); ++it)
sNewPath += *it;
}
} while(sNewPath.length() > 0 && QString(sDriveLetter + sNewPath + sFileName).length() > iMaxLen);
if(sNewPath.length() == 0)
sNewPath = QDir::separator() + QString("...");
return QDir::toNativeSeparators(sDriveLetter + sNewPath + sFileName);
}
// +-----------------------------------------------------------
vector ft::Utils::readFaceFitPointsFile(QString sFileName)
{
QFile oFile(sFileName);
if (!oFile.open(QFile::ReadOnly))
return vector();
QTextStream oStream(&oFile);
QString sLine;
QStringList lData;
int iNumPoints;
// Read the number of points from the first line
sLine = oStream.readLine();
lData = sLine.split(" ");
if (lData.size() != 2 || lData.at(0) != "n_points:")
{
oFile.close();
return vector();
}
else
iNumPoints = lData[1].toInt();
// Read the points
vector vPoints;
while (!oStream.atEnd())
{
sLine = oStream.readLine();
if (sLine == "{" || sLine == "}")
continue;
lData = sLine.split("\t");
if (lData.size() != 2)
{
oFile.close();
return vector();
}
float x = lData[0].toFloat();
float y = lData[1].toFloat();
vPoints.push_back(QPoint(x, y));
}
oFile.close();
if (vPoints.size() != iNumPoints)
return vector();
else
return vPoints;
}
================================================
FILE: src/utils.h
================================================
/*
* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#ifndef UTILS_H
#define UTILS_H
#include
#include
#include
namespace ft
{
/**
* Static class with utilitary functions of general use.
*/
class Utils
{
protected:
/**
* Protected class constructor to prevent this class from being instantiated.
*/
Utils();
public:
/**
* Shorten the given path by replacing subdirectories with "...". Mainly used
* for path displaying in the user interface. Exiting file name and drive letter
* (in case of Windows) are not replaced. Hence, the minimum string returned
* by this method will be the composition of a drive letter at the beginning,
* a file name at the end, and a single "/.../" in between.
* @param sPath QString with the path to be shortened.
* @param iMaxLen Maximum length in characters to trigger the shortening (that is,
* the path will be shortened only if its current length exceeds this maximum value).
* The default is 100 characters.
* @return QString with the path shortened and all separators changed to the native OS
* standard.
*/
static QString shortenPath(const QString &sPath, int iMaxLen = 100);
/**
* Reads a points file produced by the face-fit utility.
* @return A std::vector with a list of QPoint instances with the points
* of facial landmarks fitted to an image, or an empty vector if the reading
* failed.
*/
static std::vector readFaceFitPointsFile(QString sFileName);
};
}
#endif // UTILS_H
================================================
FILE: version.h.in
================================================
/* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
*
* This file is part of FLAT.
*
* FLAT 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.
*
* FLAT 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 .
*/
#define FLAT_VERSION_MAJOR @FLAT_VERSION_MAJOR@
#define FLAT_VERSION_MINOR @FLAT_VERSION_MINOR@
#define FLAT_VERSION_PATCH @FLAT_VERSION_PATCH@
#define FLAT_VERSION "@FLAT_VERSION@"