first commit

This commit is contained in:
Lorenzo 2020-08-20 11:33:19 +02:00
commit a37b5c7b6c
66 changed files with 18405 additions and 0 deletions

14
.gitignore vendored Normal file
View File

@ -0,0 +1,14 @@
.idea/
data/
.DS_store
__pycache__
Monoloco/*.pyc
.pytest*
build/
dist/
*.egg-info
tests/*.png
kitti-eval/build
kitti-eval/cmake-build-debug
figures/
visual_tests/

26
.pylintrc Normal file
View File

@ -0,0 +1,26 @@
[BASIC]
variable-rgx=[a-z0-9_]{1,30}$ # to accept 2 (dfferent) letters variables
Good-names=xx,dd,zz,hh,ww,pp,kk,lr,w1,w2,w3,mm,im,uv,ax,COV_MIN,CONF_MIN
[TYPECHECK]
disable=import-error,invalid-name,unused-variable,fixme,E1102,missing-docstring,useless-object-inheritance,duplicate-code,too-many-arguments,too-many-instance-attributes,too-many-locals,too-few-public-methods,arguments-differ,logging-format-interpolation
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=numpy.*,torch.*,cv2.*
ignored-modules=nuscenes, tabulate, cv2
[FORMAT]
max-line-length=120

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
Copyright 2020 by EPFL/VITA. All rights reserved.
This project and all its files are licensed under
GNU AGPLv3 or later version.
If this license is not suitable for your business or project
please contact EPFL-TTO (https://tto.epfl.ch/) for a full commercial license.
This software may not be used to harm any person deliberately.

661
LICENSE.AGPL Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<http://www.gnu.org/licenses/>.

184
README.md Normal file
View File

@ -0,0 +1,184 @@
# MonStereo
> Monocular and stereo vision are cost-effective solutions for 3D human localization
in the context of self-driving cars or social robots. However, they are usually developed independently
and have their respective strengths and limitations. We propose a novel unified learning framework that
leverages the strengths of both monocular and stereo cues for 3D human localization.
Our method jointly (i) associates humans in left-right images,
(ii) deals with occluded and distant cases in stereo settings by relying on the robustness of monocular cues,
and (iii) tackles the intrinsic ambiguity of monocular perspective projection by exploiting prior knowledge
of human height distribution.
We achieve state-of-the-art quantitative results for the 3D localization task on KITTI dataset
and estimate confidence intervals that account for challenging instances.
We show qualitative examples for the long tail challenges such as occluded,
far-away, and children instances.
```
@InProceedings{bertoni_monstereo,
author = {Bertoni, Lorenzo and Kreiss, Sven and Mordan, Taylor and Alahi, Alexandre},
title = {MonStereo: When Monocular and Stereo Meet at the Tail of 3D Human Localization},
booktitle = {ArXiv},
month = {August},
year = {2020}
}
```
# Features
The code has been built upon the ICCV'19 project [MonoLoco](https://github.com/vita-epfl/monoloco).
This repository supports
* the original MonoLoco
* An improved Monocular version (MonoLoco++) for x,y,z coordinates, orientation, and dimensions
* MonStereo
# Setup
### Install
The installation has been tested on OSX and Linux operating systems, with Python 3.6 or Python 3.7.
Packages have been installed with pip and virtual environments.
For quick installation, do not clone this repository,
and make sure there is no folder named monstereo in your current directory.
A GPU is not required, yet highly recommended for real-time performances.
MonStereo can be installed as a package, by:
```
pip3 install monstereo
```
For development of the monstereo source code itself, you need to clone this repository and then:
```
pip3 install sdist
cd monstereo
python3 setup.py sdist bdist_wheel
pip3 install -e .
```
### Data structure
Data
├── arrays
├── models
├── kitti
├── logs
├── output
Run the following to create the folders:
```
mkdir data
cd data
mkdir arrays models kitti logs output
```
### Pre-trained Models
* Download Monstereo pre-trained model from
[Google Drive](https://drive.google.com/file/d/1vrfkOl15Hpwp2YoALCojD7xlVCt8BQDB/view?usp=sharing),
and save them in `data/models`
(default) or in any folder and call it through the command line option `--model <model path>`
* Pifpaf pre-trained model will be automatically downloaded at the first run.
Three standard, pretrained models are available when using the command line option
`--checkpoint resnet50`, `--checkpoint resnet101` and `--checkpoint resnet152`.
Alternatively, you can download a Pifpaf pre-trained model from [openpifpaf](https://github.com/vita-epfl/openpifpaf)
and call it with `--checkpoint <pifpaf model path>`. All experiments have been run with v0.8 of pifpaf.
If you'd like to use an updated version, we suggest to re-train the MonStereo model as well.
* The model for the experiments is provided in *data/models/ms-200710-1511.pkl*
# Interfaces
All the commands are run through a main file called `main.py` using subparsers.
To check all the commands for the parser and the subparsers (including openpifpaf ones) run:
* `python3 -m monstereo.run --help`
* `python3 -m monstereo.run predict --help`
* `python3 -m monstereo.run train --help`
* `python3 -m monstereo.run eval --help`
* `python3 -m monstereo.run prep --help`
or check the file `monstereo/run.py`
# Prediction
The predict script receives an image (or an entire folder using glob expressions),
calls PifPaf for 2d human pose detection over the image
and runs MonStereo for 3d location of the detected poses.
Output options include json files and/or visualization of the predictions on the image in *frontal mode*,
*birds-eye-view mode* or *combined mode* and can be specified with `--output_types`
### Ground truth matching
* In case you provide a ground-truth json file to compare the predictions of MonSter,
the script will match every detection using Intersection over Union metric.
The ground truth file can be generated using the subparser `prep` and called with the command `--path_gt`.
As this step requires running the pose detector over all the training images and save the annotations, we
provide the resulting json file for the category *pedestrians* from
[Google Drive](https://drive.google.com/file/d/1e-wXTO460ip_Je2NdXojxrOrJ-Oirlgh/view?usp=sharing)
and save it into `data/arrays`.
* In case the ground-truth json file is not available, with the command `--show_all`, is possible to
show all the prediction for the image
After downloading model and ground-truth file, a demo can be tested with the following commands:
`python3 -m monstereo.run predict --glob docs/000840*.png --output_types combined --scale 2
--model data/models/ms-200710-1511.pkl --z_max 30 --checkpoint resnet152 --path_gt data/arrays/names-kitti-200615-1022.json
-o data/output`
![Crowded scene](docs/out_000840.png)
`python3 -m monstereo.run predict --glob docs/005523*.png --output_types combined --scale 2
--model data/models/ms-200710-1511.pkl --z_max 30 --checkpoint resnet152 --path_gt data/arrays/names-kitti-200615-1022.json
-o data/output`
![Occluded hard example](docs/out_005523.png)
# Preprocessing
Preprocessing and training step are already fully supported by the code provided,
but require first to run a pose detector over
all the training images and collect the annotations.
The code supports this option (by running the predict script and using `--mode pifpaf`).
Once the code will be made publicly available, we will add
links to download annotations.
### Datasets
Download KITTI ground truth files and camera calibration matrices for training
from [here](http://www.cvlibs.net/datasets/kitti/eval_object.php?obj_benchmark=3d) and
save them respectively into `data/kitti/gt` and `data/kitti/calib`.
To extract pifpaf joints, you also need to download training images soft link the folder in `
data/kitti/images`
### Annotations to preprocess
MonStereo is trained using 2D human pose joints. To create them run pifaf over KITTI training images.
You can create them running the predict script and using `--mode pifpaf`.
### Inputs joints for training
MonoStereo is trained using 2D human pose joints matched with the ground truth location provided by
KITTI Dataset. To create the joints run: `python3 -m monstereo.run prep` specifying:
1. `--dir_ann` annotation directory containing Pifpaf joints of KITTI.
### Ground truth file for evaluation
The preprocessing script also outputs a second json file called **names-<date-time>.json** which provide a dictionary indexed
by the image name to easily access ground truth files for evaluation and prediction purposes.
# Training
Provide the json file containing the preprocess joints as argument.
As simple as `python3 -m monstereo.run train --joints <json file path>`
All the hyperparameters options can be checked at `python3 -m monstereo.run train --help`.
# Evaluation (KITTI Dataset)
### Average Localization Metric (ALE)
We provide evaluation on KITTI in the eval section. Txt files for MonStereo are generated with the command:
`python -m monstereo.run eval --dir_ann <directory of pifpaf annotations> --model data/models/ms-200710-1511.pkl --generate`
### Relative Average Precision Localization (RALP-5%)
We modified the original C++ evaluation of KITTI to make it relative to distance. We use **cmake**.
To run the evaluation, first generate the txt files with:
`python -m monstereo.run eval --dir_ann <directory of pifpaf annotations> --model data/models/ms-200710-1511.pkl --generate`
Then follow the instructions of this [repository](https://github.com/cguindel/eval_kitti)
to prepare the folders accordingly (or follow kitti guidelines) and run evaluation.
The modified file is called *evaluate_object.cpp* and runs exactly as the original kitti evaluation.

BIN
docs/000840.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 736 KiB

BIN
docs/000840_right.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 732 KiB

BIN
docs/005523.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 872 KiB

BIN
docs/005523_right.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 826 KiB

BIN
docs/out_000840.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 584 KiB

BIN
docs/out_005523.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 761 KiB

View File

@ -0,0 +1,8 @@
cmake_minimum_required (VERSION 2.6)
project(devkit_object)
find_package(PNG REQUIRED)
add_executable(evaluate_object evaluate_object.cpp)
include_directories(${PNG_INCLUDE_DIR})
target_link_libraries(evaluate_object ${PNG_LIBRARY})

34
kitti-eval/README.md Normal file
View File

@ -0,0 +1,34 @@
# eval_kitti #
[![Build Status](https://travis-ci.org/cguindel/eval_kitti.svg?branch=master)](https://travis-ci.org/cguindel/eval_kitti)
[![License: CC BY-NC-SA](https://img.shields.io/badge/License-CC%20BY--NC--SA%203.0-lightgrey.svg)](https://creativecommons.org/licenses/by-nc-sa/3.0/)
The *eval_kitti* software contains tools to evaluate object detection results using the KITTI dataset. The code is based on the [KITTI object development kit](http://www.cvlibs.net/datasets/kitti/eval_object.php).
### Tools ###
* *evaluate_object* is an improved version of the official KITTI evaluation that enables multi-class evaluation and splits of the training set for validation. It's updated according to the modifications introduced in 2017 by the KITTI authors.
* *parser* is meant to provide mAP and mAOS stats from the precision-recall curves obtained with the evaluation script.
* *create_link* is a helper that can be used to create a link to the results obtained with [lsi-faster-rcnn](https://github.com/cguindel/lsi-faster-rcnn).
### Usage ###
Build *evaluate_object* with CMake:
```
mkdir build
cd build
cmake ..
make
```
The `evaluate_object` executable will be then created inside `build`. The following folders are also required to be placed there in order to perform the evaluation:
* `data/object/label_2`, with the KITTI dataset labels.
* `lists`, containing the `.txt` files with the train/validation splits. These files are expected to contain a list of the used image indices, one per row.
* `results`, in which a subfolder should be created for every test, including a second-level `data` folder with the resulting `.txt` files to be evaluated.
`evaluate_object` should be called with the name of the results folder and the validation split; e.g.: ```./evaluate_object leaderboard valsplit ```
`parser` needs the results folder; e.g.: ```./parser.py leaderboard ```. **Note**: *parser* will only provide results for *Car*, *Pedestrian* and *Cyclist*; modify it (line 8) if you need to evaluate the rest of classes.
### Copyright ###
This work is a derivative of [The KITTI Vision Benchmark Suite](http://www.cvlibs.net/datasets/kitti/eval_object.php) by A. Geiger, P. Lenz, C. Stiller and R. Urtasun, used under [CC BY-NC-SA](https://creativecommons.org/licenses/by-nc-sa/3.0/). Consequently, code in this repository is published under the same [Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License](https://creativecommons.org/licenses/by-nc-sa/3.0/). This means that you must attribute the work in the manner specified by the authors, you may not use this work for commercial purposes and if you alter, transform, or build upon this work, you may distribute the resulting work only under the same license.

File diff suppressed because it is too large Load Diff

1003
kitti-eval/original.cpp Normal file

File diff suppressed because it is too large Load Diff

59
kitti-eval/parser.py Executable file
View File

@ -0,0 +1,59 @@
#!/usr/bin/env python
import sys
import os
import numpy as np
# CLASSES = ['car', 'pedestrian', 'cyclist', 'van', 'truck', 'person_sitting', 'tram']
CLASSES = ['pedestrian']
# PARAMS = ['detection', 'orientation', 'iour', 'mppe']
PARAMS = ['detection', 'detection_1%', 'detection_5%', 'detection_10%', 'detection_3d', 'detection_ground', 'orientation']
DIFFICULTIES = ['easy', 'moderate', 'hard', 'all']
eval_type = ''
if len(sys.argv)<2:
print('Usage: parser.py results_folder [evaluation_type]')
if len(sys.argv)==3:
eval_type = sys.argv[2]
result_sha = sys.argv[1]
txt_dir = os.path.join('build','results', result_sha)
for class_name in CLASSES:
for param in PARAMS:
print("--{:s} {:s}--".format(class_name, param))
if eval_type is '':
txt_name = os.path.join(txt_dir, 'stats_' + class_name + '_' + param + '.txt')
else:
txt_name = os.path.join(txt_dir, 'stats_' + class_name + '_' + param + '_' + eval_type + '.txt')
if not os.path.isfile(txt_name):
print(txt_name, ' not found')
continue
cont = np.loadtxt(txt_name)
averages = []
for idx, difficulty in enumerate(DIFFICULTIES):
sum = 0
if param in PARAMS:
for i in range(1, 41):
sum += cont[idx][i]
average = sum/40.0
#print class_name, difficulty, param, average
averages.append(average)
#print "\n"+class_name+" "+param
print("Easy\tMod.\tHard\tAll")
print("{:.2f}\t{:.2f}\t{:.2f}\t{:.2f}".format(100*averages[0], 100*averages[1],100*averages[2],100*averages[3]))
print("---------------------------------------------------------------------------------")
if eval_type is not '' and param=='detection':
break # No orientation for 3D or bird eye
#print '================='

4
monstereo/__init__.py Normal file
View File

@ -0,0 +1,4 @@
"""Open implementation of MonStereo."""
__version__ = '0.1'

344
monstereo/activity.py Normal file
View File

@ -0,0 +1,344 @@
# pylint: disable=too-many-statements
import math
import glob
import os
import copy
from contextlib import contextmanager
import numpy as np
import torch
import torch.nn.functional as F
import torchvision
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, FancyArrow
from PIL import Image
from .network.process import laplace_sampling
from .utils import open_annotations
from .visuals.pifpaf_show import KeypointPainter, image_canvas
from .network import Loco
from .network.process import factory_for_gt, preprocess_pifpaf
def social_interactions(idx, centers, angles, dds, stds=None, social_distance=False,
n_samples=100, threshold_prob=0.25, threshold_dist=2, radii=(0.3, 0.5)):
"""
return flag of alert if social distancing is violated
"""
xx = centers[idx][0]
zz = centers[idx][1]
distances = [math.sqrt((xx - centers[i][0]) ** 2 + (zz - centers[i][1]) ** 2) for i, _ in enumerate(centers)]
sorted_idxs = np.argsort(distances)
indices = [idx_t for idx_t in sorted_idxs[1:] if distances[idx_t] <= threshold_dist]
# Deterministic
if n_samples < 2:
for idx_t in indices:
if check_f_formations(idx, idx_t, centers, angles,
radii=radii, # Binary value
social_distance=social_distance):
return True
# Probabilistic
else:
# Samples distance
dds = torch.tensor(dds).view(-1, 1)
stds = torch.tensor(stds).view(-1, 1)
# stds_te = get_task_error(dds) # similar results to MonoLoco but lower true positive
laplace_d = torch.cat((dds, stds), dim=1)
samples_d = laplace_sampling(laplace_d, n_samples=n_samples)
# Iterate over close people
for idx_t in indices:
f_forms = []
for s_d in range(n_samples):
new_centers = copy.deepcopy(centers)
for el in (idx, idx_t):
delta_d = dds[el] - float(samples_d[s_d, el])
theta = math.atan2(new_centers[el][1], new_centers[el][0])
delta_x = delta_d * math.cos(theta)
delta_z = delta_d * math.sin(theta)
new_centers[el][0] += delta_x
new_centers[el][1] += delta_z
f_forms.append(check_f_formations(idx, idx_t, new_centers, angles,
radii=radii,
social_distance=social_distance))
if (sum(f_forms) / n_samples) >= threshold_prob:
return True
return False
def check_f_formations(idx, idx_t, centers, angles, radii, social_distance=False):
"""
Check F-formations for people close together:
1) Empty space of 0.4 + meters (no other people or themselves inside)
2) People looking inward
"""
# Extract centers and angles
other_centers = np.array([cent for l, cent in enumerate(centers) if l not in (idx, idx_t)])
theta0 = angles[idx]
theta1 = angles[idx_t]
# Find the center of o-space as average of two candidates (based on their orientation)
for radius in radii:
x_0 = np.array([centers[idx][0], centers[idx][1]])
x_1 = np.array([centers[idx_t][0], centers[idx_t][1]])
mu_0 = np.array([centers[idx][0] + radius * math.cos(theta0), centers[idx][1] - radius * math.sin(theta0)])
mu_1 = np.array([centers[idx_t][0] + radius * math.cos(theta1), centers[idx_t][1] - radius * math.sin(theta1)])
o_c = (mu_0 + mu_1) / 2
# Verify they are looking inwards.
# The distance between mus and the center should be less wrt the original position and the center
d_new = np.linalg.norm(mu_0 - mu_1) / 2 if social_distance else np.linalg.norm(mu_0 - mu_1)
d_0 = np.linalg.norm(x_0 - o_c)
d_1 = np.linalg.norm(x_1 - o_c)
# Verify no intrusion for third parties
if other_centers.size:
other_distances = np.linalg.norm(other_centers - o_c.reshape(1, -1), axis=1)
else:
other_distances = 100 * np.ones((1, 1)) # Condition verified if no other people
# Binary Classification
if d_new <= min(d_0, d_1) and np.min(other_distances) > radius:
return True
return False
def predict(args):
cnt = 0
args.device = torch.device('cpu')
if torch.cuda.is_available():
args.device = torch.device('cuda')
# Load data and model
monoloco = Loco(model=args.model, net='monoloco_pp',
device=args.device, n_dropout=args.n_dropout, p_dropout=args.dropout)
images = []
images += glob.glob(args.glob) # from cli as a string or linux converts
# Option 1: Run PifPaf extract poses and run MonoLoco in a single forward pass
if args.json_dir is None:
from .network import PifPaf, ImageList
pifpaf = PifPaf(args)
data = ImageList(args.images, scale=args.scale)
data_loader = torch.utils.data.DataLoader(
data, batch_size=1, shuffle=False,
pin_memory=args.pin_memory, num_workers=args.loader_workers)
for idx, (image_paths, image_tensors, processed_images_cpu) in enumerate(data_loader):
images = image_tensors.permute(0, 2, 3, 1)
processed_images = processed_images_cpu.to(args.device, non_blocking=True)
fields_batch = pifpaf.fields(processed_images)
# unbatch
for image_path, image, processed_image_cpu, fields in zip(
image_paths, images, processed_images_cpu, fields_batch):
if args.output_directory is None:
output_path = image_path
else:
file_name = os.path.basename(image_path)
output_path = os.path.join(args.output_directory, file_name)
im_size = (float(image.size()[1] / args.scale),
float(image.size()[0] / args.scale))
print('image', idx, image_path, output_path)
_, _, pifpaf_out = pifpaf.forward(image, processed_image_cpu, fields)
kk, dic_gt = factory_for_gt(im_size, name=image_path, path_gt=args.path_gt)
image_t = image # Resized tensor
# Run Monoloco
boxes, keypoints = preprocess_pifpaf(pifpaf_out, im_size, enlarge_boxes=False)
dic_out = monoloco.forward(keypoints, kk)
dic_out = monoloco.post_process(dic_out, boxes, keypoints, kk, dic_gt, reorder=False)
# Print
show_social(args, image_t, output_path, pifpaf_out, dic_out)
print('Image {}\n'.format(cnt) + '-' * 120)
cnt += 1
# Option 2: Load json file of poses from PifPaf and run monoloco
else:
for idx, im_path in enumerate(images):
# Load image
with open(im_path, 'rb') as f:
image = Image.open(f).convert('RGB')
if args.output_directory is None:
output_path = im_path
else:
file_name = os.path.basename(im_path)
output_path = os.path.join(args.output_directory, file_name)
im_size = (float(image.size[0] / args.scale),
float(image.size[1] / args.scale)) # Width, Height (original)
kk, dic_gt = factory_for_gt(im_size, name=im_path, path_gt=args.path_gt)
image_t = torchvision.transforms.functional.to_tensor(image).permute(1, 2, 0)
# Load json
basename, ext = os.path.splitext(os.path.basename(im_path))
extension = ext + '.pifpaf.json'
path_json = os.path.join(args.json_dir, basename + extension)
annotations = open_annotations(path_json)
# Run Monoloco
boxes, keypoints = preprocess_pifpaf(annotations, im_size, enlarge_boxes=False)
dic_out = monoloco.forward(keypoints, kk)
dic_out = monoloco.post_process(dic_out, boxes, keypoints, kk, dic_gt, reorder=False)
# Print
show_social(args, image_t, output_path, annotations, dic_out)
print('Image {}\n'.format(cnt) + '-' * 120)
cnt += 1
def show_social(args, image_t, output_path, annotations, dic_out):
"""Output frontal image with poses or combined with bird eye view"""
assert 'front' in args.output_types or 'bird' in args.output_types, "outputs allowed: front and/or bird"
angles = dic_out['angles']
dds = dic_out['dds_pred']
stds = dic_out['stds_ale']
xz_centers = [[xx[0], xx[2]] for xx in dic_out['xyz_pred']]
if 'front' in args.output_types:
# Resize back the tensor image to its original dimensions
if not 0.99 < args.scale < 1.01:
size = (round(image_t.shape[0] / args.scale), round(image_t.shape[1] / args.scale)) # height width
image_t = image_t.permute(2, 0, 1).unsqueeze(0) # batch x channels x height x width
image_t = F.interpolate(image_t, size=size).squeeze().permute(1, 2, 0)
# Prepare color for social distancing
colors = ['r' if social_interactions(idx, xz_centers, angles, dds,
stds=stds,
threshold_prob=args.threshold_prob,
threshold_dist=args.threshold_dist,
radii=args.radii)
else 'deepskyblue'
for idx, _ in enumerate(dic_out['xyz_pred'])]
# Draw keypoints and orientation
keypoint_sets, scores = get_pifpaf_outputs(annotations)
uv_centers = dic_out['uv_heads']
sizes = [abs(dic_out['uv_heads'][idx][1] - uv_s[1]) / 1.5 for idx, uv_s in
enumerate(dic_out['uv_shoulders'])]
keypoint_painter = KeypointPainter(show_box=False)
with image_canvas(image_t,
output_path + '.front.png',
show=args.show,
fig_width=10,
dpi_factor=1.0) as ax:
keypoint_painter.keypoints(ax, keypoint_sets, colors=colors)
draw_orientation(ax, uv_centers, sizes, angles, colors, mode='front')
if 'bird' in args.output_types:
with bird_canvas(args, output_path) as ax1:
draw_orientation(ax1, xz_centers, [], angles, colors, mode='bird')
draw_uncertainty(ax1, xz_centers, stds)
def get_pifpaf_outputs(annotations):
"""Extract keypoints sets and scores from output dictionary"""
if not annotations:
return [], []
keypoints_sets = np.array([dic['keypoints'] for dic in annotations]).reshape(-1, 17, 3)
score_weights = np.ones((keypoints_sets.shape[0], 17))
score_weights[:, 3] = 3.0
# score_weights[:, 5:] = 0.1
# score_weights[:, -2:] = 0.0 # ears are not annotated
score_weights /= np.sum(score_weights[0, :])
kps_scores = keypoints_sets[:, :, 2]
ordered_kps_scores = np.sort(kps_scores, axis=1)[:, ::-1]
scores = np.sum(score_weights * ordered_kps_scores, axis=1)
return keypoints_sets, scores
@contextmanager
def bird_canvas(args, output_path):
fig, ax = plt.subplots(1, 1)
fig.set_tight_layout(True)
output_path = output_path + '.bird.png'
x_max = args.z_max / 1.5
ax.plot([0, x_max], [0, args.z_max], 'k--')
ax.plot([0, -x_max], [0, args.z_max], 'k--')
ax.set_ylim(0, args.z_max + 1)
yield ax
fig.savefig(output_path)
plt.close(fig)
print('Bird-eye-view image saved')
def draw_orientation(ax, centers, sizes, angles, colors, mode):
if mode == 'front':
length = 5
fill = False
alpha = 0.6
zorder_circle = 0.5
zorder_arrow = 5
linewidth = 1.5
edgecolor = 'k'
radiuses = [s / 1.2 for s in sizes]
else:
length = 1.3
head_width = 0.3
linewidth = 2
radiuses = [0.2] * len(centers)
# length = 1.6
# head_width = 0.4
# linewidth = 2.7
radiuses = [0.2] * len(centers)
fill = True
alpha = 1
zorder_circle = 2
zorder_arrow = 1
for idx, theta in enumerate(angles):
color = colors[idx]
radius = radiuses[idx]
if mode == 'front':
x_arr = centers[idx][0] + (length + radius) * math.cos(theta)
z_arr = length + centers[idx][1] + (length + radius) * math.sin(theta)
delta_x = math.cos(theta)
delta_z = math.sin(theta)
head_width = max(10, radiuses[idx] / 1.5)
else:
edgecolor = color
x_arr = centers[idx][0]
z_arr = centers[idx][1]
delta_x = length * math.cos(theta)
delta_z = - length * math.sin(theta) # keep into account kitti convention
circle = Circle(centers[idx], radius=radius, color=color, fill=fill, alpha=alpha, zorder=zorder_circle)
arrow = FancyArrow(x_arr, z_arr, delta_x, delta_z, head_width=head_width, edgecolor=edgecolor,
facecolor=color, linewidth=linewidth, zorder=zorder_arrow)
ax.add_patch(circle)
ax.add_patch(arrow)
def draw_uncertainty(ax, centers, stds):
for idx, std in enumerate(stds):
std = stds[idx]
theta = math.atan2(centers[idx][1], centers[idx][0])
delta_x = std * math.cos(theta)
delta_z = std * math.sin(theta)
x = (centers[idx][0] - delta_x, centers[idx][0] + delta_x)
z = (centers[idx][1] - delta_z, centers[idx][1] + delta_z)
ax.plot(x, z, color='g', linewidth=2.5)

View File

@ -0,0 +1,2 @@
from .eval_kitti import EvalKitti

View File

@ -0,0 +1,251 @@
import os
import glob
import csv
from collections import defaultdict
import numpy as np
import torch
from PIL import Image
from sklearn.metrics import accuracy_score
from monstereo.network import Loco
from monstereo.network.process import factory_for_gt, preprocess_pifpaf
from monstereo.activity import social_interactions
from monstereo.utils import open_annotations, get_iou_matches, get_difficulty
class ActivityEvaluator:
"""Evaluate talking activity for Collective Activity Dataset & KITTI"""
dic_cnt = dict(fp=0, fn=0, det=0)
cnt = {'pred': defaultdict(int), 'gt': defaultdict(int)} # pred is for matched instances
def __init__(self, args):
# COLLECTIVE ACTIVITY DATASET (talking)
# -------------------------------------------------------------------------------------------------------------
if args.dataset == 'collective':
self.folders_collective = ['seq02', 'seq14', 'seq12', 'seq13', 'seq11', 'seq36']
# folders_collective = ['seq02']
self.path_collective = ['data/activity/' + fold for fold in self.folders_collective]
self.THRESHOLD_PROB = 0.25 # Concordance for samples
self.THRESHOLD_DIST = 2 # Threshold to check distance of people
self.RADII = (0.3, 0.5) # expected radii of the o-space
self.PIFPAF_CONF = 0.4
self.SOCIAL_DISTANCE = False
# -------------------------------------------------------------------------------------------------------------
# KITTI DATASET (social distancing)
# ------------------------------------------------------------------------------------------------------------
else:
self.dir_ann_kitti = '/data/lorenzo-data/annotations/kitti/scale_2_july'
self.dir_gt_kitti = 'data/kitti/gt_activity'
self.dir_kk = os.path.join('data', 'kitti', 'calib')
self.THRESHOLD_PROB = 0.25 # Concordance for samples
self.THRESHOLD_DIST = 2 # Threshold to check distance of people
self.RADII = (0.3, 0.5, 1) # expected radii of the o-space
self.PIFPAF_CONF = 0.3
self.SOCIAL_DISTANCE = True
# ---------------------------------------------------------------------------------------------------------
# Load model
device = torch.device('cpu')
if torch.cuda.is_available():
device = torch.device('cuda')
self.monoloco = Loco(model=args.model, net=args.net,
device=device, n_dropout=args.n_dropout, p_dropout=args.dropout)
self.all_pred = defaultdict(list)
self.all_gt = defaultdict(list)
assert args.dataset in ('collective', 'kitti')
def eval_collective(self):
"""Parse Collective Activity Dataset and predict if people are talking or not"""
for fold in self.path_collective:
images = glob.glob(fold + '/*.jpg')
initial_path = os.path.join(fold, 'frame0001.jpg')
with open(initial_path, 'rb') as f:
image = Image.open(f).convert('RGB')
im_size = image.size
for idx, im_path in enumerate(images):
# Collect PifPaf files and calibration
basename = os.path.basename(im_path)
extension = '.pifpaf.json'
path_pif = os.path.join(fold, basename + extension)
annotations = open_annotations(path_pif)
kk, _ = factory_for_gt(im_size, verbose=False)
# Collect corresponding gt files (ys_gt: 1 or 0)
boxes_gt, ys_gt = parse_gt_collective(fold, path_pif)
# Run Monoloco
dic_out, boxes = self.run_monoloco(annotations, kk, im_size=im_size)
# Match and update stats
matches = get_iou_matches(boxes, boxes_gt, iou_min=0.3)
# Estimate activity
categories = [os.path.basename(fold)] * len(boxes_gt)
self.estimate_activity(dic_out, matches, ys_gt, categories=categories)
# Print Results
cout_results(self.cnt, self.all_gt, self.all_pred, categories=self.folders_collective)
def eval_kitti(self):
"""Parse KITTI Dataset and predict if people are talking or not"""
from ..utils import factory_file
files = glob.glob(self.dir_gt_kitti + '/*.txt')
# files = [self.dir_gt_kitti + '/001782.txt']
assert files, "Empty directory"
for file in files:
# Collect PifPaf files and calibration
basename, _ = os.path.splitext(os.path.basename(file))
path_calib = os.path.join(self.dir_kk, basename + '.txt')
annotations, kk, tt = factory_file(path_calib, self.dir_ann_kitti, basename)
# Collect corresponding gt files (ys_gt: 1 or 0)
path_gt = os.path.join(self.dir_gt_kitti, basename + '.txt')
boxes_gt, ys_gt, difficulties = parse_gt_kitti(path_gt)
# Run Monoloco
dic_out, boxes = self.run_monoloco(annotations, kk, im_size=(1242, 374))
# Match and update stats
matches = get_iou_matches(boxes, boxes_gt, iou_min=0.3)
# Estimate activity
self.estimate_activity(dic_out, matches, ys_gt, categories=difficulties)
# Print Results
cout_results(self.cnt, self.all_gt, self.all_pred, categories=('easy', 'moderate', 'hard'))
def estimate_activity(self, dic_out, matches, ys_gt, categories):
# Calculate social interaction
angles = dic_out['angles']
dds = dic_out['dds_pred']
stds = dic_out['stds_ale']
confs = dic_out['confs']
xz_centers = [[xx[0], xx[2]] for xx in dic_out['xyz_pred']]
# Count gt statistics
for key in categories:
self.cnt['gt'][key] += 1
self.cnt['gt']['all'] += 1
for i_m, (idx, idx_gt) in enumerate(matches):
# Select keys to update resultd for Collective or KITTI
keys = ('all', categories[idx_gt])
# Run social interactions rule
flag = social_interactions(idx, xz_centers, angles, dds,
stds=stds,
threshold_prob=self.THRESHOLD_PROB,
threshold_dist=self.THRESHOLD_DIST,
radii=self.RADII,
social_distance=self.SOCIAL_DISTANCE)
# Accumulate results
for key in keys:
self.all_pred[key].append(flag)
self.all_gt[key].append(ys_gt[idx_gt])
self.cnt['pred'][key] += 1
def run_monoloco(self, annotations, kk, im_size=None):
boxes, keypoints = preprocess_pifpaf(annotations, im_size, enlarge_boxes=True, min_conf=self.PIFPAF_CONF)
dic_out = self.monoloco.forward(keypoints, kk)
dic_out = self.monoloco.post_process(dic_out, boxes, keypoints, kk, dic_gt=None, reorder=False, verbose=False)
return dic_out, boxes
def parse_gt_collective(fold, path_pif):
"""Parse both gt and binary label (1/0) for talking or not"""
with open(os.path.join(fold, "annotations.txt"), "r") as ff:
reader = csv.reader(ff, delimiter='\t')
dic_frames = defaultdict(lambda: defaultdict(list))
for idx, line in enumerate(reader):
box = convert_box(line[1:5])
cat = convert_category(line[5])
dic_frames[line[0]]['boxes'].append(box)
dic_frames[line[0]]['y'].append(cat)
frame = extract_frame_number(path_pif)
boxes_gt = dic_frames[frame]['boxes']
ys_gt = np.array(dic_frames[frame]['y'])
return boxes_gt, ys_gt
def parse_gt_kitti(path_gt):
"""Parse both gt and binary label (1/0) for talking or not"""
boxes_gt = []
ys = []
difficulties = []
with open(path_gt, "r") as f_gt:
for line_gt in f_gt:
line = line_gt.split()
box = [float(x) for x in line[4:8]]
boxes_gt.append(box)
y = int(line[-1])
assert y in (1, 0), "Expected to be binary (1/0)"
ys.append(y)
trunc = float(line[1])
occ = int(line[2])
difficulties.append(get_difficulty(box, trunc, occ))
return boxes_gt, ys, difficulties
def cout_results(cnt, all_gt, all_pred, categories=()):
categories = list(categories)
categories.append('all')
print('-' * 80)
# Split by folders for collective activity
for key in categories:
acc = accuracy_score(all_gt[key], all_pred[key])
print("Accuracy of category {}: {:.2f}% , Recall: {:.2f}%, #: {}, Predicted positive: {:.2f}%"
.format(key,
acc * 100,
cnt['pred'][key] / cnt['gt'][key]*100,
cnt['pred'][key],
sum(all_gt[key]) / len(all_gt[key]) * 100))
# Final Accuracy
acc = accuracy_score(all_gt['all'], all_pred['all'])
print('-' * 80)
print("Final Accuracy: {:.2f}%".format(acc * 100))
print('-' * 80)
def convert_box(box_str):
"""from string with left and center to standard """
box = [float(el) for el in box_str] # x, y, w h
box[2] += box[0]
box[3] += box[1]
return box
def convert_category(cat):
"""Talking = 6"""
if cat == '6':
return 1
return 0
def extract_frame_number(path):
"""extract frame number from path"""
name = os.path.basename(path)
if name[5] == '0':
frame = name[6:9]
else:
frame = name[5:9]
return frame

View File

@ -0,0 +1,432 @@
"""
Evaluate MonStereo code on KITTI dataset using ALE metric
"""
# pylint: disable=attribute-defined-outside-init
import os
import math
import logging
import datetime
from collections import defaultdict
from tabulate import tabulate
from ..utils import get_iou_matches, get_task_error, get_pixel_error, check_conditions, \
get_difficulty, split_training, parse_ground_truth, get_iou_matches_matrix
from ..visuals import show_results, show_spread, show_task_error, show_box_plot
class EvalKitti:
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
CLUSTERS = ('easy', 'moderate', 'hard', 'all', '3', '5', '7', '9', '11', '13', '15', '17', '19', '21', '23', '25',
'27', '29', '31', '49')
ALP_THRESHOLDS = ('<0.5m', '<1m', '<2m')
OUR_METHODS = ['geometric', 'monoloco', 'monoloco_pp', 'pose', 'reid', 'monstereo']
METHODS_MONO = ['m3d', 'monopsr']
METHODS_STEREO = ['3dop', 'psf', 'pseudo-lidar', 'e2e', 'oc-stereo']
BASELINES = ['task_error', 'pixel_error']
HEADERS = ('method', '<0.5', '<1m', '<2m', 'easy', 'moderate', 'hard', 'all')
CATEGORIES = ('pedestrian',)
def __init__(self, thresh_iou_monoloco=0.3, thresh_iou_base=0.3, thresh_conf_monoloco=0.2, thresh_conf_base=0.5,
verbose=False):
self.main_dir = os.path.join('data', 'kitti')
self.dir_gt = os.path.join(self.main_dir, 'gt')
self.methods = self.OUR_METHODS + self.METHODS_MONO + self.METHODS_STEREO
path_train = os.path.join('splits', 'kitti_train.txt')
path_val = os.path.join('splits', 'kitti_val.txt')
dir_logs = os.path.join('data', 'logs')
assert dir_logs, "No directory to save final statistics"
now = datetime.datetime.now()
now_time = now.strftime("%Y%m%d-%H%M")[2:]
self.path_results = os.path.join(dir_logs, 'eval-' + now_time + '.json')
self.verbose = verbose
self.dic_thresh_iou = {method: (thresh_iou_monoloco if method in self.OUR_METHODS
else thresh_iou_base)
for method in self.methods}
self.dic_thresh_conf = {method: (thresh_conf_monoloco if method in self.OUR_METHODS
else thresh_conf_base)
for method in self.methods}
self.dic_thresh_conf['monopsr'] += 0.3
self.dic_thresh_conf['e2e-pl'] = -100 # They don't have enough detections
self.dic_thresh_conf['oc-stereo'] = -100
# Extract validation images for evaluation
names_gt = tuple(os.listdir(self.dir_gt))
_, self.set_val = split_training(names_gt, path_train, path_val)
# self.set_val = ('002282.txt', )
# Define variables to save statistics
self.dic_methods = self.errors = self.dic_stds = self.dic_stats = self.dic_cnt = self.cnt_gt = self.category \
= None
self.cnt = 0
def run(self):
"""Evaluate Monoloco performances on ALP and ALE metrics"""
for self.category in self.CATEGORIES:
# Initialize variables
self.errors = defaultdict(lambda: defaultdict(list))
self.dic_stds = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
self.dic_stats = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(float))))
self.dic_cnt = defaultdict(int)
self.cnt_gt = defaultdict(int)
# Iterate over each ground truth file in the training set
# self.set_val = ('000063.txt',)
for name in self.set_val:
path_gt = os.path.join(self.dir_gt, name)
self.name = name
# Iterate over each line of the gt file and save box location and distances
out_gt = parse_ground_truth(path_gt, self.category)
methods_out = defaultdict(tuple) # Save all methods for comparison
# Count ground_truth:
boxes_gt, ys, truncs_gt, occs_gt = out_gt
for idx, box in enumerate(boxes_gt):
mode = get_difficulty(box, truncs_gt[idx], occs_gt[idx])
self.cnt_gt[mode] += 1
self.cnt_gt['all'] += 1
if out_gt[0]:
for method in self.methods:
# Extract annotations
dir_method = os.path.join(self.main_dir, method)
assert os.path.exists(dir_method), "directory of the method %s does not exists" % method
path_method = os.path.join(dir_method, name)
methods_out[method] = self._parse_txts(path_method, method=method)
# Compute the error with ground truth
self._estimate_error(out_gt, methods_out[method], method=method)
# Update statistics of errors and uncertainty
for key in self.errors:
add_true_negatives(self.errors[key], self.cnt_gt['all'])
for clst in self.CLUSTERS[:-1]:
try:
get_statistics(self.dic_stats['test'][key][clst],
self.errors[key][clst],
self.dic_stds[key][clst], key)
except ZeroDivisionError:
print('\n'+'-'*100 + '\n'+f'ERROR: method {key} at cluster {clst} is empty' + '\n'+'-'*100+'\n')
raise
# Show statistics
print('\n' + self.category.upper() + ':')
self.show_statistics()
def printer(self, show, save):
if save or show:
show_results(self.dic_stats, self.CLUSTERS, show, save)
show_spread(self.dic_stats, self.CLUSTERS, show, save)
show_box_plot(self.errors, self.CLUSTERS, show, save)
show_task_error(show, save)
def _parse_txts(self, path, method):
boxes = []
dds = []
cat = []
if method == 'psf':
path = os.path.splitext(path)[0] + '.png.txt'
if method in self.OUR_METHODS:
bis, epis = [], []
output = (boxes, dds, cat, bis, epis)
else:
output = (boxes, dds, cat)
try:
with open(path, "r") as ff:
for line_str in ff:
if method == 'psf':
line = line_str.split(", ")
box = [float(x) for x in line[4:8]]
boxes.append(box)
loc = ([float(x) for x in line[11:14]])
dd = math.sqrt(loc[0] ** 2 + loc[1] ** 2 + loc[2] ** 2)
dds.append(dd)
cat.append('Pedestrian')
else:
line = line_str.split()
if check_conditions(line,
category='pedestrian',
method=method,
thresh=self.dic_thresh_conf[method]):
box = [float(x) for x in line[4:8]]
box.append(float(line[15])) # Add confidence
loc = ([float(x) for x in line[11:14]])
dd = math.sqrt(loc[0] ** 2 + loc[1] ** 2 + loc[2] ** 2)
cat.append(line[0])
boxes.append(box)
dds.append(dd)
if method in self.OUR_METHODS:
bis.append(float(line[16]))
epis.append(float(line[17]))
self.dic_cnt[method] += 1
return output
except FileNotFoundError:
return output
def _estimate_error(self, out_gt, out, method):
"""Estimate localization error"""
boxes_gt, ys, truncs_gt, occs_gt = out_gt
if method in self.OUR_METHODS:
boxes, dds, cat, bis, epis = out
else:
boxes, dds, cat = out
if method == 'psf':
matches = get_iou_matches_matrix(boxes, boxes_gt, self.dic_thresh_iou[method])
else:
matches = get_iou_matches(boxes, boxes_gt, self.dic_thresh_iou[method])
for (idx, idx_gt) in matches:
# Update error if match is found
dd_gt = ys[idx_gt][3]
zz_gt = ys[idx_gt][2]
mode = get_difficulty(boxes_gt[idx_gt], truncs_gt[idx_gt], occs_gt[idx_gt])
if cat[idx].lower() in (self.category, 'pedestrian'):
self.update_errors(dds[idx], dd_gt, mode, self.errors[method])
if method == 'monoloco':
dd_task_error = dd_gt + (get_task_error(zz_gt))**2
dd_pixel_error = dd_gt + get_pixel_error(zz_gt)
self.update_errors(dd_task_error, dd_gt, mode, self.errors['task_error'])
self.update_errors(dd_pixel_error, dd_gt, mode, self.errors['pixel_error'])
if method in self.OUR_METHODS:
epi = max(epis[idx], bis[idx])
self.update_uncertainty(bis[idx], epi, dds[idx], dd_gt, mode, self.dic_stds[method])
def update_errors(self, dd, dd_gt, cat, errors):
"""Compute and save errors between a single box and the gt box which match"""
diff = abs(dd - dd_gt)
clst = find_cluster(dd_gt, self.CLUSTERS[4:])
errors['all'].append(diff)
errors[cat].append(diff)
errors[clst].append(diff)
# Check if the distance is less than one or 2 meters
if diff <= 0.5:
errors['<0.5m'].append(1)
else:
errors['<0.5m'].append(0)
if diff <= 1:
errors['<1m'].append(1)
else:
errors['<1m'].append(0)
if diff <= 2:
errors['<2m'].append(1)
else:
errors['<2m'].append(0)
def update_uncertainty(self, std_ale, std_epi, dd, dd_gt, mode, dic_stds):
clst = find_cluster(dd_gt, self.CLUSTERS[4:])
dic_stds['all']['ale'].append(std_ale)
dic_stds[clst]['ale'].append(std_ale)
dic_stds[mode]['ale'].append(std_ale)
dic_stds['all']['epi'].append(std_epi)
dic_stds[clst]['epi'].append(std_epi)
dic_stds[mode]['epi'].append(std_epi)
dic_stds['all']['epi_rel'].append(std_epi / dd)
dic_stds[clst]['epi_rel'].append(std_epi / dd)
dic_stds[mode]['epi_rel'].append(std_epi / dd)
# Number of annotations inside the confidence interval
std = std_epi if std_epi > 0 else std_ale # consider aleatoric uncertainty if epistemic is not calculated
if abs(dd - dd_gt) <= std:
dic_stds['all']['interval'].append(1)
dic_stds[clst]['interval'].append(1)
dic_stds[mode]['interval'].append(1)
else:
dic_stds['all']['interval'].append(0)
dic_stds[clst]['interval'].append(0)
dic_stds[mode]['interval'].append(0)
# Annotations at risk inside the confidence interval
if dd_gt <= dd:
dic_stds['all']['at_risk'].append(1)
dic_stds[clst]['at_risk'].append(1)
dic_stds[mode]['at_risk'].append(1)
if abs(dd - dd_gt) <= std_epi:
dic_stds['all']['at_risk-interval'].append(1)
dic_stds[clst]['at_risk-interval'].append(1)
dic_stds[mode]['at_risk-interval'].append(1)
else:
dic_stds['all']['at_risk-interval'].append(0)
dic_stds[clst]['at_risk-interval'].append(0)
dic_stds[mode]['at_risk-interval'].append(0)
else:
dic_stds['all']['at_risk'].append(0)
dic_stds[clst]['at_risk'].append(0)
dic_stds[mode]['at_risk'].append(0)
# Precision of uncertainty
eps = 1e-4
task_error = get_task_error(dd)
prec_1 = abs(dd - dd_gt) / (std_epi + eps)
prec_2 = abs(std_epi - task_error)
dic_stds['all']['prec_1'].append(prec_1)
dic_stds[clst]['prec_1'].append(prec_1)
dic_stds[mode]['prec_1'].append(prec_1)
dic_stds['all']['prec_2'].append(prec_2)
dic_stds[clst]['prec_2'].append(prec_2)
dic_stds[mode]['prec_2'].append(prec_2)
def show_statistics(self):
all_methods = self.methods + self.BASELINES
print('-'*90)
self.summary_table(all_methods)
# Uncertainty
for net in ('monoloco_pp', 'monstereo'):
print(('-'*100))
print(net.upper())
for clst in ('easy', 'moderate', 'hard', 'all'):
print(" Annotations in clst {}: {:.0f}, Recall: {:.1f}. Precision: {:.2f}, Relative size is {:.1f} %"
.format(clst,
self.dic_stats['test'][net][clst]['cnt'],
self.dic_stats['test'][net][clst]['interval']*100,
self.dic_stats['test'][net][clst]['prec_1'],
self.dic_stats['test'][net][clst]['epi_rel']*100))
if self.verbose:
for key in all_methods:
print(key.upper())
for clst in self.CLUSTERS[:4]:
print(" {} Average error in cluster {}: {:.2f} with a max error of {:.1f}, "
"for {} annotations"
.format(key, clst, self.dic_stats['test'][key][clst]['mean'],
self.dic_stats['test'][key][clst]['max'],
self.dic_stats['test'][key][clst]['cnt']))
for perc in self.ALP_THRESHOLDS:
print("{} Instances with error {}: {:.2f} %"
.format(key, perc, 100 * average(self.errors[key][perc])))
print("\nMatched annotations: {:.1f} %".format(self.errors[key]['matched']))
print(" Detected annotations : {}/{} ".format(self.dic_cnt[key], self.cnt_gt['all']))
print("-" * 100)
print("precision 1: {:.2f}".format(self.dic_stats['test']['monoloco']['all']['prec_1']))
print("precision 2: {:.2f}".format(self.dic_stats['test']['monoloco']['all']['prec_2']))
def summary_table(self, all_methods):
"""Tabulate table for ALP and ALE metrics"""
alp = [[str(100 * average(self.errors[key][perc]))[:5]
for perc in ['<0.5m', '<1m', '<2m']]
for key in all_methods]
ale = [[str(round(self.dic_stats['test'][key][clst]['mean'], 2))[:4] + ' [' +
str(round(self.dic_stats['test'][key][clst]['cnt'] / self.cnt_gt[clst] * 100))[:2] + '%]'
for clst in self.CLUSTERS[:4]]
for key in all_methods]
results = [[key] + alp[idx] + ale[idx] for idx, key in enumerate(all_methods)]
print(tabulate(results, headers=self.HEADERS))
print('-' * 90 + '\n')
def stats_height(self):
heights = []
for name in self.set_val:
path_gt = os.path.join(self.dir_gt, name)
self.name = name
# Iterate over each line of the gt file and save box location and distances
out_gt = parse_ground_truth(path_gt, 'pedestrian')
boxes_gt, ys, truncs_gt, occs_gt = out_gt
for label in ys:
heights.append(label[4])
import numpy as np
tail1, tail2 = np.nanpercentile(np.array(heights), [5, 95])
print(average(heights))
print(len(heights))
print(tail1, tail2)
def get_statistics(dic_stats, errors, dic_stds, key):
"""Update statistics of a cluster"""
try:
dic_stats['mean'] = average(errors)
dic_stats['max'] = max(errors)
dic_stats['cnt'] = len(errors)
except ValueError:
dic_stats['mean'] = - 1
dic_stats['max'] = - 1
dic_stats['cnt'] = - 1
if key in ('monoloco', 'monoloco_pp', 'monstereo'):
dic_stats['std_ale'] = average(dic_stds['ale'])
dic_stats['std_epi'] = average(dic_stds['epi'])
dic_stats['epi_rel'] = average(dic_stds['epi_rel'])
dic_stats['interval'] = average(dic_stds['interval'])
dic_stats['at_risk'] = average(dic_stds['at_risk'])
dic_stats['prec_1'] = average(dic_stds['prec_1'])
dic_stats['prec_2'] = average(dic_stds['prec_2'])
def add_true_negatives(err, cnt_gt):
"""Update errors statistics of a specific method with missing detections"""
matched = len(err['all'])
missed = cnt_gt - matched
zeros = [0] * missed
err['<0.5m'].extend(zeros)
err['<1m'].extend(zeros)
err['<2m'].extend(zeros)
err['matched'] = 100 * matched / cnt_gt
def find_cluster(dd, clusters):
"""Find the correct cluster. Above the last cluster goes into "excluded (together with the ones from kitti cat"""
for idx, clst in enumerate(clusters[:-1]):
if int(clst) < dd <= int(clusters[idx+1]):
return clst
return 'excluded'
def extract_indices(idx_to_check, *args):
"""
Look if a given index j_gt is present in all the other series of indices (_, j)
and return the corresponding one for argument
idx_check --> gt index to check for correspondences in other method
idx_method --> index corresponding to the method
idx_gt --> index gt of the method
idx_pred --> index of the predicted box of the method
indices --> list of predicted indices for each method corresponding to the ground truth index to check
"""
checks = [False]*len(args)
indices = []
for idx_method, method in enumerate(args):
for (idx_pred, idx_gt) in method:
if idx_gt == idx_to_check:
checks[idx_method] = True
indices.append(idx_pred)
return all(checks), indices
def average(my_list):
"""calculate mean of a list"""
return sum(my_list) / len(my_list)

View File

@ -0,0 +1,238 @@
# pylint: disable=too-many-statements,cyclic-import, too-many-branches
"""Joints Analysis: Supplementary material of MonStereo"""
import json
import os
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
from .eval_kitti import find_cluster, average
from ..visuals.figures import get_distances
COCO_KEYPOINTS = [
'nose', # 0
'left_eye', # 1
'right_eye', # 2
'left_ear', # 3
'right_ear', # 4
'left_shoulder', # 5
'right_shoulder', # 6
'left_elbow', # 7
'right_elbow', # 8
'left_wrist', # 9
'right_wrist', # 10
'left_hip', # 11
'right_hip', # 12
'left_knee', # 13
'right_knee', # 14
'left_ankle', # 15
'right_ankle', # 16
]
def joints_variance(joints, clusters, dic_ms):
# CLUSTERS = ('3', '5', '7', '9', '11', '13', '15', '17', '19', '21', '23', '25', '27', '29', '31', '49')
BF = 0.54 * 721
phase = 'train'
methods = ('pifpaf', 'mask')
dic_fin = {}
for method in methods:
dic_var = defaultdict(lambda: defaultdict(list))
dic_joints = defaultdict(list)
dic_avg = defaultdict(lambda: defaultdict(float))
path_joints = joints + '_' + method + '.json'
with open(path_joints, 'r') as f:
dic_jo = json.load(f)
for idx, keypoint in enumerate(dic_jo[phase]['kps']):
# if dic_jo[phase]['names'][idx] == '005856.txt' and dic_jo[phase]['Y'][idx][2] > 14:
# aa = 4
assert len(keypoint) < 2
kps = np.array(keypoint[0])[:, :17]
kps_r = np.array(keypoint[0])[:, 17:]
disps = kps[0] - kps_r[0]
zz = dic_jo[phase]['Y'][idx][2]
disps_3 = get_variance(kps, kps_r, zz)
disps_8 = get_variance_conf(kps, kps_r, num=8)
disps_4 = get_variance_conf(kps, kps_r, num=4)
disp_gt = BF / zz
clst = find_cluster(zz, clusters) # 4 = '3' 35 = '31' 42 = 2 = 'excl'
dic_var['std_d'][clst].append(disps.std())
errors = np.minimum(30, np.abs(zz - BF / disps))
dic_var['mean_dev'][clst].append(min(30, abs(zz - BF / np.median(disps))))
dic_var['mean_3'][clst].append(min(30, abs(zz - BF / disps_3.mean())))
dic_var['mean_8'][clst].append(min(30, abs(zz - BF / np.median(disps_8))))
dic_var['mean_4'][clst].append(min(30, abs(zz - BF / np.median(disps_4))))
arg_best = np.argmin(errors)
conf = np.mean((kps[2][arg_best], kps_r[2][arg_best]))
dic_var['mean_best'][clst].append(np.min(errors))
dic_var['conf_best'][clst].append(conf)
dic_var['conf'][clst].append(np.mean((np.mean(kps[2]), np.mean(kps_r[2]))))
# dic_var['std_z'][clst].append(zzs.std())
for ii, el in enumerate(disps):
if abs(el-disp_gt) < 1:
dic_var['rep'][clst].append(1)
dic_joints[str(ii)].append(1)
else:
dic_var['rep'][clst].append(0)
dic_joints[str(ii)].append(0)
for key in dic_var:
for clst in clusters[:-1]: # 41 needs to be excluded (36 = '31')
dic_avg[key][clst] = average(dic_var[key][clst])
dic_fin[method] = dic_avg
for key in dic_joints:
dic_fin[method]['joints'][key] = average(dic_joints[key])
dic_fin['monstereo'] = {clst: dic_ms[clst]['mean'] for clst in clusters[:-1]}
variance_figures(dic_fin, clusters)
def get_variance(kps, kps_r, zz):
thresh = 0.5 - zz / 100
disps_2 = []
disps = kps[0] - kps_r[0]
arg_disp = np.argsort(disps)[::-1]
for idx in arg_disp[1:]:
if kps[2][idx] > thresh and kps_r[2][idx] > thresh:
disps_2.append(disps[idx])
if len(disps_2) >= 3:
return np.array(disps_2)
return disps
def get_variance_conf(kps, kps_r, num=8):
disps_conf = []
confs = (kps[2, :] + kps_r[2, :]) / 2
disps = kps[0] - kps_r[0]
arg_disp = np.argsort(confs)[::-1]
for idx in arg_disp[:num]:
disps_conf.append(disps[idx])
return np.array(disps_conf)
def variance_figures(dic_fin, clusters):
"""Predicted confidence intervals and task error as a function of ground-truth distance"""
dir_out = 'docs'
x_min = 3
x_max = 43
y_min = 0
y_max = 1
plt.figure(0)
plt.xlabel("Ground-truth distance [m]")
plt.title("Repeatability by distance")
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.grid(linewidth=0.2)
xxs = get_distances(clusters)
yys_p = [el for _, el in dic_fin['pifpaf']['rep'].items()]
yys_m = [el for _, el in dic_fin['mask']['rep'].items()]
plt.plot(xxs, yys_p, marker='s', label="PifPaf")
plt.plot(xxs, yys_m, marker='o', label="Mask R-CNN")
plt.tight_layout()
plt.legend()
path_fig = os.path.join(dir_out, 'repeatability.png')
plt.savefig(path_fig)
print("Figure of repeatability saved in {}".format(path_fig))
plt.figure(1)
plt.xlabel("Ground-truth distance [m]")
plt.ylabel("[m]")
plt.title("Depth error")
plt.grid(linewidth=0.2)
y_min = 0
y_max = 2.7
plt.ylim(y_min, y_max)
yys_p = [el for _, el in dic_fin['pifpaf']['mean_dev'].items()]
# yys_m = [el for _, el in dic_fin['mask']['mean_dev'].items()]
yys_p_3 = [el for _, el in dic_fin['pifpaf']['mean_3'].items()]
yys_p_8 = [el for _, el in dic_fin['pifpaf']['mean_8'].items()]
yys_p_4 = [el for _, el in dic_fin['pifpaf']['mean_4'].items()]
# yys_m_3 = [el for _, el in dic_fin['mask']['mean_3'].items()]
yys_ms = [el for _, el in dic_fin['monstereo'].items()]
yys_p_best = [el for _, el in dic_fin['pifpaf']['mean_best'].items()]
plt.plot(xxs, yys_p_4, marker='o', linestyle=':', label="PifPaf (highest 4)")
plt.plot(xxs, yys_p, marker='+', label="PifPaf (median)")
# plt.plot(xxs, yys_m, marker='o', label="Mask R-CNN (median")
plt.plot(xxs, yys_p_3, marker='s', linestyle='--', label="PifPaf (closest 3)")
plt.plot(xxs, yys_p_8, marker='*', linestyle=':', label="PifPaf (highest 8)")
plt.plot(xxs, yys_ms, marker='^', label="MonStereo")
plt.plot(xxs, yys_p_best, marker='o', label="PifPaf (best)")
# plt.plot(xxs, yys_m_3, marker='o', color='r', label="Mask R-CNN (closest 3)")
# plt.plot(xxs, yys_mon, marker='o', color='b', label="Our MonStereo")
plt.legend()
plt.tight_layout()
path_fig = os.path.join(dir_out, 'mean_deviation.png')
plt.savefig(path_fig)
print("Figure of mean deviation saved in {}".format(path_fig))
plt.figure(2)
plt.xlabel("Ground-truth distance [m]")
plt.ylabel("Pixels")
plt.title("Standard deviation of joints disparity")
yys_p = [el for _, el in dic_fin['pifpaf']['std_d'].items()]
yys_m = [el for _, el in dic_fin['mask']['std_d'].items()]
yys_p_z = [el for _, el in dic_fin['pifpaf']['std_z'].items()]
yys_m_z = [el for _, el in dic_fin['mask']['std_z'].items()]
plt.plot(xxs, yys_p, marker='s', label="PifPaf")
plt.plot(xxs, yys_m, marker='o', label="Mask R-CNN")
# plt.plot(xxs, yys_p_z, marker='s', color='b', label="PifPaf (meters)")
# plt.plot(xxs, yys_m_z, marker='o', color='r', label="Mask R-CNN (meters)")
plt.grid(linewidth=0.2)
plt.legend()
path_fig = os.path.join(dir_out, 'std_joints.png')
plt.savefig(path_fig)
print("Figure of standard deviation of joints by distance in {}".format(path_fig))
plt.figure(3)
# plt.style.use('ggplot')
width = 0.35
xxs = np.arange(len(COCO_KEYPOINTS))
yys_p = [el for _, el in dic_fin['pifpaf']['joints'].items()]
yys_m = [el for _, el in dic_fin['mask']['joints'].items()]
plt.bar(xxs, yys_p, width, color='C0', label='Pifpaf')
plt.bar(xxs + width, yys_m, width, color='C1', label='Mask R-CNN')
plt.ylim(0, 1)
plt.xlabel("Keypoints")
plt.title("Repeatability by keypoint type")
plt.xticks(xxs + width / 2, xxs)
plt.legend(loc='best')
path_fig = os.path.join(dir_out, 'repeatability_2.png')
plt.savefig(path_fig)
plt.close('all')
print("Figure of standard deviation of joints by keypointd in {}".format(path_fig))
plt.figure(4)
plt.xlabel("Ground-truth distance [m]")
plt.ylabel("Confidence")
plt.grid(linewidth=0.2)
xxs = get_distances(clusters)
yys_p_conf = [el for _, el in dic_fin['pifpaf']['conf'].items()]
yys_p_conf_best = [el for _, el in dic_fin['pifpaf']['conf_best'].items()]
yys_m_conf = [el for _, el in dic_fin['mask']['conf'].items()]
yys_m_conf_best = [el for _, el in dic_fin['mask']['conf_best'].items()]
plt.plot(xxs, yys_p_conf_best, marker='s', color='lightblue', label="PifPaf (best)")
plt.plot(xxs, yys_p_conf, marker='s', color='b', label="PifPaf (mean)")
plt.plot(xxs, yys_m_conf_best, marker='^', color='darkorange', label="Mask (best)")
plt.plot(xxs, yys_m_conf, marker='o', color='r', label="Mask R-CNN (mean)")
plt.legend()
plt.tight_layout()
path_fig = os.path.join(dir_out, 'confidence.png')
plt.savefig(path_fig)
print("Figure of confidence saved in {}".format(path_fig))

View File

@ -0,0 +1,270 @@
#pylint: disable=too-many-branches
"""
Run MonoLoco/MonStereo and converts annotations into KITTI format
"""
import os
import math
from collections import defaultdict
import torch
from ..network import Loco
from ..network.process import preprocess_pifpaf
from ..network.geom_baseline import geometric_coordinates
from ..utils import get_keypoints, pixel_to_camera, factory_file, factory_basename, make_new_directory, get_category, \
xyz_from_distance, read_and_rewrite
from .stereo_baselines import baselines_association
from .reid_baseline import get_reid_features, ReID
class GenerateKitti:
METHODS = ['monstereo', 'monoloco_pp', 'monoloco', 'geometric']
def __init__(self, model, dir_ann, p_dropout=0.2, n_dropout=0, hidden_size=1024):
# Load monoloco
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
if 'monstereo' in self.METHODS:
self.monstereo = Loco(model=model, net='monstereo', device=device, n_dropout=n_dropout, p_dropout=p_dropout,
linear_size=hidden_size)
# model_mono_pp = 'data/models/monoloco-191122-1122.pkl' # KITTI_p
# model_mono_pp = 'data/models/monoloco-191018-1459.pkl' # nuScenes_p
model_mono_pp = 'data/models/stereoloco-200604-0949.pkl' # KITTI_pp
# model_mono_pp = 'data/models/stereoloco-200608-1550.pkl' # nuScenes_pp
if 'monoloco_pp' in self.METHODS:
self.monoloco_pp = Loco(model=model_mono_pp, net='monoloco_pp', device=device, n_dropout=n_dropout,
p_dropout=p_dropout)
if 'monoloco' in self.METHODS:
model_mono = 'data/models/monoloco-190717-0952.pkl' # KITTI
# model_mono = 'data/models/monoloco-190719-0923.pkl' # NuScenes
self.monoloco = Loco(model=model_mono, net='monoloco', device=device, n_dropout=n_dropout,
p_dropout=p_dropout, linear_size=256)
self.dir_ann = dir_ann
# Extract list of pifpaf files in validation images
self.dir_gt = os.path.join('data', 'kitti', 'gt')
self.dir_gt_new = os.path.join('data', 'kitti', 'gt_new')
self.set_basename = factory_basename(dir_ann, self.dir_gt)
self.dir_kk = os.path.join('data', 'kitti', 'calib')
self.dir_byc = '/data/lorenzo-data/kitti/object_detection/left'
# For quick testing
# ------------------------------------------------------------------------------------------------------------
# self.set_basename = ('001782',)
# self.set_basename = ('002282',)
# ------------------------------------------------------------------------------------------------------------
# Calculate stereo baselines
# self.baselines = ['pose', 'reid']
self.baselines = []
self.cnt_disparity = defaultdict(int)
self.cnt_no_stereo = 0
self.dir_images = os.path.join('data', 'kitti', 'images')
self.dir_images_r = os.path.join('data', 'kitti', 'images_r')
# ReID Baseline
if 'reid' in self.baselines:
weights_path = 'data/models/reid_model_market.pkl'
self.reid_net = ReID(weights_path=weights_path, device=device, num_classes=751, height=256, width=128)
def run(self):
"""Run Monoloco and save txt files for KITTI evaluation"""
cnt_ann = cnt_file = cnt_no_file = 0
dir_out = {key: os.path.join('data', 'kitti', key) for key in self.METHODS}
print("\n")
for key in self.METHODS:
make_new_directory(dir_out[key])
for key in self.baselines:
dir_out[key] = os.path.join('data', 'kitti', key)
make_new_directory(dir_out[key])
print("Created empty output directory for {}".format(key))
# Run monoloco over the list of images
for basename in self.set_basename:
path_calib = os.path.join(self.dir_kk, basename + '.txt')
annotations, kk, tt = factory_file(path_calib, self.dir_ann, basename)
boxes, keypoints = preprocess_pifpaf(annotations, im_size=(1242, 374))
cat = get_category(keypoints, os.path.join(self.dir_byc, basename + '.json'))
if keypoints:
annotations_r, _, _ = factory_file(path_calib, self.dir_ann, basename, mode='right')
_, keypoints_r = preprocess_pifpaf(annotations_r, im_size=(1242, 374))
cnt_ann += len(boxes)
cnt_file += 1
all_inputs, all_outputs = {}, {}
# STEREOLOCO
dic_out = self.monstereo.forward(keypoints, kk, keypoints_r=keypoints_r)
all_outputs['monstereo'] = [dic_out['xyzd'], dic_out['bi'], dic_out['epi'],
dic_out['yaw'], dic_out['h'], dic_out['w'], dic_out['l']]
# MONOLOCO++
if 'monoloco_pp' in self.METHODS:
dic_out = self.monoloco_pp.forward(keypoints, kk)
all_outputs['monoloco_pp'] = [dic_out['xyzd'], dic_out['bi'], dic_out['epi'],
dic_out['yaw'], dic_out['h'], dic_out['w'], dic_out['l']]
zzs = [float(el[2]) for el in dic_out['xyzd']]
# MONOLOCO
if 'monoloco' in self.METHODS:
dic_out = self.monoloco.forward(keypoints, kk)
zzs_geom, xy_centers = geometric_coordinates(keypoints, kk, average_y=0.48)
all_outputs['monoloco'] = [dic_out['d'], dic_out['bi'], dic_out['epi']] + [zzs_geom, xy_centers]
all_outputs['geometric'] = all_outputs['monoloco']
params = [kk, tt]
for key in self.METHODS:
path_txt = {key: os.path.join(dir_out[key], basename + '.txt')}
save_txts(path_txt[key], boxes, all_outputs[key], params, mode=key, cat=cat)
# STEREO BASELINES
if self.baselines:
dic_xyz = self._run_stereo_baselines(basename, boxes, keypoints, zzs, path_calib)
for key in dic_xyz:
all_outputs[key] = all_outputs['monoloco'].copy()
all_outputs[key][0] = dic_xyz[key]
all_inputs[key] = boxes
path_txt[key] = os.path.join(dir_out[key], basename + '.txt')
save_txts(path_txt[key], all_inputs[key], all_outputs[key], params, mode='baseline', cat=cat)
print("\nSaved in {} txt {} annotations. Not found {} images".format(cnt_file, cnt_ann, cnt_no_file))
if 'monstereo' in self.METHODS:
print("STEREO:")
for key in self.baselines:
print("Annotations corrected using {} baseline: {:.1f}%".format(
key, self.cnt_disparity[key] / cnt_ann * 100))
print("Maximum possible stereo associations: {:.1f}%".format(self.cnt_disparity['max'] / cnt_ann * 100))
print("Not found {}/{} stereo files".format(self.cnt_no_stereo, cnt_file))
create_empty_files(dir_out) # Create empty files for official evaluation
def _run_stereo_baselines(self, basename, boxes, keypoints, zzs, path_calib):
annotations_r, _, _ = factory_file(path_calib, self.dir_ann, basename, mode='right')
boxes_r, keypoints_r = preprocess_pifpaf(annotations_r, im_size=(1242, 374))
_, kk, tt = factory_file(path_calib, self.dir_ann, basename)
uv_centers = get_keypoints(keypoints, mode='bottom') # Kitti uses the bottom center to calculate depth
xy_centers = pixel_to_camera(uv_centers, kk, 1)
# Stereo baselines
if keypoints_r:
path_image = os.path.join(self.dir_images, basename + '.png')
path_image_r = os.path.join(self.dir_images_r, basename + '.png')
reid_features = get_reid_features(self.reid_net, boxes, boxes_r, path_image, path_image_r)
dic_zzs, cnt = baselines_association(self.baselines, zzs, keypoints, keypoints_r, reid_features)
for key in cnt:
self.cnt_disparity[key] += cnt[key]
else:
self.cnt_no_stereo += 1
dic_zzs = {key: zzs for key in self.baselines}
# Combine the stereo zz with x, y from 2D detection (no MonoLoco involved)
dic_xyz = defaultdict(list)
for key in dic_zzs:
for idx, zz_base in enumerate(dic_zzs[key]):
xx = float(xy_centers[idx][0]) * zz_base
yy = float(xy_centers[idx][1]) * zz_base
dic_xyz[key].append([xx, yy, zz_base])
return dic_xyz
def save_txts(path_txt, all_inputs, all_outputs, all_params, mode='monoloco', cat=None):
assert mode in ('monoloco', 'monstereo', 'geometric', 'baseline', 'monoloco_pp')
if mode in ('monstereo', 'monoloco_pp'):
xyzd, bis, epis, yaws, hs, ws, ls = all_outputs[:]
xyz = xyzd[:, 0:3]
tt = [0, 0, 0]
elif mode in ('monoloco', 'geometric'):
tt = [0, 0, 0]
dds, bis, epis, zzs_geom, xy_centers = all_outputs[:]
xyz = xyz_from_distance(dds, xy_centers)
else:
_, tt = all_params[:]
xyz, bis, epis, zzs_geom, xy_centers = all_outputs[:]
uv_boxes = all_inputs[:]
assert len(uv_boxes) == len(list(xyz)), "Number of inputs different from number of outputs"
with open(path_txt, "w+") as ff:
for idx, uv_box in enumerate(uv_boxes):
xx = float(xyz[idx][0]) - tt[0]
yy = float(xyz[idx][1]) - tt[1]
zz = float(xyz[idx][2]) - tt[2]
if mode == 'geometric':
zz = zzs_geom[idx]
cam_0 = [xx, yy, zz]
bi = float(bis[idx])
epi = float(epis[idx])
if mode in ('monstereo', 'monoloco_pp'):
alpha, ry = float(yaws[0][idx]), float(yaws[1][idx])
hwl = [float(hs[idx]), float(ws[idx]), float(ls[idx])]
else:
alpha, ry, hwl = -10., -10., [0, 0, 0]
# Set the scale to obtain (approximately) same recall at evaluation
if mode == 'monstereo':
conf_scale = 0.03
elif mode == 'monoloco_pp':
conf_scale = 0.033
else:
conf_scale = 0.055
conf = conf_scale * (uv_box[-1]) / (bi / math.sqrt(xx ** 2 + yy * 2 + zz ** 2))
output_list = [alpha] + uv_box[:-1] + hwl + cam_0 + [ry, conf, bi, epi]
category = cat[idx]
if category < 0.1:
ff.write("%s " % 'Pedestrian')
else:
ff.write("%s " % 'Cyclist')
ff.write("%i %i " % (-1, -1))
for el in output_list:
ff.write("%f " % el)
ff.write("\n")
def create_empty_files(dir_out):
"""Create empty txt files to run official kitti metrics on MonStereo and all other methods"""
methods = ['pseudo-lidar', 'monopsr', '3dop', 'm3d', 'oc-stereo', 'e2e']
methods = []
dirs = [os.path.join('data', 'kitti', method) for method in methods]
dirs_orig = [os.path.join('data', 'kitti', method + '-orig') for method in methods]
for di, di_orig in zip(dirs, dirs_orig):
make_new_directory(di)
for i in range(7481):
name = "0" * (6 - len(str(i))) + str(i) + '.txt'
path_orig = os.path.join(di_orig, name)
path = os.path.join(di, name)
# If the file exits, rewrite in new folder, otherwise create empty file
read_and_rewrite(path_orig, path)
for method in ('monoloco_pp', 'monstereo'):
for i in range(7481):
name = "0" * (6 - len(str(i))) + str(i) + '.txt'
ff = open(os.path.join(dir_out[method], name), "a+")
ff.close()

View File

@ -0,0 +1,110 @@
import torch
import torch.backends.cudnn as cudnn
from torch import nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as T
from ..utils import open_image
def get_reid_features(reid_net, boxes, boxes_r, path_image, path_image_r):
pil_image = open_image(path_image)
pil_image_r = open_image(path_image_r)
assert boxes and boxes_r
cropped_img = []
for box in boxes:
cropped_img = cropped_img + [pil_image.crop((box[0], box[1], box[2], box[3]))]
cropped_img_r = []
for box in boxes_r:
cropped_img_r = cropped_img_r + [pil_image_r.crop((box[0], box[1], box[2], box[3]))]
features = reid_net.forward(cropped_img)
features_r = reid_net.forward(cropped_img_r)
return features.cpu(), features_r.cpu()
class ReID(object):
def __init__(self, weights_path, device, num_classes=751, height=256, width=128):
super(ReID, self).__init__()
torch.manual_seed(1)
self.device = device
if self.device.type == "cuda":
cudnn.benchmark = True
torch.cuda.manual_seed_all(1)
else:
print("Currently using CPU (GPU is highly recommended)")
self.transform_test = T.Compose([
T.Resize((height, width)),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
print("ReID Baseline:")
print("Initializing ResNet model")
self.model = ResNet50(num_classes=num_classes, loss={'xent'})
self.model.to(device)
num_param = sum(p.numel() for p in self.model.parameters()) / 1e+06
print("Model size: {:.3f} M".format(num_param))
# load pretrained weights but ignore layers that don't match in size
checkpoint = torch.load(weights_path)
model_dict = self.model.state_dict()
pretrain_dict = {k: v for k, v in checkpoint.items() if k in model_dict and model_dict[k].size() == v.size()}
model_dict.update(pretrain_dict)
self.model.load_state_dict(model_dict)
print("Loaded pretrained weights from '{}'".format(weights_path))
self.model.eval()
def forward(self, images):
image = torch.stack([self.transform_test(image) for image in images], dim=0)
image = image.to(self.device)
with torch.no_grad():
features = self.model(image)
return features
@staticmethod
def calculate_distmat(features_1, features_2=None, use_cosine=False):
query = features_1
if features_2 is not None:
gallery = features_2
else:
gallery = features_1
m = query.size(0)
n = gallery.size(0)
if not use_cosine:
distmat = torch.pow(query, 2).sum(dim=1, keepdim=True).expand(m, n) + \
torch.pow(gallery, 2).sum(dim=1, keepdim=True).expand(n, m).t()
distmat.addmm_(1, -2, query, gallery.t())
else:
features_norm = query/query.norm(dim=1)[:, None]
reference_norm = gallery/gallery.norm(dim=1)[:, None]
distmat = torch.mm(features_norm, reference_norm.transpose(0, 1))
return distmat
class ResNet50(nn.Module):
def __init__(self, num_classes, loss):
super(ResNet50, self).__init__()
self.loss = loss
resnet50 = torchvision.models.resnet50(pretrained=True)
self.base = nn.Sequential(*list(resnet50.children())[:-2])
self.classifier = nn.Linear(2048, num_classes)
self.feat_dim = 2048
def forward(self, x):
x = self.base(x)
x = F.avg_pool2d(x, x.size()[2:])
f = x.view(x.size(0), -1)
if not self.training:
return f
y = self.classifier(f)
if self.loss == {'xent'}:
return y
return y, f

View File

@ -0,0 +1,103 @@
""""Generate stereo baselines for kitti evaluation"""
from collections import defaultdict
import numpy as np
from ..utils import get_keypoints, mask_joint_disparity, disparity_to_depth
def baselines_association(baselines, zzs, keypoints, keypoints_right, reid_features):
"""compute stereo depth for each of the given stereo baselines"""
# Initialize variables
zzs_stereo = defaultdict()
cnt_stereo = defaultdict(int)
features, features_r, keypoints, keypoints_r = factory_features(
keypoints, keypoints_right, baselines, reid_features)
# count maximum possible associations
cnt_stereo['max'] = min(keypoints.shape[0], keypoints_r.shape[0]) # pylint: disable=E1136
# Filter joints disparity and calculate avg disparity
avg_disparities, disparities_x, disparities_y = mask_joint_disparity(keypoints, keypoints_r)
# Iterate over each left pose
for key in baselines:
# Extract features of the baseline
similarity = features_similarity(features[key], features_r[key], key, avg_disparities, zzs)
# Compute the association based on features minimization and calculate depth
zzs_stereo[key] = np.empty((keypoints.shape[0]))
indices_stereo = [] # keep track of indices
best = np.nanmin(similarity)
while not np.isnan(best):
idx, arg_best = np.unravel_index(np.nanargmin(similarity), similarity.shape) # pylint: disable=W0632
zz_stereo, flag = disparity_to_depth(avg_disparities[idx, arg_best])
zz_mono = zzs[idx]
similarity[idx, :] = np.nan
indices_stereo.append(idx)
# Filter stereo depth
# if flag and verify_stereo(zz_stereo, zz_mono, disparities_x[idx, arg_best], disparities_y[idx, arg_best]):
if flag and (1 < zz_stereo < 80): # Do not add hand-crafted verifications to stereo baselines
zzs_stereo[key][idx] = zz_stereo
cnt_stereo[key] += 1
similarity[:, arg_best] = np.nan
else:
zzs_stereo[key][idx] = zz_mono
best = np.nanmin(similarity)
indices_mono = [idx for idx, _ in enumerate(zzs) if idx not in indices_stereo]
for idx in indices_mono:
zzs_stereo[key][idx] = zzs[idx]
zzs_stereo[key] = zzs_stereo[key].tolist()
return zzs_stereo, cnt_stereo
def factory_features(keypoints, keypoints_right, baselines, reid_features):
features = defaultdict()
features_r = defaultdict()
for key in baselines:
if key == 'reid':
features[key] = np.array(reid_features[0])
features_r[key] = np.array(reid_features[1])
else:
features[key] = np.array(keypoints)
features_r[key] = np.array(keypoints_right)
return features, features_r, np.array(keypoints), np.array(keypoints_right)
def features_similarity(features, features_r, key, avg_disparities, zzs):
similarity = np.empty((features.shape[0], features_r.shape[0]))
for idx, zz_mono in enumerate(zzs):
feature = features[idx]
if key == 'ml_stereo':
expected_disparity = 0.54 * 721. / zz_mono
sim_row = np.abs(expected_disparity - avg_disparities[idx])
elif key == 'pose':
# Zero-center the keypoints
uv_center = np.array(get_keypoints(feature, mode='center').reshape(-1, 1)) # (1, 2) --> (2, 1)
uv_centers_r = np.array(get_keypoints(features_r, mode='center').unsqueeze(-1)) # (m,2) --> (m, 2, 1)
feature_0 = feature[:2, :] - uv_center
feature_0 = feature_0.reshape(1, -1) # (1, 34)
features_r_0 = features_r[:, :2, :] - uv_centers_r
features_r_0 = features_r_0.reshape(features_r_0.shape[0], -1) # (m, 34)
sim_row = np.linalg.norm(feature_0 - features_r_0, axis=1)
else:
sim_row = np.linalg.norm(feature - features_r, axis=1)
similarity[idx] = sim_row
return similarity

View File

@ -0,0 +1,4 @@
from .net import Loco
from .pifpaf import PifPaf, ImageList
from .process import unnormalize_bi, extract_outputs, extract_labels, extract_labels_aux

View File

@ -0,0 +1,434 @@
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self, input_size, output_size=2, linear_size=512, p_dropout=0.2, num_stage=3, device='cuda'):
super(SimpleModel, self).__init__()
self.num_stage = num_stage
self.stereo_size = input_size
self.mono_size = int(input_size / 2)
self.output_size = output_size - 1
self.linear_size = linear_size
self.p_dropout = p_dropout
self.num_stage = num_stage
self.linear_stages = []
self.device = device
# Initialize weights
# Preprocessing
self.w1 = nn.Linear(self.stereo_size, self.linear_size)
self.batch_norm1 = nn.BatchNorm1d(self.linear_size)
# Internal loop
for _ in range(num_stage):
self.linear_stages.append(MyLinearSimple(self.linear_size, self.p_dropout))
self.linear_stages = nn.ModuleList(self.linear_stages)
# Post processing
self.w2 = nn.Linear(self.linear_size, self.linear_size)
self.w3 = nn.Linear(self.linear_size, self.linear_size)
self.batch_norm3 = nn.BatchNorm1d(self.linear_size)
# ------------------------Other----------------------------------------------
# Auxiliary
self.w_aux = nn.Linear(self.linear_size, 1)
# Final
self.w_fin = nn.Linear(self.linear_size, self.output_size)
# NO-weight operations
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(self.p_dropout)
def forward(self, x):
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
for i in range(self.num_stage):
y = self.linear_stages[i](y)
# Auxiliary task
y = self.w2(y)
aux = self.w_aux(y)
# Final layers
y = self.w3(y)
y = self.batch_norm3(y)
y = self.relu(y)
y = self.dropout(y)
y = self.w_fin(y)
# Cat with auxiliary task
y = torch.cat((y, aux), dim=1)
return y
class MyLinearSimple(nn.Module):
def __init__(self, linear_size, p_dropout=0.5):
super(MyLinearSimple, self).__init__()
self.l_size = linear_size
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p_dropout)
self.w1 = nn.Linear(self.l_size, self.l_size)
self.batch_norm1 = nn.BatchNorm1d(self.l_size)
self.w2 = nn.Linear(self.l_size, self.l_size)
self.batch_norm2 = nn.BatchNorm1d(self.l_size)
def forward(self, x):
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
y = self.w2(y)
y = self.batch_norm2(y)
y = self.relu(y)
y = self.dropout(y)
out = x + y
return out
class DecisionModel(nn.Module):
def __init__(self, input_size, output_size=2, linear_size=512, p_dropout=0.2, num_stage=3, device='cuda:1'):
super(DecisionModel, self).__init__()
self.num_stage = num_stage
self.stereo_size = input_size
self.mono_size = int(input_size / 2)
self.output_size = output_size - 1
self.linear_size = linear_size
self.p_dropout = p_dropout
self.num_stage = num_stage
self.linear_stages_mono, self.linear_stages_stereo, self.linear_stages_dec = [], [], []
self.device = device
# Initialize weights
# ------------------------Stereo----------------------------------------------
# Preprocessing
self.w1_stereo = nn.Linear(self.stereo_size, self.linear_size)
self.batch_norm_stereo = nn.BatchNorm1d(self.linear_size)
# Internal loop
for _ in range(num_stage):
self.linear_stages_stereo.append(MyLinear_stereo(self.linear_size, self.p_dropout))
self.linear_stages_stereo = nn.ModuleList(self.linear_stages_stereo)
# Post processing
self.w2_stereo = nn.Linear(self.linear_size, self.output_size)
# ------------------------Mono----------------------------------------------
# Preprocessing
self.w1_mono = nn.Linear(self.mono_size, self.linear_size)
self.batch_norm_mono = nn.BatchNorm1d(self.linear_size)
# Internal loop
for _ in range(num_stage):
self.linear_stages_mono.append(MyLinear_stereo(self.linear_size, self.p_dropout))
self.linear_stages_mono = nn.ModuleList(self.linear_stages_mono)
# Post processing
self.w2_mono = nn.Linear(self.linear_size, self.output_size)
# ------------------------Decision----------------------------------------------
# Preprocessing
self.w1_dec = nn.Linear(self.stereo_size, self.linear_size)
self.batch_norm_dec = nn.BatchNorm1d(self.linear_size)
#
# Internal loop
for _ in range(num_stage):
self.linear_stages_dec.append(MyLinear(self.linear_size, self.p_dropout))
self.linear_stages_dec = nn.ModuleList(self.linear_stages_dec)
# Post processing
self.w2_dec = nn.Linear(self.linear_size, 1)
# ------------------------Other----------------------------------------------
# NO-weight operations
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(self.p_dropout)
def forward(self, x, label=None):
# Mono
y_m = self.w1_mono(x[:, 0:34])
y_m = self.batch_norm_mono(y_m)
y_m = self.relu(y_m)
y_m = self.dropout(y_m)
for i in range(self.num_stage):
y_m = self.linear_stages_mono[i](y_m)
y_m = self.w2_mono(y_m)
# Stereo
y_s = self.w1_stereo(x)
y_s = self.batch_norm_stereo(y_s)
y_s = self.relu(y_s)
y_s = self.dropout(y_s)
for i in range(self.num_stage):
y_s = self.linear_stages_stereo[i](y_s)
y_s = self.w2_stereo(y_s)
# Decision
y_d = self.w1_dec(x)
y_d = self.batch_norm_dec(y_d)
y_d = self.relu(y_d)
y_d = self.dropout(y_d)
for i in range(self.num_stage):
y_d = self.linear_stages_dec[i](y_d)
aux = self.w2_dec(y_d)
# Combine
if label is not None:
gate = label
else:
gate = torch.where(torch.sigmoid(aux) > 0.3,
torch.tensor([1.]).to(self.device), torch.tensor([0.]).to(self.device))
y = gate * y_s + (1-gate) * y_m
# Cat with auxiliary task
y = torch.cat((y, aux), dim=1)
return y
class AttentionModel(nn.Module):
def __init__(self, input_size, output_size=2, linear_size=512, p_dropout=0.2, num_stage=3, device='cuda'):
super(AttentionModel, self).__init__()
self.num_stage = num_stage
self.stereo_size = input_size
self.mono_size = int(input_size / 2)
self.output_size = output_size - 1
self.linear_size = linear_size
self.p_dropout = p_dropout
self.num_stage = num_stage
self.linear_stages_mono, self.linear_stages_stereo, self.linear_stages_comb = [], [], []
self.device = device
# Initialize weights
# ------------------------Stereo----------------------------------------------
# Preprocessing
self.w1_stereo = nn.Linear(self.stereo_size, self.linear_size)
self.batch_norm_stereo = nn.BatchNorm1d(self.linear_size)
# Internal loop
for _ in range(num_stage):
self.linear_stages_stereo.append(MyLinear_stereo(self.linear_size, self.p_dropout))
self.linear_stages_stereo = nn.ModuleList(self.linear_stages_stereo)
# Post processing
self.w2_stereo = nn.Linear(self.linear_size, self.linear_size)
# ------------------------Mono----------------------------------------------
# Preprocessing
self.w1_mono = nn.Linear(self.mono_size, self.linear_size)
self.batch_norm_mono = nn.BatchNorm1d(self.linear_size)
# Internal loop
for _ in range(num_stage):
self.linear_stages_mono.append(MyLinear_stereo(self.linear_size, self.p_dropout))
self.linear_stages_mono = nn.ModuleList(self.linear_stages_mono)
# Post processing
self.w2_mono = nn.Linear(self.linear_size, self.linear_size)
# ------------------------Combined----------------------------------------------
# Preprocessing
self.w1_comb = nn.Linear(self.linear_size, self.linear_size)
self.batch_norm_comb = nn.BatchNorm1d(self.linear_size)
#
# Internal loop
for _ in range(num_stage):
self.linear_stages_comb.append(MyLinear(self.linear_size, self.p_dropout))
self.linear_stages_comb = nn.ModuleList(self.linear_stages_comb)
# Post processing
self.w2_comb = nn.Linear(self.linear_size, self.linear_size)
# ------------------------Other----------------------------------------------
# Auxiliary
self.w_aux = nn.Linear(self.linear_size, 1)
# Final
self.w_fin = nn.Linear(self.linear_size, self.output_size)
# NO-weight operations
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(self.p_dropout)
def forward(self, x, label=None):
# Mono
y_m = self.w1_mono(x[:, 0:34])
y_m = self.batch_norm_mono(y_m)
y_m = self.relu(y_m)
y_m = self.dropout(y_m)
for i in range(self.num_stage):
y_m = self.linear_stages_mono[i](y_m)
y_m = self.w2_mono(y_m)
# Stereo
y_s = self.w1_stereo(x)
y_s = self.batch_norm_stereo(y_s)
y_s = self.relu(y_s)
y_s = self.dropout(y_s)
for i in range(self.num_stage):
y_s = self.linear_stages_stereo[i](y_s)
y_s = self.w2_stereo(y_s)
# Auxiliary task
aux = self.w_aux(y_s)
# Combined
if label is not None:
gate = label
else:
gate = torch.where(torch.sigmoid(aux) > 0.3,
torch.tensor([1.]).to(self.device), torch.tensor([0.]).to(self.device))
y_c = gate * y_s + (1-gate) * y_m
y_c = self.w1_comb(y_c)
y_c = self.batch_norm_comb(y_c)
y_c = self.relu(y_c)
y_c = self.dropout(y_c)
y_c = self.w_fin(y_c)
# Cat with auxiliary task
y = torch.cat((y_c, aux), dim=1)
return y
class MyLinear_stereo(nn.Module):
def __init__(self, linear_size, p_dropout=0.5):
super(MyLinear_stereo, self).__init__()
self.l_size = linear_size
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p_dropout)
# self.w0_a = nn.Linear(self.l_size, self.l_size)
# self.batch_norm0_a = nn.BatchNorm1d(self.l_size)
# self.w0_b = nn.Linear(self.l_size, self.l_size)
# self.batch_norm0_b = nn.BatchNorm1d(self.l_size)
self.w1 = nn.Linear(self.l_size, self.l_size)
self.batch_norm1 = nn.BatchNorm1d(self.l_size)
self.w2 = nn.Linear(self.l_size, self.l_size)
self.batch_norm2 = nn.BatchNorm1d(self.l_size)
def forward(self, x):
#
# x = self.w0_a(x)
# x = self.batch_norm0_a(x)
# x = self.w0_b(x)
# x = self.batch_norm0_b(x)
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
y = self.w2(y)
y = self.batch_norm2(y)
y = self.relu(y)
y = self.dropout(y)
out = x + y
return out
class MonolocoModel(nn.Module):
"""
Architecture inspired by https://github.com/una-dinosauria/3d-pose-baseline
Pytorch implementation from: https://github.com/weigq/3d_pose_baseline_pytorch
"""
def __init__(self, input_size, output_size=2, linear_size=256, p_dropout=0.2, num_stage=3):
super(MonolocoModel, self).__init__()
self.input_size = input_size
self.output_size = output_size
self.linear_size = linear_size
self.p_dropout = p_dropout
self.num_stage = num_stage
# process input to linear size
self.w1 = nn.Linear(self.input_size, self.linear_size)
self.batch_norm1 = nn.BatchNorm1d(self.linear_size)
self.linear_stages = []
for _ in range(num_stage):
self.linear_stages.append(MyLinear(self.linear_size, self.p_dropout))
self.linear_stages = nn.ModuleList(self.linear_stages)
# post processing
self.w2 = nn.Linear(self.linear_size, self.output_size)
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(self.p_dropout)
def forward(self, x):
# pre-processing
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
# linear layers
for i in range(self.num_stage):
y = self.linear_stages[i](y)
y = self.w2(y)
return y
class MyLinear(nn.Module):
def __init__(self, linear_size, p_dropout=0.5):
super(MyLinear, self).__init__()
self.l_size = linear_size
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p_dropout)
self.w1 = nn.Linear(self.l_size, self.l_size)
self.batch_norm1 = nn.BatchNorm1d(self.l_size)
self.w2 = nn.Linear(self.l_size, self.l_size)
self.batch_norm2 = nn.BatchNorm1d(self.l_size)
def forward(self, x):
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
y = self.w2(y)
y = self.batch_norm2(y)
y = self.relu(y)
y = self.dropout(y)
out = x + y
return out

View File

@ -0,0 +1,213 @@
import json
import logging
import math
from collections import defaultdict
import numpy as np
from monstereo.utils import pixel_to_camera, get_keypoints
AVERAGE_Y = 0.48
CLUSTERS = ['10', '20', '30', 'all']
def geometric_coordinates(keypoints, kk, average_y=0.48):
""" Evaluate geometric depths for a set of keypoints"""
zzs_geom = []
uv_shoulders = get_keypoints(keypoints, mode='shoulder')
uv_hips = get_keypoints(keypoints, mode='hip')
uv_centers = get_keypoints(keypoints, mode='center')
xy_shoulders = pixel_to_camera(uv_shoulders, kk, 1)
xy_hips = pixel_to_camera(uv_hips, kk, 1)
xy_centers = pixel_to_camera(uv_centers, kk, 1)
for idx, xy_shoulder in enumerate(xy_shoulders):
zz = compute_depth(xy_shoulders[idx], xy_hips[idx], average_y)
zzs_geom.append(zz)
return zzs_geom, xy_centers
def geometric_baseline(joints):
"""
List of json files --> 2 lists with mean and std for each segment and the total count of instances
For each annotation:
1. From gt boxes calculate the height (deltaY) for the segments head, shoulder, hip, ankle
2. From mask boxes calculate distance of people using average height of people and real pixel height
For left-right ambiguities we chose always the average of the joints
The joints are mapped from 0 to 16 in the following order:
['nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow',
'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle',
'right_ankle']
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
cnt_tot = 0
dic_dist = defaultdict(lambda: defaultdict(list))
# Access the joints file
with open(joints, 'r') as ff:
dic_joints = json.load(ff)
# Calculate distances for all the instances in the joints dictionary
for phase in ['train', 'val']:
cnt = update_distances(dic_joints[phase], dic_dist, phase, AVERAGE_Y)
cnt_tot += cnt
# Calculate mean and std of each segment
dic_h_means = calculate_heights(dic_dist['heights'], mode='mean')
dic_h_stds = calculate_heights(dic_dist['heights'], mode='std')
errors = calculate_error(dic_dist['error'])
# Show results
logger.info("Computed distance of {} annotations".format(cnt_tot))
for key in dic_h_means:
logger.info("Average height of segment {} is {:.2f} with a std of {:.2f}".
format(key, dic_h_means[key], dic_h_stds[key]))
for clst in CLUSTERS:
logger.info("Average error over the val set for clst {}: {:.2f}".format(clst, errors[clst]))
logger.info("Joints used: {}".format(joints))
def update_distances(dic_fin, dic_dist, phase, average_y):
# Loop over each annotation in the json file corresponding to the image
cnt = 0
for idx, kps in enumerate(dic_fin['kps']):
# Extract pixel coordinates of head, shoulder, hip, ankle and and save them
dic_uv = {mode: get_keypoints(kps, mode) for mode in ['head', 'shoulder', 'hip', 'ankle']}
# Convert segments from pixel coordinate to camera coordinate
kk = dic_fin['K'][idx]
z_met = dic_fin['boxes_3d'][idx][2]
# Create a dict with all annotations in meters
dic_xyz = {key: pixel_to_camera(dic_uv[key], kk, z_met) for key in dic_uv}
dic_xyz_norm = {key: pixel_to_camera(dic_uv[key], kk, 1) for key in dic_uv}
# Compute real height
dy_met = abs(float((dic_xyz['hip'][0][1] - dic_xyz['shoulder'][0][1])))
# Estimate distance for a single annotation
z_met_real = compute_depth(dic_xyz_norm['shoulder'][0], dic_xyz_norm['hip'][0], average_y,
mode='real', dy_met=dy_met)
z_met_approx = compute_depth(dic_xyz_norm['shoulder'][0], dic_xyz_norm['hip'][0], average_y, mode='average')
# Compute distance with respect to the center of the 3D bounding box
d_real = math.sqrt(z_met_real ** 2 + dic_fin['boxes_3d'][idx][0] ** 2 + dic_fin['boxes_3d'][idx][1] ** 2)
d_approx = math.sqrt(z_met_approx ** 2 +
dic_fin['boxes_3d'][idx][0] ** 2 + dic_fin['boxes_3d'][idx][1] ** 2)
# Update the dictionary with distance and heights metrics
dic_dist = update_dic_dist(dic_dist, dic_xyz, d_real, d_approx, phase)
cnt += 1
return cnt
def compute_depth(xyz_norm_1, xyz_norm_2, average_y, mode='average', dy_met=0):
"""
Compute depth Z of a mask annotation (solving a linear system) for 2 possible cases:
1. knowing specific height of the annotation (head-ankle) dy_met
2. using mean height of people (average_y)
"""
assert mode in ('average', 'real')
x1 = float(xyz_norm_1[0])
y1 = float(xyz_norm_1[1])
x2 = float(xyz_norm_2[0])
y2 = float(xyz_norm_2[1])
xx = (x1 + x2) / 2
# Choose if solving for provided height or average one.
if mode == 'average':
cc = - average_y # Y axis goes down
else:
cc = -dy_met
# Solving the linear system Ax = b
matrix = np.array([[y1, 0, -xx],
[0, -y1, 1],
[y2, 0, -xx],
[0, -y2, 1]])
bb = np.array([cc * xx, -cc, 0, 0]).reshape(4, 1)
xx = np.linalg.lstsq(matrix, bb, rcond=None)
z_met = abs(np.float(xx[0][1])) # Abs take into account specularity behind the observer
return z_met
def update_dic_dist(dic_dist, dic_xyz, d_real, d_approx, phase):
""" For every annotation in a single image, update the final dictionary"""
# Update the dict with heights metric
if phase == 'train':
dic_dist['heights']['head'].append(float(dic_xyz['head'][0][1]))
dic_dist['heights']['shoulder'].append(float(dic_xyz['shoulder'][0][1]))
dic_dist['heights']['hip'].append(float(dic_xyz['hip'][0][1]))
dic_dist['heights']['ankle'].append(float(dic_xyz['ankle'][0][1]))
# Update the dict with distance metrics for the test phase
if phase == 'val':
error = abs(d_real - d_approx)
if d_real <= 10:
dic_dist['error']['10'].append(error)
elif d_real <= 20:
dic_dist['error']['20'].append(error)
elif d_real <= 30:
dic_dist['error']['30'].append(error)
else:
dic_dist['error']['>30'].append(error)
dic_dist['error']['all'].append(error)
return dic_dist
def calculate_heights(heights, mode):
"""
Compute statistics of heights based on the distance
"""
assert mode in ('mean', 'std', 'max')
heights_fin = {}
head_shoulder = np.array(heights['shoulder']) - np.array(heights['head'])
shoulder_hip = np.array(heights['hip']) - np.array(heights['shoulder'])
hip_ankle = np.array(heights['ankle']) - np.array(heights['hip'])
if mode == 'mean':
heights_fin['head_shoulder'] = np.float(np.mean(head_shoulder)) * 100
heights_fin['shoulder_hip'] = np.float(np.mean(shoulder_hip)) * 100
heights_fin['hip_ankle'] = np.float(np.mean(hip_ankle)) * 100
elif mode == 'std':
heights_fin['head_shoulder'] = np.float(np.std(head_shoulder)) * 100
heights_fin['shoulder_hip'] = np.float(np.std(shoulder_hip)) * 100
heights_fin['hip_ankle'] = np.float(np.std(hip_ankle)) * 100
elif mode == 'max':
heights_fin['head_shoulder'] = np.float(np.max(head_shoulder)) * 100
heights_fin['shoulder_hip'] = np.float(np.max(shoulder_hip)) * 100
heights_fin['hip_ankle'] = np.float(np.max(hip_ankle)) * 100
return heights_fin
def calculate_error(dic_errors):
"""
Compute statistics of distances based on the distance
"""
errors = {}
for clst in dic_errors:
errors[clst] = np.float(np.mean(np.array(dic_errors[clst])))
return errors

253
monstereo/network/net.py Normal file
View File

@ -0,0 +1,253 @@
# pylint: disable=too-many-statements
"""
Loco super class for MonStereo, MonoLoco, MonoLoco++ nets.
From 2D joints to real-world distances with monocular &/or stereo cameras
"""
import math
import logging
from collections import defaultdict
import torch
from ..utils import get_iou_matches, reorder_matches, get_keypoints, pixel_to_camera, xyz_from_distance
from .process import preprocess_monstereo, preprocess_monoloco, extract_outputs, extract_outputs_mono,\
filter_outputs, cluster_outputs, unnormalize_bi
from .architectures import MonolocoModel, SimpleModel
class Loco:
"""Class for both MonoLoco and MonStereo"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
LINEAR_SIZE_MONO = 256
N_SAMPLES = 100
def __init__(self, model, net='monstereo', device=None, n_dropout=0, p_dropout=0.2, linear_size=1024):
self.net = net
assert self.net in ('monstereo', 'monoloco', 'monoloco_p', 'monoloco_pp')
if self.net == 'monstereo':
input_size = 68
output_size = 10
elif self.net == 'monoloco_p':
input_size = 34
output_size = 9
linear_size = 256
elif self.net == 'monoloco_pp':
input_size = 34
output_size = 9
else:
input_size = 34
output_size = 2
if not device:
self.device = torch.device('cpu')
else:
self.device = device
self.n_dropout = n_dropout
self.epistemic = bool(self.n_dropout > 0)
# if the path is provided load the model parameters
if isinstance(model, str):
model_path = model
if net in ('monoloco', 'monoloco_p'):
self.model = MonolocoModel(p_dropout=p_dropout, input_size=input_size, linear_size=linear_size,
output_size=output_size)
else:
self.model = SimpleModel(p_dropout=p_dropout, input_size=input_size, output_size=output_size,
linear_size=linear_size, device=self.device)
self.model.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage))
else:
self.model = model
self.model.eval() # Default is train
self.model.to(self.device)
def forward(self, keypoints, kk, keypoints_r=None):
"""
Forward pass of MonSter or monoloco network
It includes preprocessing and postprocessing of data
"""
if not keypoints:
return None
with torch.no_grad():
keypoints = torch.tensor(keypoints).to(self.device)
kk = torch.tensor(kk).to(self.device)
if self.net == 'monoloco':
inputs = preprocess_monoloco(keypoints, kk, zero_center=True)
outputs = self.model(inputs)
bi = unnormalize_bi(outputs)
dic_out = {'d': outputs[:, 0:1], 'bi': bi}
dic_out = {key: el.detach().cpu() for key, el in dic_out.items()}
elif self.net == 'monoloco_p':
inputs = preprocess_monoloco(keypoints, kk)
outputs = self.model(inputs)
dic_out = extract_outputs_mono(outputs)
elif self.net == 'monoloco_pp':
inputs = preprocess_monoloco(keypoints, kk)
outputs = self.model(inputs)
dic_out = extract_outputs(outputs)
else:
if keypoints_r:
keypoints_r = torch.tensor(keypoints_r).to(self.device)
else:
keypoints_r = keypoints[0:1, :].clone()
inputs, _ = preprocess_monstereo(keypoints, keypoints_r, kk)
outputs = self.model(inputs)
outputs = cluster_outputs(outputs, keypoints_r.shape[0])
outputs_fin, mask = filter_outputs(outputs)
dic_out = extract_outputs(outputs_fin)
# For Median baseline
# dic_out = median_disparity(dic_out, keypoints, keypoints_r, mask)
if self.n_dropout > 0 and self.net != 'monstereo':
varss = self.epistemic_uncertainty(inputs)
dic_out['epi'] = varss
else:
dic_out['epi'] = [0.] * outputs.shape[0]
# Add in the dictionary
return dic_out
def epistemic_uncertainty(self, inputs):
"""
Apply dropout at test time to obtain combined aleatoric + epistemic uncertainty
"""
assert self.net in ('monoloco', 'monoloco_p', 'monoloco_pp'), "Not supported for MonStereo"
from .process import laplace_sampling
self.model.dropout.training = True # Manually reactivate dropout in eval
total_outputs = torch.empty((0, inputs.size()[0])).to(self.device)
for _ in range(self.n_dropout):
outputs = self.model(inputs)
# Extract localization output
if self.net == 'monoloco':
db = outputs[:, 0:2]
else:
db = outputs[:, 2:4]
# Unnormalize b and concatenate
bi = unnormalize_bi(db)
outputs = torch.cat((db[:, 0:1], bi), dim=1)
samples = laplace_sampling(outputs, self.N_SAMPLES)
total_outputs = torch.cat((total_outputs, samples), 0)
varss = total_outputs.std(0)
self.model.dropout.training = False
return varss
@staticmethod
def post_process(dic_in, boxes, keypoints, kk, dic_gt=None, iou_min=0.3, reorder=True, verbose=False):
"""Post process monoloco to output final dictionary with all information for visualizations"""
dic_out = defaultdict(list)
if dic_in is None:
return dic_out
if dic_gt:
boxes_gt = dic_gt['boxes']
dds_gt = [el[3] for el in dic_gt['ys']]
matches = get_iou_matches(boxes, boxes_gt, iou_min=iou_min)
dic_out['gt'] = [True]
if verbose:
print("found {} matches with ground-truth".format(len(matches)))
# Keep track of instances non-matched
idxs_matches = (el[0] for el in matches)
not_matches = [idx for idx, _ in enumerate(boxes) if idx not in idxs_matches]
else:
matches = []
not_matches = list(range(len(boxes)))
if verbose:
print("NO ground-truth associated")
if reorder:
matches = reorder_matches(matches, boxes, mode='left_right')
all_idxs = [idx for idx, _ in matches] + not_matches
dic_out['gt'] = [True]*len(matches) + [False]*len(not_matches)
uv_shoulders = get_keypoints(keypoints, mode='shoulder')
uv_heads = get_keypoints(keypoints, mode='head')
uv_centers = get_keypoints(keypoints, mode='center')
xy_centers = pixel_to_camera(uv_centers, kk, 1)
# Add all the predicted annotations, starting with the ones that match a ground-truth
for idx in all_idxs:
kps = keypoints[idx]
box = boxes[idx]
dd_pred = float(dic_in['d'][idx])
bi = float(dic_in['bi'][idx])
var_y = float(dic_in['epi'][idx])
uu_s, vv_s = uv_shoulders.tolist()[idx][0:2]
uu_c, vv_c = uv_centers.tolist()[idx][0:2]
uu_h, vv_h = uv_heads.tolist()[idx][0:2]
uv_shoulder = [round(uu_s), round(vv_s)]
uv_center = [round(uu_c), round(vv_c)]
uv_head = [round(uu_h), round(vv_h)]
xyz_pred = xyz_from_distance(dd_pred, xy_centers[idx])[0]
distance = math.sqrt(float(xyz_pred[0])**2 + float(xyz_pred[1])**2 + float(xyz_pred[2])**2)
conf = 0.035 * (box[-1]) / (bi / distance)
dic_out['boxes'].append(box)
dic_out['confs'].append(conf)
dic_out['dds_pred'].append(dd_pred)
dic_out['stds_ale'].append(bi)
dic_out['stds_epi'].append(var_y)
dic_out['xyz_pred'].append(xyz_pred.squeeze().tolist())
dic_out['uv_kps'].append(kps)
dic_out['uv_centers'].append(uv_center)
dic_out['uv_shoulders'].append(uv_shoulder)
dic_out['uv_heads'].append(uv_head)
# Only for MonStereo
try:
angle = float(dic_in['yaw'][0][idx]) # Predicted angle
dic_out['angles'].append(angle)
dic_out['aux'].append(float(dic_in['aux'][idx]))
except KeyError:
continue
for idx, idx_gt in matches:
dd_real = dds_gt[idx_gt]
xyz_real = xyz_from_distance(dd_real, xy_centers[idx])
dic_out['dds_real'].append(dd_real)
dic_out['boxes_gt'].append(boxes_gt[idx_gt])
dic_out['xyz_real'].append(xyz_real.squeeze().tolist())
return dic_out
def median_disparity(dic_out, keypoints, keypoints_r, mask):
"""
Ablation study: whenever a matching is found, compute depth by median disparity instead of using MonSter
Filters are applied to masks nan joints and remove outlier disparities with iqr
The mask input is used to filter the all-vs-all approach
"""
import numpy as np
from ..utils import mask_joint_disparity
keypoints = keypoints.cpu().numpy()
keypoints_r = keypoints_r.cpu().numpy()
mask = mask.cpu().numpy()
avg_disparities, _, _ = mask_joint_disparity(keypoints, keypoints_r)
BF = 0.54 * 721
for idx, aux in enumerate(dic_out['aux']):
if aux > 0.5:
idx_r = np.argmax(mask[idx])
z = BF / avg_disparities[idx][idx_r]
if 1 < z < 80:
dic_out['xyzd'][idx][2] = z
dic_out['xyzd'][idx][3] = torch.norm(dic_out['xyzd'][idx][0:3])
return dic_out

102
monstereo/network/pifpaf.py Normal file
View File

@ -0,0 +1,102 @@
import glob
import numpy as np
import torchvision
import torch
from PIL import Image, ImageFile
from openpifpaf.network import nets
from openpifpaf import decoder
from .process import image_transform
class ImageList(torch.utils.data.Dataset):
"""It defines transformations to apply to images and outputs of the dataloader"""
def __init__(self, image_paths, scale):
self.image_paths = image_paths
self.image_paths.sort()
self.scale = scale
def __getitem__(self, index):
image_path = self.image_paths[index]
ImageFile.LOAD_TRUNCATED_IMAGES = True
with open(image_path, 'rb') as f:
image = Image.open(f).convert('RGB')
if self.scale > 1.01 or self.scale < 0.99:
image = torchvision.transforms.functional.resize(image,
(round(self.scale * image.size[1]),
round(self.scale * image.size[0])),
interpolation=Image.BICUBIC)
# PIL images are not iterables
original_image = torchvision.transforms.functional.to_tensor(image) # 0-255 --> 0-1
image = image_transform(image)
return image_path, original_image, image
def __len__(self):
return len(self.image_paths)
def factory_from_args(args):
# Merge the model_pifpaf argument
if not args.checkpoint:
args.checkpoint = 'resnet152' # Default model Resnet 152
# glob
if args.glob:
args.images += glob.glob(args.glob)
if not args.images:
raise Exception("no image files given")
# add args.device
args.device = torch.device('cpu')
args.pin_memory = False
if torch.cuda.is_available():
args.device = torch.device('cuda')
args.pin_memory = True
# Add num_workers
args.loader_workers = 8
# Add visualization defaults
args.figure_width = 10
args.dpi_factor = 1.0
return args
class PifPaf:
def __init__(self, args):
"""Instanciate the mdodel"""
factory_from_args(args)
model_pifpaf, _ = nets.factory_from_args(args)
model_pifpaf = model_pifpaf.to(args.device)
self.processor = decoder.factory_from_args(args, model_pifpaf)
self.keypoints_whole = []
# Scale the keypoints to the original image size for printing (if not webcam)
self.scale_np = np.array([args.scale, args.scale, 1] * 17).reshape(17, 3)
def fields(self, processed_images):
"""Encoder for pif and paf fields"""
fields_batch = self.processor.fields(processed_images)
return fields_batch
def forward(self, image, processed_image_cpu, fields):
"""Decoder, from pif and paf fields to keypoints"""
self.processor.set_cpu_image(image, processed_image_cpu)
keypoint_sets, scores = self.processor.keypoint_sets(fields)
if keypoint_sets.size > 0:
self.keypoints_whole.append(np.around((keypoint_sets / self.scale_np), 1)
.reshape(keypoint_sets.shape[0], -1).tolist())
pifpaf_out = [
{'keypoints': np.around(kps / self.scale_np, 1).reshape(-1).tolist(),
'bbox': [np.min(kps[:, 0]) / self.scale_np[0, 0], np.min(kps[:, 1]) / self.scale_np[0, 0],
np.max(kps[:, 0]) / self.scale_np[0, 0], np.max(kps[:, 1]) / self.scale_np[0, 0]]}
for kps in keypoint_sets
]
return keypoint_sets, scores, pifpaf_out

View File

@ -0,0 +1,360 @@
import json
import os
import numpy as np
import torch
import torchvision
from ..utils import get_keypoints, pixel_to_camera, to_cartesian, back_correct_angles
BF = 0.54 * 721
z_min = 4
z_max = 60
D_MIN = BF / z_max
D_MAX = BF / z_min
def preprocess_monstereo(keypoints, keypoints_r, kk):
"""
Combine left and right keypoints in all-vs-all settings
"""
clusters = []
inputs_l = preprocess_monoloco(keypoints, kk)
inputs_r = preprocess_monoloco(keypoints_r, kk)
inputs = torch.empty((0, 68)).to(inputs_l.device)
for idx, inp_l in enumerate(inputs_l.split(1)):
clst = 0
# inp_l = torch.cat((inp_l, cat[:, idx:idx+1]), dim=1)
for idx_r, inp_r in enumerate(inputs_r.split(1)):
# if D_MIN < avg_disparities[idx_r] < D_MAX: # Check the range of disparities
inp_r = inputs_r[idx_r, :]
inp = torch.cat((inp_l, inp_l - inp_r), dim=1) # (1,68)
inputs = torch.cat((inputs, inp), dim=0)
clst += 1
clusters.append(clst)
return inputs, clusters
def preprocess_monoloco(keypoints, kk, zero_center=False):
""" Preprocess batches of inputs
keypoints = torch tensors of (m, 3, 17) or list [3,17]
Outputs = torch tensors of (m, 34) in meters normalized (z=1) and zero-centered using the center of the box
"""
if isinstance(keypoints, list):
keypoints = torch.tensor(keypoints)
if isinstance(kk, list):
kk = torch.tensor(kk)
# Projection in normalized image coordinates and zero-center with the center of the bounding box
uv_center = get_keypoints(keypoints, mode='center')
xy1_center = pixel_to_camera(uv_center, kk, 10)
xy1_all = pixel_to_camera(keypoints[:, 0:2, :], kk, 10)
if zero_center:
kps_norm = xy1_all - xy1_center.unsqueeze(1) # (m, 17, 3) - (m, 1, 3)
else:
kps_norm = xy1_all
kps_out = kps_norm[:, :, 0:2].reshape(kps_norm.size()[0], -1) # no contiguous for view
# kps_out = torch.cat((kps_out, keypoints[:, 2, :]), dim=1)
return kps_out
def factory_for_gt(im_size, name=None, path_gt=None, verbose=True):
"""Look for ground-truth annotations file and define calibration matrix based on image size """
try:
with open(path_gt, 'r') as f:
dic_names = json.load(f)
if verbose:
print('-' * 120 + "\nGround-truth file opened")
except (FileNotFoundError, TypeError):
if verbose:
print('-' * 120 + "\nGround-truth file not found")
dic_names = {}
try:
kk = dic_names[name]['K']
dic_gt = dic_names[name]
if verbose:
print("Matched ground-truth file!")
except KeyError:
dic_gt = None
x_factor = im_size[0] / 1600
y_factor = im_size[1] / 900
pixel_factor = (x_factor + y_factor) / 2 # 1.7 for MOT
# pixel_factor = 1
if im_size[0] / im_size[1] > 2.5:
kk = [[718.3351, 0., 600.3891], [0., 718.3351, 181.5122], [0., 0., 1.]] # Kitti calibration
else:
kk = [[1266.4 * pixel_factor, 0., 816.27 * x_factor],
[0, 1266.4 * pixel_factor, 491.5 * y_factor],
[0., 0., 1.]] # nuScenes calibration
if verbose:
print("Using a standard calibration matrix...")
return kk, dic_gt
def laplace_sampling(outputs, n_samples):
torch.manual_seed(1)
mu = outputs[:, 0]
bi = torch.abs(outputs[:, 1])
# Analytical
# uu = np.random.uniform(low=-0.5, high=0.5, size=mu.shape[0])
# xx = mu - bi * np.sign(uu) * np.log(1 - 2 * np.abs(uu))
# Sampling
cuda_check = outputs.is_cuda
if cuda_check:
get_device = outputs.get_device()
device = torch.device(type="cuda", index=get_device)
else:
device = torch.device("cpu")
laplace = torch.distributions.Laplace(mu, bi)
xx = laplace.sample((n_samples,)).to(device)
return xx
def unnormalize_bi(loc):
"""
Unnormalize relative bi of a nunmpy array
Input --> tensor of (m, 2)
"""
assert loc.size()[1] == 2, "size of the output tensor should be (m, 2)"
bi = torch.exp(loc[:, 1:2]) * loc[:, 0:1]
return bi
def preprocess_mask(dir_ann, basename, mode='left'):
dir_ann = os.path.join(os.path.split(dir_ann)[0], 'mask')
if mode == 'left':
path_ann = os.path.join(dir_ann, basename + '.json')
elif mode == 'right':
path_ann = os.path.join(dir_ann + '_right', basename + '.json')
from ..utils import open_annotations
dic = open_annotations(path_ann)
if isinstance(dic, list):
return [], []
keypoints = []
for kps in dic['keypoints']:
kps = prepare_pif_kps(np.array(kps).reshape(51,).tolist())
keypoints.append(kps)
return dic['boxes'], keypoints
def preprocess_pifpaf(annotations, im_size=None, enlarge_boxes=True, min_conf=0.):
"""
Preprocess pif annotations:
1. enlarge the box of 10%
2. Constraint it inside the image (if image_size provided)
"""
boxes = []
keypoints = []
enlarge = 1 if enlarge_boxes else 2 # Avoid enlarge boxes for social distancing
for dic in annotations:
kps = prepare_pif_kps(dic['keypoints'])
box = dic['bbox']
try:
conf = dic['score']
# Enlarge boxes
delta_h = (box[3]) / (10 * enlarge)
delta_w = (box[2]) / (5 * enlarge)
# from width height to corners
box[2] += box[0]
box[3] += box[1]
except KeyError:
all_confs = np.array(kps[2])
score_weights = np.ones(17)
score_weights[:3] = 3.0
score_weights[5:] = 0.1
# conf = np.sum(score_weights * np.sort(all_confs)[::-1])
conf = float(np.mean(all_confs))
# Add 15% for y and 20% for x
delta_h = (box[3] - box[1]) / (7 * enlarge)
delta_w = (box[2] - box[0]) / (3.5 * enlarge)
assert delta_h > -5 and delta_w > -5, "Bounding box <=0"
box[0] -= delta_w
box[1] -= delta_h
box[2] += delta_w
box[3] += delta_h
# Put the box inside the image
if im_size is not None:
box[0] = max(0, box[0])
box[1] = max(0, box[1])
box[2] = min(box[2], im_size[0])
box[3] = min(box[3], im_size[1])
if conf >= min_conf:
box.append(conf)
boxes.append(box)
keypoints.append(kps)
return boxes, keypoints
def prepare_pif_kps(kps_in):
"""Convert from a list of 51 to a list of 3, 17"""
assert len(kps_in) % 3 == 0, "keypoints expected as a multiple of 3"
xxs = kps_in[0:][::3]
yys = kps_in[1:][::3] # from offset 1 every 3
ccs = kps_in[2:][::3]
return [xxs, yys, ccs]
def image_transform(image):
normalize = torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor(), normalize, ])
return transforms(image)
def extract_outputs(outputs, tasks=()):
"""
Extract the outputs for multi-task training and predictions
Inputs:
tensor (m, 10) or (m,9) if monoloco
Outputs:
- if tasks are provided return ordered list of raw tensors
- else return a dictionary with processed outputs
"""
dic_out = {'x': outputs[:, 0:1],
'y': outputs[:, 1:2],
'd': outputs[:, 2:4],
'h': outputs[:, 4:5],
'w': outputs[:, 5:6],
'l': outputs[:, 6:7],
'ori': outputs[:, 7:9]}
if outputs.shape[1] == 10:
dic_out['aux'] = outputs[:, 9:10]
# Multi-task training
if len(tasks) >= 1:
assert isinstance(tasks, tuple), "tasks need to be a tuple"
return [dic_out[task] for task in tasks]
# Preprocess the tensor
# AV_H, AV_W, AV_L, HWL_STD = 1.72, 0.75, 0.68, 0.1
bi = unnormalize_bi(dic_out['d'])
dic_out['bi'] = bi
dic_out = {key: el.detach().cpu() for key, el in dic_out.items()}
x = to_cartesian(outputs[:, 0:3].detach().cpu(), mode='x')
y = to_cartesian(outputs[:, 0:3].detach().cpu(), mode='y')
d = dic_out['d'][:, 0:1]
z = torch.sqrt(d**2 - x**2 - y**2)
dic_out['xyzd'] = torch.cat((x, y, z, d), dim=1)
dic_out.pop('d')
dic_out.pop('x')
dic_out.pop('y')
dic_out['d'] = d
yaw_pred = torch.atan2(dic_out['ori'][:, 0:1], dic_out['ori'][:, 1:2])
yaw_orig = back_correct_angles(yaw_pred, dic_out['xyzd'][:, 0:3])
dic_out['yaw'] = (yaw_pred, yaw_orig) # alpha, ry
if outputs.shape[1] == 10:
dic_out['aux'] = torch.sigmoid(dic_out['aux'])
return dic_out
def extract_labels_aux(labels, tasks=None):
dic_gt_out = {'aux': labels[:, 0:1]}
if tasks is not None:
assert isinstance(tasks, tuple), "tasks need to be a tuple"
return [dic_gt_out[task] for task in tasks]
dic_gt_out = {key: el.detach().cpu() for key, el in dic_gt_out.items()}
return dic_gt_out
def extract_labels(labels, tasks=None):
dic_gt_out = {'x': labels[:, 0:1], 'y': labels[:, 1:2], 'z': labels[:, 2:3], 'd': labels[:, 3:4],
'h': labels[:, 4:5], 'w': labels[:, 5:6], 'l': labels[:, 6:7],
'ori': labels[:, 7:9], 'aux': labels[:, 10:11]}
if tasks is not None:
assert isinstance(tasks, tuple), "tasks need to be a tuple"
return [dic_gt_out[task] for task in tasks]
dic_gt_out = {key: el.detach().cpu() for key, el in dic_gt_out.items()}
return dic_gt_out
def cluster_outputs(outputs, clusters):
"""Cluster the outputs based on the number of right keypoints"""
# Check for "no right keypoints" condition
if clusters == 0:
clusters = max(1, round(outputs.shape[0] / 2))
assert outputs.shape[0] % clusters == 0, "Unexpected number of inputs"
outputs = outputs.view(-1, clusters, outputs.shape[1])
return outputs
def filter_outputs(outputs):
"""Extract a single output for each left keypoint"""
# Max of auxiliary task
val = outputs[:, :, -1]
best_val, _ = val.max(dim=1, keepdim=True)
mask = val >= best_val
output = outputs[mask] # broadcasting happens only if 3rd dim not present
return output, mask
def extract_outputs_mono(outputs, tasks=None):
"""
Extract the outputs for single di
Inputs:
tensor (m, 10) or (m,9) if monoloco
Outputs:
- if tasks are provided return ordered list of raw tensors
- else return a dictionary with processed outputs
"""
dic_out = {'xyz': outputs[:, 0:3], 'zb': outputs[:, 2:4],
'h': outputs[:, 4:5], 'w': outputs[:, 5:6], 'l': outputs[:, 6:7], 'ori': outputs[:, 7:9]}
# Multi-task training
if tasks is not None:
assert isinstance(tasks, tuple), "tasks need to be a tuple"
return [dic_out[task] for task in tasks]
# Preprocess the tensor
bi = unnormalize_bi(dic_out['zb'])
dic_out = {key: el.detach().cpu() for key, el in dic_out.items()}
dd = torch.norm(dic_out['xyz'], p=2, dim=1).view(-1, 1)
dic_out['xyzd'] = torch.cat((dic_out['xyz'], dd), dim=1)
dic_out['d'], dic_out['bi'] = dd, bi
yaw_pred = torch.atan2(dic_out['ori'][:, 0:1], dic_out['ori'][:, 1:2])
yaw_orig = back_correct_angles(yaw_pred, dic_out['xyzd'][:, 0:3])
dic_out['yaw'] = (yaw_pred, yaw_orig) # alpha, ry
return dic_out

150
monstereo/predict.py Normal file
View File

@ -0,0 +1,150 @@
# pylint: disable=too-many-statements, too-many-branches, undefined-loop-variable
import os
import json
from collections import defaultdict
import torch
from PIL import Image
from .visuals.printer import Printer
from .visuals.pifpaf_show import KeypointPainter, image_canvas
from .network import PifPaf, ImageList, Loco
from .network.process import factory_for_gt, preprocess_pifpaf
def predict(args):
cnt = 0
# Load Models
pifpaf = PifPaf(args)
assert args.mode in ('mono', 'stereo', 'pifpaf')
if 'mono' in args.mode:
monoloco = Loco(model=args.model, net='monoloco_pp',
device=args.device, n_dropout=args.n_dropout, p_dropout=args.dropout)
if 'stereo' in args.mode:
monstereo = Loco(model=args.model, net='monstereo',
device=args.device, n_dropout=args.n_dropout, p_dropout=args.dropout)
# data
data = ImageList(args.images, scale=args.scale)
if args.mode == 'stereo':
assert len(data.image_paths) % 2 == 0, "Odd number of images in a stereo setting"
bs = 2
else:
bs = 1
data_loader = torch.utils.data.DataLoader(
data, batch_size=bs, shuffle=False,
pin_memory=args.pin_memory, num_workers=args.loader_workers)
for idx, (image_paths, image_tensors, processed_images_cpu) in enumerate(data_loader):
images = image_tensors.permute(0, 2, 3, 1)
processed_images = processed_images_cpu.to(args.device, non_blocking=True)
fields_batch = pifpaf.fields(processed_images)
# unbatch stereo pair
for ii, (image_path, image, processed_image_cpu, fields) in enumerate(zip(
image_paths, images, processed_images_cpu, fields_batch)):
if args.output_directory is None:
output_path = image_paths[0]
else:
file_name = os.path.basename(image_paths[0])
output_path = os.path.join(args.output_directory, file_name)
print('image', idx, image_path, output_path)
keypoint_sets, scores, pifpaf_out = pifpaf.forward(image, processed_image_cpu, fields)
if ii == 0:
pifpaf_outputs = [keypoint_sets, scores, pifpaf_out] # keypoints_sets and scores for pifpaf printing
images_outputs = [image] # List of 1 or 2 elements with pifpaf tensor and monoloco original image
pifpaf_outs = {'left': pifpaf_out}
image_path_l = image_path
else:
pifpaf_outs['right'] = pifpaf_out
if args.mode in ('stereo', 'mono'):
# Extract calibration matrix and ground truth file if present
with open(image_path_l, 'rb') as f:
pil_image = Image.open(f).convert('RGB')
images_outputs.append(pil_image)
im_name = os.path.basename(image_path_l)
im_size = (float(image.size()[1] / args.scale), float(image.size()[0] / args.scale)) # Original
kk, dic_gt = factory_for_gt(im_size, name=im_name, path_gt=args.path_gt)
# Preprocess pifpaf outputs and run monoloco
boxes, keypoints = preprocess_pifpaf(pifpaf_outs['left'], im_size, enlarge_boxes=False)
if args.mode == 'mono':
print("Prediction with MonoLoco++")
dic_out = monoloco.forward(keypoints, kk)
dic_out = monoloco.post_process(dic_out, boxes, keypoints, kk, dic_gt)
else:
print("Prediction with MonStereo")
boxes_r, keypoints_r = preprocess_pifpaf(pifpaf_outs['right'], im_size)
dic_out = monstereo.forward(keypoints, kk, keypoints_r=keypoints_r)
dic_out = monstereo.post_process(dic_out, boxes, keypoints, kk, dic_gt)
else:
dic_out = defaultdict(list)
kk = None
factory_outputs(args, images_outputs, output_path, pifpaf_outputs, dic_out=dic_out, kk=kk)
print('Image {}\n'.format(cnt) + '-' * 120)
cnt += 1
def factory_outputs(args, images_outputs, output_path, pifpaf_outputs, dic_out=None, kk=None):
"""Output json files or images according to the choice"""
# Save json file
if args.mode == 'pifpaf':
keypoint_sets, scores, pifpaf_out = pifpaf_outputs[:]
# Visualizer
keypoint_painter = KeypointPainter(show_box=False)
skeleton_painter = KeypointPainter(show_box=False, color_connections=True, markersize=1, linewidth=4)
if 'json' in args.output_types and keypoint_sets.size > 0:
with open(output_path + '.pifpaf.json', 'w') as f:
json.dump(pifpaf_out, f)
if 'keypoints' in args.output_types:
with image_canvas(images_outputs[0],
output_path + '.keypoints.png',
show=args.show,
fig_width=args.figure_width,
dpi_factor=args.dpi_factor) as ax:
keypoint_painter.keypoints(ax, keypoint_sets)
if 'skeleton' in args.output_types:
with image_canvas(images_outputs[0],
output_path + '.skeleton.png',
show=args.show,
fig_width=args.figure_width,
dpi_factor=args.dpi_factor) as ax:
skeleton_painter.keypoints(ax, keypoint_sets, scores=scores)
else:
if any((xx in args.output_types for xx in ['front', 'bird', 'combined'])):
epistemic = False
if args.n_dropout > 0:
epistemic = True
if dic_out['boxes']: # Only print in case of detections
printer = Printer(images_outputs[1], output_path, kk, output_types=args.output_types
, z_max=args.z_max, epistemic=epistemic)
figures, axes = printer.factory_axes()
printer.draw(figures, axes, dic_out, images_outputs[1], show_all=args.show_all, draw_box=args.draw_box,
save=True, show=args.show)
if 'json' in args.output_types:
with open(os.path.join(output_path + '.monoloco.json'), 'w') as ff:
json.dump(dic_out, ff)

View File

View File

@ -0,0 +1,351 @@
# pylint: disable=too-many-statements, too-many-branches, too-many-nested-blocks
"""Preprocess annotations with KITTI ground-truth"""
import os
import glob
import copy
import logging
from collections import defaultdict
import json
import datetime
from PIL import Image
import torch
import cv2
from ..utils import split_training, parse_ground_truth, get_iou_matches, append_cluster, factory_file, \
extract_stereo_matches, get_category, normalize_hwl, make_new_directory
from ..network.process import preprocess_pifpaf, preprocess_monoloco
from .transforms import flip_inputs, flip_labels, height_augmentation
class PreprocessKitti:
"""Prepare arrays with same format as nuScenes preprocessing but using ground truth txt files"""
# AV_W = 0.68
# AV_L = 0.75
# AV_H = 1.72
# WLH_STD = 0.1
# SOCIAL DISTANCING PARAMETERS
THRESHOLD_DIST = 2 # Threshold to check distance of people
RADII = (0.3, 0.5, 1) # expected radii of the o-space
SOCIAL_DISTANCE = True
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
dic_jo = {'train': dict(X=[], Y=[], names=[], kps=[], K=[],
clst=defaultdict(lambda: defaultdict(list))),
'val': dict(X=[], Y=[], names=[], kps=[], K=[],
clst=defaultdict(lambda: defaultdict(list))),
'test': dict(X=[], Y=[], names=[], kps=[], K=[],
clst=defaultdict(lambda: defaultdict(list)))}
dic_names = defaultdict(lambda: defaultdict(list))
dic_std = defaultdict(lambda: defaultdict(list))
def __init__(self, dir_ann, iou_min, monocular=False):
self.dir_ann = dir_ann
self.iou_min = iou_min
self.monocular = monocular
self.dir_gt = os.path.join('data', 'kitti', 'gt')
self.dir_images = '/data/lorenzo-data/kitti/original_images/training/image_2'
self.dir_byc_l = '/data/lorenzo-data/kitti/object_detection/left'
self.names_gt = tuple(os.listdir(self.dir_gt))
self.dir_kk = os.path.join('data', 'kitti', 'calib')
self.list_gt = glob.glob(self.dir_gt + '/*.txt')
assert os.path.exists(self.dir_gt), "Ground truth dir does not exist"
assert os.path.exists(self.dir_ann), "Annotation dir does not exist"
now = datetime.datetime.now()
now_time = now.strftime("%Y%m%d-%H%M")[2:]
dir_out = os.path.join('data', 'arrays')
self.path_joints = os.path.join(dir_out, 'joints-kitti-' + now_time + '.json')
self.path_names = os.path.join(dir_out, 'names-kitti-' + now_time + '.json')
path_train = os.path.join('splits', 'kitti_train.txt')
path_val = os.path.join('splits', 'kitti_val.txt')
self.set_train, self.set_val = split_training(self.names_gt, path_train, path_val)
def run(self):
cnt_match_l, cnt_match_r, cnt_pair, cnt_pair_tot, cnt_extra_pair, cnt_files, cnt_files_ped, cnt_fnf, \
cnt_tot, cnt_ambiguous, cnt_cyclist = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
cnt_mono = {'train': 0, 'val': 0, 'test': 0}
cnt_gt = cnt_mono.copy()
cnt_stereo = cnt_mono.copy()
correct_ped, correct_byc, wrong_ped, wrong_byc = 0, 0, 0, 0
cnt_30, cnt_less_30 = 0, 0
# self.names_gt = ('002282.txt',)
for name in self.names_gt:
path_gt = os.path.join(self.dir_gt, name)
basename, _ = os.path.splitext(name)
path_im = os.path.join(self.dir_images, basename + '.png')
phase, flag = self._factory_phase(name)
if flag:
cnt_fnf += 1
continue
if phase == 'train':
min_conf = 0
category = 'all'
else: # Remove for original results
min_conf = 0.1
category = 'pedestrian'
# Extract ground truth
boxes_gt, ys, _, _ = parse_ground_truth(path_gt, category=category, spherical=True)
cnt_gt[phase] += len(boxes_gt)
cnt_files += 1
cnt_files_ped += min(len(boxes_gt), 1) # if no boxes 0 else 1
# Extract keypoints
path_calib = os.path.join(self.dir_kk, basename + '.txt')
annotations, kk, tt = factory_file(path_calib, self.dir_ann, basename)
self.dic_names[basename + '.png']['boxes'] = copy.deepcopy(boxes_gt)
self.dic_names[basename + '.png']['ys'] = copy.deepcopy(ys)
self.dic_names[basename + '.png']['K'] = copy.deepcopy(kk)
# Check image size
with Image.open(path_im) as im:
width, height = im.size
boxes, keypoints = preprocess_pifpaf(annotations, im_size=(width, height), min_conf=min_conf)
if keypoints:
annotations_r, kk_r, tt_r = factory_file(path_calib, self.dir_ann, basename, mode='right')
boxes_r, keypoints_r = preprocess_pifpaf(annotations_r, im_size=(width, height), min_conf=min_conf)
cat = get_category(keypoints, os.path.join(self.dir_byc_l, basename + '.json'))
if not keypoints_r: # Case of no detection
all_boxes_gt, all_ys = [boxes_gt], [ys]
boxes_r, keypoints_r = boxes[0:1].copy(), keypoints[0:1].copy()
all_boxes, all_keypoints = [boxes], [keypoints]
all_keypoints_r = [keypoints_r]
else:
# Horizontal Flipping for training
if phase == 'train':
# GT)
boxes_gt_flip, ys_flip = flip_labels(boxes_gt, ys, im_w=width)
# New left
boxes_flip = flip_inputs(boxes_r, im_w=width, mode='box')
keypoints_flip = flip_inputs(keypoints_r, im_w=width)
# New right
keypoints_r_flip = flip_inputs(keypoints, im_w=width)
# combine the 2 modes
all_boxes_gt = [boxes_gt, boxes_gt_flip]
all_ys = [ys, ys_flip]
all_boxes = [boxes, boxes_flip]
all_keypoints = [keypoints, keypoints_flip]
all_keypoints_r = [keypoints_r, keypoints_r_flip]
else:
all_boxes_gt, all_ys = [boxes_gt], [ys]
all_boxes, all_keypoints = [boxes], [keypoints]
all_keypoints_r = [keypoints_r]
# Match each set of keypoint with a ground truth
self.dic_jo[phase]['K'].append(kk)
for ii, boxes_gt in enumerate(all_boxes_gt):
keypoints, keypoints_r = torch.tensor(all_keypoints[ii]), torch.tensor(all_keypoints_r[ii])
ys = all_ys[ii]
matches = get_iou_matches(all_boxes[ii], boxes_gt, self.iou_min)
for (idx, idx_gt) in matches:
keypoint = keypoints[idx:idx + 1]
lab = ys[idx_gt][:-1]
# Preprocess MonoLoco++
if self.monocular:
inp = preprocess_monoloco(keypoint, kk).view(-1).tolist()
lab = normalize_hwl(lab)
if ys[idx_gt][10] < 0.5:
self.dic_jo[phase]['kps'].append(keypoint.tolist())
self.dic_jo[phase]['X'].append(inp)
self.dic_jo[phase]['Y'].append(lab)
self.dic_jo[phase]['names'].append(name) # One image name for each annotation
append_cluster(self.dic_jo, phase, inp, lab, keypoint)
cnt_mono[phase] += 1
cnt_tot += 1
# Preprocess MonStereo
else:
zz = ys[idx_gt][2]
stereo_matches, cnt_amb = extract_stereo_matches(keypoint, keypoints_r, zz,
phase=phase, seed=cnt_pair_tot)
cnt_match_l += 1 if ii < 0.1 else 0 # matched instances
cnt_match_r += 1 if ii > 0.9 else 0
cnt_ambiguous += cnt_amb
# Monitor precision of classes
if phase == 'val':
if ys[idx_gt][10] == cat[idx] == 1:
correct_byc += 1
elif ys[idx_gt][10] == cat[idx] == 0:
correct_ped += 1
elif ys[idx_gt][10] != cat[idx] and ys[idx_gt][10] == 1:
wrong_byc += 1
elif ys[idx_gt][10] != cat[idx] and ys[idx_gt][10] == 0:
wrong_ped += 1
cnt_cyclist += 1 if ys[idx_gt][10] == 1 else 0
for num, (idx_r, s_match) in enumerate(stereo_matches):
label = ys[idx_gt][:-1] + [s_match]
if s_match > 0.9:
cnt_pair += 1
# Remove noise of very far instances for validation
# if (phase == 'val') and (ys[idx_gt][3] >= 50):
# continue
# ---> Save only positives unless there is no positive (keep positive flip and augm)
# if num > 0 and s_match < 0.9:
# continue
# Height augmentation
cnt_pair_tot += 1
cnt_extra_pair += 1 if ii == 1 else 0
flag_aug = False
if phase == 'train' and 3 < label[2] < 30 and s_match > 0.9:
flag_aug = True
elif phase == 'train' and 3 < label[2] < 30 and cnt_pair_tot % 2 == 0:
flag_aug = True
# Remove height augmentation
# flag_aug = False
if flag_aug:
kps_aug, labels_aug = height_augmentation(
keypoints[idx:idx+1], keypoints_r[idx_r:idx_r+1], label, s_match,
seed=cnt_pair_tot)
else:
kps_aug = [(keypoints[idx:idx+1], keypoints_r[idx_r:idx_r+1])]
labels_aug = [label]
for i, lab in enumerate(labels_aug):
(kps, kps_r) = kps_aug[i]
input_l = preprocess_monoloco(kps, kk).view(-1)
input_r = preprocess_monoloco(kps_r, kk).view(-1)
keypoint = torch.cat((kps, kps_r), dim=2).tolist()
inp = torch.cat((input_l, input_l - input_r)).tolist()
# Only relative distances
# inp_x = input[::2]
# inp = torch.cat((inp_x, input - input_r)).tolist()
# lab = normalize_hwl(lab)
if ys[idx_gt][10] < 0.5:
self.dic_jo[phase]['kps'].append(keypoint)
self.dic_jo[phase]['X'].append(inp)
self.dic_jo[phase]['Y'].append(lab)
self.dic_jo[phase]['names'].append(name) # One image name for each annotation
append_cluster(self.dic_jo, phase, inp, lab, keypoint)
cnt_tot += 1
if s_match > 0.9:
cnt_stereo[phase] += 1
else:
cnt_mono[phase] += 1
with open(self.path_joints, 'w') as file:
json.dump(self.dic_jo, file)
with open(os.path.join(self.path_names), 'w') as file:
json.dump(self.dic_names, file)
# cout
print(cnt_30)
print(cnt_less_30)
print('-' * 120)
print("Number of GT files: {}. Files with at least one pedestrian: {}. Files not found: {}"
.format(cnt_files, cnt_files_ped, cnt_fnf))
print("Ground truth matches : {:.1f} % for left images (train and val) and {:.1f} % for right images (train)"
.format(100*cnt_match_l / (cnt_gt['train'] + cnt_gt['val']), 100*cnt_match_r / cnt_gt['train']))
print("Total annotations: {}".format(cnt_tot))
print("Total number of cyclists: {}\n".format(cnt_cyclist))
print("Ambiguous instances removed: {}".format(cnt_ambiguous))
print("Extra pairs created with horizontal flipping: {}\n".format(cnt_extra_pair))
if not self.monocular:
print('Instances with stereo correspondence: {:.1f}% '.format(100 * cnt_pair / cnt_pair_tot))
for phase in ['train', 'val']:
cnt = cnt_mono[phase] + cnt_stereo[phase]
print("{}: annotations: {}. Stereo pairs {:.1f}% "
.format(phase.upper(), cnt, 100 * cnt_stereo[phase] / cnt))
print("\nOutput files:\n{}\n{}".format(self.path_names, self.path_joints))
print('-' * 120)
def prep_activity(self):
"""Augment ground-truth with flag activity"""
from monstereo.activity import social_interactions
main_dir = os.path.join('data', 'kitti')
dir_gt = os.path.join(main_dir, 'gt')
dir_out = os.path.join(main_dir, 'gt_activity')
make_new_directory(dir_out)
cnt_tp, cnt_tn = 0, 0
# Extract validation images for evaluation
category = 'pedestrian'
for name in self.set_val:
# Read
path_gt = os.path.join(dir_gt, name)
boxes_gt, ys, truncs_gt, occs_gt, lines = parse_ground_truth(path_gt, category, spherical=False,
verbose=True)
angles = [y[10] for y in ys]
dds = [y[4] for y in ys]
xz_centers = [[y[0], y[2]] for y in ys]
# Write
path_out = os.path.join(dir_out, name)
with open(path_out, "w+") as ff:
for idx, line in enumerate(lines):
if social_interactions(idx, xz_centers, angles, dds,
n_samples=1,
threshold_dist=self.THRESHOLD_DIST,
radii=self.RADII,
social_distance=self.SOCIAL_DISTANCE):
activity = '1'
cnt_tp += 1
else:
activity = '0'
cnt_tn += 1
line_new = line[:-1] + ' ' + activity + line[-1]
ff.write(line_new)
print(f'Written {len(self.set_val)} new files in {dir_out}')
print(f'Saved {cnt_tp} positive and {cnt_tn} negative annotations')
def _factory_phase(self, name):
"""Choose the phase"""
phase = None
flag = False
if name in self.set_train:
phase = 'train'
elif name in self.set_val:
phase = 'val'
else:
flag = True
return phase, flag
def crop_and_draw(im, box, keypoint):
box = [round(el) for el in box[:-1]]
center = (int((keypoint[0][0])), int((keypoint[1][0])))
radius = round((box[3]-box[1]) / 20)
im = cv2.circle(im, center, radius, color=(0, 255, 0), thickness=1)
crop = im[box[1]:box[3], box[0]:box[2]]
h_crop = crop.shape[0]
w_crop = crop.shape[1]
return crop, h_crop, w_crop

View File

@ -0,0 +1,284 @@
# pylint: disable=too-many-statements, import-error
"""Extract joints annotations and match with nuScenes ground truths
"""
import os
import sys
import time
import math
import copy
import json
import logging
from collections import defaultdict
import datetime
import numpy as np
from nuscenes.nuscenes import NuScenes
from nuscenes.utils import splits
from pyquaternion import Quaternion
from ..utils import get_iou_matches, append_cluster, select_categories, project_3d, correct_angle, normalize_hwl, \
to_spherical
from ..network.process import preprocess_pifpaf, preprocess_monoloco
class PreprocessNuscenes:
"""Preprocess Nuscenes dataset"""
AV_W = 0.68
AV_L = 0.75
AV_H = 1.72
WLH_STD = 0.1
social = False
CAMERAS = ('CAM_FRONT', 'CAM_FRONT_LEFT', 'CAM_FRONT_RIGHT', 'CAM_BACK', 'CAM_BACK_LEFT', 'CAM_BACK_RIGHT')
dic_jo = {'train': dict(X=[], Y=[], names=[], kps=[], boxes_3d=[], K=[],
clst=defaultdict(lambda: defaultdict(list))),
'val': dict(X=[], Y=[], names=[], kps=[], boxes_3d=[], K=[],
clst=defaultdict(lambda: defaultdict(list))),
'test': dict(X=[], Y=[], names=[], kps=[], boxes_3d=[], K=[],
clst=defaultdict(lambda: defaultdict(list)))
}
dic_names = defaultdict(lambda: defaultdict(list))
def __init__(self, dir_ann, dir_nuscenes, dataset, iou_min):
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
self.iou_min = iou_min
self.dir_ann = dir_ann
dir_out = os.path.join('data', 'arrays')
assert os.path.exists(dir_nuscenes), "Nuscenes directory does not exists"
assert os.path.exists(self.dir_ann), "The annotations directory does not exists"
assert os.path.exists(dir_out), "Joints directory does not exists"
now = datetime.datetime.now()
now_time = now.strftime("%Y%m%d-%H%M")[2:]
self.path_joints = os.path.join(dir_out, 'joints-' + dataset + '-' + now_time + '.json')
self.path_names = os.path.join(dir_out, 'names-' + dataset + '-' + now_time + '.json')
self.nusc, self.scenes, self.split_train, self.split_val = factory(dataset, dir_nuscenes)
def run(self):
"""
Prepare arrays for training
"""
cnt_scenes = cnt_samples = cnt_sd = cnt_ann = 0
start = time.time()
for ii, scene in enumerate(self.scenes):
end_scene = time.time()
current_token = scene['first_sample_token']
cnt_scenes += 1
time_left = str((end_scene - start_scene) / 60 * (len(self.scenes) - ii))[:4] if ii != 0 else "NaN"
sys.stdout.write('\r' + 'Elaborating scene {}, remaining time {} minutes'
.format(cnt_scenes, time_left) + '\t\n')
start_scene = time.time()
if scene['name'] in self.split_train:
phase = 'train'
elif scene['name'] in self.split_val:
phase = 'val'
else:
print("phase name not in training or validation split")
continue
while not current_token == "":
sample_dic = self.nusc.get('sample', current_token)
cnt_samples += 1
# Extract all the sample_data tokens for each sample
for cam in self.CAMERAS:
sd_token = sample_dic['data'][cam]
cnt_sd += 1
# Extract all the annotations of the person
path_im, boxes_obj, kk = self.nusc.get_sample_data(sd_token, box_vis_level=1) # At least one corner
boxes_gt, boxes_3d, ys = extract_ground_truth(boxes_obj, kk)
kk = kk.tolist()
name = os.path.basename(path_im)
basename, _ = os.path.splitext(name)
self.dic_names[basename + '.jpg']['boxes'] = copy.deepcopy(boxes_gt)
self.dic_names[basename + '.jpg']['ys'] = copy.deepcopy(ys)
self.dic_names[basename + '.jpg']['K'] = copy.deepcopy(kk)
# Run IoU with pifpaf detections and save
path_pif = os.path.join(self.dir_ann, name + '.pifpaf.json')
exists = os.path.isfile(path_pif)
if exists:
with open(path_pif, 'r') as file:
annotations = json.load(file)
boxes, keypoints = preprocess_pifpaf(annotations, im_size=(1600, 900))
else:
continue
if keypoints:
matches = get_iou_matches(boxes, boxes_gt, self.iou_min)
for (idx, idx_gt) in matches:
keypoint = keypoints[idx:idx + 1]
inp = preprocess_monoloco(keypoint, kk).view(-1).tolist()
lab = ys[idx_gt]
lab = normalize_hwl(lab)
self.dic_jo[phase]['kps'].append(keypoint)
self.dic_jo[phase]['X'].append(inp)
self.dic_jo[phase]['Y'].append(lab)
self.dic_jo[phase]['names'].append(name) # One image name for each annotation
self.dic_jo[phase]['boxes_3d'].append(boxes_3d[idx_gt])
append_cluster(self.dic_jo, phase, inp, lab, keypoint)
cnt_ann += 1
sys.stdout.write('\r' + 'Saved annotations {}'.format(cnt_ann) + '\t')
current_token = sample_dic['next']
with open(os.path.join(self.path_joints), 'w') as f:
json.dump(self.dic_jo, f)
with open(os.path.join(self.path_names), 'w') as f:
json.dump(self.dic_names, f)
end = time.time()
extract_box_average(self.dic_jo['train']['boxes_3d'])
print("\nSaved {} annotations for {} samples in {} scenes. Total time: {:.1f} minutes"
.format(cnt_ann, cnt_samples, cnt_scenes, (end-start)/60))
print("\nOutput files:\n{}\n{}\n".format(self.path_names, self.path_joints))
def extract_ground_truth(boxes_obj, kk, spherical=True):
boxes_gt = []
boxes_3d = []
ys = []
for box_obj in boxes_obj:
# Select category
if box_obj.name[:6] != 'animal':
general_name = box_obj.name.split('.')[0] + '.' + box_obj.name.split('.')[1]
else:
general_name = 'animal'
if general_name in select_categories('all'):
# Obtain 2D & 3D box
boxes_gt.append(project_3d(box_obj, kk))
boxes_3d.append(box_obj.center.tolist() + box_obj.wlh.tolist())
# Angle
yaw = quaternion_yaw(box_obj.orientation)
assert - math.pi <= yaw <= math.pi
sin, cos, _ = correct_angle(yaw, box_obj.center)
hwl = [float(box_obj.wlh[i]) for i in (2, 0, 1)]
# Spherical coordinates
xyz = list(box_obj.center)
dd = np.linalg.norm(box_obj.center)
if spherical:
rtp = to_spherical(xyz)
loc = rtp[1:3] + xyz[2:3] + rtp[0:1] # [theta, psi, z, r]
else:
loc = xyz + [dd]
output = loc + hwl + [sin, cos, yaw]
ys.append(output)
return boxes_gt, boxes_3d, ys
def factory(dataset, dir_nuscenes):
"""Define dataset type and split training and validation"""
assert dataset in ['nuscenes', 'nuscenes_mini', 'nuscenes_teaser']
if dataset == 'nuscenes_mini':
version = 'v1.0-mini'
else:
version = 'v1.0-trainval'
nusc = NuScenes(version=version, dataroot=dir_nuscenes, verbose=True)
scenes = nusc.scene
if dataset == 'nuscenes_teaser':
with open("splits/nuscenes_teaser_scenes.txt", "r") as file:
teaser_scenes = file.read().splitlines()
scenes = [scene for scene in scenes if scene['token'] in teaser_scenes]
with open("splits/split_nuscenes_teaser.json", "r") as file:
dic_split = json.load(file)
split_train = [scene['name'] for scene in scenes if scene['token'] in dic_split['train']]
split_val = [scene['name'] for scene in scenes if scene['token'] in dic_split['val']]
else:
split_scenes = splits.create_splits_scenes()
split_train, split_val = split_scenes['train'], split_scenes['val']
return nusc, scenes, split_train, split_val
def quaternion_yaw(q: Quaternion, in_image_frame: bool = True) -> float:
if in_image_frame:
v = np.dot(q.rotation_matrix, np.array([1, 0, 0]))
yaw = -np.arctan2(v[2], v[0])
else:
v = np.dot(q.rotation_matrix, np.array([1, 0, 0]))
yaw = np.arctan2(v[1], v[0])
return float(yaw)
def extract_box_average(boxes_3d):
boxes_np = np.array(boxes_3d)
means = np.mean(boxes_np[:, 3:], axis=0)
stds = np.std(boxes_np[:, 3:], axis=0)
print(means)
print(stds)
def extract_social(inputs, ys, keypoints, idx, matches):
"""Output a (padded) version with all the 5 neighbours
- Take the ground feet and the output z
- make relative to the person (as social LSTM)"""
all_inputs = []
# Find the lowest relative ground foot
ground_foot = np.max(np.array(inputs)[:, [31, 33]], axis=1)
rel_ground_foot = ground_foot - ground_foot[idx]
rel_ground_foot = rel_ground_foot.tolist()
# Order the people based on their distance
base = np.array([np.mean(np.array(keypoints[idx][0])), np.mean(np.array(keypoints[idx][1]))])
# delta_input = [abs((inp[31] + inp[33]) / 2 - base) for inp in inputs]
delta_input = [np.linalg.norm(base - np.array([np.mean(np.array(kp[0])), np.mean(np.array(kp[1]))]))
for kp in keypoints]
sorted_indices = sorted(range(len(delta_input)), key=lambda k: delta_input[k]) # Return a list of sorted indices
all_inputs.extend(inputs[idx])
indices_idx = [idx for (idx, idx_gt) in matches]
if len(sorted_indices) > 2:
aa = 5
for ii in range(1, 3):
try:
index = sorted_indices[ii]
# Extract the idx_gt corresponding to the input we are attaching if it exists
try:
idx_idx_gt = indices_idx.index(index)
idx_gt = matches[idx_idx_gt][1]
all_inputs.append(rel_ground_foot[index]) # Relative lower ground foot
all_inputs.append(float(ys[idx_gt][3])) # Output Z
except ValueError:
all_inputs.extend([0.] * 2)
except IndexError:
all_inputs.extend([0.] * 2)
assert len(all_inputs) == 34 + 2 * 2
return all_inputs
# def get_jean_yaw(box_obj):
# b_corners = box_obj.bottom_corners()
# center = box_obj.center
# back_point = [(b_corners[0, 2] + b_corners[0, 3]) / 2, (b_corners[2, 2] + b_corners[2, 3]) / 2]
#
# x = b_corners[0, :] - back_point[0]
# y = b_corners[2, :] - back_point[1]
#
# angle = math.atan2((x[0] + x[1]) / 2, (y[0] + y[1]) / 2) * 180 / 3.14
# angle = (angle + 360) % 360
# correction = math.atan2(center[0], center[2]) * 180 / 3.14
# return angle, correction

View File

@ -0,0 +1,141 @@
import math
from copy import deepcopy
import numpy as np
BASELINE = 0.54
BF = BASELINE * 721
COCO_KEYPOINTS = [
'nose', # 0
'left_eye', # 1
'right_eye', # 2
'left_ear', # 3
'right_ear', # 4
'left_shoulder', # 5
'right_shoulder', # 6
'left_elbow', # 7
'right_elbow', # 8
'left_wrist', # 9
'right_wrist', # 10
'left_hip', # 11
'right_hip', # 12
'left_knee', # 13
'right_knee', # 14
'left_ankle', # 15
'right_ankle', # 16
]
HFLIP = {
'nose': 'nose',
'left_eye': 'right_eye',
'right_eye': 'left_eye',
'left_ear': 'right_ear',
'right_ear': 'left_ear',
'left_shoulder': 'right_shoulder',
'right_shoulder': 'left_shoulder',
'left_elbow': 'right_elbow',
'right_elbow': 'left_elbow',
'left_wrist': 'right_wrist',
'right_wrist': 'left_wrist',
'left_hip': 'right_hip',
'right_hip': 'left_hip',
'left_knee': 'right_knee',
'right_knee': 'left_knee',
'left_ankle': 'right_ankle',
'right_ankle': 'left_ankle',
}
def transform_keypoints(keypoints, mode):
"""Egocentric horizontal flip"""
assert mode == 'flip', "mode not recognized"
kps = np.array(keypoints)
dic_kps = {key: kps[:, :, idx] for idx, key in enumerate(COCO_KEYPOINTS)}
kps_hflip = np.array([dic_kps[value] for key, value in HFLIP.items()])
kps_hflip = np.transpose(kps_hflip, (1, 2, 0))
return kps_hflip.tolist()
def flip_inputs(keypoints, im_w, mode=None):
"""Horizontal flip the keypoints or the boxes in the image"""
if mode == 'box':
boxes = deepcopy(keypoints)
for box in boxes:
temp = box[2]
box[2] = im_w - box[0]
box[0] = im_w - temp
return boxes
keypoints = np.array(keypoints)
keypoints[:, 0, :] = im_w - keypoints[:, 0, :] # Shifted
kps_flip = transform_keypoints(keypoints, mode='flip')
return kps_flip
def flip_labels(boxes_gt, labels, im_w):
"""Correct x, d positions and angles after horizontal flipping"""
from ..utils import correct_angle, to_cartesian, to_spherical
boxes_flip = deepcopy(boxes_gt)
labels_flip = deepcopy(labels)
for idx, label_flip in enumerate(labels_flip):
# Flip the box and account for disparity
disp = BF / label_flip[2]
temp = boxes_flip[idx][2]
boxes_flip[idx][2] = im_w - boxes_flip[idx][0] + disp
boxes_flip[idx][0] = im_w - temp + disp
# Flip X and D
rtp = label_flip[3:4] + label_flip[0:2] # Originally t,p,z,r
xyz = to_cartesian(rtp)
xyz[0] = -xyz[0] + BASELINE # x
rtp_r = to_spherical(xyz)
label_flip[3], label_flip[0], label_flip[1] = rtp_r[0], rtp_r[1], rtp_r[2]
# FLip and correct the angle
yaw = label_flip[9]
yaw_n = math.copysign(1, yaw) * (np.pi - abs(yaw)) # Horizontal flipping change of angle
sin, cos, yaw_corr = correct_angle(yaw_n, xyz)
label_flip[7], label_flip[8], label_flip[9] = sin, cos, yaw_n
return boxes_flip, labels_flip
def height_augmentation(kps, kps_r, label, s_match, seed=0):
"""
label: theta, psi, z, rho, wlh, sin, cos, yaw, cat
"""
from ..utils import to_cartesian
n_labels = 3 if s_match > 0.9 else 1
height_min = 1.2
height_max = 2
av_height = 1.71
kps_aug = [[kps.clone(), kps_r.clone()] for _ in range(n_labels+1)]
labels_aug = [label.copy() for _ in range(n_labels+1)] # Maintain the original
np.random.seed(seed)
heights = np.random.uniform(height_min, height_max, n_labels) # 3 samples
zzs = heights * label[2] / av_height
disp = BF / label[2]
rtp = label[3:4] + label[0:2] # Originally t,p,z,r
xyz = to_cartesian(rtp)
for i in range(n_labels):
if zzs[i] < 2:
continue
# Update keypoints
disp_new = BF / zzs[i]
delta_disp = disp - disp_new
kps_aug[i][1][0, 0, :] = kps_aug[i][1][0, 0, :] + delta_disp
# Update labels
labels_aug[i][2] = zzs[i]
xyz[2] = zzs[i]
rho = np.linalg.norm(xyz)
labels_aug[i][3] = rho
return kps_aug, labels_aug

195
monstereo/run.py Normal file
View File

@ -0,0 +1,195 @@
# pylint: disable=too-many-branches, too-many-statements
import argparse
from openpifpaf.network import nets
from openpifpaf import decoder
def cli():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Subparser definition
subparsers = parser.add_subparsers(help='Different parsers for main actions', dest='command')
predict_parser = subparsers.add_parser("predict")
prep_parser = subparsers.add_parser("prep")
training_parser = subparsers.add_parser("train")
eval_parser = subparsers.add_parser("eval")
# Preprocess input data
prep_parser.add_argument('--dir_ann', help='directory of annotations of 2d joints', required=True)
prep_parser.add_argument('--dataset',
help='datasets to preprocess: nuscenes, nuscenes_teaser, nuscenes_mini, kitti',
default='kitti')
prep_parser.add_argument('--dir_nuscenes', help='directory of nuscenes devkit', default='data/nuscenes/')
prep_parser.add_argument('--iou_min', help='minimum iou to match ground truth', type=float, default=0.3)
prep_parser.add_argument('--variance', help='new', action='store_true')
prep_parser.add_argument('--activity', help='new', action='store_true')
prep_parser.add_argument('--monocular', help='new', action='store_true')
# Predict (2D pose and/or 3D location from images)
# General
predict_parser.add_argument('--mode', help='pifpaf, mono, stereo', default='stereo')
predict_parser.add_argument('images', nargs='*', help='input images')
predict_parser.add_argument('--glob', help='glob expression for input images (for many images)')
predict_parser.add_argument('-o', '--output-directory', help='Output directory')
predict_parser.add_argument('--output_types', nargs='+', default=['json'],
help='what to output: json keypoints skeleton for Pifpaf'
'json bird front combined for Monoloco')
predict_parser.add_argument('--show', help='to show images', action='store_true')
# Pifpaf
nets.cli(predict_parser)
decoder.cli(predict_parser, force_complete_pose=True, instance_threshold=0.15)
predict_parser.add_argument('--scale', default=1.0, type=float, help='change the scale of the image to preprocess')
# Monoloco
predict_parser.add_argument('--model', help='path of MonoLoco model to load', required=True)
predict_parser.add_argument('--hidden_size', type=int, help='Number of hidden units in the model', default=512)
predict_parser.add_argument('--path_gt', help='path of json file with gt 3d localization',
default='data/arrays/names-kitti-200615-1022.json')
predict_parser.add_argument('--transform', help='transformation for the pose', default='None')
predict_parser.add_argument('--draw_box', help='to draw box in the images', action='store_true')
predict_parser.add_argument('--z_max', type=int, help='maximum meters distance for predictions', default=22)
predict_parser.add_argument('--n_dropout', type=int, help='Epistemic uncertainty evaluation', default=0)
predict_parser.add_argument('--dropout', type=float, help='dropout parameter', default=0.2)
predict_parser.add_argument('--show_all', help='only predict ground-truth matches or all', action='store_true')
# Social distancing and social interactions
predict_parser.add_argument('--social', help='social', action='store_true')
predict_parser.add_argument('--activity', help='activity', action='store_true')
predict_parser.add_argument('--json_dir', help='for social')
predict_parser.add_argument('--threshold_prob', type=float, help='concordance for samples', default=0.25)
predict_parser.add_argument('--threshold_dist', type=float, help='min distance of people', default=2)
predict_parser.add_argument('--margin', type=float, help='conservative for noise in orientation', default=1.5)
predict_parser.add_argument('--radii', type=tuple, help='o-space radii', default=(0.25, 1, 2))
# Training
training_parser.add_argument('--joints', help='Json file with input joints',
default='data/arrays/joints-nuscenes_teaser-190513-1846.json')
training_parser.add_argument('--save', help='whether to not save model and log file', action='store_true')
training_parser.add_argument('-e', '--epochs', type=int, help='number of epochs to train for', default=500)
training_parser.add_argument('--bs', type=int, default=512, help='input batch size')
training_parser.add_argument('--monocular', help='whether to train monoloco', action='store_true')
training_parser.add_argument('--dropout', type=float, help='dropout. Default no dropout', default=0.2)
training_parser.add_argument('--lr', type=float, help='learning rate', default=0.001)
training_parser.add_argument('--sched_step', type=float, help='scheduler step time (epochs)', default=30)
training_parser.add_argument('--sched_gamma', type=float, help='Scheduler multiplication every step', default=0.98)
training_parser.add_argument('--hidden_size', type=int, help='Number of hidden units in the model', default=1024)
training_parser.add_argument('--n_stage', type=int, help='Number of stages in the model', default=3)
training_parser.add_argument('--hyp', help='run hyperparameters tuning', action='store_true')
training_parser.add_argument('--multiplier', type=int, help='Size of the grid of hyp search', default=1)
training_parser.add_argument('--r_seed', type=int, help='specify the seed for training and hyp tuning', default=1)
training_parser.add_argument('--activity', help='new', action='store_true')
# Evaluation
eval_parser.add_argument('--dataset', help='datasets to evaluate, kitti or nuscenes', default='kitti')
eval_parser.add_argument('--geometric', help='to evaluate geometric distance', action='store_true')
eval_parser.add_argument('--generate', help='create txt files for KITTI evaluation', action='store_true')
eval_parser.add_argument('--dir_ann', help='directory of annotations of 2d joints (for KITTI evaluation)')
eval_parser.add_argument('--model', help='path of MonoLoco model to load')
eval_parser.add_argument('--joints', help='Json file with input joints to evaluate (for nuScenes evaluation)')
eval_parser.add_argument('--n_dropout', type=int, help='Epistemic uncertainty evaluation', default=0)
eval_parser.add_argument('--dropout', type=float, help='dropout. Default no dropout', default=0.2)
eval_parser.add_argument('--hidden_size', type=int, help='Number of hidden units in the model', default=1024)
eval_parser.add_argument('--n_stage', type=int, help='Number of stages in the model', default=3)
eval_parser.add_argument('--show', help='whether to show statistic graphs', action='store_true')
eval_parser.add_argument('--save', help='whether to save statistic graphs', action='store_true')
eval_parser.add_argument('--verbose', help='verbosity of statistics', action='store_true')
eval_parser.add_argument('--monocular', help='whether to train using the baseline', action='store_true')
eval_parser.add_argument('--new', help='new', action='store_true')
eval_parser.add_argument('--variance', help='evaluate keypoints variance', action='store_true')
eval_parser.add_argument('--activity', help='evaluate activities', action='store_true')
eval_parser.add_argument('--net', help='Choose network: monoloco, monoloco_p, monoloco_pp, monstereo')
args = parser.parse_args()
return args
def main():
args = cli()
if args.command == 'predict':
if args.activity:
from .activity import predict
else:
from .predict import predict
predict(args)
elif args.command == 'prep':
if 'nuscenes' in args.dataset:
from .prep.preprocess_nu import PreprocessNuscenes
prep = PreprocessNuscenes(args.dir_ann, args.dir_nuscenes, args.dataset, args.iou_min)
prep.run()
else:
from .prep.prep_kitti import PreprocessKitti
prep = PreprocessKitti(args.dir_ann, args.iou_min, args.monocular)
if args.activity:
prep.prep_activity()
else:
prep.run()
elif args.command == 'train':
from .train import HypTuning
if args.hyp:
hyp_tuning = HypTuning(joints=args.joints, epochs=args.epochs,
monocular=args.monocular, dropout=args.dropout,
multiplier=args.multiplier, r_seed=args.r_seed)
hyp_tuning.train()
else:
from .train import Trainer
training = Trainer(joints=args.joints, epochs=args.epochs, bs=args.bs,
monocular=args.monocular, dropout=args.dropout, lr=args.lr, sched_step=args.sched_step,
n_stage=args.n_stage, sched_gamma=args.sched_gamma, hidden_size=args.hidden_size,
r_seed=args.r_seed, save=args.save)
_ = training.train()
_ = training.evaluate()
elif args.command == 'eval':
if args.activity:
from .eval.eval_activity import ActivityEvaluator
evaluator = ActivityEvaluator(args)
if 'collective' in args.dataset:
evaluator.eval_collective()
else:
evaluator.eval_kitti()
elif args.geometric:
assert args.joints, "joints argument not provided"
from .network.geom_baseline import geometric_baseline
geometric_baseline(args.joints)
elif args.variance:
from .eval.eval_variance import joints_variance
joints_variance(args.joints, clusters=None, dic_ms=None)
else:
if args.generate:
from .eval.generate_kitti import GenerateKitti
kitti_txt = GenerateKitti(args.model, args.dir_ann, p_dropout=args.dropout, n_dropout=args.n_dropout,
hidden_size=args.hidden_size)
kitti_txt.run()
if args.dataset == 'kitti':
from .eval import EvalKitti
kitti_eval = EvalKitti(verbose=args.verbose)
kitti_eval.run()
kitti_eval.printer(show=args.show, save=args.save)
elif 'nuscenes' in args.dataset:
from .train import Trainer
training = Trainer(joints=args.joints, hidden_size=args.hidden_size)
_ = training.evaluate(load=True, model=args.model, debug=False)
else:
raise ValueError("Option not recognized")
else:
raise ValueError("Main subparser not recognized or not provided")
if __name__ == '__main__':
main()

View File

@ -0,0 +1,3 @@
from .hyp_tuning import HypTuning
from .trainer import Trainer

View File

@ -0,0 +1,92 @@
import json
import torch
from torch.utils.data import Dataset
class ActivityDataset(Dataset):
"""
Dataloader for activity dataset
"""
def __init__(self, joints, phase):
"""
Load inputs and outputs from the pickles files from gt joints, mask joints or both
"""
assert(phase in ['train', 'val', 'test'])
with open(joints, 'r') as f:
dic_jo = json.load(f)
# Define input and output for normal training and inference
self.inputs_all = torch.tensor(dic_jo[phase]['X'])
self.outputs_all = torch.tensor(dic_jo[phase]['Y']).view(-1, 1)
# self.kps_all = torch.tensor(dic_jo[phase]['kps'])
def __len__(self):
"""
:return: number of samples (m)
"""
return self.inputs_all.shape[0]
def __getitem__(self, idx):
"""
Reading the tensors when required. E.g. Retrieving one element or one batch at a time
:param idx: corresponding to m
"""
inputs = self.inputs_all[idx, :]
outputs = self.outputs_all[idx]
# kps = self.kps_all[idx, :]
return inputs, outputs
class KeypointsDataset(Dataset):
"""
Dataloader fro nuscenes or kitti datasets
"""
def __init__(self, joints, phase):
"""
Load inputs and outputs from the pickles files from gt joints, mask joints or both
"""
assert(phase in ['train', 'val', 'test'])
with open(joints, 'r') as f:
dic_jo = json.load(f)
# Define input and output for normal training and inference
self.inputs_all = torch.tensor(dic_jo[phase]['X'])
self.outputs_all = torch.tensor(dic_jo[phase]['Y'])
self.names_all = dic_jo[phase]['names']
self.kps_all = torch.tensor(dic_jo[phase]['kps'])
# Extract annotations divided in clusters
self.dic_clst = dic_jo[phase]['clst']
def __len__(self):
"""
:return: number of samples (m)
"""
return self.inputs_all.shape[0]
def __getitem__(self, idx):
"""
Reading the tensors when required. E.g. Retrieving one element or one batch at a time
:param idx: corresponding to m
"""
inputs = self.inputs_all[idx, :]
outputs = self.outputs_all[idx]
names = self.names_all[idx]
kps = self.kps_all[idx, :]
return inputs, outputs, names, kps
def get_cluster_annotations(self, clst):
"""Return normalized annotations corresponding to a certain cluster
"""
inputs = torch.tensor(self.dic_clst[clst]['X'])
outputs = torch.tensor(self.dic_clst[clst]['Y']).float()
count = len(self.dic_clst[clst]['Y'])
return inputs, outputs, count

View File

@ -0,0 +1,129 @@
import math
import os
import json
import time
import logging
import random
import datetime
import torch
import numpy as np
from .trainer import Trainer
class HypTuning:
def __init__(self, joints, epochs, monocular, dropout, multiplier=1, r_seed=1):
"""
Initialize directories, load the data and parameters for the training
"""
# Initialize Directories
self.joints = joints
self.monocular = monocular
self.dropout = dropout
self.num_epochs = epochs
self.r_seed = r_seed
dir_out = os.path.join('data', 'models')
dir_logs = os.path.join('data', 'logs')
assert os.path.exists(dir_out), "Output directory not found"
if not os.path.exists(dir_logs):
os.makedirs(dir_logs)
name_out = 'hyp-monoloco-' if monocular else 'hyp-ms-'
self.path_log = os.path.join(dir_logs, name_out)
self.path_model = os.path.join(dir_out, name_out)
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
# Initialize grid of parameters
random.seed(r_seed)
np.random.seed(r_seed)
self.sched_gamma_list = [0.8, 0.9, 1, 0.8, 0.9, 1] * multiplier
random.shuffle(self.sched_gamma_list)
self.sched_step = [10, 20, 40, 60, 80, 100] * multiplier
random.shuffle(self.sched_step)
self.bs_list = [64, 128, 256, 512, 512, 1024] * multiplier
random.shuffle(self.bs_list)
self.hidden_list = [512, 1024, 2048, 512, 1024, 2048] * multiplier
random.shuffle(self.hidden_list)
self.n_stage_list = [3, 3, 3, 3, 3, 3] * multiplier
random.shuffle(self.n_stage_list)
# Learning rate
aa = math.log(0.0005, 10)
bb = math.log(0.01, 10)
log_lr_list = np.random.uniform(aa, bb, int(6 * multiplier)).tolist()
self.lr_list = [10 ** xx for xx in log_lr_list]
# plt.hist(self.lr_list, bins=50)
# plt.show()
def train(self):
"""Train multiple times using log-space random search"""
best_acc_val = 20
dic_best = {}
dic_err_best = {}
start = time.time()
cnt = 0
for idx, lr in enumerate(self.lr_list):
bs = self.bs_list[idx]
sched_gamma = self.sched_gamma_list[idx]
sched_step = self.sched_step[idx]
hidden_size = self.hidden_list[idx]
n_stage = self.n_stage_list[idx]
training = Trainer(joints=self.joints, epochs=self.num_epochs,
bs=bs, monocular=self.monocular, dropout=self.dropout, lr=lr, sched_step=sched_step,
sched_gamma=sched_gamma, hidden_size=hidden_size, n_stage=n_stage,
save=False, print_loss=False, r_seed=self.r_seed)
best_epoch = training.train()
dic_err, model = training.evaluate()
acc_val = dic_err['val']['all']['mean']
cnt += 1
print("Combination number: {}".format(cnt))
if acc_val < best_acc_val:
dic_best['lr'] = lr
dic_best['joints'] = self.joints
dic_best['bs'] = bs
dic_best['monocular'] = self.monocular
dic_best['sched_gamma'] = sched_gamma
dic_best['sched_step'] = sched_step
dic_best['hidden_size'] = hidden_size
dic_best['n_stage'] = n_stage
dic_best['acc_val'] = dic_err['val']['all']['d']
dic_best['best_epoch'] = best_epoch
dic_best['random_seed'] = self.r_seed
# dic_best['acc_test'] = dic_err['test']['all']['mean']
dic_err_best = dic_err
best_acc_val = acc_val
model_best = model
# Save model and log
now = datetime.datetime.now()
now_time = now.strftime("%Y%m%d-%H%M")[2:]
self.path_model = self.path_model + now_time + '.pkl'
torch.save(model_best.state_dict(), self.path_model)
with open(self.path_log + now_time, 'w') as f:
json.dump(dic_best, f)
end = time.time()
print('\n\n\n')
self.logger.info(" Tried {} combinations".format(cnt))
self.logger.info(" Total time for hyperparameters search: {:.2f} minutes".format((end - start) / 60))
self.logger.info(" Best hyperparameters are:")
for key, value in dic_best.items():
self.logger.info(" {}: {}".format(key, value))
print()
self.logger.info("Accuracy in each cluster:")
for key in ('10', '20', '30', '>30', 'all'):
self.logger.info("Val: error in cluster {} = {} ".format(key, dic_err_best['val'][key]['d']))
self.logger.info("Final accuracy Val: {:.2f}".format(dic_best['acc_val']))
self.logger.info("\nSaved the model: {}".format(self.path_model))

196
monstereo/train/losses.py Normal file
View File

@ -0,0 +1,196 @@
"""Inspired by Openpifpaf"""
import math
import torch
import torch.nn as nn
import numpy as np
from ..network import extract_labels, extract_labels_aux, extract_outputs
class AutoTuneMultiTaskLoss(torch.nn.Module):
def __init__(self, losses_tr, losses_val, lambdas, tasks):
super().__init__()
assert all(l in (0.0, 1.0) for l in lambdas)
self.losses = torch.nn.ModuleList(losses_tr)
self.losses_val = losses_val
self.lambdas = lambdas
self.tasks = tasks
self.log_sigmas = torch.nn.Parameter(torch.zeros((len(lambdas),), dtype=torch.float32), requires_grad=True)
def forward(self, outputs, labels, phase='train'):
assert phase in ('train', 'val')
out = extract_outputs(outputs, tasks=self.tasks)
gt_out = extract_labels(labels, tasks=self.tasks)
loss_values = [lam * l(o, g) / (2.0 * (log_sigma.exp() ** 2))
for lam, log_sigma, l, o, g in zip(self.lambdas, self.log_sigmas, self.losses, out, gt_out)]
auto_reg = [log_sigma for log_sigma in self.log_sigmas]
loss = sum(loss_values) + sum(auto_reg)
if phase == 'val':
loss_values_val = [l(o, g) for l, o, g in zip(self.losses_val, out, gt_out)]
loss_values_val.extend([s.exp() for s in self.log_sigmas])
return loss, loss_values_val
return loss, loss_values
class MultiTaskLoss(torch.nn.Module):
def __init__(self, losses_tr, losses_val, lambdas, tasks):
super().__init__()
self.losses = torch.nn.ModuleList(losses_tr)
self.losses_val = losses_val
self.lambdas = lambdas
self.tasks = tasks
if len(self.tasks) == 1 and self.tasks[0] == 'aux':
self.flag_aux = True
else:
self.flag_aux = False
def forward(self, outputs, labels, phase='train'):
assert phase in ('train', 'val')
out = extract_outputs(outputs, tasks=self.tasks)
if self.flag_aux:
gt_out = extract_labels_aux(labels, tasks=self.tasks)
else:
gt_out = extract_labels(labels, tasks=self.tasks)
loss_values = [lam * l(o, g) for lam, l, o, g in zip(self.lambdas, self.losses, out, gt_out)]
loss = sum(loss_values)
if phase == 'val':
loss_values_val = [l(o, g) for l, o, g in zip(self.losses_val, out, gt_out)]
return loss, loss_values_val
return loss, loss_values
class CompositeLoss(torch.nn.Module):
def __init__(self, tasks):
super(CompositeLoss, self).__init__()
self.tasks = tasks
self.multi_loss_tr = {task: (LaplacianLoss() if task == 'd'
else (nn.BCEWithLogitsLoss() if task in ('aux', )
else nn.L1Loss())) for task in tasks}
self.multi_loss_val = {}
for task in tasks:
if task == 'd':
loss = l1_loss_from_laplace
elif task == 'ori':
loss = angle_loss
elif task in ('aux', ):
loss = nn.BCEWithLogitsLoss()
else:
loss = nn.L1Loss()
self.multi_loss_val[task] = loss
def forward(self):
losses_tr = [self.multi_loss_tr[l] for l in self.tasks]
losses_val = [self.multi_loss_val[l] for l in self.tasks]
return losses_tr, losses_val
class LaplacianLoss(torch.nn.Module):
"""1D Gaussian with std depending on the absolute distance"""
def __init__(self, size_average=True, reduce=True, evaluate=False):
super(LaplacianLoss, self).__init__()
self.size_average = size_average
self.reduce = reduce
self.evaluate = evaluate
def laplacian_1d(self, mu_si, xx):
"""
1D Gaussian Loss. f(x | mu, sigma). The network outputs mu and sigma. X is the ground truth distance.
This supports backward().
Inspired by
https://github.com/naba89/RNN-Handwriting-Generation-Pytorch/blob/master/loss_functions.py
"""
eps = 0.01 # To avoid 0/0 when no uncertainty
mu, si = mu_si[:, 0:1], mu_si[:, 1:2]
norm = 1 - mu / xx # Relative
const = 2
term_a = torch.abs(norm) * torch.exp(-si) + eps
term_b = si
norm_bi = (np.mean(np.abs(norm.cpu().detach().numpy())), np.mean(torch.exp(si).cpu().detach().numpy()))
if self.evaluate:
return norm_bi
return term_a + term_b + const
def forward(self, outputs, targets):
values = self.laplacian_1d(outputs, targets)
if not self.reduce or self.evaluate:
return values
if self.size_average:
mean_values = torch.mean(values)
return mean_values
return torch.sum(values)
class GaussianLoss(torch.nn.Module):
"""1D Gaussian with std depending on the absolute distance
"""
def __init__(self, device, size_average=True, reduce=True, evaluate=False):
super(GaussianLoss, self).__init__()
self.size_average = size_average
self.reduce = reduce
self.evaluate = evaluate
self.device = device
def gaussian_1d(self, mu_si, xx):
"""
1D Gaussian Loss. f(x | mu, sigma). The network outputs mu and sigma. X is the ground truth distance.
This supports backward().
Inspired by
https://github.com/naba89/RNN-Handwriting-Generation-Pytorch/blob/master/loss_functions.py
"""
mu, si = mu_si[:, 0:1], mu_si[:, 1:2]
min_si = torch.ones(si.size()).cuda(self.device) * 0.1
si = torch.max(min_si, si)
norm = xx - mu
term_a = (norm / si)**2 / 2
term_b = torch.log(si * math.sqrt(2 * math.pi))
norm_si = (np.mean(np.abs(norm.cpu().detach().numpy())), np.mean(si.cpu().detach().numpy()))
if self.evaluate:
return norm_si
return term_a + term_b
def forward(self, outputs, targets):
values = self.gaussian_1d(outputs, targets)
if not self.reduce or self.evaluate:
return values
if self.size_average:
mean_values = torch.mean(values)
return mean_values
return torch.sum(values)
def angle_loss(orient, gt_orient):
"""Only for evaluation"""
angles = torch.atan2(orient[:, 0], orient[:, 1])
gt_angles = torch.atan2(gt_orient[:, 0], gt_orient[:, 1])
# assert all(angles < math.pi) & all(angles > - math.pi)
# assert all(gt_angles < math.pi) & all(gt_angles > - math.pi)
loss = torch.mean(torch.abs(angles - gt_angles)) * 180 / 3.14
return loss
def l1_loss_from_laplace(out, gt_out):
"""Only for evaluation"""
loss = torch.mean(torch.abs(out[:, 0:1] - gt_out))
return loss

364
monstereo/train/trainer.py Normal file
View File

@ -0,0 +1,364 @@
# pylint: disable=too-many-statements
"""
Training and evaluation of a neural network which predicts 3D localization and confidence intervals
given 2d joints
"""
import copy
import os
import datetime
import logging
from collections import defaultdict
import sys
import time
import warnings
from itertools import chain
import matplotlib.pyplot as plt
import torch
from torch.utils.data import DataLoader
from torch.optim import lr_scheduler
from .datasets import KeypointsDataset
from .losses import CompositeLoss, MultiTaskLoss, AutoTuneMultiTaskLoss
from ..network import extract_outputs, extract_labels
from ..network.architectures import SimpleModel
from ..utils import set_logger
class Trainer:
# Constants
VAL_BS = 10000
tasks = ('d', 'x', 'y', 'h', 'w', 'l', 'ori', 'aux')
val_task = 'd'
lambdas = (1, 1, 1, 1, 1, 1, 1, 1)
def __init__(self, joints, epochs=100, bs=256, dropout=0.2, lr=0.002,
sched_step=20, sched_gamma=1, hidden_size=256, n_stage=3, r_seed=1, n_samples=100,
monocular=False, save=False, print_loss=True):
"""
Initialize directories, load the data and parameters for the training
"""
# Initialize directories and parameters
dir_out = os.path.join('data', 'models')
if not os.path.exists(dir_out):
warnings.warn("Warning: output directory not found, the model will not be saved")
dir_logs = os.path.join('data', 'logs')
if not os.path.exists(dir_logs):
warnings.warn("Warning: default logs directory not found")
assert os.path.exists(joints), "Input file not found"
self.joints = joints
self.num_epochs = epochs
self.save = save
self.print_loss = print_loss
self.monocular = monocular
self.lr = lr
self.sched_step = sched_step
self.sched_gamma = sched_gamma
self.clusters = ['10', '20', '30', '50', '>50']
self.hidden_size = hidden_size
self.n_stage = n_stage
self.dir_out = dir_out
self.n_samples = n_samples
self.r_seed = r_seed
self.auto_tune_mtl = False
# Select the device
use_cuda = torch.cuda.is_available()
self.device = torch.device("cuda" if use_cuda else "cpu")
print('Device: ', self.device)
torch.manual_seed(r_seed)
if use_cuda:
torch.cuda.manual_seed(r_seed)
# Remove auxiliary task if monocular
if self.monocular and self.tasks[-1] == 'aux':
self.tasks = self.tasks[:-1]
self.lambdas = self.lambdas[:-1]
losses_tr, losses_val = CompositeLoss(self.tasks)()
if self.auto_tune_mtl:
self.mt_loss = AutoTuneMultiTaskLoss(losses_tr, losses_val, self.lambdas, self.tasks)
else:
self.mt_loss = MultiTaskLoss(losses_tr, losses_val, self.lambdas, self.tasks)
self.mt_loss.to(self.device)
if not self.monocular:
input_size = 68
output_size = 10
else:
input_size = 34
output_size = 9
now = datetime.datetime.now()
now_time = now.strftime("%Y%m%d-%H%M")[2:]
name_out = 'ms-' + now_time
if self.save:
self.path_model = os.path.join(dir_out, name_out + '.pkl')
self.logger = set_logger(os.path.join(dir_logs, name_out))
self.logger.info("Training arguments: \nepochs: {} \nbatch_size: {} \ndropout: {}"
"\nmonocular: {} \nlearning rate: {} \nscheduler step: {} \nscheduler gamma: {} "
"\ninput_size: {} \noutput_size: {}\nhidden_size: {} \nn_stages: {} "
"\nr_seed: {} \nlambdas: {} \ninput_file: {}"
.format(epochs, bs, dropout, self.monocular, lr, sched_step, sched_gamma, input_size,
output_size, hidden_size, n_stage, r_seed, self.lambdas, self.joints))
else:
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
# Dataloader
self.dataloaders = {phase: DataLoader(KeypointsDataset(self.joints, phase=phase),
batch_size=bs, shuffle=True) for phase in ['train', 'val']}
self.dataset_sizes = {phase: len(KeypointsDataset(self.joints, phase=phase))
for phase in ['train', 'val']}
# Define the model
self.logger.info('Sizes of the dataset: {}'.format(self.dataset_sizes))
print(">>> creating model")
self.model = SimpleModel(input_size=input_size, output_size=output_size, linear_size=hidden_size,
p_dropout=dropout, num_stage=self.n_stage, device=self.device)
self.model.to(self.device)
print(">>> model params: {:.3f}M".format(sum(p.numel() for p in self.model.parameters()) / 1000000.0))
print(">>> loss params: {}".format(sum(p.numel() for p in self.mt_loss.parameters())))
# Optimizer and scheduler
all_params = chain(self.model.parameters(), self.mt_loss.parameters())
self.optimizer = torch.optim.Adam(params=all_params, lr=lr)
self.scheduler = lr_scheduler.StepLR(self.optimizer, step_size=self.sched_step, gamma=self.sched_gamma)
def train(self):
since = time.time()
best_model_wts = copy.deepcopy(self.model.state_dict())
best_acc = 1e6
best_training_acc = 1e6
best_epoch = 0
epoch_losses = defaultdict(lambda: defaultdict(list))
for epoch in range(self.num_epochs):
running_loss = defaultdict(lambda: defaultdict(int))
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
self.model.train() # Set model to training mode
else:
self.model.eval() # Set model to evaluate mode
for inputs, labels, _, _ in self.dataloaders[phase]:
inputs = inputs.to(self.device)
labels = labels.to(self.device)
with torch.set_grad_enabled(phase == 'train'):
if phase == 'train':
outputs = self.model(inputs)
loss, loss_values = self.mt_loss(outputs, labels, phase=phase)
self.optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 2)
self.optimizer.step()
self.scheduler.step()
else:
outputs = self.model(inputs)
with torch.no_grad():
loss_eval, loss_values_eval = self.mt_loss(outputs, labels, phase='val')
self.epoch_logs(phase, loss_eval, loss_values_eval, inputs, running_loss)
self.cout_values(epoch, epoch_losses, running_loss)
# deep copy the model
if epoch_losses['val'][self.val_task][-1] < best_acc:
best_acc = epoch_losses['val'][self.val_task][-1]
best_training_acc = epoch_losses['train']['all'][-1]
best_epoch = epoch
best_model_wts = copy.deepcopy(self.model.state_dict())
time_elapsed = time.time() - since
print('\n\n' + '-' * 120)
self.logger.info('Training:\nTraining complete in {:.0f}m {:.0f}s'
.format(time_elapsed // 60, time_elapsed % 60))
self.logger.info('Best training Accuracy: {:.3f}'.format(best_training_acc))
self.logger.info('Best validation Accuracy for {}: {:.3f}'.format(self.val_task, best_acc))
self.logger.info('Saved weights of the model at epoch: {}'.format(best_epoch))
if self.print_loss:
print_losses(epoch_losses)
# load best model weights
self.model.load_state_dict(best_model_wts)
return best_epoch
def epoch_logs(self, phase, loss, loss_values, inputs, running_loss):
running_loss[phase]['all'] += loss.item() * inputs.size(0)
for i, task in enumerate(self.tasks):
running_loss[phase][task] += loss_values[i].item() * inputs.size(0)
def evaluate(self, load=False, model=None, debug=False):
# To load a model instead of using the trained one
if load:
self.model.load_state_dict(torch.load(model, map_location=lambda storage, loc: storage))
# Average distance on training and test set after unnormalizing
self.model.eval()
dic_err = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0))) # initialized to zero
dic_err['val']['sigmas'] = [0.] * len(self.tasks)
dataset = KeypointsDataset(self.joints, phase='val')
size_eval = len(dataset)
start = 0
with torch.no_grad():
for end in range(self.VAL_BS, size_eval + self.VAL_BS, self.VAL_BS):
end = end if end < size_eval else size_eval
inputs, labels, _, _ = dataset[start:end]
start = end
inputs = inputs.to(self.device)
labels = labels.to(self.device)
# Debug plot for input-output distributions
if debug:
debug_plots(inputs, labels)
sys.exit()
# Forward pass
outputs = self.model(inputs)
self.compute_stats(outputs, labels, dic_err['val'], size_eval, clst='all')
self.cout_stats(dic_err['val'], size_eval, clst='all')
# Evaluate performances on different clusters and save statistics
for clst in self.clusters:
inputs, labels, size_eval = dataset.get_cluster_annotations(clst)
inputs, labels = inputs.to(self.device), labels.to(self.device)
# Forward pass on each cluster
outputs = self.model(inputs)
self.compute_stats(outputs, labels, dic_err['val'], size_eval, clst=clst)
self.cout_stats(dic_err['val'], size_eval, clst=clst)
# Save the model and the results
if self.save and not load:
torch.save(self.model.state_dict(), self.path_model)
print('-' * 120)
self.logger.info("\nmodel saved: {} \n".format(self.path_model))
else:
self.logger.info("\nmodel not saved\n")
return dic_err, self.model
def compute_stats(self, outputs, labels, dic_err, size_eval, clst):
"""Compute mean, bi and max of torch tensors"""
loss, loss_values = self.mt_loss(outputs, labels, phase='val')
rel_frac = outputs.size(0) / size_eval
tasks = self.tasks[:-1] if self.tasks[-1] == 'aux' else self.tasks # Exclude auxiliary
for idx, task in enumerate(tasks):
dic_err[clst][task] += float(loss_values[idx].item()) * (outputs.size(0) / size_eval)
# Distance
errs = torch.abs(extract_outputs(outputs)['d'] - extract_labels(labels)['d'])
assert rel_frac > 0.99, "Variance of errors not supported with partial evaluation"
# Uncertainty
bis = extract_outputs(outputs)['bi'].cpu()
bi = float(torch.mean(bis).item())
bi_perc = float(torch.sum(errs <= bis)) / errs.shape[0]
dic_err[clst]['bi'] += bi * rel_frac
dic_err[clst]['bi%'] += bi_perc * rel_frac
dic_err[clst]['std'] = errs.std()
# (Don't) Save auxiliary task results
if self.monocular:
dic_err[clst]['aux'] = 0
dic_err['sigmas'].append(0)
else:
acc_aux = get_accuracy(extract_outputs(outputs)['aux'], extract_labels(labels)['aux'])
dic_err[clst]['aux'] += acc_aux * rel_frac
if self.auto_tune_mtl:
assert len(loss_values) == 2 * len(self.tasks)
for i, _ in enumerate(self.tasks):
dic_err['sigmas'][i] += float(loss_values[len(tasks) + i + 1].item()) * rel_frac
def cout_stats(self, dic_err, size_eval, clst):
if clst == 'all':
print('-' * 120)
self.logger.info("Evaluation, val set: \nAv. dist D: {:.2f} m with bi {:.2f} ({:.1f}%), \n"
"X: {:.1f} cm, Y: {:.1f} cm \nOri: {:.1f} "
"\n H: {:.1f} cm, W: {:.1f} cm, L: {:.1f} cm"
"\nAuxiliary Task: {:.1f} %, "
.format(dic_err[clst]['d'], dic_err[clst]['bi'], dic_err[clst]['bi%'] * 100,
dic_err[clst]['x'] * 100, dic_err[clst]['y'] * 100,
dic_err[clst]['ori'], dic_err[clst]['h'] * 100, dic_err[clst]['w'] * 100,
dic_err[clst]['l'] * 100, dic_err[clst]['aux'] * 100))
if self.auto_tune_mtl:
self.logger.info("Sigmas: Z: {:.2f}, X: {:.2f}, Y:{:.2f}, H: {:.2f}, W: {:.2f}, L: {:.2f}, ORI: {:.2f}"
" AUX:{:.2f}\n"
.format(*dic_err['sigmas']))
else:
self.logger.info("Val err clust {} --> D:{:.2f}m, bi:{:.2f} ({:.1f}%), STD:{:.1f}m X:{:.1f} Y:{:.1f} "
"Ori:{:.1f}d, H: {:.0f} W: {:.0f} L:{:.0f} for {} pp. "
.format(clst, dic_err[clst]['d'], dic_err[clst]['bi'], dic_err[clst]['bi%'] * 100,
dic_err[clst]['std'], dic_err[clst]['x'] * 100, dic_err[clst]['y'] * 100,
dic_err[clst]['ori'], dic_err[clst]['h'] * 100, dic_err[clst]['w'] * 100,
dic_err[clst]['l'] * 100, size_eval))
def cout_values(self, epoch, epoch_losses, running_loss):
string = '\r' + '{:.0f} '
format_list = [epoch]
for phase in running_loss:
string = string + phase[0:1].upper() + ':'
for el in running_loss['train']:
loss = running_loss[phase][el] / self.dataset_sizes[phase]
epoch_losses[phase][el].append(loss)
if el == 'all':
string = string + ':{:.1f} '
format_list.append(loss)
elif el in ('ori', 'aux'):
string = string + el + ':{:.1f} '
format_list.append(loss)
else:
string = string + el + ':{:.0f} '
format_list.append(loss * 100)
if epoch % 10 == 0:
print(string.format(*format_list))
def debug_plots(inputs, labels):
inputs_shoulder = inputs.cpu().numpy()[:, 5]
inputs_hip = inputs.cpu().numpy()[:, 11]
labels = labels.cpu().numpy()
heights = inputs_hip - inputs_shoulder
plt.figure(1)
plt.hist(heights, bins='auto')
plt.show()
plt.figure(2)
plt.hist(labels, bins='auto')
plt.show()
def print_losses(epoch_losses):
for idx, phase in enumerate(epoch_losses):
for idx_2, el in enumerate(epoch_losses['train']):
plt.figure(idx + idx_2)
plt.plot(epoch_losses[phase][el][10:], label='{} Loss: {}'.format(phase, el))
plt.savefig('figures/{}_loss_{}.png'.format(phase, el))
plt.close()
def get_accuracy(outputs, labels):
"""From Binary cross entropy outputs to accuracy"""
mask = outputs >= 0.5
accuracy = 1. - torch.mean(torch.abs(mask.float() - labels)).item()
return accuracy

View File

@ -0,0 +1,11 @@
from .iou import get_iou_matches, reorder_matches, get_iou_matrix, get_iou_matches_matrix
from .misc import get_task_error, get_pixel_error, append_cluster, open_annotations, make_new_directory, normalize_hwl
from .kitti import check_conditions, get_difficulty, split_training, parse_ground_truth, get_calibration, \
factory_basename, factory_file, get_category, read_and_rewrite
from .camera import xyz_from_distance, get_keypoints, pixel_to_camera, project_3d, open_image, correct_angle,\
to_spherical, to_cartesian, back_correct_angles, project_to_pixels
from .logs import set_logger
from ..utils.nuscenes import select_categories
from ..utils.stereo import mask_joint_disparity, average_locations, extract_stereo_matches, \
verify_stereo, disparity_to_depth

250
monstereo/utils/camera.py Normal file
View File

@ -0,0 +1,250 @@
import math
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
def pixel_to_camera(uv_tensor, kk, z_met):
"""
Convert a tensor in pixel coordinate to absolute camera coordinates
It accepts lists or torch/numpy tensors of (m, 2) or (m, x, 2)
where x is the number of keypoints
"""
if isinstance(uv_tensor, (list, np.ndarray)):
uv_tensor = torch.tensor(uv_tensor)
if isinstance(kk, list):
kk = torch.tensor(kk)
if uv_tensor.size()[-1] != 2:
uv_tensor = uv_tensor.permute(0, 2, 1) # permute to have 2 as last dim to be padded
assert uv_tensor.size()[-1] == 2, "Tensor size not recognized"
uv_padded = F.pad(uv_tensor, pad=(0, 1), mode="constant", value=1) # pad only last-dim below with value 1
kk_1 = torch.inverse(kk)
xyz_met_norm = torch.matmul(uv_padded, kk_1.t()) # More general than torch.mm
xyz_met = xyz_met_norm * z_met
return xyz_met
def project_to_pixels(xyz, kk):
"""Project a single point in space into the image"""
xx, yy, zz = np.dot(kk, xyz)
uu = round(xx / zz)
vv = round(yy / zz)
return [uu, vv]
def project_3d(box_obj, kk):
"""
Project a 3D bounding box into the image plane using the central corners
"""
box_2d = []
# Obtain the 3d points of the box
xc, yc, zc = box_obj.center
ww, _, hh, = box_obj.wlh
# Points corresponding to a box at the z of the center
x1 = xc - ww/2
y1 = yc - hh/2 # Y axis directed below
x2 = xc + ww/2
y2 = yc + hh/2
xyz1 = np.array([x1, y1, zc])
xyz2 = np.array([x2, y2, zc])
corners_3d = np.array([xyz1, xyz2])
# Project them and convert into pixel coordinates
for xyz in corners_3d:
xx, yy, zz = np.dot(kk, xyz)
uu = xx / zz
vv = yy / zz
box_2d.append(uu)
box_2d.append(vv)
return box_2d
def get_keypoints(keypoints, mode):
"""
Extract center, shoulder or hip points of a keypoint
Input --> list or torch/numpy tensor [(m, 3, 17) or (3, 17)]
Output --> torch.tensor [(m, 2)]
"""
if isinstance(keypoints, (list, np.ndarray)):
keypoints = torch.tensor(keypoints)
if len(keypoints.size()) == 2: # add batch dim
keypoints = keypoints.unsqueeze(0)
assert len(keypoints.size()) == 3 and keypoints.size()[1] == 3, "tensor dimensions not recognized"
assert mode in ['center', 'bottom', 'head', 'shoulder', 'hip', 'ankle']
kps_in = keypoints[:, 0:2, :] # (m, 2, 17)
if mode == 'center':
kps_max, _ = kps_in.max(2) # returns value, indices
kps_min, _ = kps_in.min(2)
kps_out = (kps_max - kps_min) / 2 + kps_min # (m, 2) as keepdims is False
elif mode == 'bottom': # bottom center for kitti evaluation
kps_max, _ = kps_in.max(2)
kps_min, _ = kps_in.min(2)
kps_out_x = (kps_max[:, 0:1] - kps_min[:, 0:1]) / 2 + kps_min[:, 0:1]
kps_out_y = kps_max[:, 1:2]
kps_out = torch.cat((kps_out_x, kps_out_y), -1)
elif mode == 'head':
kps_out = kps_in[:, :, 0:5].mean(2)
elif mode == 'shoulder':
kps_out = kps_in[:, :, 5:7].mean(2)
elif mode == 'hip':
kps_out = kps_in[:, :, 11:13].mean(2)
elif mode == 'ankle':
kps_out = kps_in[:, :, 15:17].mean(2)
return kps_out # (m, 2)
def transform_kp(kps, tr_mode):
"""Apply different transformations to the keypoints based on the tr_mode"""
assert tr_mode in ("None", "singularity", "upper", "lower", "horizontal", "vertical", "lateral",
'shoulder', 'knee', 'upside', 'falling', 'random')
uu_c, vv_c = get_keypoints(kps, mode='center')
if tr_mode == "None":
return kps
if tr_mode == "singularity":
uus = [uu_c for uu in kps[0]]
vvs = [vv_c for vv in kps[1]]
elif tr_mode == "vertical":
uus = [uu_c for uu in kps[0]]
vvs = kps[1]
elif tr_mode == 'horizontal':
uus = kps[0]
vvs = [vv_c for vv in kps[1]]
elif tr_mode == 'shoulder':
uus = kps[0]
vvs = kps[1][:7] + [kps[1][6] for vv in kps[1][7:]]
elif tr_mode == 'knee':
uus = kps[0]
vvs = [kps[1][14] for vv in kps[1][:13]] + kps[1][13:]
elif tr_mode == 'up':
uus = kps[0]
vvs = [kp - 300 for kp in kps[1]]
elif tr_mode == 'falling':
uus = [kps[0][16] - kp + kps[1][16] for kp in kps[1]]
vvs = [kps[1][16] - kp + kps[0][16] for kp in kps[0]]
elif tr_mode == 'random':
uu_min = min(kps[0])
uu_max = max(kps[0])
vv_min = min(kps[1])
vv_max = max(kps[1])
np.random.seed(6)
uus = np.random.uniform(uu_min, uu_max, len(kps[0])).tolist()
vvs = np.random.uniform(vv_min, vv_max, len(kps[1])).tolist()
return [uus, vvs, kps[2], []]
def xyz_from_distance(distances, xy_centers):
"""
From distances and normalized image coordinates (z=1), extract the real world position xyz
distances --> tensor (m,1) or (m) or float
xy_centers --> tensor(m,3) or (3)
"""
if isinstance(distances, float):
distances = torch.tensor(distances).unsqueeze(0)
if len(distances.size()) == 1:
distances = distances.unsqueeze(1)
if len(xy_centers.size()) == 1:
xy_centers = xy_centers.unsqueeze(0)
assert xy_centers.size()[-1] == 3 and distances.size()[-1] == 1, "Size of tensor not recognized"
return xy_centers * distances / torch.sqrt(1 + xy_centers[:, 0:1].pow(2) + xy_centers[:, 1:2].pow(2))
def open_image(path_image):
with open(path_image, 'rb') as f:
pil_image = Image.open(f).convert('RGB')
return pil_image
def correct_angle(yaw, xyz):
"""
Correct the angle from the egocentric (global/ rotation_y)
to allocentric (camera perspective / observation angle)
and to be -pi < angle < pi
"""
correction = math.atan2(xyz[0], xyz[2])
yaw = yaw - correction
if yaw > np.pi:
yaw -= 2 * np.pi
elif yaw < -np.pi:
yaw += 2 * np.pi
assert -2 * np.pi <= yaw <= 2 * np.pi
return math.sin(yaw), math.cos(yaw), yaw
def back_correct_angles(yaws, xyz):
corrections = torch.atan2(xyz[:, 0], xyz[:, 2])
yaws = yaws + corrections.view(-1, 1)
mask_up = yaws > math.pi
yaws[mask_up] -= 2 * math.pi
mask_down = yaws < -math.pi
yaws[mask_down] += 2 * math.pi
assert torch.all(yaws < math.pi) & torch.all(yaws > - math.pi)
return yaws
def to_spherical(xyz):
"""convert from cartesian to spherical"""
xyz = np.array(xyz)
r = np.linalg.norm(xyz)
theta = math.atan2(xyz[2], xyz[0])
assert 0 <= theta < math.pi # 0 when positive x and no z.
psi = math.acos(xyz[1] / r)
assert 0 <= psi <= math.pi
return [r, theta, psi]
def to_cartesian(rtp, mode=None):
"""convert from spherical to cartesian"""
if isinstance(rtp, torch.Tensor):
if mode in ('x', 'y'):
r = rtp[:, 2]
t = rtp[:, 0]
p = rtp[:, 1]
if mode == 'x':
x = r * torch.sin(p) * torch.cos(t)
return x.view(-1, 1)
if mode == 'y':
y = r * torch.cos(p)
return y.view(-1, 1)
xyz = rtp.clone()
xyz[:, 0] = rtp[:, 0] * torch.sin(rtp[:, 2]) * torch.cos(rtp[:, 1])
xyz[:, 1] = rtp[:, 0] * torch.cos(rtp[:, 2])
xyz[:, 2] = rtp[:, 0] * torch.sin(rtp[:, 2]) * torch.sin(rtp[:, 1])
return xyz
x = rtp[0] * math.sin(rtp[2]) * math.cos(rtp[1])
y = rtp[0] * math.cos(rtp[2])
z = rtp[0] * math.sin(rtp[2]) * math.sin(rtp[1])
return[x, y, z]

98
monstereo/utils/iou.py Normal file
View File

@ -0,0 +1,98 @@
import numpy as np
def calculate_iou(box1, box2):
# Calculate the (x1, y1, x2, y2) coordinates of the intersection of box1 and box2. Calculate its Area.
# box1 = [-3, 8.5, 3, 11.5]
# box2 = [-3, 9.5, 3, 12.5]
# box1 = [1086.84, 156.24, 1181.62, 319.12]
# box2 = [1078.333357, 159.086347, 1193.771014, 322.239107]
xi1 = max(box1[0], box2[0])
yi1 = max(box1[1], box2[1])
xi2 = min(box1[2], box2[2])
yi2 = min(box1[3], box2[3])
inter_area = max((xi2 - xi1), 0) * max((yi2 - yi1), 0) # Max keeps into account not overlapping box
# Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
union_area = box1_area + box2_area - inter_area
# compute the IoU
iou = inter_area / union_area
return iou
def get_iou_matrix(boxes, boxes_gt):
"""
Get IoU matrix between predicted and ground truth boxes
Dim: (boxes, boxes_gt)
"""
iou_matrix = np.zeros((len(boxes), len(boxes_gt)))
for idx, box in enumerate(boxes):
for idx_gt, box_gt in enumerate(boxes_gt):
iou_matrix[idx, idx_gt] = calculate_iou(box, box_gt)
return iou_matrix
def get_iou_matches(boxes, boxes_gt, iou_min=0.3):
"""From 2 sets of boxes and a minimum threshold, compute the matching indices for IoU matches"""
matches = []
used = []
if not boxes or not boxes_gt:
return []
confs = [box[4] for box in boxes]
indices = list(np.argsort(confs))
for idx in indices[::-1]:
box = boxes[idx]
ious = []
for idx_gt, box_gt in enumerate(boxes_gt):
iou = calculate_iou(box, box_gt)
ious.append(iou)
idx_gt_max = int(np.argmax(ious))
if (ious[idx_gt_max] >= iou_min) and (idx_gt_max not in used):
matches.append((idx, idx_gt_max))
used.append(idx_gt_max)
return matches
def get_iou_matches_matrix(boxes, boxes_gt, thresh):
"""From 2 sets of boxes and a minimum threshold, compute the matching indices for IoU matchings"""
iou_matrix = get_iou_matrix(boxes, boxes_gt)
if not iou_matrix.size:
return []
matches = []
iou_max = np.max(iou_matrix)
while iou_max > thresh:
# Extract the indeces of the max
args_max = np.unravel_index(np.argmax(iou_matrix, axis=None), iou_matrix.shape)
matches.append(args_max)
iou_matrix[args_max[0], :] = 0
iou_matrix[:, args_max[1]] = 0
iou_max = np.max(iou_matrix)
return matches
def reorder_matches(matches, boxes, mode='left_rigth'):
"""
Reorder a list of (idx, idx_gt) matches based on position of the detections in the image
ordered_boxes = (5, 6, 7, 0, 1, 4, 2, 4)
matches = [(0, x), (2,x), (4,x), (3,x), (5,x)]
Output --> [(5, x), (0, x), (3, x), (2, x), (5, x)]
"""
assert mode == 'left_right'
# Order the boxes based on the left-right position in the image and
ordered_boxes = np.argsort([box[0] for box in boxes]) # indices of boxes ordered from left to right
matches_left = [idx for (idx, _) in matches]
return [matches[matches_left.index(idx_boxes)] for idx_boxes in ordered_boxes if idx_boxes in matches_left]

268
monstereo/utils/kitti.py Normal file
View File

@ -0,0 +1,268 @@
import math
import os
import glob
import numpy as np
def get_calibration(path_txt):
"""Read calibration parameters from txt file:
For the left color camera we use P2 which is K * [I|t]
P = [fu, 0, x0, fu*t1-x0*t3
0, fv, y0, fv*t2-y0*t3
0, 0, 1, t3]
check also http://ksimek.github.io/2013/08/13/intrinsic/
Simple case test:
xyz = np.array([2, 3, 30, 1]).reshape(4, 1)
xyz_2 = xyz[0:-1] + tt
uv_temp = np.dot(kk, xyz_2)
uv_1 = uv_temp / uv_temp[-1]
kk_1 = np.linalg.inv(kk)
xyz_temp2 = np.dot(kk_1, uv_1)
xyz_new_2 = xyz_temp2 * xyz_2[2]
xyz_fin_2 = xyz_new_2 - tt
"""
with open(path_txt, "r") as ff:
file = ff.readlines()
p2_str = file[2].split()[1:]
p2_list = [float(xx) for xx in p2_str]
p2 = np.array(p2_list).reshape(3, 4)
p3_str = file[3].split()[1:]
p3_list = [float(xx) for xx in p3_str]
p3 = np.array(p3_list).reshape(3, 4)
kk, tt = get_translation(p2)
kk_right, tt_right = get_translation(p3)
return [kk, tt], [kk_right, tt_right]
def get_translation(pp):
"""Separate intrinsic matrix from translation and convert in lists"""
kk = pp[:, :-1]
f_x = kk[0, 0]
f_y = kk[1, 1]
x0, y0 = kk[2, 0:2]
aa, bb, t3 = pp[0:3, 3]
t1 = float((aa - x0*t3) / f_x)
t2 = float((bb - y0*t3) / f_y)
tt = [t1, t2, float(t3)]
return kk.tolist(), tt
def get_simplified_calibration(path_txt):
with open(path_txt, "r") as ff:
file = ff.readlines()
for line in file:
if line[:4] == 'K_02':
kk_str = line[4:].split()[1:]
kk_list = [float(xx) for xx in kk_str]
kk = np.array(kk_list).reshape(3, 3).tolist()
return kk
raise ValueError('Matrix K_02 not found in the file')
def check_conditions(line, category, method, thresh=0.3):
"""Check conditions of our or m3d txt file"""
check = False
assert category in ['pedestrian', 'cyclist', 'all']
if category == 'all':
category = ['pedestrian', 'person_sitting', 'cyclist']
if method == 'gt':
if line.split()[0].lower() in category:
check = True
else:
conf = float(line[15])
if line[0].lower() in category and conf >= thresh:
check = True
return check
def get_difficulty(box, trunc, occ):
hh = box[3] - box[1]
if hh >= 40 and trunc <= 0.15 and occ <= 0:
cat = 'easy'
elif trunc <= 0.3 and occ <= 1 and hh >= 25:
cat = 'moderate'
elif trunc <= 0.5 and occ <= 2 and hh >= 25:
cat = 'hard'
else:
cat = 'excluded'
return cat
def split_training(names_gt, path_train, path_val):
"""Split training and validation images"""
set_gt = set(names_gt)
set_train = set()
set_val = set()
with open(path_train, "r") as f_train:
for line in f_train:
set_train.add(line[:-1] + '.txt')
with open(path_val, "r") as f_val:
for line in f_val:
set_val.add(line[:-1] + '.txt')
set_train = set_gt.intersection(set_train)
set_train.remove('000518.txt')
set_train.remove('005692.txt')
set_train.remove('003009.txt')
set_train = tuple(set_train)
set_val = tuple(set_gt.intersection(set_val))
assert set_train and set_val, "No validation or training annotations"
return set_train, set_val
def parse_ground_truth(path_gt, category, spherical=False, verbose=False):
"""Parse KITTI ground truth files"""
from ..utils import correct_angle, to_spherical
boxes_gt = []
ys = []
truncs_gt = [] # Float from 0 to 1
occs_gt = [] # Either 0,1,2,3 fully visible, partly occluded, largely occluded, unknown
lines = []
with open(path_gt, "r") as f_gt:
for line_gt in f_gt:
line = line_gt.split()
if check_conditions(line_gt, category, method='gt'):
truncs_gt.append(float(line[1]))
occs_gt.append(int(line[2]))
boxes_gt.append([float(x) for x in line[4:8]])
xyz = [float(x) for x in line[11:14]]
hwl = [float(x) for x in line[8:11]]
dd = float(math.sqrt(xyz[0] ** 2 + xyz[1] ** 2 + xyz[2] ** 2))
yaw = float(line[14])
assert - math.pi <= yaw <= math.pi
alpha = float(line[3])
sin, cos, yaw_corr = correct_angle(yaw, xyz)
assert min(abs(-yaw_corr - alpha), (abs(yaw_corr - alpha))) < 0.15, "more than 10 degrees of error"
if spherical:
rtp = to_spherical(xyz)
loc = rtp[1:3] + xyz[2:3] + rtp[0:1] # [theta, psi, z, r]
else:
loc = xyz + [dd]
# cat = 0 if line[0] in ('Pedestrian', 'Person_sitting') else 1
if line[0] in ('Pedestrian', 'Person_sitting'):
cat = 0
else:
cat = 1
output = loc + hwl + [sin, cos, yaw, cat]
ys.append(output)
if verbose:
lines.append(line_gt)
if verbose:
return boxes_gt, ys, truncs_gt, occs_gt, lines
return boxes_gt, ys, truncs_gt, occs_gt
def factory_basename(dir_ann, dir_gt):
""" Return all the basenames in the annotations folder corresponding to validation images"""
# Extract ground truth validation images
names_gt = tuple(os.listdir(dir_gt))
path_train = os.path.join('splits', 'kitti_train.txt')
path_val = os.path.join('splits', 'kitti_val.txt')
_, set_val_gt = split_training(names_gt, path_train, path_val)
set_val_gt = {os.path.basename(x).split('.')[0] for x in set_val_gt}
# Extract pifpaf files corresponding to validation images
list_ann = glob.glob(os.path.join(dir_ann, '*.json'))
set_basename = {os.path.basename(x).split('.')[0] for x in list_ann}
set_val = set_basename.intersection(set_val_gt)
assert set_val, " Missing json annotations file to create txt files for KITTI datasets"
return set_val
def factory_file(path_calib, dir_ann, basename, mode='left'):
"""Choose the annotation and the calibration files. Stereo option with ite = 1"""
assert mode in ('left', 'right')
p_left, p_right = get_calibration(path_calib)
if mode == 'left':
kk, tt = p_left[:]
path_ann = os.path.join(dir_ann, basename + '.png.pifpaf.json')
else:
kk, tt = p_right[:]
path_ann = os.path.join(dir_ann + '_right', basename + '.png.pifpaf.json')
from ..utils import open_annotations
annotations = open_annotations(path_ann)
return annotations, kk, tt
def get_category(keypoints, path_byc):
"""Find the category for each of the keypoints"""
from ..utils import open_annotations
dic_byc = open_annotations(path_byc)
boxes_byc = dic_byc['boxes'] if dic_byc else []
boxes_ped = make_lower_boxes(keypoints)
matches = get_matches_bikes(boxes_ped, boxes_byc)
list_byc = [match[0] for match in matches]
categories = [1.0 if idx in list_byc else 0.0 for idx, _ in enumerate(boxes_ped)]
return categories
def get_matches_bikes(boxes_ped, boxes_byc):
from . import get_iou_matches_matrix
matches = get_iou_matches_matrix(boxes_ped, boxes_byc, thresh=0.15)
matches_b = []
for idx, idx_byc in matches:
box_ped = boxes_ped[idx]
box_byc = boxes_byc[idx_byc]
width_ped = box_ped[2] - box_ped[0]
width_byc = box_byc[2] - box_byc[0]
center_ped = (box_ped[2] + box_ped[0]) / 2
center_byc = (box_byc[2] + box_byc[0]) / 2
if abs(center_ped - center_byc) < min(width_ped, width_byc) / 4:
matches_b.append((idx, idx_byc))
return matches_b
def make_lower_boxes(keypoints):
lower_boxes = []
keypoints = np.array(keypoints)
for kps in keypoints:
lower_boxes.append([min(kps[0, 9:]), min(kps[1, 9:]), max(kps[0, 9:]), max(kps[1, 9:])])
return lower_boxes
def read_and_rewrite(path_orig, path_new):
"""Read and write same txt file. If file not found, create open file"""
try:
with open(path_orig, "r") as f_gt:
with open(path_new, "w+") as ff:
for line_gt in f_gt:
# if check_conditions(line_gt, category='all', method='gt'):
line = line_gt.split()
hwl = [float(x) for x in line[8:11]]
hwl = " ".join([str(i)[0:4] for i in hwl])
temp_1 = " ".join([str(i) for i in line[0: 8]])
temp_2 = " ".join([str(i) for i in line[11:]])
line_new = temp_1 + ' ' + hwl + ' ' + temp_2 + '\n'
ff.write("%s" % line_new)
except FileNotFoundError:
ff = open(path_new, "a+")
ff.close()

27
monstereo/utils/logs.py Normal file
View File

@ -0,0 +1,27 @@
import logging
def set_logger(log_path):
"""Set the logger to log info in terminal and file `log_path`.
```
logging.info("Starting training...")
```
Args:
log_path: (string) where to log
"""
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.propagate = False
# Logging to a file
file_handler = logging.FileHandler(log_path)
file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))
logger.addHandler(file_handler)
# Logging to console
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(stream_handler)
return logger

74
monstereo/utils/misc.py Normal file
View File

@ -0,0 +1,74 @@
import json
import shutil
import os
import numpy as np
def append_cluster(dic_jo, phase, xx, ys, kps):
"""Append the annotation based on its distance"""
if ys[3] <= 10:
dic_jo[phase]['clst']['10']['kps'].append(kps)
dic_jo[phase]['clst']['10']['X'].append(xx)
dic_jo[phase]['clst']['10']['Y'].append(ys)
elif ys[3] <= 20:
dic_jo[phase]['clst']['20']['kps'].append(kps)
dic_jo[phase]['clst']['20']['X'].append(xx)
dic_jo[phase]['clst']['20']['Y'].append(ys)
elif ys[3] <= 30:
dic_jo[phase]['clst']['30']['kps'].append(kps)
dic_jo[phase]['clst']['30']['X'].append(xx)
dic_jo[phase]['clst']['30']['Y'].append(ys)
elif ys[3] < 50:
dic_jo[phase]['clst']['50']['kps'].append(kps)
dic_jo[phase]['clst']['50']['X'].append(xx)
dic_jo[phase]['clst']['50']['Y'].append(ys)
else:
dic_jo[phase]['clst']['>50']['kps'].append(kps)
dic_jo[phase]['clst']['>50']['X'].append(xx)
dic_jo[phase]['clst']['>50']['Y'].append(ys)
def get_task_error(dd):
"""Get target error not knowing the gender, modeled through a Gaussian Mixure model"""
mm = 0.046
return dd * mm
def get_pixel_error(zz_gt):
"""calculate error in stereo distance due to 1 pixel mismatch (function of depth)"""
disp = 0.54 * 721 / zz_gt
error = abs(zz_gt - 0.54 * 721 / (disp - 1))
return error
def open_annotations(path_ann):
try:
with open(path_ann, 'r') as f:
annotations = json.load(f)
except FileNotFoundError:
annotations = []
return annotations
def make_new_directory(dir_out):
"""Remove the output directory if already exists (avoid residual txt files)"""
if os.path.exists(dir_out):
shutil.rmtree(dir_out)
os.makedirs(dir_out)
print("Created empty output directory for {} txt files".format(dir_out))
def normalize_hwl(lab):
AV_H = 1.72
AV_W = 0.75
AV_L = 0.68
HLW_STD = 0.1
hwl = lab[4:7]
hwl_new = list((np.array(hwl) - np.array([AV_H, AV_W, AV_L])) / HLW_STD)
lab_new = lab[0:4] + hwl_new + lab[7:]
return lab_new

100
monstereo/utils/nuscenes.py Normal file
View File

@ -0,0 +1,100 @@
import random
import json
import os
import numpy as np
def get_unique_tokens(list_fin):
"""
list of json files --> list of unique scene tokens
"""
list_token_scene = []
# Open one json file at a time
for name_fin in list_fin:
with open(name_fin, 'r') as f:
dict_fin = json.load(f)
# Check if the token scene is already in the list and if not add it
if dict_fin['token_scene'] not in list_token_scene:
list_token_scene.append(dict_fin['token_scene'])
return list_token_scene
def split_scenes(list_token_scene, train, val, dir_main, save=False, load=True):
"""
Split the list according tr, val percentages (test percentage is a consequence) after shuffling the order
"""
path_split = os.path.join(dir_main, 'scenes', 'split_scenes.json')
if save:
random.seed(1)
random.shuffle(list_token_scene) # it shuffles in place
n_scenes = len(list_token_scene)
n_train = round(n_scenes * train / 100)
n_val = round(n_scenes * val / 100)
list_train = list_token_scene[0: n_train]
list_val = list_token_scene[n_train: n_train + n_val]
list_test = list_token_scene[n_train + n_val:]
dic_split = {'train': list_train, 'val': list_val, 'test': list_test}
with open(path_split, 'w') as f:
json.dump(dic_split, f)
if load:
with open(path_split, 'r') as f:
dic_split = json.load(f)
return dic_split
def select_categories(cat):
"""
Choose the categories to extract annotations from
"""
assert cat in ['person', 'all', 'car', 'cyclist']
if cat == 'person':
categories = ['human.pedestrian']
elif cat == 'all':
categories = ['human.pedestrian', 'vehicle.bicycle', 'vehicle.motorcycle']
elif cat == 'cyclist':
categories = ['vehicle.bicycle']
elif cat == 'car':
categories = ['vehicle']
return categories
def update_with_tokens(dict_gt, nusc, token_sd):
"""
Update with tokens corresponding to the token_sd
"""
table_sample_data = nusc.get('sample_data', token_sd) # Extract the whole record to get the sample token
token_sample = table_sample_data['sample_token'] # Extract the sample_token from the table
table_sample = nusc.get('sample', token_sample) # Get the record of the sample
token_scene = table_sample['scene_token']
dict_gt['token_sample_data'] = token_sd
dict_gt['token_sample'] = token_sample
dict_gt['token_scene'] = token_scene
return dict_gt
def update_with_box(dict_gt, box):
bbox = np.zeros(7, )
flag_child = False
# Save the 3D bbox
bbox[0:3] = box.center
bbox[3:6] = box.wlh
bbox[6] = box.orientation.degrees
dict_gt['boxes'].append(bbox.tolist()) # Save as list to be serializable by a json file
if box.name == 'human.pedestrian.child':
flag_child = True
return dict_gt, flag_child

198
monstereo/utils/stereo.py Normal file
View File

@ -0,0 +1,198 @@
import warnings
import numpy as np
BF = 0.54 * 721
z_min = 4
z_max = 60
D_MIN = BF / z_max
D_MAX = BF / z_min
def extract_stereo_matches(keypoint, keypoints_r, zz, phase='train', seed=0, method=None):
"""Return binaries representing the match between the pose in the left and the ones in the right"""
stereo_matches = []
cnt_ambiguous = 0
if method == 'mask':
conf_min = 0.1
else:
conf_min = 0.2
avgs_x_l, avgs_x_r, disparities_x, disparities_y = average_locations(keypoint, keypoints_r, conf_min=conf_min)
avg_disparities = [abs(float(l) - BF / zz - float(r)) for l, r in zip(avgs_x_l, avgs_x_r)]
idx_matches = np.argsort(avg_disparities)
# error_max_stereo = 1 * 0.0028 * zz**2 + 0.2 # 2m at 20 meters of depth + 20 cm of offset
error_max_stereo = 0.2 * zz + 0.2 # 2m at 20 meters of depth + 20 cm of offset
error_min_mono = 0.25 * zz + 0.2
error_max_mono = 1 * zz + 0.5
used = []
# Add positive and negative samples
for idx, idx_match in enumerate(idx_matches):
match = avg_disparities[idx_match]
zz_stereo, flag = disparity_to_depth(match + BF / zz)
# Conditions to accept stereo match
conditions = (idx == 0
and match < depth_to_pixel_error(zz, depth_error=error_max_stereo)
and flag
and verify_stereo(zz_stereo, zz, disparities_x[idx_match], disparities_y[idx_match]))
# Positive matches
if conditions:
stereo_matches.append((idx_match, 1))
# Ambiguous
elif match < depth_to_pixel_error(zz, depth_error=error_min_mono):
cnt_ambiguous += 1
# Disparity-range negative
# elif D_MIN < match + BF / zz < D_MAX:
# stereo_matches.append((idx_match, 0))
elif phase == 'val' \
and match < depth_to_pixel_error(zz, depth_error=error_max_mono) \
and not stereo_matches\
and zz < 40:
stereo_matches.append((idx_match, 0))
# # Hard-negative for training
elif phase == 'train' \
and match < depth_to_pixel_error(zz, depth_error=error_max_mono) \
and len(stereo_matches) < 3:
stereo_matches.append((idx_match, 0))
# # Easy-negative
elif phase == 'train' \
and len(stereo_matches) < 3:
np.random.seed(seed + idx)
num = np.random.randint(idx, len(idx_matches))
if idx_matches[num] not in used:
stereo_matches.append((idx_matches[num], 0))
# elif len(stereo_matches) < 1:
# stereo_matches.append((idx_match, 0))
# Easy-negative
# elif len(idx_matches) > len(stereo_matches):
# stereo_matches.append((idx_matches[-1], 0))
# break # matches are ordered
else:
break
used.append(idx_match)
# Make sure each left has at least a negative match
# if not stereo_matches:
# stereo_matches.append((idx_matches[0], 0))
return stereo_matches, cnt_ambiguous
def depth_to_pixel_error(zz, depth_error=1):
"""
Calculate the pixel error at a certain depth due to depth error according to:
e_d = b * f * e_z / (z**2)
"""
e_d = BF * depth_error / (zz**2)
return e_d
def mask_joint_disparity(keypoints, keypoints_r):
"""filter joints based on confidence and interquartile range of the distribution"""
# TODO Merge with average location
CONF_MIN = 0.3
with warnings.catch_warnings() and np.errstate(invalid='ignore'):
disparity_x_mask = np.empty((keypoints.shape[0], keypoints_r.shape[0], 17))
disparity_y_mask = np.empty((keypoints.shape[0], keypoints_r.shape[0], 17))
avg_disparity = np.empty((keypoints.shape[0], keypoints_r.shape[0]))
for idx, kps in enumerate(keypoints):
disparity_x = kps[0, :] - keypoints_r[:, 0, :]
disparity_y = kps[1, :] - keypoints_r[:, 1, :]
# Mask for low confidence
mask_conf_left = kps[2, :] > CONF_MIN
mask_conf_right = keypoints_r[:, 2, :] > CONF_MIN
mask_conf = mask_conf_left & mask_conf_right
disparity_x_conf = np.where(mask_conf, disparity_x, np.nan)
disparity_y_conf = np.where(mask_conf, disparity_y, np.nan)
# Mask outliers using iqr
mask_outlier = interquartile_mask(disparity_x_conf)
x_mask_row = np.where(mask_outlier, disparity_x_conf, np.nan)
y_mask_row = np.where(mask_outlier, disparity_y_conf, np.nan)
avg_row = np.nanmedian(x_mask_row, axis=1) # ignore the nan
# Append
disparity_x_mask[idx] = x_mask_row
disparity_y_mask[idx] = y_mask_row
avg_disparity[idx] = avg_row
return avg_disparity, disparity_x_mask, disparity_y_mask
def average_locations(keypoint, keypoints_r, conf_min=0.2):
"""
Extract absolute average location of keypoints
INPUT: arrays of (1, 3, 17) & (m,3,17)
OUTPUT: 2 arrays of (m).
The left keypoint will have different absolute positions based on the right keypoints they are paired with
"""
keypoint, keypoints_r = np.array(keypoint), np.array(keypoints_r)
assert keypoints_r.shape[0] > 0, "No right keypoints"
with warnings.catch_warnings() and np.errstate(invalid='ignore'):
# Mask by confidence
mask_l_conf = keypoint[0, 2, :] > conf_min
mask_r_conf = keypoints_r[:, 2, :] > conf_min
abs_x_l = np.where(mask_l_conf, keypoint[0, 0:1, :], np.nan)
abs_x_r = np.where(mask_r_conf, keypoints_r[:, 0, :], np.nan)
# Mask by iqr
mask_l_iqr = interquartile_mask(abs_x_l)
mask_r_iqr = interquartile_mask(abs_x_r)
# Combine masks
mask = mask_l_iqr & mask_r_iqr
# Compute absolute locations and relative disparities
x_l = np.where(mask, abs_x_l, np.nan)
x_r = np.where(mask, abs_x_r, np.nan)
x_disp = x_l - x_r
y_disp = np.where(mask, keypoint[0, 1, :] - keypoints_r[:, 1, :], np.nan)
avgs_x_l = np.nanmedian(x_l, axis=1)
avgs_x_r = np.nanmedian(x_r, axis=1)
return avgs_x_l, avgs_x_r, x_disp, y_disp
def interquartile_mask(distribution):
quartile_1, quartile_3 = np.nanpercentile(distribution, [25, 75], axis=1)
iqr = quartile_3 - quartile_1
lower_bound = quartile_1 - (iqr * 1.5)
upper_bound = quartile_3 + (iqr * 1.5)
return (distribution < upper_bound.reshape(-1, 1)) & (distribution > lower_bound.reshape(-1, 1))
def disparity_to_depth(avg_disparity):
try:
zz_stereo = 0.54 * 721. / float(avg_disparity)
flag = True
except (ZeroDivisionError, ValueError): # All nan-slices or zero division
zz_stereo = np.nan
flag = False
return zz_stereo, flag
def verify_stereo(zz_stereo, zz_mono, disparity_x, disparity_y):
"""Verify disparities based on coefficient of variation, maximum y difference and z difference wrt monoloco"""
# COV_MIN = 0.1
y_max_difference = (80 / zz_mono)
z_max_difference = 1 * zz_mono
cov = float(np.nanstd(disparity_x) / np.abs(np.nanmean(disparity_x))) # Coefficient of variation
avg_disparity_y = np.nanmedian(disparity_y)
return abs(zz_stereo - zz_mono) < z_max_difference and avg_disparity_y < y_max_difference and 1 < zz_stereo < 80
# cov < COV_MIN and \

View File

@ -0,0 +1,3 @@
from .printer import Printer
from .figures import show_results, show_spread, show_task_error, show_box_plot

View File

@ -0,0 +1,311 @@
# pylint: disable=R0915
import math
import itertools
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from ..utils import get_task_error, get_pixel_error
def show_results(dic_stats, clusters, show=False, save=False, stereo=True):
"""
Visualize error as function of the distance and compare it with target errors based on human height analyses
"""
dir_out = 'docs'
phase = 'test'
x_min = 3
x_max = 42
y_min = 0
# y_max = 2.2
y_max = 3.5 if stereo else 5.2
xx = np.linspace(x_min, x_max, 100)
excl_clusters = ['all', 'easy', 'moderate', 'hard']
clusters = [clst for clst in clusters if clst not in excl_clusters]
plt.figure(0)
styles = printing_styles(stereo)
for idx_style, style in enumerate(styles.items()):
plt.figure(idx_style)
plt.grid(linewidth=0.2)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xlabel("Ground-truth distance [m]")
plt.ylabel("Average localization error (ALE) [m]")
for idx, method in enumerate(styles['methods']):
errs = [dic_stats[phase][method][clst]['mean'] for clst in clusters[:-1]] # last cluster only a bound
cnts = [dic_stats[phase][method][clst]['cnt'] for clst in clusters[:-1]] # last cluster only a bound
assert errs, "method %s empty" % method
xxs = get_distances(clusters)
plt.plot(xxs, errs, marker=styles['mks'][idx], markersize=styles['mksizes'][idx],
linewidth=styles['lws'][idx],
label=styles['labels'][idx], linestyle=styles['lstyles'][idx], color=styles['colors'][idx])
if method in ('monstereo', 'pseudo-lidar'):
for i, x in enumerate(xxs):
plt.text(x, errs[i], str(cnts[i]), fontsize=10)
if not stereo:
plt.plot(xx, get_task_error(xx), '--', label="Task error", color='lightgreen', linewidth=2.5)
# if stereo:
# yy_stereo = get_pixel_error(xx)
# plt.plot(xx, yy_stereo, linewidth=1.4, color='k', label='Pixel error')
plt.legend(loc='upper left')
if save:
plt.tight_layout()
mode = 'stereo' if stereo else 'mono'
path_fig = os.path.join(dir_out, 'results_' + mode + '.png')
plt.savefig(path_fig)
print("Figure of results " + mode + " saved in {}".format(path_fig))
if show:
plt.show()
plt.close('all')
def show_spread(dic_stats, clusters, show=False, save=False):
"""Predicted confidence intervals and task error as a function of ground-truth distance"""
phase = 'test'
dir_out = 'docs'
excl_clusters = ['all', 'easy', 'moderate', 'hard']
clusters = [clst for clst in clusters if clst not in excl_clusters]
x_min = 3
x_max = 42
y_min = 0
for method in ('monoloco_pp', 'monstereo'):
plt.figure(2)
xxs = get_distances(clusters)
bbs = np.array([dic_stats[phase][method][key]['std_ale'] for key in clusters[:-1]])
if method == 'monoloco_pp':
y_max = 5
color = 'deepskyblue'
epis = np.array([dic_stats[phase][method][key]['std_epi'] for key in clusters[:-1]])
plt.plot(xxs, epis, marker='o', color='coral', label="Combined uncertainty (\u03C3)")
else:
y_max = 3.5
color = 'b'
plt.plot(xx, get_pixel_error(xx), linewidth=1.4, color='k', label='Pixel error')
plt.plot(xxs, bbs, marker='s', color=color, label="Aleatoric uncertainty (b)")
xx = np.linspace(x_min, x_max, 100)
plt.plot(xx, get_task_error(xx), '--', label="Task error (monocular bound)", color='lightgreen', linewidth=2.5)
plt.xlabel("Ground-truth distance [m]")
plt.ylabel("Uncertainty [m]")
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.grid(linewidth=0.2)
plt.legend()
if save:
plt.tight_layout()
path_fig = os.path.join(dir_out, 'spread_' + method + '.png')
plt.savefig(path_fig)
print("Figure of confidence intervals saved in {}".format(path_fig))
if show:
plt.show()
plt.close('all')
def show_task_error(show, save):
"""Task error figure"""
plt.figure(3)
dir_out = 'docs'
xx = np.linspace(0.1, 50, 100)
mu_men = 178
mu_women = 165
mu_child_m = 164
mu_child_w = 156
mm_gmm, mm_male, mm_female = calculate_gmm()
mm_young_male = mm_male + (mu_men - mu_child_m) / mu_men
mm_young_female = mm_female + (mu_women - mu_child_w) / mu_women
yy_male = target_error(xx, mm_male)
yy_female = target_error(xx, mm_female)
yy_young_male = target_error(xx, mm_young_male)
yy_young_female = target_error(xx, mm_young_female)
yy_gender = target_error(xx, mm_gmm)
yy_stereo = get_pixel_error(xx)
plt.grid(linewidth=0.3)
plt.plot(xx, yy_young_male, linestyle='dotted', linewidth=2.1, color='b', label='Adult/young male')
plt.plot(xx, yy_young_female, linestyle='dotted', linewidth=2.1, color='darkorange', label='Adult/young female')
plt.plot(xx, yy_gender, '--', color='lightgreen', linewidth=2.8, label='Generic adult (task error)')
plt.plot(xx, yy_female, '-.', linewidth=1.7, color='darkorange', label='Adult female')
plt.plot(xx, yy_male, '-.', linewidth=1.7, color='b', label='Adult male')
plt.plot(xx, yy_stereo, linewidth=1.7, color='k', label='Pixel error')
plt.xlim(np.min(xx), np.max(xx))
plt.xlabel("Ground-truth distance from the camera $d_{gt}$ [m]")
plt.ylabel("Localization error $\hat{e}$ due to human height variation [m]") # pylint: disable=W1401
plt.legend(loc=(0.01, 0.55)) # Location from 0 to 1 from lower left
if save:
path_fig = os.path.join(dir_out, 'task_error.png')
plt.savefig(path_fig)
print("Figure of task error saved in {}".format(path_fig))
if show:
plt.show()
plt.close('all')
def show_method(save):
""" method figure"""
dir_out = 'docs'
std_1 = 0.75
fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
ell_3 = Ellipse((0, 2), width=std_1 * 2, height=0.3, angle=-90, color='b', fill=False, linewidth=2.5)
ell_4 = Ellipse((0, 2), width=std_1 * 3, height=0.3, angle=-90, color='r', fill=False,
linestyle='dashed', linewidth=2.5)
ax.add_patch(ell_4)
ax.add_patch(ell_3)
plt.plot(0, 2, marker='o', color='skyblue', markersize=9)
plt.plot([0, 3], [0, 4], 'k--')
plt.plot([0, -3], [0, 4], 'k--')
plt.xlim(-3, 3)
plt.ylim(0, 3.5)
plt.xticks([])
plt.yticks([])
plt.xlabel('X [m]')
plt.ylabel('Z [m]')
if save:
path_fig = os.path.join(dir_out, 'output_method.png')
plt.savefig(path_fig)
print("Figure of method saved in {}".format(path_fig))
def show_box_plot(dic_errors, clusters, show=False, save=False):
import pandas as pd
dir_out = 'docs'
excl_clusters = ['all', 'easy', 'moderate', 'hard']
clusters = [int(clst) for clst in clusters if clst not in excl_clusters]
methods = ('monstereo', 'pseudo-lidar', '3dop', 'monoloco')
y_min = 0
y_max = 25 # 18 for the other
xxs = get_distances(clusters)
labels = [str(xx) for xx in xxs]
for idx, method in enumerate(methods):
df = pd.DataFrame([dic_errors[method][str(clst)] for clst in clusters[:-1]]).T
df.columns = labels
plt.figure(idx)
_ = df.boxplot()
name = 'MonStereo' if method == 'monstereo' else method
plt.title(name)
plt.ylabel('Average localization error (ALE) [m]')
plt.xlabel('Ground-truth distance [m]')
plt.ylim(y_min, y_max)
if save:
path_fig = os.path.join(dir_out, 'box_plot_' + name + '.png')
plt.tight_layout()
plt.savefig(path_fig)
print("Figure of box plot saved in {}".format(path_fig))
if show:
plt.show()
plt.close('all')
def target_error(xx, mm):
return mm * xx
def calculate_gmm():
dist_gmm, dist_male, dist_female = height_distributions()
# get_percentile(dist_gmm)
mu_gmm = np.mean(dist_gmm)
mm_gmm = np.mean(np.abs(1 - mu_gmm / dist_gmm))
mm_male = np.mean(np.abs(1 - np.mean(dist_male) / dist_male))
mm_female = np.mean(np.abs(1 - np.mean(dist_female) / dist_female))
print("Mean of GMM distribution: {:.4f}".format(mu_gmm))
print("coefficient for gmm: {:.4f}".format(mm_gmm))
print("coefficient for men: {:.4f}".format(mm_male))
print("coefficient for women: {:.4f}".format(mm_female))
return mm_gmm, mm_male, mm_female
def get_confidence(xx, zz, std):
theta = math.atan2(zz, xx)
delta_x = std * math.cos(theta)
delta_z = std * math.sin(theta)
return (xx - delta_x, xx + delta_x), (zz - delta_z, zz + delta_z)
def get_distances(clusters):
"""Extract distances as intermediate values between 2 clusters"""
distances = []
for idx, _ in enumerate(clusters[:-1]):
clst_0 = float(clusters[idx])
clst_1 = float(clusters[idx + 1])
distances.append((clst_1 - clst_0) / 2 + clst_0)
return tuple(distances)
def get_confidence_points(confidences, distances, errors):
confidence_points = []
distance_points = []
for idx, dd in enumerate(distances):
conf_perc = confidences[idx]
confidence_points.append(errors[idx] + conf_perc)
confidence_points.append(errors[idx] - conf_perc)
distance_points.append(dd)
distance_points.append(dd)
return distance_points, confidence_points
def height_distributions():
mu_men = 178
std_men = 7
mu_women = 165
std_women = 7
dist_men = np.random.normal(mu_men, std_men, int(1e7))
dist_women = np.random.normal(mu_women, std_women, int(1e7))
dist_gmm = np.concatenate((dist_men, dist_women))
return dist_gmm, dist_men, dist_women
def expandgrid(*itrs):
mm = 0
combinations = list(itertools.product(*itrs))
for h_i, h_gt in combinations:
mm += abs(float(1 - h_i / h_gt))
mm /= len(combinations)
return combinations
def get_percentile(dist_gmm):
dd_gt = 1000
mu_gmm = np.mean(dist_gmm)
dist_d = dd_gt * mu_gmm / dist_gmm
perc_d, _ = np.nanpercentile(dist_d, [18.5, 81.5]) # Laplace bi => 63%
perc_d2, _ = np.nanpercentile(dist_d, [23, 77])
mu_d = np.mean(dist_d)
# mm_bi = (mu_d - perc_d) / mu_d
# mm_test = (mu_d - perc_d2) / mu_d
# mad_d = np.mean(np.abs(dist_d - mu_d))
def printing_styles(stereo):
if stereo:
style = {"labels": ['3DOP', 'PSF', 'MonoLoco', 'MonoPSR', 'Pseudo-Lidar', 'Our MonStereo'],
"methods": ['3dop', 'psf', 'monoloco', 'monopsr', 'pseudo-lidar', 'monstereo'],
"mks": ['s', 'p', 'o', 'v', '*', '^'],
"mksizes": [6, 6, 6, 6, 6, 6], "lws": [1.2, 1.2, 1.2, 1.2, 1.3, 1.5],
"colors": ['gold', 'skyblue', 'darkgreen', 'pink', 'darkorange', 'b'],
"lstyles": ['solid', 'solid', 'dashed', 'dashed', 'solid', 'solid']}
else:
style = {"labels": ['Mono3D', 'Geometric Baseline', 'MonoPSR', '3DOP (stereo)', 'MonoLoco', 'Monoloco++'],
"methods": ['m3d', 'geometric', 'monopsr', '3dop', 'monoloco', 'monoloco_pp'],
"mks": ['*', '^', 'p', '.', 's', 'o', 'o'],
"mksizes": [6, 6, 6, 6, 6, 6], "lws": [1.5, 1.5, 1.5, 1.5, 1.5, 2.2],
"colors": ['r', 'purple', 'olive', 'darkorange', 'b', 'darkblue'],
"lstyles": ['solid', 'solid', 'solid', 'dashdot', 'solid', 'solid', ]}
return style

View File

@ -0,0 +1,334 @@
from contextlib import contextmanager
import numpy as np
from PIL import Image
try:
import matplotlib
import matplotlib.pyplot as plt
import scipy.ndimage as ndimage
except ImportError:
matplotlib = None
plt = None
ndimage = None
COCO_PERSON_SKELETON = [
[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13],
[6, 7], [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], [1, 2], [1, 3],
[2, 4], [3, 5], [4, 6], [5, 7]]
@contextmanager
def canvas(fig_file=None, show=True, **kwargs):
if 'figsize' not in kwargs:
# kwargs['figsize'] = (15, 8)
kwargs['figsize'] = (10, 6)
fig, ax = plt.subplots(**kwargs)
yield ax
fig.set_tight_layout(True)
if fig_file:
fig.savefig(fig_file, dpi=200) # , bbox_inches='tight')
if show:
plt.show()
plt.close(fig)
@contextmanager
def image_canvas(image, fig_file=None, show=True, dpi_factor=1.0, fig_width=10.0, **kwargs):
if 'figsize' not in kwargs:
kwargs['figsize'] = (fig_width, fig_width * image.shape[0] / image.shape[1])
fig = plt.figure(**kwargs)
ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
ax.set_axis_off()
ax.set_xlim(0, image.shape[1])
ax.set_ylim(image.shape[0], 0)
fig.add_axes(ax)
image_2 = ndimage.gaussian_filter(image, sigma=2.5)
ax.imshow(image_2, alpha=0.4)
yield ax
if fig_file:
fig.savefig(fig_file, dpi=image.shape[1] / kwargs['figsize'][0] * dpi_factor)
print('keypoints image saved')
if show:
plt.show()
plt.close(fig)
def load_image(path, scale=1.0):
with open(path, 'rb') as f:
image = Image.open(f).convert('RGB')
image = np.asarray(image) * scale / 255.0
return image
class KeypointPainter(object):
def __init__(self, *,
skeleton=None,
xy_scale=1.0, highlight=None, highlight_invisible=False,
show_box=True, linewidth=2, markersize=3,
color_connections=False,
solid_threshold=0.5):
self.skeleton = skeleton or COCO_PERSON_SKELETON
self.xy_scale = xy_scale
self.highlight = highlight
self.highlight_invisible = highlight_invisible
self.show_box = show_box
self.linewidth = linewidth
self.markersize = markersize
self.color_connections = color_connections
self.solid_threshold = solid_threshold
self.dashed_threshold = 0.1 # Patch to still allow force complete pose (set to zero to resume original)
def _draw_skeleton(self, ax, x, y, v, *, color=None):
if not np.any(v > 0):
return
if self.skeleton is not None:
for ci, connection in enumerate(np.array(self.skeleton) - 1):
c = color
if self.color_connections:
c = matplotlib.cm.get_cmap('tab20')(ci / len(self.skeleton))
if np.all(v[connection] > self.dashed_threshold):
ax.plot(x[connection], y[connection],
linewidth=self.linewidth, color=c,
linestyle='dashed', dash_capstyle='round')
if np.all(v[connection] > self.solid_threshold):
ax.plot(x[connection], y[connection],
linewidth=self.linewidth, color=c, solid_capstyle='round')
# highlight invisible keypoints
inv_color = 'k' if self.highlight_invisible else color
ax.plot(x[v > self.dashed_threshold], y[v > self.dashed_threshold],
'o', markersize=self.markersize,
markerfacecolor=color, markeredgecolor=inv_color, markeredgewidth=2)
ax.plot(x[v > self.solid_threshold], y[v > self.solid_threshold],
'o', markersize=self.markersize,
markerfacecolor=color, markeredgecolor=color, markeredgewidth=2)
if self.highlight is not None:
v_highlight = v[self.highlight]
ax.plot(x[self.highlight][v_highlight > 0],
y[self.highlight][v_highlight > 0],
'o', markersize=self.markersize*2, markeredgewidth=2,
markerfacecolor=color, markeredgecolor=color)
@staticmethod
def _draw_box(ax, x, y, v, color, score=None):
if not np.any(v > 0):
return
# keypoint bounding box
x1, x2 = np.min(x[v > 0]), np.max(x[v > 0])
y1, y2 = np.min(y[v > 0]), np.max(y[v > 0])
if x2 - x1 < 5.0:
x1 -= 2.0
x2 += 2.0
if y2 - y1 < 5.0:
y1 -= 2.0
y2 += 2.0
ax.add_patch(
matplotlib.patches.Rectangle(
(x1, y1), x2 - x1, y2 - y1, fill=False, color=color))
if score:
ax.text(x1, y1, '{:.4f}'.format(score), fontsize=8, color=color)
@staticmethod
def _draw_text(ax, x, y, v, text, color):
if not np.any(v > 0):
return
# keypoint bounding box
x1, x2 = np.min(x[v > 0]), np.max(x[v > 0])
y1, y2 = np.min(y[v > 0]), np.max(y[v > 0])
if x2 - x1 < 5.0:
x1 -= 2.0
x2 += 2.0
if y2 - y1 < 5.0:
y1 -= 2.0
y2 += 2.0
ax.text(x1 + 2, y1 - 2, text, fontsize=8,
color='white', bbox={'facecolor': color, 'alpha': 0.5, 'linewidth': 0})
@staticmethod
def _draw_scales(ax, xs, ys, vs, color, scales):
for x, y, v, scale in zip(xs, ys, vs, scales):
if v == 0.0:
continue
ax.add_patch(
matplotlib.patches.Rectangle(
(x - scale, y - scale), 2 * scale, 2 * scale, fill=False, color=color))
def keypoints(self, ax, keypoint_sets, *, scores=None, color=None, colors=None, texts=None):
if keypoint_sets is None:
return
if color is None and self.color_connections:
color = 'white'
if color is None and colors is None:
colors = range(len(keypoint_sets))
for i, kps in enumerate(np.asarray(keypoint_sets)):
assert kps.shape[1] == 3
x = kps[:, 0] * self.xy_scale
y = kps[:, 1] * self.xy_scale
v = kps[:, 2]
if colors is not None:
color = colors[i]
if isinstance(color, (int, np.integer)):
color = matplotlib.cm.get_cmap('tab20')((color % 20 + 0.05) / 20)
self._draw_skeleton(ax, x, y, v, color=color)
if self.show_box:
score = scores[i] if scores is not None else None
self._draw_box(ax, x, y, v, color, score)
if texts is not None:
self._draw_text(ax, x, y, v, texts[i], color)
def annotations(self, ax, annotations, *,
color=None, colors=None, texts=None):
if annotations is None:
return
if color is None and self.color_connections:
color = 'white'
if color is None and colors is None:
colors = range(len(annotations))
for i, ann in enumerate(annotations):
if colors is not None:
color = colors[i]
text = texts[i] if texts is not None else None
self.annotation(ax, ann, color=color, text=text)
def annotation(self, ax, ann, *, color, text=None):
if isinstance(color, (int, np.integer)):
color = matplotlib.cm.get_cmap('tab20')((color % 20 + 0.05) / 20)
kps = ann.data
assert kps.shape[1] == 3
x = kps[:, 0] * self.xy_scale
y = kps[:, 1] * self.xy_scale
v = kps[:, 2]
self._draw_skeleton(ax, x, y, v, color=color)
if ann.joint_scales is not None:
self._draw_scales(ax, x, y, v, color, ann.joint_scales)
if self.show_box:
self._draw_box(ax, x, y, v, color, ann.score())
if text is not None:
self._draw_text(ax, x, y, v, text, color)
def quiver(ax, vector_field, intensity_field=None, step=1, threshold=0.5,
xy_scale=1.0, uv_is_offset=False,
reg_uncertainty=None, **kwargs):
x, y, u, v, c, r = [], [], [], [], [], []
for j in range(0, vector_field.shape[1], step):
for i in range(0, vector_field.shape[2], step):
if intensity_field is not None and intensity_field[j, i] < threshold:
continue
x.append(i * xy_scale)
y.append(j * xy_scale)
u.append(vector_field[0, j, i] * xy_scale)
v.append(vector_field[1, j, i] * xy_scale)
c.append(intensity_field[j, i] if intensity_field is not None else 1.0)
r.append(reg_uncertainty[j, i] * xy_scale if reg_uncertainty is not None else None)
x = np.array(x)
y = np.array(y)
u = np.array(u)
v = np.array(v)
c = np.array(c)
r = np.array(r)
s = np.argsort(c)
if uv_is_offset:
u -= x
v -= y
for xx, yy, uu, vv, _, rr in zip(x, y, u, v, c, r):
if not rr:
continue
circle = matplotlib.patches.Circle(
(xx + uu, yy + vv), rr / 2.0, zorder=11, linewidth=1, alpha=1.0,
fill=False, color='orange')
ax.add_artist(circle)
return ax.quiver(x[s], y[s], u[s], v[s], c[s],
angles='xy', scale_units='xy', scale=1, zOrder=10, **kwargs)
def arrows(ax, fourd, xy_scale=1.0, threshold=0.0, **kwargs):
mask = np.min(fourd[:, 2], axis=0) >= threshold
fourd = fourd[:, :, mask]
(x1, y1), (x2, y2) = fourd[:, :2, :] * xy_scale
c = np.min(fourd[:, 2], axis=0)
s = np.argsort(c)
return ax.quiver(x1[s], y1[s], (x2 - x1)[s], (y2 - y1)[s], c[s],
angles='xy', scale_units='xy', scale=1, zOrder=10, **kwargs)
def boxes(ax, scalar_field, intensity_field=None, xy_scale=1.0, step=1, threshold=0.5,
cmap='viridis_r', clim=(0.5, 1.0), **kwargs):
x, y, s, c = [], [], [], []
for j in range(0, scalar_field.shape[0], step):
for i in range(0, scalar_field.shape[1], step):
if intensity_field is not None and intensity_field[j, i] < threshold:
continue
x.append(i * xy_scale)
y.append(j * xy_scale)
s.append(scalar_field[j, i] * xy_scale)
c.append(intensity_field[j, i] if intensity_field is not None else 1.0)
cmap = matplotlib.cm.get_cmap(cmap)
cnorm = matplotlib.colors.Normalize(vmin=clim[0], vmax=clim[1])
for xx, yy, ss, cc in zip(x, y, s, c):
color = cmap(cnorm(cc))
rectangle = matplotlib.patches.Rectangle(
(xx - ss, yy - ss), ss * 2.0, ss * 2.0,
color=color, zorder=10, linewidth=1, **kwargs)
ax.add_artist(rectangle)
def circles(ax, scalar_field, intensity_field=None, xy_scale=1.0, step=1, threshold=0.5,
cmap='viridis_r', clim=(0.5, 1.0), **kwargs):
x, y, s, c = [], [], [], []
for j in range(0, scalar_field.shape[0], step):
for i in range(0, scalar_field.shape[1], step):
if intensity_field is not None and intensity_field[j, i] < threshold:
continue
x.append(i * xy_scale)
y.append(j * xy_scale)
s.append(scalar_field[j, i] * xy_scale)
c.append(intensity_field[j, i] if intensity_field is not None else 1.0)
cmap = matplotlib.cm.get_cmap(cmap)
cnorm = matplotlib.colors.Normalize(vmin=clim[0], vmax=clim[1])
for xx, yy, ss, cc in zip(x, y, s, c):
color = cmap(cnorm(cc))
circle = matplotlib.patches.Circle(
(xx, yy), ss,
color=color, zorder=10, linewidth=1, **kwargs)
ax.add_artist(circle)
def white_screen(ax, alpha=0.9):
ax.add_patch(
plt.Rectangle((0, 0), 1, 1, transform=ax.transAxes, alpha=alpha,
facecolor='white')
)

View File

@ -0,0 +1,98 @@
import numpy as np
def correct_boxes(boxes, hwls, xyzs, yaws, path_calib):
with open(path_calib, "r") as ff:
file = ff.readlines()
p2_str = file[2].split()[1:]
p2_list = [float(xx) for xx in p2_str]
P = np.array(p2_list).reshape(3, 4)
boxes_new = []
for idx, box in enumerate(boxes):
hwl = hwls[idx]
xyz = xyzs[idx]
yaw = yaws[idx]
corners_2d, corners_3d = compute_box_3d(hwl, xyz, yaw, P)
box_new = project_8p_to_4p(corners_2d).reshape(-1).tolist()
boxes_new.append(box_new)
return boxes_new
def compute_box_3d(hwl, xyz, ry, P):
""" Takes an object and a projection matrix (P) and projects the 3d
bounding box into the image plane.
Returns:
corners_2d: (8,2) array in left image coord.
corners_3d: (8,3) array in in rect camera coord.
"""
# compute rotational matrix around yaw axis
R = roty(ry)
# 3d bounding box dimensions
l = hwl[2]
w = hwl[1]
h = hwl[0]
# 3d bounding box corners
x_corners = [l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2]
y_corners = [0, 0, 0, 0, -h, -h, -h, -h]
z_corners = [w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2]
# rotate and translate 3d bounding box
corners_3d = np.dot(R, np.vstack([x_corners, y_corners, z_corners]))
# print corners_3d.shape
corners_3d[0, :] = corners_3d[0, :] + xyz[0]
corners_3d[1, :] = corners_3d[1, :] + xyz[1]
corners_3d[2, :] = corners_3d[2, :] + xyz[2]
# print 'cornsers_3d: ', corners_3d
# only draw 3d bounding box for objs in front of the camera
if np.any(corners_3d[2, :] < 0.1):
corners_2d = None
return corners_2d, np.transpose(corners_3d)
# project the 3d bounding box into the image plane
corners_2d = project_to_image(np.transpose(corners_3d), P)
# print 'corners_2d: ', corners_2d
return corners_2d, np.transpose(corners_3d)
def roty(t):
""" Rotation about the y-axis. """
c = np.cos(t)
s = np.sin(t)
return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
def project_to_image(pts_3d, P):
""" Project 3d points to image plane.
Usage: pts_2d = projectToImage(pts_3d, P)
input: pts_3d: nx3 matrix
P: 3x4 projection matrix
output: pts_2d: nx2 matrix
P(3x4) dot pts_3d_extended(4xn) = projected_pts_2d(3xn)
=> normalize projected_pts_2d(2xn)
<=> pts_3d_extended(nx4) dot P'(4x3) = projected_pts_2d(nx3)
=> normalize projected_pts_2d(nx2)
"""
n = pts_3d.shape[0]
pts_3d_extend = np.hstack((pts_3d, np.ones((n, 1))))
# print(('pts_3d_extend shape: ', pts_3d_extend.shape))
pts_2d = np.dot(pts_3d_extend, np.transpose(P)) # nx3
pts_2d[:, 0] /= pts_2d[:, 2]
pts_2d[:, 1] /= pts_2d[:, 2]
return pts_2d[:, 0:2]
def project_8p_to_4p(pts_2d):
x0 = np.min(pts_2d[:, 0])
x1 = np.max(pts_2d[:, 0])
y0 = np.min(pts_2d[:, 1])
y1 = np.max(pts_2d[:, 1])
x0 = max(0, x0)
y0 = max(0, y0)
return np.array([x0, y0, x1, y1])

View File

@ -0,0 +1,330 @@
"""
Class for drawing frontal, bird-eye-view and combined figures
"""
# pylint: disable=attribute-defined-outside-init
import math
from collections import OrderedDict
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.patches import Ellipse, Circle, Rectangle
from mpl_toolkits.axes_grid1 import make_axes_locatable
from ..utils import pixel_to_camera, get_task_error
class Printer:
"""
Print results on images: birds eye view and computed distance
"""
FONTSIZE_BV = 16
FONTSIZE = 18
TEXTCOLOR = 'darkorange'
COLOR_KPS = 'yellow'
def __init__(self, image, output_path, kk, output_types, epistemic=False, z_max=30, fig_width=10):
self.im = image
self.kk = kk
self.output_types = output_types
self.epistemic = epistemic
self.z_max = z_max # To include ellipses in the image
self.y_scale = 1
self.width = self.im.size[0]
self.height = self.im.size[1]
self.fig_width = fig_width
# Define the output dir
self.output_path = output_path
self.cmap = cm.get_cmap('jet')
self.extensions = []
# Define variables of the class to change for every image
self.mpl_im0 = self.stds_ale = self.stds_epi = self.xx_gt = self.zz_gt = self.xx_pred = self.zz_pred =\
self.dds_real = self.uv_centers = self.uv_shoulders = self.uv_kps = self.boxes = self.boxes_gt = \
self.uv_camera = self.radius = self.auxs = None
def _process_results(self, dic_ann):
# Include the vectors inside the interval given by z_max
self.stds_ale = dic_ann['stds_ale']
self.stds_epi = dic_ann['stds_epi']
self.gt = dic_ann['gt'] # regulate ground-truth matching
self.xx_gt = [xx[0] for xx in dic_ann['xyz_real']]
self.xx_pred = [xx[0] for xx in dic_ann['xyz_pred']]
# Do not print instances outside z_max
self.zz_gt = [xx[2] if xx[2] < self.z_max - self.stds_epi[idx] else 0
for idx, xx in enumerate(dic_ann['xyz_real'])]
self.zz_pred = [xx[2] if xx[2] < self.z_max - self.stds_epi[idx] else 0
for idx, xx in enumerate(dic_ann['xyz_pred'])]
self.dds_real = dic_ann['dds_real']
self.uv_shoulders = dic_ann['uv_shoulders']
self.boxes = dic_ann['boxes']
self.boxes_gt = dic_ann['boxes_gt']
self.uv_camera = (int(self.im.size[0] / 2), self.im.size[1])
self.radius = 11 / 1600 * self.width
if dic_ann['aux']:
self.auxs = dic_ann['aux'] if dic_ann['aux'] else None
def factory_axes(self):
"""Create axes for figures: front bird combined"""
axes = []
figures = []
# Initialize combined figure, resizing it for aesthetic proportions
if 'combined' in self.output_types:
assert 'bird' and 'front' not in self.output_types, \
"combined figure cannot be print together with front or bird ones"
self.y_scale = self.width / (self.height * 2) # Defined proportion
if self.y_scale < 0.95 or self.y_scale > 1.05: # allows more variation without resizing
self.im = self.im.resize((self.width, round(self.height * self.y_scale)))
self.width = self.im.size[0]
self.height = self.im.size[1]
fig_width = self.fig_width + 0.6 * self.fig_width
fig_height = self.fig_width * self.height / self.width
# Distinguish between KITTI images and general images
fig_ar_1 = 0.8
width_ratio = 1.9
self.extensions.append('.combined.png')
fig, (ax0, ax1) = plt.subplots(1, 2, sharey=False, gridspec_kw={'width_ratios': [width_ratio, 1]},
figsize=(fig_width, fig_height))
ax1.set_aspect(fig_ar_1)
fig.set_tight_layout(True)
fig.subplots_adjust(left=0.02, right=0.98, bottom=0, top=1, hspace=0, wspace=0.02)
figures.append(fig)
assert 'front' not in self.output_types and 'bird' not in self.output_types, \
"--combined arguments is not supported with other visualizations"
# Initialize front figure
elif 'front' in self.output_types:
width = self.fig_width
height = self.fig_width * self.height / self.width
self.extensions.append(".front.png")
plt.figure(0)
fig0, ax0 = plt.subplots(1, 1, figsize=(width, height))
fig0.set_tight_layout(True)
figures.append(fig0)
# Create front figure axis
if any(xx in self.output_types for xx in ['front', 'combined']):
ax0 = self.set_axes(ax0, axis=0)
divider = make_axes_locatable(ax0)
cax = divider.append_axes('right', size='3%', pad=0.05)
bar_ticks = self.z_max // 5 + 1
norm = matplotlib.colors.Normalize(vmin=0, vmax=self.z_max)
scalar_mappable = plt.cm.ScalarMappable(cmap=self.cmap, norm=norm)
scalar_mappable.set_array([])
plt.colorbar(scalar_mappable, ticks=np.linspace(0, self.z_max, bar_ticks),
boundaries=np.arange(- 0.05, self.z_max + 0.1, .1), cax=cax, label='Z [m]')
axes.append(ax0)
if not axes:
axes.append(None)
# Initialize bird-eye-view figure
if 'bird' in self.output_types:
self.extensions.append(".bird.png")
fig1, ax1 = plt.subplots(1, 1)
fig1.set_tight_layout(True)
figures.append(fig1)
if any(xx in self.output_types for xx in ['bird', 'combined']):
ax1 = self.set_axes(ax1, axis=1) # Adding field of view
axes.append(ax1)
return figures, axes
def draw(self, figures, axes, dic_out, image, show_all=False, draw_text=True, legend=True, draw_box=False,
save=False, show=False):
# Process the annotation dictionary of monoloco
self._process_results(dic_out)
# whether to include instances that don't match the ground-truth
iterator = range(len(self.zz_pred)) if show_all else range(len(self.zz_gt))
if not iterator:
print("-"*110 + '\n' + "! No instances detected, be sure to include file with ground-truth values or "
"use the command --show_all" + '\n' + "-"*110)
# Draw the front figure
num = 0
self.mpl_im0.set_data(image)
for idx in iterator:
if any(xx in self.output_types for xx in ['front', 'combined']) and self.zz_pred[idx] > 0:
color = self.cmap((self.zz_pred[idx] % self.z_max) / self.z_max)
self.draw_circle(axes, self.uv_shoulders[idx], color)
if draw_box:
self.draw_boxes(axes, idx, color)
if draw_text:
self.draw_text_front(axes, self.uv_shoulders[idx], num)
num += 1
# Draw the bird figure
num = 0
for idx in iterator:
if any(xx in self.output_types for xx in ['bird', 'combined']) and self.zz_pred[idx] > 0:
# Draw ground truth and uncertainty
self.draw_uncertainty(axes, idx)
# Draw bird eye view text
if draw_text:
self.draw_text_bird(axes, idx, num)
num += 1
# Add the legend
if legend:
draw_legend(axes)
# Draw, save or/and show the figures
for idx, fig in enumerate(figures):
fig.canvas.draw()
if save:
fig.savefig(self.output_path + self.extensions[idx], bbox_inches='tight')
if show:
fig.show()
plt.close(fig)
def draw_uncertainty(self, axes, idx):
theta = math.atan2(self.zz_pred[idx], self.xx_pred[idx])
dic_std = {'ale': self.stds_ale[idx], 'epi': self.stds_epi[idx]}
dic_x, dic_y = {}, {}
# Aleatoric and epistemic
for key, std in dic_std.items():
delta_x = std * math.cos(theta)
delta_z = std * math.sin(theta)
dic_x[key] = (self.xx_pred[idx] - delta_x, self.xx_pred[idx] + delta_x)
dic_y[key] = (self.zz_pred[idx] - delta_z, self.zz_pred[idx] + delta_z)
# MonoLoco
if not self.auxs:
axes[1].plot(dic_x['epi'], dic_y['epi'], color='coral', linewidth=2, label="Epistemic Uncertainty")
axes[1].plot(dic_x['ale'], dic_y['ale'], color='deepskyblue', linewidth=4, label="Aleatoric Uncertainty")
axes[1].plot(self.xx_pred[idx], self.zz_pred[idx], color='cornflowerblue', label="Prediction", markersize=6,
marker='o')
if self.gt[idx]:
axes[1].plot(self.xx_gt[idx], self.zz_gt[idx],
color='k', label="Ground-truth", markersize=8, marker='x')
# MonStereo(stereo case)
elif self.auxs[idx] > 0.5:
axes[1].plot(dic_x['ale'], dic_y['ale'], color='r', linewidth=4, label="Prediction (mono)")
axes[1].plot(dic_x['ale'], dic_y['ale'], color='deepskyblue', linewidth=4, label="Prediction (stereo+mono)")
if self.gt[idx]:
axes[1].plot(self.xx_gt[idx], self.zz_gt[idx],
color='k', label="Ground-truth", markersize=8, marker='x')
# MonStereo (monocular case)
else:
axes[1].plot(dic_x['ale'], dic_y['ale'], color='deepskyblue', linewidth=4, label="Prediction (stereo+mono)")
axes[1].plot(dic_x['ale'], dic_y['ale'], color='r', linewidth=4, label="Prediction (mono)")
if self.gt[idx]:
axes[1].plot(self.xx_gt[idx], self.zz_gt[idx],
color='k', label="Ground-truth", markersize=8, marker='x')
def draw_ellipses(self, axes, idx):
"""draw uncertainty ellipses"""
target = get_task_error(self.dds_real[idx])
angle_gt = get_angle(self.xx_gt[idx], self.zz_gt[idx])
ellipse_real = Ellipse((self.xx_gt[idx], self.zz_gt[idx]), width=target * 2, height=1,
angle=angle_gt, color='lightgreen', fill=True, label="Task error")
axes[1].add_patch(ellipse_real)
if abs(self.zz_gt[idx] - self.zz_pred[idx]) > 0.001:
axes[1].plot(self.xx_gt[idx], self.zz_gt[idx], 'kx', label="Ground truth", markersize=3)
angle = get_angle(self.xx_pred[idx], self.zz_pred[idx])
ellipse_ale = Ellipse((self.xx_pred[idx], self.zz_pred[idx]), width=self.stds_ale[idx] * 2,
height=1, angle=angle, color='b', fill=False, label="Aleatoric Uncertainty",
linewidth=1.3)
ellipse_var = Ellipse((self.xx_pred[idx], self.zz_pred[idx]), width=self.stds_epi[idx] * 2,
height=1, angle=angle, color='r', fill=False, label="Uncertainty",
linewidth=1, linestyle='--')
axes[1].add_patch(ellipse_ale)
if self.epistemic:
axes[1].add_patch(ellipse_var)
axes[1].plot(self.xx_pred[idx], self.zz_pred[idx], 'ro', label="Predicted", markersize=3)
def draw_boxes(self, axes, idx, color):
ww_box = self.boxes[idx][2] - self.boxes[idx][0]
hh_box = (self.boxes[idx][3] - self.boxes[idx][1]) * self.y_scale
ww_box_gt = self.boxes_gt[idx][2] - self.boxes_gt[idx][0]
hh_box_gt = (self.boxes_gt[idx][3] - self.boxes_gt[idx][1]) * self.y_scale
rectangle = Rectangle((self.boxes[idx][0], self.boxes[idx][1] * self.y_scale),
width=ww_box, height=hh_box, fill=False, color=color, linewidth=3)
rectangle_gt = Rectangle((self.boxes_gt[idx][0], self.boxes_gt[idx][1] * self.y_scale),
width=ww_box_gt, height=hh_box_gt, fill=False, color='g', linewidth=2)
axes[0].add_patch(rectangle_gt)
axes[0].add_patch(rectangle)
def draw_text_front(self, axes, uv, num):
axes[0].text(uv[0] + self.radius, uv[1] * self.y_scale - self.radius, str(num),
fontsize=self.FONTSIZE, color=self.TEXTCOLOR, weight='bold')
def draw_text_bird(self, axes, idx, num):
"""Plot the number in the bird eye view map"""
std = self.stds_epi[idx] if self.stds_epi[idx] > 0 else self.stds_ale[idx]
theta = math.atan2(self.zz_pred[idx], self.xx_pred[idx])
delta_x = std * math.cos(theta)
delta_z = std * math.sin(theta)
axes[1].text(self.xx_pred[idx] + delta_x, self.zz_pred[idx] + delta_z,
str(num), fontsize=self.FONTSIZE_BV, color='darkorange')
def draw_circle(self, axes, uv, color):
circle = Circle((uv[0], uv[1] * self.y_scale), radius=self.radius, color=color, fill=True)
axes[0].add_patch(circle)
def set_axes(self, ax, axis):
assert axis in (0, 1)
if axis == 0:
ax.set_axis_off()
ax.set_xlim(0, self.width)
ax.set_ylim(self.height, 0)
self.mpl_im0 = ax.imshow(self.im)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
else:
uv_max = [0., float(self.height)]
xyz_max = pixel_to_camera(uv_max, self.kk, self.z_max)
x_max = abs(xyz_max[0]) # shortcut to avoid oval circles in case of different kk
corr = round(float(x_max / 3))
ax.plot([0, x_max], [0, self.z_max], 'k--')
ax.plot([0, -x_max], [0, self.z_max], 'k--')
ax.set_xlim(-x_max+corr, x_max-corr)
ax.set_ylim(0, self.z_max+1)
ax.set_xlabel("X [m]")
return ax
def draw_legend(axes):
handles, labels = axes[1].get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
axes[1].legend(by_label.values(), by_label.keys(), loc='best')
def get_angle(xx, zz):
"""Obtain the points to plot the confidence of each annotation"""
theta = math.atan2(zz, xx)
angle = theta * (180 / math.pi)
return angle

44
setup.py Normal file
View File

@ -0,0 +1,44 @@
from setuptools import setup
# extract version from __init__.py
with open('monstereo/__init__.py', 'r') as f:
VERSION_LINE = [l for l in f if l.startswith('__version__')][0]
VERSION = VERSION_LINE.split('=')[1].strip()[1:-1]
setup(
name='monstereo',
version=VERSION,
packages=[
'monstereo',
'monstereo.network',
'monstereo.eval',
'monstereo.train',
'monstereo.prep',
'monstereo.visuals',
'monstereo.utils'
],
license='GNU AGPLv3',
description='MonStereo',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='None',
zip_safe=False,
install_requires=[
'openpifpaf==0.8.0',
'torch==1.1.0',
'torchvision==0.3.0'
],
extras_require={
'eval': [
'tabulate==0.8.3',
'sklearn',
'pandas',
'pylint',
'pytest',
],
'prep': [
'nuscenes-devkit==1.0.2',
],
},
)

3712
splits/kitti_train.txt Normal file

File diff suppressed because it is too large Load Diff

3769
splits/kitti_val.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,100 @@
0d2cc345342a460e94ff54748338ac22
bc4fd5a05a004333b9411754630f4cba
6ab3d1e9476d4cd89d4949d69d056901
75a4ec12042542149b0a77a0a10d6330
8fbbe701baf641359129ea166e1674ec
15e1fa06e30e438a98430cc1fd0e8a69
448cf480b0b8400a86881d28c2c5f734
bef135921f374f838bf0badae55cac83
a0942c87bc704f74a86b6513860e3f05
ab6eea0e06c84f70be411a9d36636a7a
2ffd7e2a1daf4b928464ddb2ed3dca59
634a8c5835e44aec912604a9a1972a5d
8931a57994764c9b945a7a1b352c9ae5
fd5a3c6d3ad44954a8045edbe9d93763
7cf32f906f50415786414ce8bbe10e9b
c7492bdc08f8450fa580b7787331f0c9
265f002f02d447ad9074813292eef75e
73030fb67d3c46cfb5e590168088ae39
c3e0e9f6ee8d4170a3d22a6179f1ca3a
25496f19ffd14bd088cb430bfc01a4d7
6f5133fe62b240e797bac25aeff8b531
7deb4760e2244f32b57f9d631b535b66
bc219c0fa63b43b4b9dddab47fce1fef
9a61a88ed9094334a73aa93c08222110
dd61533869aa48f2aaa7e8a6418bdbe6
daa9fce50073470398da3c2bccdaf21b
c075fbdd97124beaba95bc5c25149f30
41fde20fedcd4d22ab26811688612870
d1e57234fd6a463d963670938f9f556e
813213458a214a39a1d1fc77fa52fa34
efa5c96f05594f41a2498eb9f2e7ad99
3dd9ad3f963e4f588d75c112cbf07f56
b51869782c0e464b8021eb798609f35f
de943e246dad4ad686de98008a634ecf
4d475873416a4860900f5af213e0027c
03ee880dd4e348f4b3407f0d073c7c70
7e3a6bdd6c6f4c8fb018cff404974446
d0880a386b6d434bb5cd13c134af7a3e
d7ebcbbd26d849b384c11bec8df28a9b
0c601ff2bf004fccafec366b08bf29e2
b79d940da8df43d09ee972c2414ffeca
1d4db80d13f342aba4881b38099bc4b7
3a1850241080418b88dcee97c7d17ed7
6520b5f0d568414c973f791b30ee1548
82aef599650d462db73731b7ff40918b
f444b757d7e2444c889da10f02b73491
9047b53fd41540649dce014a128cbe1b
6e81ee0f64274490a403bbd6482c2bf9
bb73edb93a0a46c4be997c576e9beb61
3dd2be428534403ba150a0b60abc6a0a
5a0dd8908a3a459b83ec5eb6ac7d0f82
7a74411015ad4aadaa9f15b8a7001652
2f56eb47c64f43df8902d9f88aa8a019
8edbc31083ab4fb187626e5b3c0411f7
bc1e8034cf774087bb59af4484125e7d
359f9c029ae44e1d9d47c05bc7915561
70368a18644046f898ab836fc8a3c03f
8758419c03ab47a59ea6d6620176f3a3
eac3102e4cc24d4b95532bcc711a902f
798e8504b4364d378270333a349ef508
4047f251c21a475abb49518e0fa6fa9e
cf550d9670274ac1a7f274fbacb39c48
095d9b93b583425f910ae2afaf1d017d
9a81caa3d5134d7f87ee4786ccef68f7
0e37d4a357db4246a908cfd97d17efc6
37b32e4e8cf846679b2c0cb342dbd4aa
6d4b2bd795ae4c66900ad98ccd2371a6
8b43539a55374b6c8ed60c95a42d63a2
446af4b1d7da4735a607bc3e45c2e0b3
83773bcf46ac486383529098de0542dd
433a14f8dcf5457fb2c4def5c749122a
9a1188aba4bf458c8220818a6c0be55a
dcd5bc29543747e28ef02816dd458290
bb028034cb474e3da8953f83752a70a9
cc8c0bf57f984915a77078b10eb33198
a1ca2ba59ac9452fb3da60019bf32c71
ce2d6bdc33084dc1a2780f41f6740e06
e6cb595f6df44b3999db28c65f2244ac
cb3ef7b7ef124983b336c781f134cdfb
bed8426a524d45afab05b19cf02386b2
36fbee38a28543ea9e27a67d64e1dee4
00590cbfa24a430a8c274b51e1c71231
52b30ecd104a4f4eab6f8f5684a73e56
5c9bd7ead37e4aa9989f7909f3a78baa
ef5f216134a94e308697ab4c75402a20
dc6235e2281943548084c484cb38b876
8857cf15fa7049a6b000490835d3b9fc
4f28b42169f4404cbab4b43476e13885
f57957ebc5654b649a0786d993b64be4
d90b94e8bfd446cd9407f48665122268
4db0eee3b82d49b198c1a411cf7f7d68
3700281722c1440e9605ec077bdce397
df28f1cfafc04219a7f7caab45e12d28
7365754410624f2f85087003f4ed41ad
01c8c59260db4a3682d7b4f8da65425e
7365495b74464629813b41eacdb711af
cba3ddd5c3664a43b6a08e586e094900
91c071bcc1ad4fa1b555399e1cfbab79
b4b82c4d338a4b6d86835388ce076345
68e79a88244f447f993a72da444b29ba

View File

@ -0,0 +1 @@
{"train": ["83773bcf46ac486383529098de0542dd", "8fbbe701baf641359129ea166e1674ec", "15e1fa06e30e438a98430cc1fd0e8a69", "eac3102e4cc24d4b95532bcc711a902f", "634a8c5835e44aec912604a9a1972a5d", "b79d940da8df43d09ee972c2414ffeca", "73030fb67d3c46cfb5e590168088ae39", "3dd9ad3f963e4f588d75c112cbf07f56", "37b32e4e8cf846679b2c0cb342dbd4aa", "4db0eee3b82d49b198c1a411cf7f7d68", "c075fbdd97124beaba95bc5c25149f30", "433a14f8dcf5457fb2c4def5c749122a", "bc1e8034cf774087bb59af4484125e7d", "00590cbfa24a430a8c274b51e1c71231", "7a74411015ad4aadaa9f15b8a7001652", "36fbee38a28543ea9e27a67d64e1dee4", "8758419c03ab47a59ea6d6620176f3a3", "bef135921f374f838bf0badae55cac83", "6d4b2bd795ae4c66900ad98ccd2371a6", "448cf480b0b8400a86881d28c2c5f734", "df28f1cfafc04219a7f7caab45e12d28", "25496f19ffd14bd088cb430bfc01a4d7", "265f002f02d447ad9074813292eef75e", "91c071bcc1ad4fa1b555399e1cfbab79", "70368a18644046f898ab836fc8a3c03f", "a0942c87bc704f74a86b6513860e3f05", "dc6235e2281943548084c484cb38b876", "ef5f216134a94e308697ab4c75402a20", "8931a57994764c9b945a7a1b352c9ae5", "9047b53fd41540649dce014a128cbe1b", "bc219c0fa63b43b4b9dddab47fce1fef", "0c601ff2bf004fccafec366b08bf29e2", "4047f251c21a475abb49518e0fa6fa9e", "6f5133fe62b240e797bac25aeff8b531", "7365495b74464629813b41eacdb711af", "7365754410624f2f85087003f4ed41ad", "cba3ddd5c3664a43b6a08e586e094900", "1d4db80d13f342aba4881b38099bc4b7", "dcd5bc29543747e28ef02816dd458290", "8b43539a55374b6c8ed60c95a42d63a2", "bc4fd5a05a004333b9411754630f4cba", "82aef599650d462db73731b7ff40918b", "d0880a386b6d434bb5cd13c134af7a3e", "d90b94e8bfd446cd9407f48665122268", "6e81ee0f64274490a403bbd6482c2bf9", "daa9fce50073470398da3c2bccdaf21b", "cf550d9670274ac1a7f274fbacb39c48", "efa5c96f05594f41a2498eb9f2e7ad99", "41fde20fedcd4d22ab26811688612870", "01c8c59260db4a3682d7b4f8da65425e", "fd5a3c6d3ad44954a8045edbe9d93763", "68e79a88244f447f993a72da444b29ba", "c7492bdc08f8450fa580b7787331f0c9", "03ee880dd4e348f4b3407f0d073c7c70", "ce2d6bdc33084dc1a2780f41f6740e06", "0d2cc345342a460e94ff54748338ac22", "d7ebcbbd26d849b384c11bec8df28a9b", "cb3ef7b7ef124983b336c781f134cdfb", "52b30ecd104a4f4eab6f8f5684a73e56", "5a0dd8908a3a459b83ec5eb6ac7d0f82", "dd61533869aa48f2aaa7e8a6418bdbe6", "3dd2be428534403ba150a0b60abc6a0a", "095d9b93b583425f910ae2afaf1d017d", "cc8c0bf57f984915a77078b10eb33198"], "val": ["f57957ebc5654b649a0786d993b64be4", "bb028034cb474e3da8953f83752a70a9", "6520b5f0d568414c973f791b30ee1548", "0e37d4a357db4246a908cfd97d17efc6", "3700281722c1440e9605ec077bdce397", "2ffd7e2a1daf4b928464ddb2ed3dca59", "798e8504b4364d378270333a349ef508", "de943e246dad4ad686de98008a634ecf", "7deb4760e2244f32b57f9d631b535b66", "3a1850241080418b88dcee97c7d17ed7", "5c9bd7ead37e4aa9989f7909f3a78baa", "bed8426a524d45afab05b19cf02386b2", "9a1188aba4bf458c8220818a6c0be55a", "446af4b1d7da4735a607bc3e45c2e0b3", "2f56eb47c64f43df8902d9f88aa8a019", "f444b757d7e2444c889da10f02b73491", "4d475873416a4860900f5af213e0027c", "7e3a6bdd6c6f4c8fb018cff404974446", "8857cf15fa7049a6b000490835d3b9fc", "ab6eea0e06c84f70be411a9d36636a7a", "6ab3d1e9476d4cd89d4949d69d056901", "c3e0e9f6ee8d4170a3d22a6179f1ca3a", "a1ca2ba59ac9452fb3da60019bf32c71", "b4b82c4d338a4b6d86835388ce076345", "9a81caa3d5134d7f87ee4786ccef68f7", "b51869782c0e464b8021eb798609f35f", "8edbc31083ab4fb187626e5b3c0411f7", "9a61a88ed9094334a73aa93c08222110"], "test": []}

File diff suppressed because one or more lines are too long

1
tests/joints_sample.json Normal file

File diff suppressed because one or more lines are too long

89
tests/test_iou.ipynb Normal file
View File

@ -0,0 +1,89 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import math\n",
"def calculate_iou(box1, box2):\n",
"\n",
" # Calculate the (x1, y1, x2, y2) coordinates of the intersection of box1 and box2. Calculate its Area.\n",
" xi1 = max(box1[0], box2[0])\n",
" yi1 = max(box1[1], box2[1])\n",
" xi2 = min(box1[2], box2[2])\n",
" yi2 = min(box1[3], box2[3])\n",
" inter_area = max((xi2 - xi1), 0) * max((yi2 - yi1), 0) # Max keeps into account not overlapping box\n",
"\n",
" # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)\n",
" box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])\n",
" box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])\n",
" union_area = box1_area + box2_area - inter_area\n",
"\n",
" # compute the IoU\n",
" iou = inter_area / union_area\n",
"\n",
" return iou"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"15.0\n",
"[8.450052369622647, 12.393410142113215, 88.45005236962265, 77.39341014211321]\n",
"0.4850460596873889\n"
]
}
],
"source": [
"x1 = 75\n",
"y1 = 60\n",
"\n",
"box1 = [0, 0, x1, y1]\n",
"alpha = math.atan2(110,75) # good number\n",
"diag = 15\n",
"x_cateto = diag * math.cos(alpha)\n",
"y_cateto = diag * math.sin(alpha)\n",
"print(math.sqrt(x_cateto**2 + y_cateto**2))\n",
"box2 = [x_cateto, y_cateto, x1 + x_cateto + 5, y1 + y_cateto+ 5]\n",
"print(box2)\n",
"print(calculate_iou(box1, box2))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

69
tests/test_package.py Normal file
View File

@ -0,0 +1,69 @@
"""Test if the main modules of the package run correctly"""
import os
import sys
import json
# Python does not consider the current directory to be a package
sys.path.insert(0, os.path.join('..', 'monoloco'))
from PIL import Image
from stereoloco.train import Trainer
from stereoloco.network import MonoLoco
from stereoloco.network.process import preprocess_pifpaf, factory_for_gt
from stereoloco.visuals.printer import Printer
JOINTS = 'tests/joints_sample.json'
PIFPAF_KEYPOINTS = 'tests/002282.png.pifpaf.json'
IMAGE = 'docs/002282.png'
def tst_trainer(joints):
trainer = Trainer(joints=joints, epochs=150, lr=0.01)
_ = trainer.train()
dic_err, model = trainer.evaluate()
return dic_err['val']['all']['mean'], model
def tst_prediction(model, path_keypoints):
with open(path_keypoints, 'r') as f:
pifpaf_out = json.load(f)
kk, _ = factory_for_gt(im_size=[1240, 340])
# Preprocess pifpaf outputs and run monoloco
boxes, keypoints = preprocess_pifpaf(pifpaf_out)
monoloco = MonoLoco(model)
outputs, varss = monoloco.forward(keypoints, kk)
dic_out = monoloco.post_process(outputs, varss, boxes, keypoints, kk)
return dic_out, kk
def tst_printer(dic_out, kk, image_path):
"""Draw a fake figure"""
with open(image_path, 'rb') as f:
pil_image = Image.open(f).convert('RGB')
printer = Printer(image=pil_image, output_path='tests/test_image', kk=kk, output_types=['combined'], z_max=15)
figures, axes = printer.factory_axes()
printer.draw(figures, axes, dic_out, pil_image, save=True)
def test_package():
# Training test
val_acc, model = tst_trainer(JOINTS)
assert val_acc < 2.5
# Prediction test
dic_out, kk = tst_prediction(model, PIFPAF_KEYPOINTS)
assert dic_out['boxes'] and kk
# Visualization test
tst_printer(dic_out, kk, IMAGE)

24
tests/test_utils.py Normal file
View File

@ -0,0 +1,24 @@
import os
import sys
# Python does not consider the current directory to be a package
sys.path.insert(0, os.path.join('..', 'monoloco'))
def test_iou():
from stereoloco.utils import get_iou_matrix
boxes_pred = [[1, 100, 1, 200]]
boxes_gt = [[100., 120., 150., 160.],[12, 110, 130., 160.]]
iou_matrix = get_iou_matrix(boxes_pred, boxes_gt)
assert iou_matrix.shape == (len(boxes_pred), len(boxes_gt))
def test_pixel_to_camera():
from stereoloco.utils import pixel_to_camera
kk = [[718.3351, 0., 600.3891], [0., 718.3351, 181.5122], [0., 0., 1.]]
zz = 10
uv_vector = [1000., 400.]
xx_norm = pixel_to_camera(uv_vector, kk, 1)[0]
xx_1 = xx_norm * zz
xx_2 = pixel_to_camera(uv_vector, kk, zz)[0]
assert xx_1 == xx_2

23
tests/test_visuals.py Normal file
View File

@ -0,0 +1,23 @@
import os
import sys
from collections import defaultdict
from PIL import Image
# Python does not consider the current directory to be a package
sys.path.insert(0, os.path.join('..', 'monoloco'))
def test_printer():
"""Draw a fake figure"""
from stereoloco.visuals.printer import Printer
test_list = [[718.3351, 0., 600.3891], [0., 718.3351, 181.5122], [0., 0., 1.]]
boxes = [xx + [0] for xx in test_list]
kk = test_list
dict_ann = defaultdict(lambda: [1., 2., 3.], xyz_real=test_list, xyz_pred=test_list, uv_shoulders=test_list,
boxes=boxes, boxes_gt=boxes)
with open('docs/002282.png', 'rb') as f:
pil_image = Image.open(f).convert('RGB')
printer = Printer(image=pil_image, output_path=None, kk=kk, output_types=['combined'])
figures, axes = printer.factory_axes()
printer.draw(figures, axes, dict_ann, pil_image)