Commit ·
a3341ee
1
Parent(s): e7fca21
Include evaluation tools for 2024 edition
Browse filesFiles changed (24)
- MTMC_Tracking_2024/eval/3rdParty_Licenses.mdAdded+882
- MTMC_Tracking_2024/eval/README.mdAdded+41
- MTMC_Tracking_2024/eval/main.pyAdded+228
- MTMC_Tracking_2024/eval/sample_file/ground_truth_test_full.txtAdded+3
- MTMC_Tracking_2024/eval/sample_file/pred.txtAdded+3
- MTMC_Tracking_2024/eval/sample_file/scene_name_2_cam_id_full.jsonAdded+3
- MTMC_Tracking_2024/eval/trackeval/__init__.pyAdded+6
- MTMC_Tracking_2024/eval/trackeval/_timing.pyAdded+81
- MTMC_Tracking_2024/eval/trackeval/datasets/__init__.pyAdded+3
- MTMC_Tracking_2024/eval/trackeval/datasets/_base_dataset.pyAdded+362
- MTMC_Tracking_2024/eval/trackeval/datasets/mot_challenge_2d_box.pyAdded+471
- MTMC_Tracking_2024/eval/trackeval/datasets/mot_challenge_3d_location.pyAdded+475
- MTMC_Tracking_2024/eval/trackeval/datasets/test_mot.pyAdded+475
- MTMC_Tracking_2024/eval/trackeval/eval.pyAdded+233
- MTMC_Tracking_2024/eval/trackeval/metrics/__init__.pyAdded+5
- MTMC_Tracking_2024/eval/trackeval/metrics/_base_metric.pyAdded+199
- MTMC_Tracking_2024/eval/trackeval/metrics/clear.pyAdded+223
- MTMC_Tracking_2024/eval/trackeval/metrics/count.pyAdded+76
- MTMC_Tracking_2024/eval/trackeval/metrics/hota.pyAdded+245
- MTMC_Tracking_2024/eval/trackeval/metrics/identity.pyAdded+172
- MTMC_Tracking_2024/eval/trackeval/plotting.pyAdded+322
- MTMC_Tracking_2024/eval/trackeval/utils.pyAdded+204
- MTMC_Tracking_2024/eval/utils/__init__.pyAdded+1
- MTMC_Tracking_2024/eval/utils/io_utils.pyAdded+217
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882# Third-Party Licenses
This project incorporates components from the following open-source software. We have provided links to the licenses for each component below.
| Package / Component Name | Version | License | Link to Component's License ||---|---|---|---|| pandas | 2.3.1 | GNU General Public License v3.0 | [link](https://github.com/PandasWS/Pandas/blob/master/LICENSE)| matplotlib | 3.5.2 | Other (Please describe in Comments) | [link](https://github.com/matplotlib/matplotlib/blob/main/LICENSE/LICENSE) || scipy | 1.15.3 | BSD (any variant) | [link](https://github.com/scipy/scipy/tree/main?tab=BSD-3-Clause-1-ov-file#readme) |
### MIT License```MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.```
### BSD License ```BSD License
Copyright (c) [year] [fullname]All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BELIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OFSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESSINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER INCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.```
### OtherNumpy license ```Copyright (c) 2005-2023, NumPy Developers.All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.```
### MatplotLib
```License agreement for matplotlib versions 1.3.0 and later=========================================================
1. This LICENSE AGREEMENT is between the Matplotlib Development Team("MDT"), and the Individual or Organization ("Licensee") accessing andotherwise using matplotlib software in source or binary form and itsassociated documentation.
2. Subject to the terms and conditions of this License Agreement, MDThereby grants Licensee a nonexclusive, royalty-free, world-wide licenseto reproduce, analyze, test, perform and/or display publicly, preparederivative works, distribute, and otherwise use matplotlibalone or in any derivative version, provided, however, that MDT'sLicense Agreement and MDT's notice of copyright, i.e., "Copyright (c)2012- Matplotlib Development Team; All Rights Reserved" are retained inmatplotlib alone or in any derivative version prepared byLicensee.
3. In the event Licensee prepares a derivative work that is based on orincorporates matplotlib or any part thereof, and wants tomake the derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe changes made to matplotlib .
4. MDT is making matplotlib available to Licensee on an "ASIS" basis. MDT MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIBWILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES ORLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USINGMATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OFTHE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create anyrelationship of agency, partnership, or joint venture between MDT andLicensee. This License Agreement does not grant permission to use MDTtrademarks or trade name in a trademark sense to endorse or promoteproducts or services of Licensee, or any third party.
8. By copying, installing or otherwise using matplotlib ,Licensee agrees to be bound by the terms and conditions of this LicenseAgreement.
License agreement for matplotlib versions prior to 1.3.0========================================================
1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and theIndividual or Organization ("Licensee") accessing and otherwise usingmatplotlib software in source or binary form and its associateddocumentation.
2. Subject to the terms and conditions of this License Agreement, JDHhereby grants Licensee a nonexclusive, royalty-free, world-wide licenseto reproduce, analyze, test, perform and/or display publicly, preparederivative works, distribute, and otherwise use matplotlibalone or in any derivative version, provided, however, that JDH'sLicense Agreement and JDH's notice of copyright, i.e., "Copyright (c)2002-2011 John D. Hunter; All Rights Reserved" are retained inmatplotlib alone or in any derivative version prepared byLicensee.
3. In the event Licensee prepares a derivative work that is based on orincorporates matplotlib or any part thereof, and wants tomake the derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe changes made to matplotlib.
4. JDH is making matplotlib available to Licensee on an "ASIS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIBWILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES ORLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USINGMATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OFTHE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create anyrelationship of agency, partnership, or joint venture between JDH andLicensee. This License Agreement does not grant permission to use JDHtrademarks or trade name in a trademark sense to endorse or promoteproducts or services of Licensee, or any third party.
8. By copying, installing or otherwise using matplotlib,Licensee agrees to be bound by the terms and conditions of this LicenseAgreement.```
### GNU
GNU GENERAL PUBLIC LICENSE Version 3, 29 June 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 General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. 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 workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha 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 visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation 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 toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients 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 toproduce it from the Program, in the form of source code under theterms 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 independentworks, 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 notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-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 excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe 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 installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional 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 youadd to a covered work, you may (if authorized by the copyright holders ofthat 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 "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform 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 expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered 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 automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent 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 anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain 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 limitingany implied license or other defenses to infringement that mayotherwise 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 orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES 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 OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy 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 greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "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 General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<http://www.gnu.org/philosophy/why-not-lgpl.html>.1234567891011121314151617181920212223242526272829303132333435363738394041# Evaluation Code for - MTMC Tracking 2024 Dataset
Evaluation code for the Multi-Target Multi-Camera (MTMC) 2024 dataset.
The evaluation utilizes Higher Order Tracking Accuracy (HOTA) score as an evaluation metric for multi-object tracking that addresses the limitations of previous metrics like MOTA and IDF1. It integrates three key aspects of MOT: accurate detection, association, and localization into a unified metric. This comprehensive approach balances the importance of detecting each object (detection), correctly identifying objects across different frames (association), and accurately localizing objects in each frame (localization). Furthermore, HOTA can be decomposed into simpler components, allowing for detailed analysis of different aspects of tracking behavior.
HOTA scores calculated using 3D distance measurements in a multi-camera setting.
# Environment setup:```- [Optional] conda create -n mtmc_eval_2024 python=3.10- [Optional] conda activate mtmc_eval_2024
- pip3 install pandas- pip3 install matplotlib- pip3 install scipy```
# Usage:
- Set the --prediction_file argument to a valid prediction file. - Set the --ground_truth_file argument to a valid test file. - Set the --num_cores argument based on your setup. - Set the --scene_2_camera_id_file argument
Example below:```python3 main.py --prediction_file ./sample_file/pred.txt --ground_truth_file ./sample_file/ground_truth_test_full.txt --num_cores 16 --scene_2_camera_id_file ./sample_file/scene_name_2_cam_id_full.json
Sample Result:Total runtime: 187.0887589454651 seconds.HOTA: 49.2825%DetA: 49.1998%AssA: 49.3655%LocA: 77.0546%```
## Acknowledgements
This project utilizes a portion of code from [TrackEval](https://github.com/JonathonLuiten/TrackEval), an open-source project by Jonathon Luiten for evaluating multi-camera tracking results. TrackEval is licensed under the MIT License, which you can find in full [here](https://github.com/JonathonLuiten/TrackEval/blob/master/LICENSE).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228#!/usr/bin/python3"""Evaluation script for the Multi-Camera People Tracking track in the AI City Challenge, Track 1 in 2024.
# Environment setup:[Optional] conda create -n aicity24-track1 python=3.10[Optional] conda activate aicity24-track1
pip3 install pandaspip3 install matplotlibpip3 install scipy
# Usage: Set number of cores based on your cpu core count.
python3 aicityeval-track1.py --prediction_file ./sample_file/pred.txt --ground_truth_file ./sample_file/ground_truth_test_full.txt --num_cores 16 --scene_2_camera_id_file ./sample_file/scene_name_2_cam_id_full.json
python3 aicityeval-track1.py --prediction_file ./sample_file/pred.txt --ground_truth_file ./sample_file/ground_truth_test_half.txt --num_cores 16 --scene_2_camera_id_file ./sample_file/scene_name_2_cam_id_half.json
"""import osimport sysimport timeimport tempfileimport trackevalimport pandas as pdimport numpy as np
from argparse import ArgumentParser, ArgumentTypeErrorfrom typing import Listfrom utils.io_utils import load_csv_to_dataframe_from_file, write_dataframe_to_csv_to_file, make_seq_maps_file, make_seq_ini_file, make_dir, check_file_size, get_scene_to_camera_id_dict
def get_unique_entry_per_scene(dataframe, scene_name, scene_2_camera_id): camera_ids = scene_2_camera_id[scene_name] filtered_df = dataframe[dataframe["CameraId"].isin(camera_ids)] unique_entries_df = filtered_df.drop_duplicates(subset=["FrameId", "Id"]) return unique_entries_df
def check_positive(value): int_value = int(value) if int_value <= 0: raise ArgumentTypeError(f"{value} is an invalid num of cores") return int_value
def computes_mot_metrics(prediction_file_path: str, ground_truth_path: str, output_dir: str, num_cores: int, scene_2_cam_id_file: str) -> None:
check_file_size(prediction_file_path)
# Create a temp directory if output_dir is not specified is_temp_dir = False if output_dir is None: temp_dir = tempfile.TemporaryDirectory() is_temp_dir = True output_dir = temp_dir.name print(f"Temp files will be created here: {output_dir}")
# Create a scene 2 camera_id dict scene_2_camera_id = get_scene_to_camera_id_dict(scene_2_cam_id_file) camera_ids = {camera_id for camera_ids in scene_2_camera_id.values() for camera_id in camera_ids}
# Load ground truth and prediction files in dataframe column_names = ["CameraId", "Id", "FrameId", "X", "Y", "Width", "Height", "Xworld", "Yworld"] mot_pred_dataframe = load_csv_to_dataframe_from_file(prediction_file_path, column_names, camera_ids) ground_truth_dataframe = load_csv_to_dataframe_from_file(ground_truth_path, column_names, camera_ids)
# Create evaluater configs for trackeval lib default_eval_config = trackeval.eval.Evaluator.get_default_eval_config() default_eval_config["PRINT_CONFIG"] = False default_eval_config["USE_PARALLEL"] = True default_eval_config["LOG_ON_ERROR"] = None default_eval_config["NUM_PARALLEL_CORES"] = num_cores
# Create dataset configs for trackeval lib default_dataset_config = trackeval.datasets.MotChallenge3DLocation.get_default_dataset_config() default_dataset_config["DO_PREPROC"] = False default_dataset_config["SPLIT_TO_EVAL"] = "all" default_dataset_config["GT_FOLDER"] = os.path.join(output_dir, "evaluation", "gt") default_dataset_config["TRACKERS_FOLDER"] = os.path.join(output_dir, "evaluation", "scores") default_dataset_config["PRINT_CONFIG"] = False
# Make output directory for storing results make_dir(default_dataset_config["GT_FOLDER"]) make_dir(default_dataset_config["TRACKERS_FOLDER"])
# Create sequence maps file for evaluation seq_maps_file = os.path.join(default_dataset_config["GT_FOLDER"], "seqmaps") make_seq_maps_file(seq_maps_file, scene_2_camera_id.keys(), default_dataset_config["BENCHMARK"], default_dataset_config["SPLIT_TO_EVAL"])
# Set the metrics to obtain default_metrics_config = {"METRICS": ["HOTA"], "THRESHOLD": 0.5} default_metrics_config["PRINT_CONFIG"] = False config = {**default_eval_config, **default_dataset_config, **default_metrics_config} # Merge default configs eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()} dataset_config = {k: v for k, v in config.items() if k in default_dataset_config.keys()} metrics_config = {k: v for k, v in config.items() if k in default_metrics_config.keys()}
# Create prediction and ground truth list for scene_name in scene_2_camera_id.keys(): # Convert ground truth multi-camera dataframe to single camera in MOT format ground_truth_dataframe_per_scene = get_unique_entry_per_scene(ground_truth_dataframe, scene_name, scene_2_camera_id) ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Xworld", "Yworld"]] ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene.sort_values(by="FrameId")
# Make ground truth frame-ids 1-based ground_truth_dataframe_per_scene["FrameId"] += 1
# Set other defaults ground_truth_dataframe_per_scene["Conf"] = 1 ground_truth_dataframe_per_scene["Zworld"] = -1 ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Conf", "Xworld", "Yworld", "Zworld"]]
# Remove logs for negative frame ids ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene[ground_truth_dataframe_per_scene["FrameId"] >= 1]
# Save single camera ground truth in MOT format as CSV mot_version = default_dataset_config["BENCHMARK"] + "-" + default_dataset_config["SPLIT_TO_EVAL"] gt_dir = os.path.join(default_dataset_config["GT_FOLDER"], mot_version) dir_name = os.path.join(gt_dir, str(scene_name)) gt_file_dir = os.path.join(gt_dir, str(scene_name), "gt") gt_file_name = os.path.join(gt_file_dir, "gt.txt") make_dir(gt_file_dir) write_dataframe_to_csv_to_file(gt_file_name, ground_truth_dataframe_per_scene)
# Convert predicted multi-camera dataframe to MOT format mot_pred_dataframe_per_scene = get_unique_entry_per_scene(mot_pred_dataframe, scene_name, scene_2_camera_id) mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Xworld", "Yworld"]] mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene.sort_values(by="FrameId")
# Make MOT prediction frame-ids 1-based mot_pred_dataframe_per_scene["FrameId"] += 1
# Remove logs for negative frame ids mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene[mot_pred_dataframe_per_scene["FrameId"] >= 1]
# Set other defaults mot_pred_dataframe_per_scene["Conf"] = 1 mot_pred_dataframe_per_scene["Zworld"] = -1 mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Conf", "Xworld", "Yworld", "Zworld"]] # Save single camera prediction in MOT format as CSV mot_file_dir = os.path.join(default_dataset_config["TRACKERS_FOLDER"], mot_version, "data", "data") make_dir(mot_file_dir) tracker_file_name = str(scene_name) + ".txt" mot_file_name = os.path.join(mot_file_dir, tracker_file_name) write_dataframe_to_csv_to_file(mot_file_name, mot_pred_dataframe_per_scene)
# Make sequence ini file for trackeval library if np.isnan(mot_pred_dataframe_per_scene["FrameId"].max()): last_frame_id = ground_truth_dataframe_per_scene["FrameId"].max() elif np.isnan(ground_truth_dataframe_per_scene["FrameId"].max()): last_frame_id = mot_pred_dataframe_per_scene["FrameId"].max() else: last_frame_id = max(mot_pred_dataframe_per_scene["FrameId"].max(), ground_truth_dataframe_per_scene["FrameId"].max()) make_seq_ini_file(dir_name, scene=str(scene_name), seq_length=last_frame_id)
# Evaluate ground truth & prediction to get all exhaustive metrics evaluator = trackeval.eval.Evaluator(eval_config) dataset_list = [trackeval.datasets.MotChallenge3DLocation(dataset_config)] temp_metrics_list = [trackeval.metrics.HOTA]
metrics_list = [] for metric in temp_metrics_list: if metric.get_name() in metrics_config["METRICS"]: metrics_list.append(metric(metrics_config))
results = evaluator.evaluate(dataset_list, metrics_list)
if is_temp_dir: temp_dir.cleanup() return results
def evaluate(prediction_file: str, ground_truth_file: str, output_dir: str, num_cores: int, scene_2_camera_id_file: str) -> None: # Collect the result sequence_result = computes_mot_metrics(prediction_file, ground_truth_file, output_dir, num_cores, scene_2_camera_id_file) # Compute average final_result = dict() HOTA_scores = [] DetA_scores = [] AssA_scores = [] LocA_scores = [] for scene_name, result in sequence_result[0]["MotChallenge3DLocation"]["data"].items(): if scene_name == "COMBINED_SEQ": continue result = result["pedestrian"]["HOTA"] HOTA_scores.append(np.mean(result["HOTA"])) DetA_scores.append(np.mean(result["DetA"])) AssA_scores.append(np.mean(result["AssA"])) LocA_scores.append(np.mean(result["LocA"]))
final_result["FINAL"] = dict() final_result["FINAL"]["HOTA"] = np.mean(np.array(HOTA_scores)) final_result["FINAL"]["DetA"] = np.mean(np.array(DetA_scores)) final_result["FINAL"]["AssA"] = np.mean(np.array(AssA_scores)) final_result["FINAL"]["LocA"] = np.mean(np.array(LocA_scores)) return final_result
if __name__ == '__main__': start = time.time() # Parse arguments parser = ArgumentParser() parser.add_argument('--prediction_file', required=True) parser.add_argument('--ground_truth_file', required=True) parser.add_argument('--output_dir') parser.add_argument('--num_cores', type=check_positive, default=1) parser.add_argument('--scene_2_camera_id_file', required=True) args = parser.parse_args()
# Run evaluation final_result = evaluate(args.prediction_file, args.ground_truth_file, args.output_dir, args.num_cores, args.scene_2_camera_id_file)
end = time.time()
print(f"Total runtime: {end-start} seconds.") print(f"HOTA: {float(final_result['FINAL']['HOTA'] * 100):.4f}%") print(f"DetA: {float(final_result['FINAL']['DetA'] * 100):.4f}%") print(f"AssA: {float(final_result['FINAL']['AssA'] * 100):.4f}%") print(f"LocA: {float(final_result['FINAL']['LocA'] * 100):.4f}%")
123version https://git-lfs.github.com/spec/v1oid sha256:76fc83dae03807622ef62246ba7ebdf43f8109f5a99a2447e681fd8c94955c14size 1508235913123version https://git-lfs.github.com/spec/v1oid sha256:a51d3f9ff529cfcc1ed7c7e5dbe65307f05ce1e634b369cfedb4d23f5c83fcc3size 1341211632123version https://git-lfs.github.com/spec/v1oid sha256:f1f1c873d40a50e075d85a364554d902968b2c6717f16ebd5e63d43300f50bacsize 9555123456"""MTMC analytics trackeval modules"""from .eval import Evaluatorfrom . import datasetsfrom . import metricsfrom . import plottingfrom . import utils123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081from functools import wrapsfrom time import perf_counterimport inspect
DO_TIMING = FalseDISPLAY_LESS_PROGRESS = Falsetimer_dict = {}counter = 0
def time(f): """ Decorator function for timing the execution of a function.
:param f: The function to be timed. :type f: function :return: A wrapped function that measures the execution time of the original function. :rtype: function
The wrapped function measures the execution time of the original function `f`. If the `DO_TIMING` flag is set to `True`, the wrapped function records the accumulated time for each function and provides timing analysis when the code is finished. If the flag is set to `False` or certain conditions are met, the wrapped function runs the original function without timing.
Note that the timing analysis is printed to the console. Modify the implementation to save the timing information in a different format or location if desired. """ @wraps(f) def wrap(*args, **kw): if DO_TIMING: # Run function with timing ts = perf_counter() result = f(*args, **kw) te = perf_counter() tt = te-ts
# Get function name arg_names = inspect.getfullargspec(f)[0] if arg_names[0] == 'self' and DISPLAY_LESS_PROGRESS: return result elif arg_names[0] == 'self': method_name = type(args[0]).__name__ + '.' + f.__name__ else: method_name = f.__name__
# Record accumulative time in each function for analysis if method_name in timer_dict.keys(): timer_dict[method_name] += tt else: timer_dict[method_name] = tt
# If code is finished, display timing summary if method_name == "Evaluator.evaluate": print("") print("Timing analysis:") for key, value in timer_dict.items(): print('%-70s %2.4f sec' % (key, value)) else: # Get function argument values for printing special arguments of interest arg_titles = ['tracker', 'seq', 'cls'] arg_vals = [] for i, a in enumerate(arg_names): if a in arg_titles: arg_vals.append(args[i]) arg_text = '(' + ', '.join(arg_vals) + ')'
# Display methods and functions with different indentation. if arg_names[0] == 'self': print('%-74s %2.4f sec' % (' '*4 + method_name + arg_text, tt)) elif arg_names[0] == 'test': pass else: global counter counter += 1 print('%i %-70s %2.4f sec' % (counter, method_name + arg_text, tt))
return result else: # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing. return f(*args, **kw) return wrap123"""MTMC analytics datasets modules"""from .mot_challenge_2d_box import MotChallenge2DBoxfrom .mot_challenge_3d_location import MotChallenge3DLocation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362import csvimport ioimport zipfileimport osimport tracebackimport numpy as npfrom copy import deepcopyfrom abc import ABC, abstractmethodfrom trackeval import _timingfrom trackeval.utils import TrackEvalException
class _BaseDataset(ABC): """ Module to create a skeleton of dataset formats """ @abstractmethod def __init__(self): self.tracker_list = None self.seq_list = None self.class_list = None self.output_fol = None self.output_sub_fol = None self.should_classes_combine = True self.use_super_categories = False
@staticmethod @abstractmethod def get_default_dataset_config(): ...
@abstractmethod def _load_raw_file(self, tracker, seq, is_gt): ...
@_timing.time @abstractmethod def get_preprocessed_seq_data(self, raw_data, cls): ...
@abstractmethod def _calculate_similarities(self, gt_dets_t, tracker_dets_t): ...
@classmethod def get_class_name(cls): return cls.__name__
def get_name(self): return self.get_class_name()
def get_output_fol(self, tracker): return os.path.join(self.output_fol, tracker, self.output_sub_fol)
def get_display_name(self, tracker): """ Can be overwritten if the trackers name (in files) is different to how it should be displayed. By default this method just returns the trackers name as is.
:param tracker: name of tracker :return: None """ return tracker
def get_eval_info(self): """Return info about the dataset needed for the Evaluator :return: List[str] tracker_list: list of all trackers :return: List[str] seq_list: list of all sequences :return: List[str] class_list: list of all classes """ return self.tracker_list, self.seq_list, self.class_list
@_timing.time def get_raw_seq_data(self, tracker, seq): """ Loads raw data (tracker and ground-truth) for a single tracker on a single sequence. Raw data includes all of the information needed for both preprocessing and evaluation, for all classes. A later function (get_processed_seq_data) will perform such preprocessing and extract relevant information for the evaluation of each class.
This returns a dict which contains the fields: [num_timesteps]: integer [gt_ids, tracker_ids, gt_classes, tracker_classes, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det). [gt_dets, tracker_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections. [similarity_scores]: list (for each timestep) of 2D NDArrays. [gt_extras]: dict (for each extra) of lists (for each timestep) of 1D NDArrays (for each det).
gt_extras contains dataset specific information used for preprocessing such as occlusion and truncation levels.
Note that similarities are extracted as part of the dataset and not the metric, because almost all metrics are independent of the exact method of calculating the similarity. However datasets are not (e.g. segmentation masks vs 2D boxes vs 3D boxes). We calculate the similarity before preprocessing because often both preprocessing and evaluation require it and we don't wish to calculate this twice. We calculate similarity between all gt and tracker classes (not just each class individually) to allow for calculation of metrics such as class confusion matrices. Typically the impact of this on performance is low.
:param: str tracker: name of tracker :param: str sequence: name of sequence :return: raw_data: similarity scores among all gt & tracker classes """ # Load raw data. raw_gt_data = self._load_raw_file(tracker, seq, is_gt=True) raw_tracker_data = self._load_raw_file(tracker, seq, is_gt=False) raw_data = {**raw_tracker_data, **raw_gt_data} # Merges dictionaries
# Calculate similarities for each timestep. similarity_scores = [] for t, (gt_dets_t, tracker_dets_t) in enumerate(zip(raw_data['gt_dets'], raw_data['tracker_dets'])): ious = self._calculate_similarities(gt_dets_t, tracker_dets_t) similarity_scores.append(ious) raw_data['similarity_scores'] = similarity_scores return raw_data
@staticmethod def _load_simple_text_file(file, time_col=0, id_col=None, remove_negative_ids=False, valid_filter=None, crowd_ignore_filter=None, convert_filter=None, is_zipped=False, zip_file=None, force_delimiters=None): """ Function that loads data which is in a commonly used text file format. Assumes each det is given by one row of a text file. There is no limit to the number or meaning of each column, however one column needs to give the timestep of each det (time_col) which is default col 0.
The file dialect (deliminator, num cols, etc) is determined automatically. This function automatically separates dets by timestep, and is much faster than alternatives such as np.loadtext or pandas.
If remove_negative_ids is True and id_col is not None, dets with negative values in id_col are excluded. These are not excluded from ignore data.
valid_filter can be used to only include certain classes. It is a dict with ints as keys, and lists as values, such that a row is included if "row[key].lower() is in value" for all key/value pairs in the dict. If None, all classes are included.
crowd_ignore_filter can be used to read crowd_ignore regions separately. It has the same format as valid filter.
convert_filter can be used to convert value read to another format. This is used most commonly to convert classes given as string to a class id. This is a dict such that the key is the column to convert, and the value is another dict giving the mapping.
Optionally, input files could be a zip of multiple text files for storage efficiency.
Returns read_data and ignore_data. Each is a dict (with keys as timesteps as strings) of lists (over dets) of lists (over column values). Note that all data is returned as strings, and must be converted to float/int later if needed. Note that timesteps will not be present in the returned dict keys if there are no dets for them
:param str file: Path to the input text file or the name of the file within the zip file (if is_zipped is True). :param int time_col: Index of the column containing the timestep of each detection, defaults to 0. :param int id_col: Index of the column containing the ID of each detection, defaults to None. :param bool remove_negative_ids: Whether to exclude dets with negative IDs, defaults to False. :param dict valid_filter: Dictionary to include only certain classes, defaults to None. :param dict crowd_ignore_filter: Dictionary to read crowd_ignore regions separately, defaults to None. :param dict convert_filter: Dictionary to convert values read to another format, defaults to None. :param bool is_zipped: Whether the input file is a zip file, defaults to False. :param str zip_file: Path to the zip file (if is_zipped is True), defaults to None. :param list force_delimiters: List of potential delimiters to override the automatic delimiter detection, defaults to None. :raises TrackEvalException: If remove_negative_ids is True but id_col is not given, or if there's an error reading the file. :return: A tuple containing read_data and crowd_ignore_data dictionaries. read_data: dictionary with timesteps as keys (strings) and lists (over detections) of lists (over column values). crowd_ignore_data: dictionary with timesteps as keys (strings) and lists (over detections) of lists (over column values). :rtype: tuple """
if remove_negative_ids and id_col is None: raise TrackEvalException('remove_negative_ids is True, but id_col is not given.') if crowd_ignore_filter is None: crowd_ignore_filter = {} if convert_filter is None: convert_filter = {} try: if is_zipped: # Either open file directly or within a zip. if zip_file is None: raise TrackEvalException('is_zipped set to True, but no zip_file is given.') archive = zipfile.ZipFile(os.path.join(zip_file), 'r') fp = io.TextIOWrapper(archive.open(file, 'r')) else: fp = open(file) read_data = {} crowd_ignore_data = {} fp.seek(0, os.SEEK_END) # check if file is empty if fp.tell(): fp.seek(0) dialect = csv.Sniffer().sniff(fp.readline(), delimiters=force_delimiters) # Auto determine structure. dialect.skipinitialspace = True # Deal with extra spaces between columns fp.seek(0) reader = csv.reader(fp, dialect) for row in reader: try: # Deal with extra trailing spaces at the end of rows if row[-1] in '': row = row[:-1] timestep = str(int(float(row[time_col]))) # Read ignore regions separately. is_ignored = False for ignore_key, ignore_value in crowd_ignore_filter.items(): if row[ignore_key].lower() in ignore_value: # Convert values in one column (e.g. string to id) for convert_key, convert_value in convert_filter.items(): row[convert_key] = convert_value[row[convert_key].lower()] # Save data separated by timestep. if timestep in crowd_ignore_data.keys(): crowd_ignore_data[timestep].append(row) else: crowd_ignore_data[timestep] = [row] is_ignored = True if is_ignored: # if det is an ignore region, it cannot be a normal det. continue # Exclude some dets if not valid. if valid_filter is not None: for key, value in valid_filter.items(): if row[key].lower() not in value: continue if remove_negative_ids: if int(float(row[id_col])) < 0: continue # Convert values in one column (e.g. string to id) for convert_key, convert_value in convert_filter.items(): row[convert_key] = convert_value[row[convert_key].lower()] # Save data separated by timestep. if timestep in read_data.keys(): read_data[timestep].append(row) else: read_data[timestep] = [row] except Exception: exc_str_init = 'In file %s the following line cannot be read correctly: \n' % os.path.basename( file) exc_str = ' '.join([exc_str_init]+row) raise TrackEvalException(exc_str) fp.close() except Exception: print('Error loading file: %s, printing traceback.' % file) traceback.print_exc() raise TrackEvalException( 'File %s cannot be read because it is either not present or invalidly formatted' % os.path.basename( file)) return read_data, crowd_ignore_data
@staticmethod def _calculate_mask_ious(masks1, masks2, is_encoded=False, do_ioa=False): """ Calculates the IOU (intersection over union) between two arrays of segmentation masks. If is_encoded a run length encoding with pycocotools is assumed as input format, otherwise an input of numpy arrays of the shape (num_masks, height, width) is assumed and the encoding is performed. If do_ioa (intersection over area) , then calculates the intersection over the area of masks1 - this is commonly used to determine if detections are within crowd ignore region. :param masks1: first set of masks (numpy array of shape (num_masks, height, width) if not encoded, else pycocotools rle encoded format) :param masks2: second set of masks (numpy array of shape (num_masks, height, width) if not encoded, else pycocotools rle encoded format) :param is_encoded: whether the input is in pycocotools rle encoded format :param do_ioa: whether to perform IoA computation :return: the IoU/IoA scores """
# Only loaded when run to reduce minimum requirements from pycocotools import mask as mask_utils
# use pycocotools for run length encoding of masks if not is_encoded: masks1 = mask_utils.encode(np.array(np.transpose(masks1, (1, 2, 0)), order='F')) masks2 = mask_utils.encode(np.array(np.transpose(masks2, (1, 2, 0)), order='F'))
# use pycocotools for iou computation of rle encoded masks ious = mask_utils.iou(masks1, masks2, [do_ioa]*len(masks2)) if len(masks1) == 0 or len(masks2) == 0: ious = np.asarray(ious).reshape(len(masks1), len(masks2)) assert (ious >= 0 - np.finfo('float').eps).all() assert (ious <= 1 + np.finfo('float').eps).all()
return ious
@staticmethod def _calculate_box_ious(bboxes1, bboxes2, box_format='xywh', do_ioa=False): """ Calculates the IOU (intersection over union) between two arrays of boxes. Allows variable box formats ('xywh' and 'x0y0x1y1'). If do_ioa (intersection over area) , then calculates the intersection over the area of boxes1 - this is commonly used to determine if detections are within crowd ignore region.
:param bboxes1: first list of bounding boxes :param bboxes2: second list of bounding boxes :return: ious: the IoU/IoA scores """ if box_format in 'xywh': # layout: (x0, y0, w, h) bboxes1 = deepcopy(bboxes1) bboxes2 = deepcopy(bboxes2)
bboxes1[:, 2] = bboxes1[:, 0] + bboxes1[:, 2] bboxes1[:, 3] = bboxes1[:, 1] + bboxes1[:, 3] bboxes2[:, 2] = bboxes2[:, 0] + bboxes2[:, 2] bboxes2[:, 3] = bboxes2[:, 1] + bboxes2[:, 3] elif box_format not in 'x0y0x1y1': raise (TrackEvalException('box_format %s is not implemented' % box_format))
# layout: (x0, y0, x1, y1) min_ = np.minimum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) max_ = np.maximum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) intersection = np.maximum(min_[..., 2] - max_[..., 0], 0) * np.maximum(min_[..., 3] - max_[..., 1], 0) area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
if do_ioa: ioas = np.zeros_like(intersection) valid_mask = area1 > 0 + np.finfo('float').eps ioas[valid_mask, :] = intersection[valid_mask, :] / area1[valid_mask][:, np.newaxis]
return ioas else: area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) union = area1[:, np.newaxis] + area2[np.newaxis, :] - intersection intersection[area1 <= 0 + np.finfo('float').eps, :] = 0 intersection[:, area2 <= 0 + np.finfo('float').eps] = 0 intersection[union <= 0 + np.finfo('float').eps] = 0 union[union <= 0 + np.finfo('float').eps] = 1 ious = intersection / union return ious
@staticmethod def _calculate_euclidean_similarity(dets1, dets2, zero_distance): """ Calculates the euclidean distance between two sets of detections, and then converts this into a similarity measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance). The default zero_distance of 2.0, corresponds to the default used in MOT15_3D, such that a 0.5 similarity threshold corresponds to a 1m distance threshold for TPs.
:param dets1: first list of detections :param dets2: second list of detections :return: sim: the similarity score """ dist = np.linalg.norm(dets1[:, np.newaxis]-dets2[np.newaxis, :], axis=2) sim = np.maximum(0, 1 - dist/zero_distance) return sim
@staticmethod def _check_unique_ids(data, after_preproc=False): """Check the requirement that the tracker_ids and gt_ids are unique per timestep""" gt_ids = data['gt_ids'] tracker_ids = data['tracker_ids'] for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(gt_ids, tracker_ids)): if len(tracker_ids_t) > 0: unique_ids, counts = np.unique(tracker_ids_t, return_counts=True) if np.max(counts) != 1: duplicate_ids = unique_ids[counts > 1] exc_str_init = 'Tracker predicts the same ID more than once in a single timestep ' \ '(seq: %s, frame: %i, ids:' % (data['seq'], t+1) exc_str = ' '.join([exc_str_init] + [str(d) for d in duplicate_ids]) + ')' if after_preproc: exc_str_init += '\n Note that this error occurred after preprocessing (but not before), ' \ 'so ids may not be as in file, and something seems wrong with preproc.' raise TrackEvalException(exc_str) if len(gt_ids_t) > 0: unique_ids, counts = np.unique(gt_ids_t, return_counts=True) if np.max(counts) != 1: duplicate_ids = unique_ids[counts > 1] exc_str_init = 'Ground-truth has the same ID more than once in a single timestep ' \ '(seq: %s, frame: %i, ids:' % (data['seq'], t+1) exc_str = ' '.join([exc_str_init] + [str(d) for d in duplicate_ids]) + ')' if after_preproc: exc_str_init += '\n Note that this error occurred after preprocessing (but not before), ' \ 'so ids may not be as in file, and something seems wrong with preproc.' raise TrackEvalException(exc_str)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471import osimport csvimport configparserimport numpy as npfrom scipy.optimize import linear_sum_assignmentfrom trackeval import utilsfrom trackeval import _timingfrom trackeval.utils import TrackEvalExceptionfrom trackeval.datasets._base_dataset import _BaseDataset
class MotChallenge2DBox(_BaseDataset): """ Dataset class for MOT Challenge 2D bounding box tracking :param dict config: configuration for the app ::
default_dataset = trackeeval.datasets.MotChallenge2DBox(config) """ @staticmethod def get_default_dataset_config(): """Default class config values""" code_path = utils.get_code_path() default_config = { 'GT_FOLDER': os.path.join(code_path, 'data/gt/mot_challenge/'), # Location of GT data 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/mot_challenge/'), # Trackers location 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER) 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder) 'CLASSES_TO_EVAL': ['pedestrian'], # Valid: ['pedestrian'] 'BENCHMARK': 'MOT17', # Valid: 'MOT17', 'MOT16', 'MOT20', 'MOT15' 'SPLIT_TO_EVAL': 'train', # Valid: 'train', 'test', 'all' 'INPUT_AS_ZIP': False, # Whether tracker input files are zipped 'PRINT_CONFIG': True, # Whether to print current config 'DO_PREPROC': True, # Whether to perform preprocessing (never done for MOT15) 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL 'SEQMAP_FOLDER': None, # Where seqmaps are found (if None, GT_FOLDER/seqmaps) 'SEQMAP_FILE': None, # Directly specify seqmap file (if none use seqmap_folder/benchmark-split_to_eval) 'SEQ_INFO': None, # If not None, directly specify sequences to eval and their number of timesteps 'GT_LOC_FORMAT': '{gt_folder}/{seq}/gt/gt.txt', # '{gt_folder}/{seq}/gt/gt.txt' 'SKIP_SPLIT_FOL': False, # If False, data is in GT_FOLDER/BENCHMARK-SPLIT_TO_EVAL/ and in # TRACKERS_FOLDER/BENCHMARK-SPLIT_TO_EVAL/tracker/ # If True, then the middle 'benchmark-split' folder is skipped for both. } return default_config
def __init__(self, config=None): """Initialise dataset, checking that all required files are present""" super().__init__() # Fill non-given config values with defaults self.config = utils.init_config(config, self.get_default_dataset_config(), self.get_name())
self.benchmark = self.config['BENCHMARK'] gt_set = self.config['BENCHMARK'] + '-' + self.config['SPLIT_TO_EVAL'] self.gt_set = gt_set if not self.config['SKIP_SPLIT_FOL']: split_fol = gt_set else: split_fol = '' self.gt_fol = os.path.join(self.config['GT_FOLDER'], split_fol) self.tracker_fol = os.path.join(self.config['TRACKERS_FOLDER'], split_fol) self.should_classes_combine = False self.use_super_categories = False self.data_is_zipped = self.config['INPUT_AS_ZIP'] self.do_preproc = self.config['DO_PREPROC']
self.output_fol = self.config['OUTPUT_FOLDER'] if self.output_fol is None: self.output_fol = self.tracker_fol
self.tracker_sub_fol = self.config['TRACKER_SUB_FOLDER'] self.output_sub_fol = self.config['OUTPUT_SUB_FOLDER']
# Get classes to eval self.valid_classes = ['pedestrian'] self.class_list = [cls.lower() if cls.lower() in self.valid_classes else None for cls in self.config['CLASSES_TO_EVAL']] if not all(self.class_list): raise TrackEvalException('Attempted to evaluate an invalid class. Only pedestrian class is valid.') self.class_name_to_class_id = {'pedestrian': 1, 'person_on_vehicle': 2, 'car': 3, 'bicycle': 4, 'motorbike': 5, 'non_mot_vehicle': 6, 'static_person': 7, 'distractor': 8, 'occluder': 9, 'occluder_on_ground': 10, 'occluder_full': 11, 'reflection': 12, 'crowd': 13} self.valid_class_numbers = list(self.class_name_to_class_id.values())
# Get sequences to eval and check gt files exist self.seq_list, self.seq_lengths = self._get_seq_info() if len(self.seq_list) < 1: raise TrackEvalException('No sequences are selected to be evaluated.')
# Check gt files exist for seq in self.seq_list: if not self.data_is_zipped: curr_file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq) if not os.path.isfile(curr_file): print('GT file not found ' + curr_file) raise TrackEvalException('GT file not found for sequence: ' + seq) if self.data_is_zipped: curr_file = os.path.join(self.gt_fol, 'data.zip') if not os.path.isfile(curr_file): print('GT file not found ' + curr_file) raise TrackEvalException('GT file not found: ' + os.path.basename(curr_file))
# Get trackers to eval if self.config['TRACKERS_TO_EVAL'] is None: self.tracker_list = os.listdir(self.tracker_fol) else: self.tracker_list = self.config['TRACKERS_TO_EVAL']
if self.config['TRACKER_DISPLAY_NAMES'] is None: self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list)) elif (self.config['TRACKERS_TO_EVAL'] is not None) and ( len(self.config['TRACKER_DISPLAY_NAMES']) == len(self.tracker_list)): self.tracker_to_disp = dict(zip(self.tracker_list, self.config['TRACKER_DISPLAY_NAMES'])) else: raise TrackEvalException('List of tracker files and tracker display names do not match.')
for tracker in self.tracker_list: if self.data_is_zipped: curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip') if not os.path.isfile(curr_file): print('Tracker file not found: ' + curr_file) raise TrackEvalException('Tracker file not found: ' + tracker + '/' + os.path.basename(curr_file)) else: for seq in self.seq_list: curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt') if not os.path.isfile(curr_file): print('Tracker file not found: ' + curr_file) raise TrackEvalException( 'Tracker file not found: ' + tracker + '/' + self.tracker_sub_fol + '/' + os.path.basename( curr_file))
def get_display_name(self, tracker): """ Gets the display name of the tracker
:param str tracker: Class of tracker :return: str ::
dataset.get_display_name(tracker) """
return self.tracker_to_disp[tracker]
def _get_seq_info(self): seq_list = [] seq_lengths = {} if self.config["SEQ_INFO"]: seq_list = list(self.config["SEQ_INFO"].keys()) seq_lengths = self.config["SEQ_INFO"]
# If sequence length is 'None' tries to read sequence length from .ini files. for seq, seq_length in seq_lengths.items(): if seq_length is None: ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini') if not os.path.isfile(ini_file): raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file)) ini_data = configparser.ConfigParser() ini_data.read(ini_file) seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
else: if self.config["SEQMAP_FILE"]: seqmap_file = self.config["SEQMAP_FILE"] else: if self.config["SEQMAP_FOLDER"] is None: seqmap_file = os.path.join(self.config['GT_FOLDER'], 'seqmaps', self.gt_set + '.txt') else: seqmap_file = os.path.join(self.config["SEQMAP_FOLDER"], self.gt_set + '.txt') if not os.path.isfile(seqmap_file): print('no seqmap found: ' + seqmap_file) raise TrackEvalException('no seqmap found: ' + os.path.basename(seqmap_file)) with open(seqmap_file) as fp: reader = csv.reader(fp) for i, row in enumerate(reader): if i == 0 or row[0] == '': continue seq = row[0] seq_list.append(seq) ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini') if not os.path.isfile(ini_file): raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file)) ini_data = configparser.ConfigParser() ini_data.read(ini_file) seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength'])) return seq_list, seq_lengths
def _load_raw_file(self, tracker, seq, is_gt): """Load a file (gt or tracker) in the MOT Challenge 2D box format
If is_gt, this returns a dict which contains the fields: [gt_ids, gt_classes] : list (for each timestep) of 1D NDArrays (for each det). [gt_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections. [gt_extras] : list (for each timestep) of dicts (for each extra) of 1D NDArrays (for each det).
if not is_gt, this returns a dict which contains the fields: [tracker_ids, tracker_classes, tracker_confidences] : list (for each timestep) of 1D NDArrays (for each det). [tracker_dets]: list (for each timestep) of lists of detections.
:param str tracker: Name of the tracker. :param str seq: Sequence identifier. :param bool is_gt: Indicates whether the file is ground truth or from a tracker. :raises TrackEvalException: If there's an error loading the file or if the data is corrupted. :return: dictionary containing the loaded data. :rtype: dict """ # File location if self.data_is_zipped: if is_gt: zip_file = os.path.join(self.gt_fol, 'data.zip') else: zip_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip') file = seq + '.txt' else: zip_file = None if is_gt: file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq) else: file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
# Load raw data from text file read_data, ignore_data = self._load_simple_text_file(file, is_zipped=self.data_is_zipped, zip_file=zip_file)
# Convert data to required format num_timesteps = self.seq_lengths[seq] data_keys = ['ids', 'classes', 'dets'] if is_gt: data_keys += ['gt_crowd_ignore_regions', 'gt_extras'] else: data_keys += ['tracker_confidences'] raw_data = {key: [None] * num_timesteps for key in data_keys}
# Check for any extra time keys current_time_keys = [str( t+ 1) for t in range(num_timesteps)] extra_time_keys = [x for x in read_data.keys() if x not in current_time_keys] if len(extra_time_keys) > 0: if is_gt: text = 'Ground-truth' else: text = 'Tracking' raise TrackEvalException( text + ' data contains the following invalid timesteps in seq %s: ' % seq + ', '.join( [str(x) + ', ' for x in extra_time_keys]))
for t in range(num_timesteps): time_key = str(t+1) if time_key in read_data.keys(): try: time_data = np.asarray(read_data[time_key], dtype=float) except ValueError: if is_gt: raise TrackEvalException( 'Cannot convert gt data for sequence %s to float. Is data corrupted?' % seq) else: raise TrackEvalException( 'Cannot convert tracking data from tracker %s, sequence %s to float. Is data corrupted?' % ( tracker, seq)) try: raw_data['dets'][t] = np.atleast_2d(time_data[:, 2:6]) raw_data['ids'][t] = np.atleast_1d(time_data[:, 1]).astype(int) except IndexError: if is_gt: err = 'Cannot load gt data from sequence %s, because there is not enough ' \ 'columns in the data.' % seq raise TrackEvalException(err) else: err = 'Cannot load tracker data from tracker %s, sequence %s, because there is not enough ' \ 'columns in the data.' % (tracker, seq) raise TrackEvalException(err) if time_data.shape[1] >= 8: raw_data['classes'][t] = np.atleast_1d(time_data[:, 7]).astype(int) else: if not is_gt: raw_data['classes'][t] = np.ones_like(raw_data['ids'][t]) else: raise TrackEvalException( 'GT data is not in a valid format, there is not enough rows in seq %s, timestep %i.' % ( seq, t)) if is_gt: gt_extras_dict = {'zero_marked': np.atleast_1d(time_data[:, 6].astype(int))} raw_data['gt_extras'][t] = gt_extras_dict else: raw_data['tracker_confidences'][t] = np.atleast_1d(time_data[:, 6]) else: raw_data['dets'][t] = np.empty((0, 4)) raw_data['ids'][t] = np.empty(0).astype(int) raw_data['classes'][t] = np.empty(0).astype(int) if is_gt: gt_extras_dict = {'zero_marked': np.empty(0)} raw_data['gt_extras'][t] = gt_extras_dict else: raw_data['tracker_confidences'][t] = np.empty(0) if is_gt: raw_data['gt_crowd_ignore_regions'][t] = np.empty((0, 4))
if is_gt: key_map = {'ids': 'gt_ids', 'classes': 'gt_classes', 'dets': 'gt_dets'} else: key_map = {'ids': 'tracker_ids', 'classes': 'tracker_classes', 'dets': 'tracker_dets'} for k, v in key_map.items(): raw_data[v] = raw_data.pop(k) raw_data['num_timesteps'] = num_timesteps raw_data['seq'] = seq return raw_data
@_timing.time def get_preprocessed_seq_data(self, raw_data, cls): """ Preprocess data for a single sequence for a single class ready for evaluation. Inputs: - raw_data is a dict containing the data for the sequence already read in by get_raw_seq_data(). - cls is the class to be evaluated. Outputs: - data is a dict containing all of the information that metrics need to perform evaluation. It contains the following fields: [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets] : integers. [gt_ids, tracker_ids, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det). [gt_dets, tracker_dets]: list (for each timestep) of lists of detections. [similarity_scores]: list (for each timestep) of 2D NDArrays. Notes: General preprocessing (preproc) occurs in 4 steps. Some datasets may not use all of these steps. 1) Extract only detections relevant for the class to be evaluated (including distractor detections). 2) Match gt dets and tracker dets. Remove tracker dets that are matched to a gt det that is of a distractor class, or otherwise marked as to be removed. 3) Remove unmatched tracker dets if they fall within a crowd ignore region or don't meet a certain other criteria (e.g. are too small). 4) Remove gt dets that were only useful for preprocessing and not for actual evaluation. After the above preprocessing steps, this function also calculates the number of gt and tracker detections and unique track ids. It also relabels gt and tracker ids to be contiguous and checks that ids are unique within each timestep.
MOT Challenge: In MOT Challenge, the 4 preproc steps are as follow: 1) There is only one class (pedestrian) to be evaluated, but all other classes are used for preproc. 2) Predictions are matched against all gt boxes (regardless of class), those matching with distractor objects are removed. 3) There is no crowd ignore regions. 4) All gt dets except pedestrian are removed, also removes pedestrian gt dets marked with zero_marked. :param raw_data: A dict containing the data for the sequence already read in by `get_raw_seq_data()`. :param cls: The class to be evaluated.
:return: A dict containing all of the information that metrics need to perform evaluation. It contains the following fields: - [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets]: Integers. - [gt_ids, tracker_ids, tracker_confidences]: List (for each timestep) of 1D NDArrays (for each detection). - [gt_dets, tracker_dets]: List (for each timestep) of lists of detections. - [similarity_scores]: List (for each timestep) of 2D NDArrays.
""" # Check that input data has unique ids self._check_unique_ids(raw_data)
distractor_class_names = ['person_on_vehicle', 'static_person', 'distractor', 'reflection'] if self.benchmark == 'MOT20': distractor_class_names.append('non_mot_vehicle') distractor_classes = [self.class_name_to_class_id[x] for x in distractor_class_names] cls_id = self.class_name_to_class_id[cls]
data_keys = ['gt_ids', 'tracker_ids', 'gt_dets', 'tracker_dets', 'tracker_confidences', 'similarity_scores'] data = {key: [None] * raw_data['num_timesteps'] for key in data_keys} unique_gt_ids = [] unique_tracker_ids = [] num_gt_dets = 0 num_tracker_dets = 0 for t in range(raw_data['num_timesteps']):
# Get all data gt_ids = raw_data['gt_ids'][t] gt_dets = raw_data['gt_dets'][t] gt_classes = raw_data['gt_classes'][t] gt_zero_marked = raw_data['gt_extras'][t]['zero_marked']
tracker_ids = raw_data['tracker_ids'][t] tracker_dets = raw_data['tracker_dets'][t] tracker_classes = raw_data['tracker_classes'][t] tracker_confidences = raw_data['tracker_confidences'][t] similarity_scores = raw_data['similarity_scores'][t]
# Evaluation is ONLY valid for pedestrian class if len(tracker_classes) > 0 and np.max(tracker_classes) > 1: raise TrackEvalException( 'Evaluation is only valid for pedestrian class. Non pedestrian class (%i) found in sequence %s at ' 'timestep %i.' % (np.max(tracker_classes), raw_data['seq'], t))
# Match tracker and gt dets (with hungarian algorithm) and remove tracker dets which match with gt dets # which are labeled as belonging to a distractor class. to_remove_tracker = np.array([], int) if self.do_preproc and self.benchmark != 'MOT15' and gt_ids.shape[0] > 0 and tracker_ids.shape[0] > 0:
# Check all classes are valid: invalid_classes = np.setdiff1d(np.unique(gt_classes), self.valid_class_numbers) if len(invalid_classes) > 0: print(' '.join([str(x) for x in invalid_classes])) raise(TrackEvalException('Attempting to evaluate using invalid gt classes. ' 'This warning only triggers if preprocessing is performed, ' 'e.g. not for MOT15 or where prepropressing is explicitly disabled. ' 'Please either check your gt data, or disable preprocessing. ' 'The following invalid classes were found in timestep ' + str(t) + ': ' + ' '.join([str(x) for x in invalid_classes])))
matching_scores = similarity_scores.copy() matching_scores[matching_scores < 0.5 - np.finfo('float').eps] = 0 match_rows, match_cols = linear_sum_assignment(-matching_scores) actually_matched_mask = matching_scores[match_rows, match_cols] > 0 + np.finfo('float').eps match_rows = match_rows[actually_matched_mask] match_cols = match_cols[actually_matched_mask]
is_distractor_class = np.isin(gt_classes[match_rows], distractor_classes) to_remove_tracker = match_cols[is_distractor_class]
# Apply preprocessing to remove all unwanted tracker dets. data['tracker_ids'][t] = np.delete(tracker_ids, to_remove_tracker, axis=0) data['tracker_dets'][t] = np.delete(tracker_dets, to_remove_tracker, axis=0) data['tracker_confidences'][t] = np.delete(tracker_confidences, to_remove_tracker, axis=0) similarity_scores = np.delete(similarity_scores, to_remove_tracker, axis=1)
# Remove gt detections marked as to remove (zero marked), and also remove gt detections not in pedestrian # class (not applicable for MOT15) if self.do_preproc and self.benchmark != 'MOT15': gt_to_keep_mask = (np.not_equal(gt_zero_marked, 0)) & \ (np.equal(gt_classes, cls_id)) else: # There are no classes for MOT15 gt_to_keep_mask = np.not_equal(gt_zero_marked, 0) data['gt_ids'][t] = gt_ids[gt_to_keep_mask] data['gt_dets'][t] = gt_dets[gt_to_keep_mask, :] data['similarity_scores'][t] = similarity_scores[gt_to_keep_mask]
unique_gt_ids += list(np.unique(data['gt_ids'][t])) unique_tracker_ids += list(np.unique(data['tracker_ids'][t])) num_tracker_dets += len(data['tracker_ids'][t]) num_gt_dets += len(data['gt_ids'][t])
# Re-label IDs such that there are no empty IDs if len(unique_gt_ids) > 0: unique_gt_ids = np.unique(unique_gt_ids) gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1)) gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids)) for t in range(raw_data['num_timesteps']): if len(data['gt_ids'][t]) > 0: data['gt_ids'][t] = gt_id_map[data['gt_ids'][t]].astype(int) if len(unique_tracker_ids) > 0: unique_tracker_ids = np.unique(unique_tracker_ids) tracker_id_map = np.nan * np.ones((np.max(unique_tracker_ids) + 1)) tracker_id_map[unique_tracker_ids] = np.arange(len(unique_tracker_ids)) for t in range(raw_data['num_timesteps']): if len(data['tracker_ids'][t]) > 0: data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(int)
# Record overview statistics. data['num_tracker_dets'] = num_tracker_dets data['num_gt_dets'] = num_gt_dets data['num_tracker_ids'] = len(unique_tracker_ids) data['num_gt_ids'] = len(unique_gt_ids) data['num_timesteps'] = raw_data['num_timesteps'] data['seq'] = raw_data['seq']
# Ensure again that ids are unique per timestep after preproc. self._check_unique_ids(data, after_preproc=True)
return data
def _calculate_similarities(self, gt_dets_t, tracker_dets_t): similarity_scores = self._calculate_box_ious(gt_dets_t, tracker_dets_t, box_format='xywh') return similarity_scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475import osimport csvimport configparserimport numpy as npfrom scipy.optimize import linear_sum_assignmentfrom trackeval import utilsfrom trackeval import _timingfrom trackeval.utils import TrackEvalExceptionfrom trackeval.datasets._base_dataset import _BaseDataset
class MotChallenge3DLocation(_BaseDataset): """ Dataset class for MOT Challenge 3D tracking :param dict config: configuration for the app ::
default_dataset = trackeeval.datasets.MotChallenge2DBox(config) """ @staticmethod def get_default_dataset_config(): """Default class config values""" code_path = utils.get_code_path() default_config = { 'GT_FOLDER': os.path.join(code_path, 'data/gt/mot_challenge/'), # Location of GT data 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/mot_challenge/'), # Trackers location 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER) 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder) 'CLASSES_TO_EVAL': ['pedestrian'], # Valid: ['pedestrian'] 'BENCHMARK': 'MOT17', # Valid: 'MOT17', 'MOT16', 'MOT20', 'MOT15' 'SPLIT_TO_EVAL': 'train', # Valid: 'train', 'test', 'all' 'INPUT_AS_ZIP': False, # Whether tracker input files are zipped 'PRINT_CONFIG': True, # Whether to print current config 'DO_PREPROC': True, # Whether to perform preprocessing (never done for MOT15) 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL 'SEQMAP_FOLDER': None, # Where seqmaps are found (if None, GT_FOLDER/seqmaps) 'SEQMAP_FILE': None, # Directly specify seqmap file (if none use seqmap_folder/benchmark-split_to_eval) 'SEQ_INFO': None, # If not None, directly specify sequences to eval and their number of timesteps 'GT_LOC_FORMAT': '{gt_folder}/{seq}/gt/gt.txt', # '{gt_folder}/{seq}/gt/gt.txt' 'SKIP_SPLIT_FOL': False, # If False, data is in GT_FOLDER/BENCHMARK-SPLIT_TO_EVAL/ and in # TRACKERS_FOLDER/BENCHMARK-SPLIT_TO_EVAL/tracker/ # If True, then the middle 'benchmark-split' folder is skipped for both. } return default_config
def __init__(self, config=None, zd=2.0): """Initialise dataset, checking that all required files are present""" super().__init__() # Fill non-given config values with defaults self.config = utils.init_config(config, self.get_default_dataset_config(), self.get_name()) self.zero_distance = zd self.benchmark = self.config['BENCHMARK'] gt_set = self.config['BENCHMARK'] + '-' + self.config['SPLIT_TO_EVAL'] self.gt_set = gt_set if not self.config['SKIP_SPLIT_FOL']: split_fol = gt_set else: split_fol = '' self.gt_fol = os.path.join(self.config['GT_FOLDER'], split_fol) self.tracker_fol = os.path.join(self.config['TRACKERS_FOLDER'], split_fol) self.should_classes_combine = False self.use_super_categories = False self.data_is_zipped = self.config['INPUT_AS_ZIP'] self.do_preproc = self.config['DO_PREPROC']
self.output_fol = self.config['OUTPUT_FOLDER'] if self.output_fol is None: self.output_fol = self.tracker_fol
self.tracker_sub_fol = self.config['TRACKER_SUB_FOLDER'] self.output_sub_fol = self.config['OUTPUT_SUB_FOLDER']
# Get classes to eval self.valid_classes = ['pedestrian'] self.class_list = [cls.lower() if cls.lower() in self.valid_classes else None for cls in self.config['CLASSES_TO_EVAL']] if not all(self.class_list): raise TrackEvalException('Attempted to evaluate an invalid class. Only pedestrian class is valid.') self.class_name_to_class_id = {'pedestrian': 1, 'person_on_vehicle': 2, 'car': 3, 'bicycle': 4, 'motorbike': 5, 'non_mot_vehicle': 6, 'static_person': 7, 'distractor': 8, 'occluder': 9, 'occluder_on_ground': 10, 'occluder_full': 11, 'reflection': 12, 'crowd': 13} self.valid_class_numbers = list(self.class_name_to_class_id.values())
# Get sequences to eval and check gt files exist self.seq_list, self.seq_lengths = self._get_seq_info() if len(self.seq_list) < 1: raise TrackEvalException('No sequences are selected to be evaluated.')
# Check gt files exist for seq in self.seq_list: if not self.data_is_zipped: curr_file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq) if not os.path.isfile(curr_file): print('GT file not found ' + curr_file) raise TrackEvalException('GT file not found for sequence: ' + seq) if self.data_is_zipped: curr_file = os.path.join(self.gt_fol, 'data.zip') if not os.path.isfile(curr_file): print('GT file not found ' + curr_file) raise TrackEvalException('GT file not found: ' + os.path.basename(curr_file))
# Get trackers to eval if self.config['TRACKERS_TO_EVAL'] is None: self.tracker_list = os.listdir(self.tracker_fol) else: self.tracker_list = self.config['TRACKERS_TO_EVAL']
if self.config['TRACKER_DISPLAY_NAMES'] is None: self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list)) elif (self.config['TRACKERS_TO_EVAL'] is not None) and ( len(self.config['TRACKER_DISPLAY_NAMES']) == len(self.tracker_list)): self.tracker_to_disp = dict(zip(self.tracker_list, self.config['TRACKER_DISPLAY_NAMES'])) else: raise TrackEvalException('List of tracker files and tracker display names do not match.')
for tracker in self.tracker_list: if self.data_is_zipped: curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip') if not os.path.isfile(curr_file): print('Tracker file not found: ' + curr_file) raise TrackEvalException('Tracker file not found: ' + tracker + '/' + os.path.basename(curr_file)) else: for seq in self.seq_list: curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt') if not os.path.isfile(curr_file): print('Tracker file not found: ' + curr_file) raise TrackEvalException( 'Tracker file not found: ' + tracker + '/' + self.tracker_sub_fol + '/' + os.path.basename( curr_file))
def get_display_name(self, tracker): """ Gets the display name of the tracker
:param str tracker: Class of tracker :return: str ::
dataset.get_display_name(tracker) """
return self.tracker_to_disp[tracker]
def _get_seq_info(self): seq_list = [] seq_lengths = {} if self.config["SEQ_INFO"]: seq_list = list(self.config["SEQ_INFO"].keys()) seq_lengths = self.config["SEQ_INFO"]
# If sequence length is 'None' tries to read sequence length from .ini files. for seq, seq_length in seq_lengths.items(): if seq_length is None: ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini') if not os.path.isfile(ini_file): raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file)) ini_data = configparser.ConfigParser() ini_data.read(ini_file) seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
else: if self.config["SEQMAP_FILE"]: seqmap_file = self.config["SEQMAP_FILE"] else: if self.config["SEQMAP_FOLDER"] is None: seqmap_file = os.path.join(self.config['GT_FOLDER'], 'seqmaps', self.gt_set + '.txt') else: seqmap_file = os.path.join(self.config["SEQMAP_FOLDER"], self.gt_set + '.txt') if not os.path.isfile(seqmap_file): print('no seqmap found: ' + seqmap_file) raise TrackEvalException('no seqmap found: ' + os.path.basename(seqmap_file)) with open(seqmap_file) as fp: reader = csv.reader(fp) for i, row in enumerate(reader): if i == 0 or row[0] == '': continue seq = row[0] seq_list.append(seq) ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini') if not os.path.isfile(ini_file): raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file)) ini_data = configparser.ConfigParser() ini_data.read(ini_file) seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength'])) return seq_list, seq_lengths
def _load_raw_file(self, tracker, seq, is_gt): """Load a file (gt or tracker) in the MOT Challenge 3D location format
If is_gt, this returns a dict which contains the fields: [gt_ids, gt_classes] : list (for each timestep) of 1D NDArrays (for each det). [gt_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections. [gt_extras] : list (for each timestep) of dicts (for each extra) of 1D NDArrays (for each det).
if not is_gt, this returns a dict which contains the fields: [tracker_ids, tracker_classes, tracker_confidences] : list (for each timestep) of 1D NDArrays (for each det). [tracker_dets]: list (for each timestep) of lists of detections.
:param str tracker: Name of the tracker. :param str seq: Sequence identifier. :param bool is_gt: Indicates whether the file is ground truth or from a tracker. :raises TrackEvalException: If there's an error loading the file or if the data is corrupted. :return: dictionary containing the loaded data. :rtype: dict """ # File location if self.data_is_zipped: if is_gt: zip_file = os.path.join(self.gt_fol, 'data.zip') else: zip_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip') file = seq + '.txt' else: zip_file = None if is_gt: file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq) else: file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
# Load raw data from text file read_data, ignore_data = self._load_simple_text_file(file, is_zipped=self.data_is_zipped, zip_file=zip_file)
# Convert data to required format num_timesteps = self.seq_lengths[seq] data_keys = ['ids', 'classes', 'dets'] if is_gt: data_keys += ['gt_crowd_ignore_regions', 'gt_extras'] else: data_keys += ['tracker_confidences'] raw_data = {key: [None] * num_timesteps for key in data_keys}
# Check for any extra time keys current_time_keys = [str( t+ 1) for t in range(num_timesteps)] extra_time_keys = [x for x in read_data.keys() if x not in current_time_keys] if len(extra_time_keys) > 0: if is_gt: text = 'Ground-truth' else: text = 'Tracking' raise TrackEvalException( text + ' data contains the following invalid timesteps in seq %s: ' % seq + ', '.join( [str(x) + ', ' for x in extra_time_keys]))
for t in range(num_timesteps): time_key = str(t+1) if time_key in read_data.keys(): try: time_data = np.asarray(read_data[time_key], dtype=float) except ValueError: if is_gt: raise TrackEvalException( 'Cannot convert gt data for sequence %s to float. Is data corrupted?' % seq) else: raise TrackEvalException( 'Cannot convert tracking data from tracker %s, sequence %s to float. Is data corrupted?' % ( tracker, seq)) try: if is_gt: raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9]) else: raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9]) raw_data['ids'][t] = np.atleast_1d(time_data[:, 1]).astype(int) except IndexError: if is_gt: err = 'Cannot load gt data from sequence %s, because there is not enough ' \ 'columns in the data.' % seq raise TrackEvalException(err) else: err = 'Cannot load tracker data from tracker %s, sequence %s, because there is not enough ' \ 'columns in the data.' % (tracker, seq) raise TrackEvalException(err) if time_data.shape[1] >= 8: raw_data['classes'][t] = np.ones_like(raw_data['ids'][t]) # raw_data['classes'][t] = np.atleast_1d(time_data[:, 7]).astype(int) else: if not is_gt: raw_data['classes'][t] = np.ones_like(raw_data['ids'][t]) else: raise TrackEvalException( 'GT data is not in a valid format, there is not enough rows in seq %s, timestep %i.' % ( seq, t)) if is_gt: gt_extras_dict = {'zero_marked': np.atleast_1d(time_data[:, 6].astype(int))} raw_data['gt_extras'][t] = gt_extras_dict else: raw_data['tracker_confidences'][t] = np.atleast_1d(time_data[:, 6]) else: raw_data['dets'][t] = np.empty((0, 2)) raw_data['ids'][t] = np.empty(0).astype(int) raw_data['classes'][t] = np.empty(0).astype(int) if is_gt: gt_extras_dict = {'zero_marked': np.empty(0)} raw_data['gt_extras'][t] = gt_extras_dict else: raw_data['tracker_confidences'][t] = np.empty(0) if is_gt: raw_data['gt_crowd_ignore_regions'][t] = np.empty((0, 2))
if is_gt: key_map = {'ids': 'gt_ids', 'classes': 'gt_classes', 'dets': 'gt_dets'} else: key_map = {'ids': 'tracker_ids', 'classes': 'tracker_classes', 'dets': 'tracker_dets'} for k, v in key_map.items(): raw_data[v] = raw_data.pop(k) raw_data['num_timesteps'] = num_timesteps raw_data['seq'] = seq return raw_data
@_timing.time def get_preprocessed_seq_data(self, raw_data, cls): """ Preprocess data for a single sequence for a single class ready for evaluation. Inputs: - raw_data is a dict containing the data for the sequence already read in by get_raw_seq_data(). - cls is the class to be evaluated. Outputs: - data is a dict containing all of the information that metrics need to perform evaluation. It contains the following fields: [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets] : integers. [gt_ids, tracker_ids, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det). [gt_dets, tracker_dets]: list (for each timestep) of lists of detections. [similarity_scores]: list (for each timestep) of 2D NDArrays. Notes: General preprocessing (preproc) occurs in 4 steps. Some datasets may not use all of these steps. 1) Extract only detections relevant for the class to be evaluated (including distractor detections). 2) Match gt dets and tracker dets. Remove tracker dets that are matched to a gt det that is of a distractor class, or otherwise marked as to be removed. 3) Remove unmatched tracker dets if they fall within a crowd ignore region or don't meet a certain other criteria (e.g. are too small). 4) Remove gt dets that were only useful for preprocessing and not for actual evaluation. After the above preprocessing steps, this function also calculates the number of gt and tracker detections and unique track ids. It also relabels gt and tracker ids to be contiguous and checks that ids are unique within each timestep.
MOT Challenge: In MOT Challenge, the 4 preproc steps are as follow: 1) There is only one class (pedestrian) to be evaluated, but all other classes are used for preproc. 2) Predictions are matched against all gt boxes (regardless of class), those matching with distractor objects are removed. 3) There is no crowd ignore regions. 4) All gt dets except pedestrian are removed, also removes pedestrian gt dets marked with zero_marked. :param raw_data: A dict containing the data for the sequence already read in by `get_raw_seq_data()`. :param cls: The class to be evaluated.
:return: A dict containing all of the information that metrics need to perform evaluation. It contains the following fields: - [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets]: Integers. - [gt_ids, tracker_ids, tracker_confidences]: List (for each timestep) of 1D NDArrays (for each detection). - [gt_dets, tracker_dets]: List (for each timestep) of lists of detections. - [similarity_scores]: List (for each timestep) of 2D NDArrays.
""" # Check that input data has unique ids self._check_unique_ids(raw_data)
distractor_class_names = ['person_on_vehicle', 'static_person', 'distractor', 'reflection'] if self.benchmark == 'MOT20': distractor_class_names.append('non_mot_vehicle') distractor_classes = [self.class_name_to_class_id[x] for x in distractor_class_names] cls_id = self.class_name_to_class_id[cls]
data_keys = ['gt_ids', 'tracker_ids', 'gt_dets', 'tracker_dets', 'tracker_confidences', 'similarity_scores'] data = {key: [None] * raw_data['num_timesteps'] for key in data_keys} unique_gt_ids = [] unique_tracker_ids = [] num_gt_dets = 0 num_tracker_dets = 0 for t in range(raw_data['num_timesteps']):
# Get all data gt_ids = raw_data['gt_ids'][t] gt_dets = raw_data['gt_dets'][t] gt_classes = raw_data['gt_classes'][t] gt_zero_marked = raw_data['gt_extras'][t]['zero_marked']
tracker_ids = raw_data['tracker_ids'][t] tracker_dets = raw_data['tracker_dets'][t] tracker_classes = raw_data['tracker_classes'][t] tracker_confidences = raw_data['tracker_confidences'][t] similarity_scores = raw_data['similarity_scores'][t]
# Evaluation is ONLY valid for pedestrian class if len(tracker_classes) > 0 and np.max(tracker_classes) > 1: raise TrackEvalException( 'Evaluation is only valid for pedestrian class. Non pedestrian class (%i) found in sequence %s at ' 'timestep %i.' % (np.max(tracker_classes), raw_data['seq'], t))
# Match tracker and gt dets (with hungarian algorithm) and remove tracker dets which match with gt dets # which are labeled as belonging to a distractor class. to_remove_tracker = np.array([], int) if self.do_preproc and self.benchmark != 'MOT15' and gt_ids.shape[0] > 0 and tracker_ids.shape[0] > 0:
# Check all classes are valid: invalid_classes = np.setdiff1d(np.unique(gt_classes), self.valid_class_numbers) if len(invalid_classes) > 0: print(' '.join([str(x) for x in invalid_classes])) raise(TrackEvalException('Attempting to evaluate using invalid gt classes. ' 'This warning only triggers if preprocessing is performed, ' 'e.g. not for MOT15 or where prepropressing is explicitly disabled. ' 'Please either check your gt data, or disable preprocessing. ' 'The following invalid classes were found in timestep ' + str(t) + ': ' + ' '.join([str(x) for x in invalid_classes])))
matching_scores = similarity_scores.copy() matching_scores[matching_scores < 0.5 - np.finfo('float').eps] = 0 match_rows, match_cols = linear_sum_assignment(-matching_scores) actually_matched_mask = matching_scores[match_rows, match_cols] > 0 + np.finfo('float').eps match_rows = match_rows[actually_matched_mask] match_cols = match_cols[actually_matched_mask]
is_distractor_class = np.isin(gt_classes[match_rows], distractor_classes) to_remove_tracker = match_cols[is_distractor_class]
# Apply preprocessing to remove all unwanted tracker dets. data['tracker_ids'][t] = np.delete(tracker_ids, to_remove_tracker, axis=0) data['tracker_dets'][t] = np.delete(tracker_dets, to_remove_tracker, axis=0) data['tracker_confidences'][t] = np.delete(tracker_confidences, to_remove_tracker, axis=0) similarity_scores = np.delete(similarity_scores, to_remove_tracker, axis=1)
# Remove gt detections marked as to remove (zero marked), and also remove gt detections not in pedestrian # class (not applicable for MOT15) if self.do_preproc and self.benchmark != 'MOT15': gt_to_keep_mask = (np.not_equal(gt_zero_marked, 0)) & \ (np.equal(gt_classes, cls_id)) else: # There are no classes for MOT15 gt_to_keep_mask = np.not_equal(gt_zero_marked, 0) data['gt_ids'][t] = gt_ids[gt_to_keep_mask] data['gt_dets'][t] = gt_dets[gt_to_keep_mask, :] data['similarity_scores'][t] = similarity_scores[gt_to_keep_mask]
unique_gt_ids += list(np.unique(data['gt_ids'][t])) unique_tracker_ids += list(np.unique(data['tracker_ids'][t])) num_tracker_dets += len(data['tracker_ids'][t]) num_gt_dets += len(data['gt_ids'][t])
# Re-label IDs such that there are no empty IDs if len(unique_gt_ids) > 0: unique_gt_ids = np.unique(unique_gt_ids) gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1)) gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids)) for t in range(raw_data['num_timesteps']): if len(data['gt_ids'][t]) > 0: data['gt_ids'][t] = gt_id_map[data['gt_ids'][t]].astype(int) if len(unique_tracker_ids) > 0: unique_tracker_ids = np.unique(unique_tracker_ids) tracker_id_map = np.nan * np.ones((np.max(unique_tracker_ids) + 1)) tracker_id_map[unique_tracker_ids] = np.arange(len(unique_tracker_ids)) for t in range(raw_data['num_timesteps']): if len(data['tracker_ids'][t]) > 0: data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(int)
# Record overview statistics. data['num_tracker_dets'] = num_tracker_dets data['num_gt_dets'] = num_gt_dets data['num_tracker_ids'] = len(unique_tracker_ids) data['num_gt_ids'] = len(unique_gt_ids) data['num_timesteps'] = raw_data['num_timesteps'] data['seq'] = raw_data['seq']
# Ensure again that ids are unique per timestep after preproc. self._check_unique_ids(data, after_preproc=True)
return data
def _calculate_similarities(self, gt_dets_t, tracker_dets_t): similarity_scores = self._calculate_euclidean_similarity(gt_dets_t, tracker_dets_t, zero_distance=self.zero_distance) return similarity_scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475import osimport csvimport configparserimport numpy as npfrom scipy.optimize import linear_sum_assignmentfrom trackeval import utilsfrom trackeval import _timingfrom trackeval.utils import TrackEvalExceptionfrom trackeval.datasets._base_dataset import _BaseDataset
class MotChallenge2DLocation(_BaseDataset): """ Dataset class for MOT Challenge 2D bounding box tracking :param dict config: configuration for the app ::
default_dataset = trackeeval.datasets.MotChallenge2DBox(config) """ @staticmethod def get_default_dataset_config(): """Default class config values""" code_path = utils.get_code_path() default_config = { 'GT_FOLDER': os.path.join(code_path, 'data/gt/mot_challenge/'), # Location of GT data 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/mot_challenge/'), # Trackers location 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER) 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder) 'CLASSES_TO_EVAL': ['pedestrian'], # Valid: ['pedestrian'] 'BENCHMARK': 'MOT17', # Valid: 'MOT17', 'MOT16', 'MOT20', 'MOT15' 'SPLIT_TO_EVAL': 'train', # Valid: 'train', 'test', 'all' 'INPUT_AS_ZIP': False, # Whether tracker input files are zipped 'PRINT_CONFIG': True, # Whether to print current config 'DO_PREPROC': True, # Whether to perform preprocessing (never done for MOT15) 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL 'SEQMAP_FOLDER': None, # Where seqmaps are found (if None, GT_FOLDER/seqmaps) 'SEQMAP_FILE': None, # Directly specify seqmap file (if none use seqmap_folder/benchmark-split_to_eval) 'SEQ_INFO': None, # If not None, directly specify sequences to eval and their number of timesteps 'GT_LOC_FORMAT': '{gt_folder}/{seq}/gt/gt.txt', # '{gt_folder}/{seq}/gt/gt.txt' 'SKIP_SPLIT_FOL': False, # If False, data is in GT_FOLDER/BENCHMARK-SPLIT_TO_EVAL/ and in # TRACKERS_FOLDER/BENCHMARK-SPLIT_TO_EVAL/tracker/ # If True, then the middle 'benchmark-split' folder is skipped for both. } return default_config
def __init__(self, config=None): """Initialise dataset, checking that all required files are present""" super().__init__() # Fill non-given config values with defaults self.config = utils.init_config(config, self.get_default_dataset_config(), self.get_name())
self.benchmark = self.config['BENCHMARK'] gt_set = self.config['BENCHMARK'] + '-' + self.config['SPLIT_TO_EVAL'] self.gt_set = gt_set if not self.config['SKIP_SPLIT_FOL']: split_fol = gt_set else: split_fol = '' self.gt_fol = os.path.join(self.config['GT_FOLDER'], split_fol) self.tracker_fol = os.path.join(self.config['TRACKERS_FOLDER'], split_fol) self.should_classes_combine = False self.use_super_categories = False self.data_is_zipped = self.config['INPUT_AS_ZIP'] self.do_preproc = self.config['DO_PREPROC']
self.output_fol = self.config['OUTPUT_FOLDER'] if self.output_fol is None: self.output_fol = self.tracker_fol
self.tracker_sub_fol = self.config['TRACKER_SUB_FOLDER'] self.output_sub_fol = self.config['OUTPUT_SUB_FOLDER']
# Get classes to eval self.valid_classes = ['pedestrian'] self.class_list = [cls.lower() if cls.lower() in self.valid_classes else None for cls in self.config['CLASSES_TO_EVAL']] if not all(self.class_list): raise TrackEvalException('Attempted to evaluate an invalid class. Only pedestrian class is valid.') self.class_name_to_class_id = {'pedestrian': 1, 'person_on_vehicle': 2, 'car': 3, 'bicycle': 4, 'motorbike': 5, 'non_mot_vehicle': 6, 'static_person': 7, 'distractor': 8, 'occluder': 9, 'occluder_on_ground': 10, 'occluder_full': 11, 'reflection': 12, 'crowd': 13} self.valid_class_numbers = list(self.class_name_to_class_id.values())
# Get sequences to eval and check gt files exist self.seq_list, self.seq_lengths = self._get_seq_info() if len(self.seq_list) < 1: raise TrackEvalException('No sequences are selected to be evaluated.')
# Check gt files exist for seq in self.seq_list: if not self.data_is_zipped: curr_file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq) if not os.path.isfile(curr_file): print('GT file not found ' + curr_file) raise TrackEvalException('GT file not found for sequence: ' + seq) if self.data_is_zipped: curr_file = os.path.join(self.gt_fol, 'data.zip') if not os.path.isfile(curr_file): print('GT file not found ' + curr_file) raise TrackEvalException('GT file not found: ' + os.path.basename(curr_file))
# Get trackers to eval if self.config['TRACKERS_TO_EVAL'] is None: self.tracker_list = os.listdir(self.tracker_fol) else: self.tracker_list = self.config['TRACKERS_TO_EVAL']
if self.config['TRACKER_DISPLAY_NAMES'] is None: self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list)) elif (self.config['TRACKERS_TO_EVAL'] is not None) and ( len(self.config['TRACKER_DISPLAY_NAMES']) == len(self.tracker_list)): self.tracker_to_disp = dict(zip(self.tracker_list, self.config['TRACKER_DISPLAY_NAMES'])) else: raise TrackEvalException('List of tracker files and tracker display names do not match.')
for tracker in self.tracker_list: if self.data_is_zipped: curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip') if not os.path.isfile(curr_file): print('Tracker file not found: ' + curr_file) raise TrackEvalException('Tracker file not found: ' + tracker + '/' + os.path.basename(curr_file)) else: for seq in self.seq_list: curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt') if not os.path.isfile(curr_file): print('Tracker file not found: ' + curr_file) raise TrackEvalException( 'Tracker file not found: ' + tracker + '/' + self.tracker_sub_fol + '/' + os.path.basename( curr_file))
def get_display_name(self, tracker): """ Gets the display name of the tracker
:param str tracker: Class of tracker :return: str ::
dataset.get_display_name(tracker) """
return self.tracker_to_disp[tracker]
def _get_seq_info(self): seq_list = [] seq_lengths = {} if self.config["SEQ_INFO"]: seq_list = list(self.config["SEQ_INFO"].keys()) seq_lengths = self.config["SEQ_INFO"]
# If sequence length is 'None' tries to read sequence length from .ini files. for seq, seq_length in seq_lengths.items(): if seq_length is None: ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini') if not os.path.isfile(ini_file): raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file)) ini_data = configparser.ConfigParser() ini_data.read(ini_file) seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
else: if self.config["SEQMAP_FILE"]: seqmap_file = self.config["SEQMAP_FILE"] else: if self.config["SEQMAP_FOLDER"] is None: seqmap_file = os.path.join(self.config['GT_FOLDER'], 'seqmaps', self.gt_set + '.txt') else: seqmap_file = os.path.join(self.config["SEQMAP_FOLDER"], self.gt_set + '.txt') if not os.path.isfile(seqmap_file): print('no seqmap found: ' + seqmap_file) raise TrackEvalException('no seqmap found: ' + os.path.basename(seqmap_file)) with open(seqmap_file) as fp: reader = csv.reader(fp) for i, row in enumerate(reader): if i == 0 or row[0] == '': continue seq = row[0] seq_list.append(seq) ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini') if not os.path.isfile(ini_file): raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file)) ini_data = configparser.ConfigParser() ini_data.read(ini_file) seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength'])) return seq_list, seq_lengths
def _load_raw_file(self, tracker, seq, is_gt): """Load a file (gt or tracker) in the MOT Challenge 2D box format
If is_gt, this returns a dict which contains the fields: [gt_ids, gt_classes] : list (for each timestep) of 1D NDArrays (for each det). [gt_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections. [gt_extras] : list (for each timestep) of dicts (for each extra) of 1D NDArrays (for each det).
if not is_gt, this returns a dict which contains the fields: [tracker_ids, tracker_classes, tracker_confidences] : list (for each timestep) of 1D NDArrays (for each det). [tracker_dets]: list (for each timestep) of lists of detections.
:param str tracker: Name of the tracker. :param str seq: Sequence identifier. :param bool is_gt: Indicates whether the file is ground truth or from a tracker. :raises TrackEvalException: If there's an error loading the file or if the data is corrupted. :return: dictionary containing the loaded data. :rtype: dict """ # File location if self.data_is_zipped: if is_gt: zip_file = os.path.join(self.gt_fol, 'data.zip') else: zip_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip') file = seq + '.txt' else: zip_file = None if is_gt: file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq) else: file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
# Load raw data from text file read_data, ignore_data = self._load_simple_text_file(file, is_zipped=self.data_is_zipped, zip_file=zip_file)
# Convert data to required format num_timesteps = self.seq_lengths[seq] data_keys = ['ids', 'classes', 'dets'] if is_gt: data_keys += ['gt_crowd_ignore_regions', 'gt_extras'] else: data_keys += ['tracker_confidences'] raw_data = {key: [None] * num_timesteps for key in data_keys}
# Check for any extra time keys current_time_keys = [str( t+ 1) for t in range(num_timesteps)] extra_time_keys = [x for x in read_data.keys() if x not in current_time_keys] if len(extra_time_keys) > 0: if is_gt: text = 'Ground-truth' else: text = 'Tracking' raise TrackEvalException( text + ' data contains the following invalid timesteps in seq %s: ' % seq + ', '.join( [str(x) + ', ' for x in extra_time_keys]))
for t in range(num_timesteps): time_key = str(t+1) if time_key in read_data.keys(): try: time_data = np.asarray(read_data[time_key], dtype=float) except ValueError: if is_gt: raise TrackEvalException( 'Cannot convert gt data for sequence %s to float. Is data corrupted?' % seq) else: raise TrackEvalException( 'Cannot convert tracking data from tracker %s, sequence %s to float. Is data corrupted?' % ( tracker, seq)) try: if is_gt: raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9]) else: raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9]) raw_data['ids'][t] = np.atleast_1d(time_data[:, 1]).astype(int) except IndexError: if is_gt: err = 'Cannot load gt data from sequence %s, because there is not enough ' \ 'columns in the data.' % seq raise TrackEvalException(err) else: err = 'Cannot load tracker data from tracker %s, sequence %s, because there is not enough ' \ 'columns in the data.' % (tracker, seq) raise TrackEvalException(err) if time_data.shape[1] >= 8: raw_data['classes'][t] = np.ones_like(raw_data['ids'][t]) # raw_data['classes'][t] = np.atleast_1d(time_data[:, 7]).astype(int) else: if not is_gt: raw_data['classes'][t] = np.ones_like(raw_data['ids'][t]) else: raise TrackEvalException( 'GT data is not in a valid format, there is not enough rows in seq %s, timestep %i.' % ( seq, t)) if is_gt: gt_extras_dict = {'zero_marked': np.atleast_1d(time_data[:, 6].astype(int))} raw_data['gt_extras'][t] = gt_extras_dict else: raw_data['tracker_confidences'][t] = np.atleast_1d(time_data[:, 6]) else: raw_data['dets'][t] = np.empty((0, 4)) raw_data['ids'][t] = np.empty(0).astype(int) raw_data['classes'][t] = np.empty(0).astype(int) if is_gt: gt_extras_dict = {'zero_marked': np.empty(0)} raw_data['gt_extras'][t] = gt_extras_dict else: raw_data['tracker_confidences'][t] = np.empty(0) if is_gt: raw_data['gt_crowd_ignore_regions'][t] = np.empty((0, 4))
if is_gt: key_map = {'ids': 'gt_ids', 'classes': 'gt_classes', 'dets': 'gt_dets'} else: key_map = {'ids': 'tracker_ids', 'classes': 'tracker_classes', 'dets': 'tracker_dets'} for k, v in key_map.items(): raw_data[v] = raw_data.pop(k) raw_data['num_timesteps'] = num_timesteps raw_data['seq'] = seq return raw_data
@_timing.time def get_preprocessed_seq_data(self, raw_data, cls): """ Preprocess data for a single sequence for a single class ready for evaluation. Inputs: - raw_data is a dict containing the data for the sequence already read in by get_raw_seq_data(). - cls is the class to be evaluated. Outputs: - data is a dict containing all of the information that metrics need to perform evaluation. It contains the following fields: [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets] : integers. [gt_ids, tracker_ids, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det). [gt_dets, tracker_dets]: list (for each timestep) of lists of detections. [similarity_scores]: list (for each timestep) of 2D NDArrays. Notes: General preprocessing (preproc) occurs in 4 steps. Some datasets may not use all of these steps. 1) Extract only detections relevant for the class to be evaluated (including distractor detections). 2) Match gt dets and tracker dets. Remove tracker dets that are matched to a gt det that is of a distractor class, or otherwise marked as to be removed. 3) Remove unmatched tracker dets if they fall within a crowd ignore region or don't meet a certain other criteria (e.g. are too small). 4) Remove gt dets that were only useful for preprocessing and not for actual evaluation. After the above preprocessing steps, this function also calculates the number of gt and tracker detections and unique track ids. It also relabels gt and tracker ids to be contiguous and checks that ids are unique within each timestep.
MOT Challenge: In MOT Challenge, the 4 preproc steps are as follow: 1) There is only one class (pedestrian) to be evaluated, but all other classes are used for preproc. 2) Predictions are matched against all gt boxes (regardless of class), those matching with distractor objects are removed. 3) There is no crowd ignore regions. 4) All gt dets except pedestrian are removed, also removes pedestrian gt dets marked with zero_marked. :param raw_data: A dict containing the data for the sequence already read in by `get_raw_seq_data()`. :param cls: The class to be evaluated.
:return: A dict containing all of the information that metrics need to perform evaluation. It contains the following fields: - [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets]: Integers. - [gt_ids, tracker_ids, tracker_confidences]: List (for each timestep) of 1D NDArrays (for each detection). - [gt_dets, tracker_dets]: List (for each timestep) of lists of detections. - [similarity_scores]: List (for each timestep) of 2D NDArrays.
""" # Check that input data has unique ids self._check_unique_ids(raw_data)
distractor_class_names = ['person_on_vehicle', 'static_person', 'distractor', 'reflection'] if self.benchmark == 'MOT20': distractor_class_names.append('non_mot_vehicle') distractor_classes = [self.class_name_to_class_id[x] for x in distractor_class_names] cls_id = self.class_name_to_class_id[cls]
data_keys = ['gt_ids', 'tracker_ids', 'gt_dets', 'tracker_dets', 'tracker_confidences', 'similarity_scores'] data = {key: [None] * raw_data['num_timesteps'] for key in data_keys} unique_gt_ids = [] unique_tracker_ids = [] num_gt_dets = 0 num_tracker_dets = 0 for t in range(raw_data['num_timesteps']):
# Get all data gt_ids = raw_data['gt_ids'][t] gt_dets = raw_data['gt_dets'][t] gt_classes = raw_data['gt_classes'][t] gt_zero_marked = raw_data['gt_extras'][t]['zero_marked']
tracker_ids = raw_data['tracker_ids'][t] tracker_dets = raw_data['tracker_dets'][t] tracker_classes = raw_data['tracker_classes'][t] tracker_confidences = raw_data['tracker_confidences'][t] similarity_scores = raw_data['similarity_scores'][t]
# Evaluation is ONLY valid for pedestrian class if len(tracker_classes) > 0 and np.max(tracker_classes) > 1: raise TrackEvalException( 'Evaluation is only valid for pedestrian class. Non pedestrian class (%i) found in sequence %s at ' 'timestep %i.' % (np.max(tracker_classes), raw_data['seq'], t))
# Match tracker and gt dets (with hungarian algorithm) and remove tracker dets which match with gt dets # which are labeled as belonging to a distractor class. to_remove_tracker = np.array([], int) if self.do_preproc and self.benchmark != 'MOT15' and gt_ids.shape[0] > 0 and tracker_ids.shape[0] > 0:
# Check all classes are valid: invalid_classes = np.setdiff1d(np.unique(gt_classes), self.valid_class_numbers) if len(invalid_classes) > 0: print(' '.join([str(x) for x in invalid_classes])) raise(TrackEvalException('Attempting to evaluate using invalid gt classes. ' 'This warning only triggers if preprocessing is performed, ' 'e.g. not for MOT15 or where prepropressing is explicitly disabled. ' 'Please either check your gt data, or disable preprocessing. ' 'The following invalid classes were found in timestep ' + str(t) + ': ' + ' '.join([str(x) for x in invalid_classes])))
matching_scores = similarity_scores.copy() matching_scores[matching_scores < 0.5 - np.finfo('float').eps] = 0 match_rows, match_cols = linear_sum_assignment(-matching_scores) actually_matched_mask = matching_scores[match_rows, match_cols] > 0 + np.finfo('float').eps match_rows = match_rows[actually_matched_mask] match_cols = match_cols[actually_matched_mask]
is_distractor_class = np.isin(gt_classes[match_rows], distractor_classes) to_remove_tracker = match_cols[is_distractor_class]
# Apply preprocessing to remove all unwanted tracker dets. data['tracker_ids'][t] = np.delete(tracker_ids, to_remove_tracker, axis=0) data['tracker_dets'][t] = np.delete(tracker_dets, to_remove_tracker, axis=0) data['tracker_confidences'][t] = np.delete(tracker_confidences, to_remove_tracker, axis=0) similarity_scores = np.delete(similarity_scores, to_remove_tracker, axis=1)
# Remove gt detections marked as to remove (zero marked), and also remove gt detections not in pedestrian # class (not applicable for MOT15) if self.do_preproc and self.benchmark != 'MOT15': gt_to_keep_mask = (np.not_equal(gt_zero_marked, 0)) & \ (np.equal(gt_classes, cls_id)) else: # There are no classes for MOT15 gt_to_keep_mask = np.not_equal(gt_zero_marked, 0) data['gt_ids'][t] = gt_ids[gt_to_keep_mask] data['gt_dets'][t] = gt_dets[gt_to_keep_mask, :] data['similarity_scores'][t] = similarity_scores[gt_to_keep_mask]
unique_gt_ids += list(np.unique(data['gt_ids'][t])) unique_tracker_ids += list(np.unique(data['tracker_ids'][t])) num_tracker_dets += len(data['tracker_ids'][t]) num_gt_dets += len(data['gt_ids'][t])
# Re-label IDs such that there are no empty IDs if len(unique_gt_ids) > 0: unique_gt_ids = np.unique(unique_gt_ids) gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1)) gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids)) for t in range(raw_data['num_timesteps']): if len(data['gt_ids'][t]) > 0: data['gt_ids'][t] = gt_id_map[data['gt_ids'][t]].astype(int) if len(unique_tracker_ids) > 0: unique_tracker_ids = np.unique(unique_tracker_ids) tracker_id_map = np.nan * np.ones((np.max(unique_tracker_ids) + 1)) tracker_id_map[unique_tracker_ids] = np.arange(len(unique_tracker_ids)) for t in range(raw_data['num_timesteps']): if len(data['tracker_ids'][t]) > 0: data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(int)
# Record overview statistics. data['num_tracker_dets'] = num_tracker_dets data['num_gt_dets'] = num_gt_dets data['num_tracker_ids'] = len(unique_tracker_ids) data['num_gt_ids'] = len(unique_gt_ids) data['num_timesteps'] = raw_data['num_timesteps'] data['seq'] = raw_data['seq']
# Ensure again that ids are unique per timestep after preproc. self._check_unique_ids(data, after_preproc=True)
return data
def _calculate_similarities(self, gt_dets_t, tracker_dets_t): similarity_scores = self._calculate_euclidean_similarity(gt_dets_t, tracker_dets_t) return similarity_scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233import timeimport loggingimport tracebackfrom multiprocessing.pool import Poolfrom functools import partialimport osfrom . import utilsfrom .utils import TrackEvalExceptionfrom . import _timingfrom .metrics import Count
class Evaluator: """ Evaluator class for evaluating different metrics for different datasets :param dict config: configuration for the app ::
evaluator = Evaluator(config) """
@staticmethod def get_default_eval_config(): """Returns the default config values for evaluation""" code_path = utils.get_code_path() default_config = { 'USE_PARALLEL': False, 'NUM_PARALLEL_CORES': 8, 'BREAK_ON_ERROR': True, # Raises exception and exits with error 'RETURN_ON_ERROR': False, # if not BREAK_ON_ERROR, then returns from function on error 'LOG_ON_ERROR': os.path.join(code_path, 'error_log.txt'), # if not None, save any errors into a log file.
'PRINT_RESULTS': True, 'PRINT_ONLY_COMBINED': False, 'PRINT_CONFIG': True, 'TIME_PROGRESS': True, 'DISPLAY_LESS_PROGRESS': True,
'OUTPUT_SUMMARY': True, 'OUTPUT_EMPTY_CLASSES': True, # If False, summary files are not output for classes with no detections 'OUTPUT_DETAILED': True, 'PLOT_CURVES': True, } return default_config
def __init__(self, config=None): self.config = utils.init_config(config, self.get_default_eval_config(), 'Eval') # Only run timing analysis if not run in parallel. if self.config['TIME_PROGRESS'] and not self.config['USE_PARALLEL']: _timing.DO_TIMING = True if self.config['DISPLAY_LESS_PROGRESS']: _timing.DISPLAY_LESS_PROGRESS = True
@_timing.time def evaluate(self, dataset_list, metrics_list): """ Evaluate a list of datasets with a list of metrics :param List[str] dataset_list: list of all datasets :param List[str] metrics_list: list of all metrics
:return: str output_res: results of the evaluation :return: str output_msg: status of the evaluation
::
trackeval.eval.evaluate(dataset_list, metrics_list) """ config = self.config metrics_list = metrics_list + [Count()] # Count metrics are always run metric_names = utils.validate_metrics_list(metrics_list) dataset_names = [dataset.get_name() for dataset in dataset_list] output_res = {} output_msg = {}
for dataset, dataset_name in zip(dataset_list, dataset_names): # Get dataset info about what to evaluate output_res[dataset_name] = {} output_msg[dataset_name] = {} tracker_list, seq_list, class_list = dataset.get_eval_info() logging.info('Evaluating %i tracker(s) on %i sequence(s) for %i class(es) on %s dataset using the following ' 'metrics: %s\n' % (len(tracker_list), len(seq_list), len(class_list), dataset_name, ', '.join(metric_names)))
# Evaluate each tracker for tracker in tracker_list: # if not config['BREAK_ON_ERROR'] then go to next tracker without breaking try: # Evaluate each sequence in parallel or in series. # returns a nested dict (res), indexed like: res[seq][class][metric_name][sub_metric field] # e.g. res[seq_0001][pedestrian][hota][DetA] logging.info('Evaluating %s\n' % tracker) time_start = time.time() if config['USE_PARALLEL']: with Pool(config['NUM_PARALLEL_CORES']) as pool: _eval_sequence = partial(eval_sequence, dataset=dataset, tracker=tracker, class_list=class_list, metrics_list=metrics_list, metric_names=metric_names) results = pool.map(_eval_sequence, seq_list) res = dict(zip(seq_list, results)) else: res = {} for curr_seq in sorted(seq_list): res[curr_seq] = eval_sequence(curr_seq, dataset, tracker, class_list, metrics_list, metric_names)
# Combine results over all sequences and then over all classes
# collecting combined cls keys (cls averaged, det averaged, super classes) combined_cls_keys = [] res['COMBINED_SEQ'] = {} # combine sequences for each class for c_cls in class_list: res['COMBINED_SEQ'][c_cls] = {} for metric, metric_name in zip(metrics_list, metric_names): curr_res = {seq_key: seq_value[c_cls][metric_name] for seq_key, seq_value in res.items() if seq_key != 'COMBINED_SEQ'} # print(curr_res) res['COMBINED_SEQ'][c_cls][metric_name] = metric.combine_sequences(curr_res) # print(res['COMBINED_SEQ'][c_cls][metric_name]) # combine classes if dataset.should_classes_combine: combined_cls_keys += ['cls_comb_cls_av', 'cls_comb_det_av', 'all'] res['COMBINED_SEQ']['cls_comb_cls_av'] = {} res['COMBINED_SEQ']['cls_comb_det_av'] = {} for metric, metric_name in zip(metrics_list, metric_names): cls_res = {cls_key: cls_value[metric_name] for cls_key, cls_value in res['COMBINED_SEQ'].items() if cls_key not in combined_cls_keys} res['COMBINED_SEQ']['cls_comb_cls_av'][metric_name] = \ metric.combine_classes_class_averaged(cls_res) res['COMBINED_SEQ']['cls_comb_det_av'][metric_name] = \ metric.combine_classes_det_averaged(cls_res) # combine classes to super classes if dataset.use_super_categories: for cat, sub_cats in dataset.super_categories.items(): combined_cls_keys.append(cat) res['COMBINED_SEQ'][cat] = {} for metric, metric_name in zip(metrics_list, metric_names): cat_res = {cls_key: cls_value[metric_name] for cls_key, cls_value in res['COMBINED_SEQ'].items() if cls_key in sub_cats} res['COMBINED_SEQ'][cat][metric_name] = metric.combine_classes_det_averaged(cat_res)
# Print and output results in various formats if config['TIME_PROGRESS']: logging.info('All sequences for %s finished in %.2f seconds' % (tracker, time.time() - time_start)) output_fol = dataset.get_output_fol(tracker) tracker_display_name = dataset.get_display_name(tracker) for c_cls in res['COMBINED_SEQ'].keys(): # class_list + combined classes if calculated summaries = [] details = [] num_dets = res['COMBINED_SEQ'][c_cls]['Count']['Dets'] if config['OUTPUT_EMPTY_CLASSES'] or num_dets > 0: for metric, metric_name in zip(metrics_list, metric_names): # for combined classes there is no per sequence evaluation if c_cls in combined_cls_keys: table_res = {'COMBINED_SEQ': res['COMBINED_SEQ'][c_cls][metric_name]} else: table_res = {seq_key: seq_value[c_cls][metric_name] for seq_key, seq_value in res.items()}
if config['PRINT_RESULTS'] and config['PRINT_ONLY_COMBINED']: dont_print = dataset.should_classes_combine and c_cls not in combined_cls_keys if not dont_print: metric.print_table({'COMBINED_SEQ': table_res['COMBINED_SEQ']}, tracker_display_name, c_cls) elif config['PRINT_RESULTS']: # print(table_res['FINAL']) metric.print_table(table_res, tracker_display_name, c_cls) if config['OUTPUT_SUMMARY']: summaries.append(metric.summary_results(table_res)) if config['OUTPUT_DETAILED']: details.append(metric.detailed_results(table_res)) if config['PLOT_CURVES']: metric.plot_single_tracker_results(table_res, tracker_display_name, c_cls, output_fol) if config['OUTPUT_SUMMARY']: utils.write_summary_results(summaries, c_cls, output_fol) if config['OUTPUT_DETAILED']: utils.write_detailed_results(details, c_cls, output_fol)
# Output for returning from function output_res[dataset_name][tracker] = res output_msg[dataset_name][tracker] = 'Success'
except Exception as err: output_res[dataset_name][tracker] = None if type(err) == TrackEvalException: output_msg[dataset_name][tracker] = str(err) else: output_msg[dataset_name][tracker] = 'Unknown error occurred.' logging.info('Tracker %s was unable to be evaluated.' % tracker) logging.error(err) traceback.print_exc() if config['LOG_ON_ERROR'] is not None: with open(config['LOG_ON_ERROR'], 'a') as f: logging.info(dataset_name, file=f) logging.info(tracker, file=f) logging.info(traceback.format_exc(), file=f) logging.info('\n\n\n', file=f) if config['BREAK_ON_ERROR']: raise err elif config['RETURN_ON_ERROR']: return output_res, output_msg
return output_res, output_msg
@_timing.timedef eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names): """ Function for evaluating a single sequence
:param str seq: name of the sequence :param str dataset: name of the dataset :param str tracker: name of the tracker :param List[str] class_list: list of all classes to be evaluated :param List[str] metrics_list: list of all metrics :param List[str] metric_names: list of all metrics names
:return: Dict[str] seq_res: results of the eval sequence ::
trackeval.eval.eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names) """ raw_data = dataset.get_raw_seq_data(tracker, seq) seq_res = {} for cls in class_list: seq_res[cls] = {} data = dataset.get_preprocessed_seq_data(raw_data, cls) for metric, met_name in zip(metrics_list, metric_names): seq_res[cls][met_name] = metric.eval_sequence(data) return seq_res12345"""MTMC analytics hota-metrics submodules"""from .hota import HOTAfrom .clear import CLEARfrom .identity import Identityfrom .count import Count123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import numpy as npfrom abc import ABC, abstractmethodfrom trackeval import _timingfrom trackeval.utils import TrackEvalException
class _BaseMetric(ABC): @abstractmethod def __init__(self): self.plottable = False self.integer_fields = [] self.float_fields = [] self.array_labels = [] self.integer_array_fields = [] self.float_array_fields = [] self.fields = [] self.summary_fields = [] self.registered = False
##################################################################### # Abstract functions for subclasses to implement
@_timing.time @abstractmethod def eval_sequence(self, data): ...
@abstractmethod def combine_sequences(self, all_res): ...
@abstractmethod def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False): ...
@ abstractmethod def combine_classes_det_averaged(self, all_res): ...
def plot_single_tracker_results(self, all_res, tracker, output_folder, cls): """ Plot results of metrics, only valid for metrics with self.plottable :param Dict all_res: dictionary containing all results :param str tracker: The tracker to plot results for :param str output_folder: The output folder for saving the plots :param str cls: The class to plot results for
:raises NotImplementedError: If the metric does not have self.plottable
""" if self.plottable: raise NotImplementedError('plot_results is not implemented for metric %s' % self.get_name()) else: pass
##################################################################### # Helper functions which are useful for all metrics:
@classmethod def get_name(cls): return cls.__name__
@staticmethod def _combine_sum(all_res, field): """ Combine sequence results via sum :param Dict all_res: dictionary containing sequence results :param str field: The field to be combined :return: The sum of the combined results :rtype: float """ return sum([all_res[k][field] for k in all_res.keys()])
@staticmethod def _combine_weighted_av(all_res, field, comb_res, weight_field): """ Combine sequence results via weighted average
:param Dict all_res: dictionary containing sequence results :param str field: The field to be combined :param Dict comb_res: dictionary containing combined results :param str weight_field: The field representing the weight :return: The weighted average of the combined results :rtype: float """ return sum([all_res[k][field] * all_res[k][weight_field] for k in all_res.keys()]) / np.maximum(1.0, comb_res[ weight_field])
def print_table(self, table_res, tracker, cls): """ Prints table of results for all sequences :param Dict table_res: dictionary containing the results for each sequence. :param str tracker: The name of the tracker. :param str cls: The name of the class. :return None """ print('') metric_name = self.get_name() self._row_print([metric_name + ': ' + tracker + '-' + cls] + self.summary_fields) for seq, results in sorted(table_res.items()): if seq == 'COMBINED_SEQ': continue # if seq == 'FINAL': summary_res = self._summary_row(results) self._row_print([seq] + summary_res) summary_res = self._summary_row(table_res['COMBINED_SEQ']) # self._row_print(['COMBINED'] + summary_res)
def _summary_row(self, results_): """ Generate a summary row of values based on the provided results. :param Dict results_: dictionary containing the metric results.
:return: A list of formatted values for the summary row. :rtype: list :raises NotImplementedError: If the summary function is not implemented for a field type. """ vals = [] for h in self.summary_fields: if h in self.float_array_fields: vals.append("{0:1.5g}".format(100 * np.mean(results_[h]))) elif h in self.float_fields: vals.append("{0:1.5g}".format(100 * float(results_[h]))) elif h in self.integer_fields: vals.append("{0:d}".format(int(results_[h]))) else: raise NotImplementedError("Summary function not implemented for this field type.") return vals
@staticmethod def _row_print(*argv): """ Prints results in an evenly spaced rows, with more space in first row :param argv: The values to be printed in each column of the row. :type argv: tuple or list """ if len(argv) == 1: argv = argv[0] to_print = '%-35s' % argv[0] for v in argv[1:]: to_print += '%-10s' % str(v) print(to_print)
def summary_results(self, table_res): """ Returns a simple summary of final results for a tracker :param Dict table_res: The table of results containing per-sequence and combined sequence results. :return: dictionary representing the summary of final results. :rtype: Dict """ return dict(zip(self.summary_fields, self._summary_row(table_res['COMBINED_SEQ'])))
def detailed_results(self, table_res): """ Returns detailed final results for a tracker :param Dict table_res: The table of results containing per-sequence and combined sequence results. :return: Detailed results for each sequence as a dictionary of dictionaries. :rtype: Dict :raises TrackEvalException: If the field names and data have different sizes. """ # Get detailed field information detailed_fields = self.float_fields + self.integer_fields for h in self.float_array_fields + self.integer_array_fields: for alpha in [int(100*x) for x in self.array_labels]: detailed_fields.append(h + '___' + str(alpha)) detailed_fields.append(h + '___AUC')
# Get detailed results detailed_results = {} for seq, res in table_res.items(): detailed_row = self._detailed_row(res) if len(detailed_row) != len(detailed_fields): raise TrackEvalException( 'Field names and data have different sizes (%i and %i)' % (len(detailed_row), len(detailed_fields))) detailed_results[seq] = dict(zip(detailed_fields, detailed_row)) return detailed_results
def _detailed_row(self, res): """ Calculates a detailed row of results for a given set of metrics.
:param Dict res: The results containing the metrics. :return: Detailed row of results. :rtype: list """ detailed_row = [] for h in self.float_fields + self.integer_fields: detailed_row.append(res[h]) for h in self.float_array_fields + self.integer_array_fields: for i, alpha in enumerate([int(100 * x) for x in self.array_labels]): detailed_row.append(res[h][i]) detailed_row.append(np.mean(res[h])) return detailed_row123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223import numpy as npfrom scipy.optimize import linear_sum_assignmentfrom ._base_metric import _BaseMetricfrom trackeval import _timingfrom trackeval import utils
class CLEAR(_BaseMetric): """ Class which implements the CLEAR metrics :param Dict config: configuration for the app ::
identity = trackeval.metrics.CLEAR(config) """
@staticmethod def get_default_config(): """Default class config values""" default_config = { 'THRESHOLD': 0.5, # Similarity score threshold required for a TP match. Default 0.5. 'PRINT_CONFIG': True, # Whether to print the config information on init. Default: False. } return default_config
def __init__(self, config=None): super().__init__() main_integer_fields = ['CLR_TP', 'CLR_FN', 'CLR_FP', 'IDSW', 'MT', 'PT', 'ML', 'Frag'] extra_integer_fields = ['CLR_Frames'] self.integer_fields = main_integer_fields + extra_integer_fields main_float_fields = ['MOTA', 'MOTP', 'MODA', 'CLR_Re', 'CLR_Pr', 'MTR', 'PTR', 'MLR', 'sMOTA'] extra_float_fields = ['CLR_F1', 'FP_per_frame', 'MOTAL', 'MOTP_sum'] self.float_fields = main_float_fields + extra_float_fields self.fields = self.float_fields + self.integer_fields self.summed_fields = self.integer_fields + ['MOTP_sum'] self.summary_fields = main_float_fields + main_integer_fields
# Configuration options: self.config = utils.init_config(config, self.get_default_config(), self.get_name()) self.threshold = float(self.config['THRESHOLD'])
@_timing.time def eval_sequence(self, data): """ Calculates CLEAR metrics for one sequence :param Dict[str, float] data: dictionary containing the data for the sequence :return: dictionary containing the calculated count metrics :rtype: Dict[str, float] """ # Initialise results res = {} for field in self.fields: res[field] = 0
# Return result quickly if tracker or gt sequence is empty if data['num_tracker_dets'] == 0: res['CLR_FN'] = data['num_gt_dets'] res['ML'] = data['num_gt_ids'] res['MLR'] = 1.0 return res if data['num_gt_dets'] == 0: res['CLR_FP'] = data['num_tracker_dets'] res['MLR'] = 1.0 return res
# Variables counting global association num_gt_ids = data['num_gt_ids'] gt_id_count = np.zeros(num_gt_ids) # For MT/ML/PT gt_matched_count = np.zeros(num_gt_ids) # For MT/ML/PT gt_frag_count = np.zeros(num_gt_ids) # For Frag
# Note that IDSWs are counted based on the last time each gt_id was present (any number of frames previously), # but are only used in matching to continue current tracks based on the gt_id in the single previous timestep. prev_tracker_id = np.nan * np.zeros(num_gt_ids) # For scoring IDSW prev_timestep_tracker_id = np.nan * np.zeros(num_gt_ids) # For matching IDSW
# Calculate scores for each timestep for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])): # Deal with the case that there are no gt_det/tracker_det in a timestep. if len(gt_ids_t) == 0: res['CLR_FP'] += len(tracker_ids_t) continue if len(tracker_ids_t) == 0: res['CLR_FN'] += len(gt_ids_t) gt_id_count[gt_ids_t] += 1 continue
# Calc score matrix to first minimise IDSWs from previous frame, and then maximise MOTP secondarily similarity = data['similarity_scores'][t] score_mat = (tracker_ids_t[np.newaxis, :] == prev_timestep_tracker_id[gt_ids_t[:, np.newaxis]]) score_mat = 1000 * score_mat + similarity score_mat[similarity < self.threshold - np.finfo('float').eps] = 0
# Hungarian algorithm to find best matches match_rows, match_cols = linear_sum_assignment(-score_mat) actually_matched_mask = score_mat[match_rows, match_cols] > 0 + np.finfo('float').eps match_rows = match_rows[actually_matched_mask] match_cols = match_cols[actually_matched_mask]
matched_gt_ids = gt_ids_t[match_rows] matched_tracker_ids = tracker_ids_t[match_cols]
# Calc IDSW for MOTA prev_matched_tracker_ids = prev_tracker_id[matched_gt_ids] is_idsw = (np.logical_not(np.isnan(prev_matched_tracker_ids))) & ( np.not_equal(matched_tracker_ids, prev_matched_tracker_ids)) res['IDSW'] += np.sum(is_idsw)
# Update counters for MT/ML/PT/Frag and record for IDSW/Frag for next timestep gt_id_count[gt_ids_t] += 1 gt_matched_count[matched_gt_ids] += 1 not_previously_tracked = np.isnan(prev_timestep_tracker_id) prev_tracker_id[matched_gt_ids] = matched_tracker_ids prev_timestep_tracker_id[:] = np.nan prev_timestep_tracker_id[matched_gt_ids] = matched_tracker_ids currently_tracked = np.logical_not(np.isnan(prev_timestep_tracker_id)) gt_frag_count += np.logical_and(not_previously_tracked, currently_tracked)
# Calculate and accumulate basic statistics num_matches = len(matched_gt_ids) res['CLR_TP'] += num_matches res['CLR_FN'] += len(gt_ids_t) - num_matches res['CLR_FP'] += len(tracker_ids_t) - num_matches if num_matches > 0: res['MOTP_sum'] += sum(similarity[match_rows, match_cols])
# Calculate MT/ML/PT/Frag/MOTP tracked_ratio = gt_matched_count[gt_id_count > 0] / gt_id_count[gt_id_count > 0] res['MT'] = np.sum(np.greater(tracked_ratio, 0.8)) res['PT'] = np.sum(np.greater_equal(tracked_ratio, 0.2)) - res['MT'] res['ML'] = num_gt_ids - res['MT'] - res['PT'] res['Frag'] = np.sum(np.subtract(gt_frag_count[gt_frag_count > 0], 1)) res['MOTP'] = res['MOTP_sum'] / np.maximum(1.0, res['CLR_TP'])
res['CLR_Frames'] = data['num_timesteps']
# Calculate final CLEAR scores res = self._compute_final_fields(res) return res
def combine_sequences(self, all_res): """ Combines metrics across all sequences :param Dict[str, float] all_res: dictionary containing the metrics for each sequence :return: dictionary containing the combined metrics across sequences :rtype: Dict[str, float] """ res = {} for field in self.summed_fields: res[field] = self._combine_sum(all_res, field) res = self._compute_final_fields(res) return res
def combine_classes_det_averaged(self, all_res): """ Combines metrics across all classes by averaging over the detection values :param Dict[str, float] all_res: dictionary containing the metrics for each class :return: dictionary containing the combined metrics averaged over detections :rtype: Dict[str, float] """ res = {} for field in self.summed_fields: res[field] = self._combine_sum(all_res, field) res = self._compute_final_fields(res) return res
def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False): """ Combines metrics across all classes by averaging over the class values. If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection. :param Dict[str, float] all_res: dictionary containing the ID metrics for each class :param bool ignore_empty_classes: Flag to ignore empty classes, defaults to False :return: dictionary containing the combined metrics averaged over classes :rtype: Dict[str, float] """ res = {} for field in self.integer_fields: if ignore_empty_classes: res[field] = self._combine_sum( {k: v for k, v in all_res.items() if v['CLR_TP'] + v['CLR_FN'] + v['CLR_FP'] > 0}, field) else: res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field) for field in self.float_fields: if ignore_empty_classes: res[field] = np.mean( [v[field] for v in all_res.values() if v['CLR_TP'] + v['CLR_FN'] + v['CLR_FP'] > 0], axis=0) else: res[field] = np.mean([v[field] for v in all_res.values()], axis=0) return res
@staticmethod def _compute_final_fields(res): """ Calculate sub-metric ('field') values which only depend on other sub-metric values. This function is used both for both per-sequence calculation, and in combining values across sequences. :param Dict[str, float] res: dictionary containing the sub-metric values :return: dictionary containing the updated sub-metric values :rtype: Dict[str, float] """ num_gt_ids = res['MT'] + res['ML'] + res['PT'] res['MTR'] = res['MT'] / np.maximum(1.0, num_gt_ids) res['MLR'] = res['ML'] / np.maximum(1.0, num_gt_ids) res['PTR'] = res['PT'] / np.maximum(1.0, num_gt_ids) res['CLR_Re'] = res['CLR_TP'] / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN']) res['CLR_Pr'] = res['CLR_TP'] / np.maximum(1.0, res['CLR_TP'] + res['CLR_FP']) res['MODA'] = (res['CLR_TP'] - res['CLR_FP']) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN']) res['MOTA'] = (res['CLR_TP'] - res['CLR_FP'] - res['IDSW']) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN']) res['MOTP'] = res['MOTP_sum'] / np.maximum(1.0, res['CLR_TP']) res['sMOTA'] = (res['MOTP_sum'] - res['CLR_FP'] - res['IDSW']) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN'])
res['CLR_F1'] = res['CLR_TP'] / np.maximum(1.0, res['CLR_TP'] + 0.5*res['CLR_FN'] + 0.5*res['CLR_FP']) res['FP_per_frame'] = res['CLR_FP'] / np.maximum(1.0, res['CLR_Frames']) safe_log_idsw = np.log10(res['IDSW']) if res['IDSW'] > 0 else res['IDSW'] res['MOTAL'] = (res['CLR_TP'] - res['CLR_FP'] - safe_log_idsw) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN']) return res12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576from ._base_metric import _BaseMetricfrom trackeval import _timing
class Count(_BaseMetric): """ Class which simply counts the number of tracker and gt detections and ids. :param Dict config: configuration for the app ::
identity = trackeval.metrics.Count(config) """ def __init__(self, config=None): super().__init__() self.integer_fields = ['Dets', 'GT_Dets', 'IDs', 'GT_IDs'] self.fields = self.integer_fields self.summary_fields = self.fields
@_timing.time def eval_sequence(self, data): """ Returns counts for one sequence :param Dict data: dictionary containing the data for the sequence :return: dictionary containing the calculated count metrics :rtype: Dict[str, Dict[str]] """ # Get results res = {'Dets': data['num_tracker_dets'], 'GT_Dets': data['num_gt_dets'], 'IDs': data['num_tracker_ids'], 'GT_IDs': data['num_gt_ids'], 'Frames': data['num_timesteps']} return res
def combine_sequences(self, all_res): """ Combines metrics across all sequences :param Dict[str, float] all_res: dictionary containing the metrics for each sequence :return: dictionary containing the combined metrics across sequences :rtype: Dict[str, float] """ res = {} for field in self.integer_fields: res[field] = self._combine_sum(all_res, field) return res
def combine_classes_class_averaged(self, all_res, ignore_empty_classes=None): """ Combines metrics across all classes by averaging over the class values :param Dict[str, float] all_res: dictionary containing the ID metrics for each class :param bool ignore_empty_classes: Flag to ignore empty classes, defaults to False :return: dictionary containing the combined metrics averaged over classes :rtype: Dict[str, float] """ res = {} for field in self.integer_fields: res[field] = self._combine_sum(all_res, field) return res
def combine_classes_det_averaged(self, all_res): """ Combines metrics across all classes by averaging over the detection values :param Dict[str, float] all_res: dictionary containing the metrics for each class :return: dictionary containing the combined metrics averaged over detections :rtype: Dict[str, float] """ res = {} for field in self.integer_fields: res[field] = self._combine_sum(all_res, field) return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245import osimport numpy as npfrom trackeval import _timingfrom scipy.optimize import linear_sum_assignmentfrom trackeval.metrics._base_metric import _BaseMetric
class HOTA(_BaseMetric): """ Class which implements the HOTA metrics. See: https://link.springer.com/article/10.1007/s11263-020-01375-2 :param Dict config: configuration for the app ::
identity = trackeval.metrics.HOTA(config) """
def __init__(self, config=None): super().__init__() self.plottable = True self.array_labels = np.arange(0.05, 0.99, 0.05) self.integer_array_fields = ['HOTA_TP', 'HOTA_FN', 'HOTA_FP'] self.float_array_fields = ['HOTA', 'DetA', 'AssA', 'DetRe', 'DetPr', 'AssRe', 'AssPr', 'LocA', 'OWTA'] self.float_fields = ['HOTA(0)', 'LocA(0)', 'HOTALocA(0)'] self.fields = self.float_array_fields + self.integer_array_fields + self.float_fields self.summary_fields = self.float_array_fields + self.float_fields
@_timing.time def eval_sequence(self, data): """ Calculates the HOTA metrics for one sequence :param Dict data: dictionary containing the data for the sequence :return: dictionary containing the calculated hota metrics :rtype: Dict """ # Initialise results res = {} for field in self.float_array_fields + self.integer_array_fields: res[field] = np.zeros((len(self.array_labels)), dtype=float) for field in self.float_fields: res[field] = 0
# Return result quickly if tracker or gt sequence is empty if data['num_tracker_dets'] == 0: res['HOTA_FN'] = data['num_gt_dets'] * np.ones((len(self.array_labels)), dtype=float) res['LocA'] = np.ones((len(self.array_labels)), dtype=float) res['LocA(0)'] = 1.0 return res if data['num_gt_dets'] == 0: res['HOTA_FP'] = data['num_tracker_dets'] * np.ones((len(self.array_labels)), dtype=float) res['LocA'] = np.ones((len(self.array_labels)), dtype=float) res['LocA(0)'] = 1.0 return res
# Variables counting global association potential_matches_count = np.zeros((data['num_gt_ids'], data['num_tracker_ids'])) gt_id_count = np.zeros((data['num_gt_ids'], 1)) tracker_id_count = np.zeros((1, data['num_tracker_ids']))
# First loop through each timestep and accumulate global track information. for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])): # Count the potential matches between ids in each timestep # These are normalised, weighted by the match similarity. similarity = data['similarity_scores'][t] sim_iou_denom = similarity.sum(0)[np.newaxis, :] + similarity.sum(1)[:, np.newaxis] - similarity sim_iou = np.zeros_like(similarity) sim_iou_mask = sim_iou_denom > 0 + np.finfo('float').eps sim_iou[sim_iou_mask] = similarity[sim_iou_mask] / sim_iou_denom[sim_iou_mask] potential_matches_count[gt_ids_t[:, np.newaxis], tracker_ids_t[np.newaxis, :]] += sim_iou
# Calculate the total number of dets for each gt_id and tracker_id. gt_id_count[gt_ids_t] += 1 tracker_id_count[0, tracker_ids_t] += 1
# Calculate overall jaccard alignment score (before unique matching) between IDs global_alignment_score = potential_matches_count / (gt_id_count + tracker_id_count - potential_matches_count) matches_counts = [np.zeros_like(potential_matches_count) for _ in self.array_labels]
# Calculate scores for each timestep for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])): # Deal with the case that there are no gt_det/tracker_det in a timestep. if len(gt_ids_t) == 0: for a, alpha in enumerate(self.array_labels): res['HOTA_FP'][a] += len(tracker_ids_t) continue if len(tracker_ids_t) == 0: for a, alpha in enumerate(self.array_labels): res['HOTA_FN'][a] += len(gt_ids_t) continue
# Get matching scores between pairs of dets for optimizing HOTA similarity = data['similarity_scores'][t] score_mat = global_alignment_score[gt_ids_t[:, np.newaxis], tracker_ids_t[np.newaxis, :]] * similarity
# Hungarian algorithm to find best matches match_rows, match_cols = linear_sum_assignment(-score_mat)
# Calculate and accumulate basic statistics for a, alpha in enumerate(self.array_labels): actually_matched_mask = similarity[match_rows, match_cols] >= alpha - np.finfo('float').eps alpha_match_rows = match_rows[actually_matched_mask] alpha_match_cols = match_cols[actually_matched_mask] num_matches = len(alpha_match_rows) res['HOTA_TP'][a] += num_matches res['HOTA_FN'][a] += len(gt_ids_t) - num_matches res['HOTA_FP'][a] += len(tracker_ids_t) - num_matches if num_matches > 0: res['LocA'][a] += sum(similarity[alpha_match_rows, alpha_match_cols]) matches_counts[a][gt_ids_t[alpha_match_rows], tracker_ids_t[alpha_match_cols]] += 1
# Calculate association scores (AssA, AssRe, AssPr) for the alpha value. # First calculate scores per gt_id/tracker_id combo and then average over the number of detections. for a, alpha in enumerate(self.array_labels): matches_count = matches_counts[a] ass_a = matches_count / np.maximum(1, gt_id_count + tracker_id_count - matches_count) res['AssA'][a] = np.sum(matches_count * ass_a) / np.maximum(1, res['HOTA_TP'][a]) ass_re = matches_count / np.maximum(1, gt_id_count) res['AssRe'][a] = np.sum(matches_count * ass_re) / np.maximum(1, res['HOTA_TP'][a]) ass_pr = matches_count / np.maximum(1, tracker_id_count) res['AssPr'][a] = np.sum(matches_count * ass_pr) / np.maximum(1, res['HOTA_TP'][a])
# Calculate final scores res['LocA'] = np.maximum(0, res['LocA']) / np.maximum(1e-10, res['HOTA_TP']) res = self._compute_final_fields(res) return res
def combine_sequences(self, all_res): """ Combines metrics across all sequences :param Dict[str, float] all_res: dictionary containing the metrics for each sequence :return: dictionary containing the combined metrics across sequences :rtype: Dict[str, float] """ res = {} for field in self.integer_array_fields: res[field] = self._combine_sum(all_res, field) for field in ['AssRe', 'AssPr', 'AssA']: res[field] = self._combine_weighted_av(all_res, field, res, weight_field='HOTA_TP') loca_weighted_sum = sum([all_res[k]['LocA'] * all_res[k]['HOTA_TP'] for k in all_res.keys()]) res['LocA'] = np.maximum(1e-10, loca_weighted_sum) / np.maximum(1e-10, res['HOTA_TP']) res = self._compute_final_fields(res) return res
def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False): """ Combines metrics across all classes by averaging over the class values. If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection. :param Dict[str, float] all_res: dictionary containing the ID metrics for each class :param bool ignore_empty_classes: Flag to ignore empty classes, defaults to False :return: dictionary containing the combined metrics averaged over classes :rtype: Dict[str, float] """ res = {} for field in self.integer_array_fields: if ignore_empty_classes: res[field] = self._combine_sum( {k: v for k, v in all_res.items() if (v['HOTA_TP'] + v['HOTA_FN'] + v['HOTA_FP'] > 0 + np.finfo('float').eps).any()}, field) else: res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field)
for field in self.float_fields + self.float_array_fields: if ignore_empty_classes: res[field] = np.mean([v[field] for v in all_res.values() if (v['HOTA_TP'] + v['HOTA_FN'] + v['HOTA_FP'] > 0 + np.finfo('float').eps).any()], axis=0) else: res[field] = np.mean([v[field] for v in all_res.values()], axis=0) return res
def combine_classes_det_averaged(self, all_res): """ Combines metrics across all classes by averaging over the detection values :param Dict[str, float] all_res: dictionary containing the metrics for each class :return: dictionary containing the combined metrics averaged over detections :rtype: Dict[str, float] """ res = {} for field in self.integer_array_fields: res[field] = self._combine_sum(all_res, field) for field in ['AssRe', 'AssPr', 'AssA']: res[field] = self._combine_weighted_av(all_res, field, res, weight_field='HOTA_TP') loca_weighted_sum = sum([all_res[k]['LocA'] * all_res[k]['HOTA_TP'] for k in all_res.keys()]) res['LocA'] = np.maximum(1e-10, loca_weighted_sum) / np.maximum(1e-10, res['HOTA_TP']) res = self._compute_final_fields(res) return res
@staticmethod def _compute_final_fields(res): """ Calculate sub-metric ('field') values which only depend on other sub-metric values. This function is used both for both per-sequence calculation, and in combining values across sequences. :param Dict[str, float] res: dictionary containing the sub-metric values :return: dictionary containing the updated sub-metric values :rtype: Dict[str, float] """ res['DetRe'] = res['HOTA_TP'] / np.maximum(1, res['HOTA_TP'] + res['HOTA_FN']) res['DetPr'] = res['HOTA_TP'] / np.maximum(1, res['HOTA_TP'] + res['HOTA_FP']) res['DetA'] = res['HOTA_TP'] / np.maximum(1, res['HOTA_TP'] + res['HOTA_FN'] + res['HOTA_FP']) res['HOTA'] = np.sqrt(res['DetA'] * res['AssA']) res['OWTA'] = np.sqrt(res['DetRe'] * res['AssA'])
res['HOTA(0)'] = res['HOTA'][0] res['LocA(0)'] = res['LocA'][0] res['HOTALocA(0)'] = res['HOTA(0)']*res['LocA(0)'] return res
def plot_single_tracker_results(self, table_res, tracker, cls, output_folder): """ Create plot of results :param Dict table_res: dictionary containing the evaluation results :param str tracker: The name of the tracker :param str cls: The class name :param str output_folder: The output folder path for saving the plot """
# Only loaded when run to reduce minimum requirements from matplotlib import pyplot as plt
res = table_res['COMBINED_SEQ'] styles_to_plot = ['r', 'b', 'g', 'b--', 'b:', 'g--', 'g:', 'm'] for name, style in zip(self.float_array_fields, styles_to_plot): plt.plot(self.array_labels, res[name], style) plt.xlabel('alpha') plt.ylabel('score') plt.title(tracker + ' - ' + cls) plt.axis([0, 1, 0, 1]) legend = [] for name in self.float_array_fields: legend += [name + ' (' + str(np.round(np.mean(res[name]), 2)) + ')'] plt.legend(legend, loc='lower left') out_file = os.path.join(output_folder, cls + '_plot.pdf') os.makedirs(os.path.dirname(out_file), exist_ok=True) plt.savefig(out_file) plt.savefig(out_file.replace('.pdf', '.png')) plt.clf()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import numpy as npfrom scipy.optimize import linear_sum_assignmentfrom trackeval import _timingfrom trackeval import utilsfrom trackeval.metrics._base_metric import _BaseMetric
class Identity(_BaseMetric): """ Class which implements the Identity metrics :param Dict config: configuration for the app ::
identity = trackeval.metrics.Identity(config) """
@staticmethod def get_default_config(): """Default class config values""" default_config = { 'THRESHOLD': 0.5, # Similarity score threshold required for a IDTP match. Default 0.5. 'PRINT_CONFIG': True, # Whether to print the config information on init. Default: False. } return default_config
def __init__(self, config=None): super().__init__() self.integer_fields = ['IDTP', 'IDFN', 'IDFP'] self.float_fields = ['IDF1', 'IDR', 'IDP'] self.fields = self.float_fields + self.integer_fields self.summary_fields = self.fields
# Configuration options: self.config = utils.init_config(config, self.get_default_config(), self.get_name()) self.threshold = float(self.config['THRESHOLD'])
@_timing.time def eval_sequence(self, data): """ Calculates ID metrics for one sequence :param Dict[str, float] data: dictionary containing the data for the sequence :return: dictionary containing the calculated ID metrics :rtype: Dict[str, float] """ # Initialise results res = {} for field in self.fields: res[field] = 0
# Return result quickly if tracker or gt sequence is empty if data['num_tracker_dets'] == 0: res['IDFN'] = data['num_gt_dets'] return res if data['num_gt_dets'] == 0: res['IDFP'] = data['num_tracker_dets'] return res
# Variables counting global association potential_matches_count = np.zeros((data['num_gt_ids'], data['num_tracker_ids'])) gt_id_count = np.zeros(data['num_gt_ids']) tracker_id_count = np.zeros(data['num_tracker_ids'])
# First loop through each timestep and accumulate global track information. for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])): # Count the potential matches between ids in each timestep matches_mask = np.greater_equal(data['similarity_scores'][t], self.threshold) match_idx_gt, match_idx_tracker = np.nonzero(matches_mask) potential_matches_count[gt_ids_t[match_idx_gt], tracker_ids_t[match_idx_tracker]] += 1
# Calculate the total number of dets for each gt_id and tracker_id. gt_id_count[gt_ids_t] += 1 tracker_id_count[tracker_ids_t] += 1
# Calculate optimal assignment cost matrix for ID metrics num_gt_ids = data['num_gt_ids'] num_tracker_ids = data['num_tracker_ids'] fp_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids)) fn_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids)) fp_mat[num_gt_ids:, :num_tracker_ids] = 1e10 fn_mat[:num_gt_ids, num_tracker_ids:] = 1e10 for gt_id in range(num_gt_ids): fn_mat[gt_id, :num_tracker_ids] = gt_id_count[gt_id] fn_mat[gt_id, num_tracker_ids + gt_id] = gt_id_count[gt_id] for tracker_id in range(num_tracker_ids): fp_mat[:num_gt_ids, tracker_id] = tracker_id_count[tracker_id] fp_mat[tracker_id + num_gt_ids, tracker_id] = tracker_id_count[tracker_id] fn_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count fp_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count
# Hungarian algorithm match_rows, match_cols = linear_sum_assignment(fn_mat + fp_mat)
# Accumulate basic statistics res['IDFN'] = fn_mat[match_rows, match_cols].sum().astype(int) res['IDFP'] = fp_mat[match_rows, match_cols].sum().astype(int) res['IDTP'] = (gt_id_count.sum() - res['IDFN']).astype(int)
# Calculate final ID scores res = self._compute_final_fields(res) return res
def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False): """ Combines metrics across all classes by averaging over the class values. If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection. :param Dict[str, float] all_res: dictionary containing the ID metrics for each class :param bool ignore_empty_classes: flag to ignore empty classes, defaults to False :return: dictionary containing the combined metrics averaged over classes :rtype: Dict[str, float] """ res = {} for field in self.integer_fields: if ignore_empty_classes: res[field] = self._combine_sum({k: v for k, v in all_res.items() if v['IDTP'] + v['IDFN'] + v['IDFP'] > 0 + np.finfo('float').eps}, field) else: res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field) for field in self.float_fields: if ignore_empty_classes: res[field] = np.mean([v[field] for v in all_res.values() if v['IDTP'] + v['IDFN'] + v['IDFP'] > 0 + np.finfo('float').eps], axis=0) else: res[field] = np.mean([v[field] for v in all_res.values()], axis=0) return res
def combine_classes_det_averaged(self, all_res): """ Combines metrics across all classes by averaging over the detection values :param Dict[str, float] all_res: dictionary containing the metrics for each class :return: dictionary containing the combined metrics averaged over detections :rtype: Dict[str, float] """ res = {} for field in self.integer_fields: res[field] = self._combine_sum(all_res, field) res = self._compute_final_fields(res) return res
def combine_sequences(self, all_res): """ Combines metrics across all sequences :param Dict[str, float] all_res: dictionary containing the metrics for each sequence :return: dictionary containing the combined metrics across sequences :rtype: Dict[str, float][str, float] """ res = {} for field in self.integer_fields: res[field] = self._combine_sum(all_res, field) res = self._compute_final_fields(res) return res
@staticmethod def _compute_final_fields(res): """ Calculate sub-metric ('field') values which only depend on other sub-metric values. This function is used both for both per-sequence calculation, and in combining values across sequences. :param Dict[str, float] res: dictionary containing the sub-metric values :return: dictionary containing the updated sub-metric values :rtype: Dict[str, float] """ res['IDR'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + res['IDFN']) res['IDP'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + res['IDFP']) res['IDF1'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + 0.5 * res['IDFP'] + 0.5 * res['IDFN']) return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322import osimport loggingimport numpy as npfrom .utils import TrackEvalException
def plot_compare_trackers(tracker_folder, tracker_list, cls, output_folder, plots_list=None): """ Create plots which compare metrics across different trackers
:param str tracker_folder: root tracker folder :param str tracker_list: names of all trackers :param List[cls] cls: names of classes :param str output_folder: root folder to save the plots in :param List[str] plots_list: list of all plots to generate :return: None ::
plotting.plot_compare_trackers(tracker_folder, tracker_list, cls, output_folder, plots_list) """ if plots_list is None: plots_list = get_default_plots_list()
# Load data data = load_multiple_tracker_summaries(tracker_folder, tracker_list, cls) out_loc = os.path.join(output_folder, cls)
# Plot print("\n") for args in plots_list: create_comparison_plot(data, out_loc, *args)
def get_default_plots_list(): """ Create a intermediate config to define the type of plots. The plot uses the following order to generate the charts: y_label, x_label, sort_label, bg_label, bg_function
:param None :return: List[List[str]] plots_list: detailed description of the plots ::
plotting.get_default_plots_list(tracker_folder, tracker_list, cls, output_folder, plots_list) """ plots_list = [ ['AssA', 'DetA', 'HOTA', 'HOTA', 'geometric_mean'], ['AssPr', 'AssRe', 'HOTA', 'AssA', 'jaccard'], ['DetPr', 'DetRe', 'HOTA', 'DetA', 'jaccard'], ['HOTA(0)', 'LocA(0)', 'HOTA', 'HOTALocA(0)', 'multiplication'], ['HOTA', 'LocA', 'HOTA', None, None],
['HOTA', 'MOTA', 'HOTA', None, None], ['HOTA', 'IDF1', 'HOTA', None, None], ['IDF1', 'MOTA', 'HOTA', None, None], ] return plots_list
def load_multiple_tracker_summaries(tracker_folder, tracker_list, cls): """ Loads summary data for multiple trackers
:param str tracker_folder: directory of the tracker folder :param str tracker_list: names of the trackers :param str cls: names of all classes
:return: Dict[str] data: summaried data of the trackers ::
plotting.load_multiple_tracker_summaries(tracker_folder, tracker_list, cls, output_folder, plots_list) """ data = {} for tracker in tracker_list: with open(os.path.join(tracker_folder, tracker, cls + '_summary.txt')) as f: keys = next(f).split(' ') done = False while not done: values = next(f).split(' ') if len(values) == len(keys): done = True data[tracker] = dict(zip(keys, map(float, values))) return data
def create_comparison_plot(data, out_loc, y_label, x_label, sort_label, bg_label=None, bg_function=None, settings=None): """ Creates a scatter plot comparing multiple trackers between two metric fields, with one on the x-axis and the other on the y axis. Adds pareto optical lines and (optionally) a background contour.
:param data: dict of dicts such that data[tracker_name][metric_field_name] = float :param str y_label: the metric_field_name to be plotted on the y-axis :param strx_label: the metric_field_name to be plotted on the x-axis :param str sort_label: the metric_field_name by which trackers are ordered and ranked :param str bg_label: the metric_field_name by which (optional) background contours are plotted :param str bg_function: the (optional) function bg_function(x,y) which converts the x_label / y_label values into bg_label. :param Dict[str] settings: dict of plot settings with keys: 'gap_val': gap between axis ticks and bg curves. 'num_to_plot': maximum number of trackers to plot
:return: None ::
plotting.create_comparison_plot(x_values, y_values) """
# Only loaded when run to reduce minimum requirements from matplotlib import pyplot as plt
# Get plot settings if settings is None: gap_val = 2 num_to_plot = 20 else: gap_val = settings['gap_val'] num_to_plot = settings['num_to_plot']
if (bg_label is None) != (bg_function is None): raise TrackEvalException('bg_function and bg_label must either be both given or neither given.')
# Extract data tracker_names = np.array(list(data.keys())) sort_index = np.array([data[t][sort_label] for t in tracker_names]).argsort()[::-1] x_values = np.array([data[t][x_label] for t in tracker_names])[sort_index][:num_to_plot] y_values = np.array([data[t][y_label] for t in tracker_names])[sort_index][:num_to_plot]
# Print info on what is being plotted tracker_names = tracker_names[sort_index][:num_to_plot] logging.info('Plotting %s vs %s...' % (y_label, x_label)) #for i, name in enumerate(tracker_names): #print('%i: %s' % (i+1, name))
# Find best fitting boundaries for data boundaries = _get_boundaries(x_values, y_values, round_val=gap_val/2)
fig = plt.figure()
# Plot background contour if bg_function is not None: _plot_bg_contour(bg_function, boundaries, gap_val)
# Plot pareto optimal lines _plot_pareto_optimal_lines(x_values, y_values)
# Plot data points with number labels labels = np.arange(len(y_values)) + 1 plt.plot(x_values, y_values, 'b.', markersize=15) for xx, yy, l in zip(x_values, y_values, labels): plt.text(xx, yy, str(l), color="red", fontsize=15)
# Add extra explanatory text to plots plt.text(0, -0.11, 'label order:\nHOTA', horizontalalignment='left', verticalalignment='center', transform=fig.axes[0].transAxes, color="red", fontsize=12) if bg_label is not None: plt.text(1, -0.11, 'curve values:\n' + bg_label, horizontalalignment='right', verticalalignment='center', transform=fig.axes[0].transAxes, color="grey", fontsize=12)
plt.xlabel(x_label, fontsize=15) plt.ylabel(y_label, fontsize=15) title = y_label + ' vs ' + x_label if bg_label is not None: title += ' (' + bg_label + ')' plt.title(title, fontsize=17) plt.xticks(np.arange(0, 100, gap_val)) plt.yticks(np.arange(0, 100, gap_val)) min_x, max_x, min_y, max_y = boundaries plt.xlim(min_x, max_x) plt.ylim(min_y, max_y) plt.gca().set_aspect('equal', adjustable='box') plt.tight_layout()
os.makedirs(out_loc, exist_ok=True) filename = os.path.join(out_loc, title.replace(' ', '_')) plt.savefig(filename + '.pdf', bbox_inches='tight', pad_inches=0.05) plt.savefig(filename + '.png', bbox_inches='tight', pad_inches=0.05)
def _get_boundaries(x_values, y_values, round_val): """ Computes boundaries of a plot
:param List[Float] x_values: x values :param List[Float] y_values: y values :param Float round_val: interval
:return: Float, Float, Float, Float: boundaries of the plot ::
plotting._get_boundaries(x_values, y_values) """ x1 = np.min(np.floor((x_values - 0.5) / round_val) * round_val) x2 = np.max(np.ceil((x_values + 0.5) / round_val) * round_val) y1 = np.min(np.floor((y_values - 0.5) / round_val) * round_val) y2 = np.max(np.ceil((y_values + 0.5) / round_val) * round_val) x_range = x2 - x1 y_range = y2 - y1 max_range = max(x_range, y_range) x_center = (x1 + x2) / 2 y_center = (y1 + y2) / 2 min_x = max(x_center - max_range / 2, 0) max_x = min(x_center + max_range / 2, 100) min_y = max(y_center - max_range / 2, 0) max_y = min(y_center + max_range / 2, 100) return min_x, max_x, min_y, max_y
def geometric_mean(x, y): """ Computes geometric mean
:param Float x: x values :param Float y: y values
:return: Float: geometric mean value ::
plotting.geometric_mean(x_values, y_values) """ return np.sqrt(x * y)
def jaccard(x, y): x = x / 100 y = y / 100 return 100 * (x * y) / (x + y - x * y)
def multiplication(x, y): """ Computes multiplication for plots
:param Float x: x values :param Float y: y values
:return: Float: multiplied value ::
plotting.multiplication(x_values, y_values) """ return x * y / 100
bg_function_dict = { "geometric_mean": geometric_mean, "jaccard": jaccard, "multiplication": multiplication, }
def _plot_bg_contour(bg_function, plot_boundaries, gap_val): """ Plot background contour
:param Dict[str:func()] bg_function: sort order function :param List[float] plot_boundaries: limit values for the plot :param int gap_val: interval value
:return: None ::
plotting._plot_bg_contour(x_values, y_values) """ # Only loaded when run to reduce minimum requirements from matplotlib import pyplot as plt
# Plot background contour min_x, max_x, min_y, max_y = plot_boundaries x = np.arange(min_x, max_x, 0.1) y = np.arange(min_y, max_y, 0.1) x_grid, y_grid = np.meshgrid(x, y) if bg_function in bg_function_dict.keys(): z_grid = bg_function_dict[bg_function](x_grid, y_grid) else: raise TrackEvalException("background plotting function '%s' is not defined." % bg_function) levels = np.arange(0, 100, gap_val) con = plt.contour(x_grid, y_grid, z_grid, levels, colors='grey')
def bg_format(val): s = '{:1f}'.format(val) return '{:.0f}'.format(val) if s[-1] == '0' else s
con.levels = [bg_format(val) for val in con.levels] plt.clabel(con, con.levels, inline=True, fmt='%r', fontsize=8)
def _plot_pareto_optimal_lines(x_values, y_values): """ Plot pareto optimal lines
:param List[float] x_values: values to plot on x axis :param List[float] y_values: values to plot on y axis
:return: None ::
plotting._plot_pareto_optimal_lines(x_values, y_values) """
# Only loaded when run to reduce minimum requirements from matplotlib import pyplot as plt
# Plot pareto optimal lines cxs = x_values cys = y_values best_y = np.argmax(cys) x_pareto = [0, cxs[best_y]] y_pareto = [cys[best_y], cys[best_y]] t = 2 remaining = cxs > x_pareto[t - 1] cys = cys[remaining] cxs = cxs[remaining] while len(cxs) > 0 and len(cys) > 0: best_y = np.argmax(cys) x_pareto += [x_pareto[t - 1], cxs[best_y]] y_pareto += [cys[best_y], cys[best_y]] t += 2 remaining = cxs > x_pareto[t - 1] cys = cys[remaining] cxs = cxs[remaining] x_pareto.append(x_pareto[t - 1]) y_pareto.append(0) plt.plot(np.array(x_pareto), np.array(y_pareto), '--r')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204import osimport csvimport argparsefrom collections import OrderedDict
def init_config(config, default_config, name=None): """ Initialise non-given config values with defaults
:param str config: config :param str default_config: default config :param str name: name of dataset/metric :return: None ::
trackeval.utils.init_config(config, default_config, name) """ if config is None: config = default_config else: for k in default_config.keys(): if k not in config.keys(): config[k] = default_config[k] if name and config['PRINT_CONFIG']: print('\n%s Config:' % name) for c in config.keys(): print('%-20s : %-30s' % (c, config[c])) return config
def update_config(config): """ Parse the arguments of a script and updates the config values for a given value if specified in the arguments.
:param str config: the config to update :return: the updated config ::
trackeval.utils.update_config(config, default_config, name) """ parser = argparse.ArgumentParser() for setting in config.keys(): if type(config[setting]) == list or type(config[setting]) == type(None): parser.add_argument("--" + setting, nargs='+') else: parser.add_argument("--" + setting) args = parser.parse_args().__dict__ for setting in args.keys(): if args[setting] is not None: if type(config[setting]) == type(True): if args[setting] == 'True': x = True elif args[setting] == 'False': x = False else: raise Exception('Command line parameter ' + setting + 'must be True or False') elif type(config[setting]) == type(1): x = int(args[setting]) elif type(args[setting]) == type(None): x = None else: x = args[setting] config[setting] = x return config
def get_code_path(): """ Get base path where the trackeval library is located
:param None :return: str: base path of trackeval library ::
trackeval.utils.get_code_path(config, default_config, name) """ return os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
def validate_metrics_list(metrics_list): """ Get names of metric class and ensures they are unique, further checks that the fields within each metric class do not have overlapping names.
:param List[str] metrics_list: list of all metrics to test :return: List[str] metric_names: valid list of all metrics to test ::
trackeval.utils.get_code_path(config, default_config, name) """ metric_names = [metric.get_name() for metric in metrics_list] # check metric names are unique if len(metric_names) != len(set(metric_names)): raise TrackEvalException('Code being run with multiple metrics of the same name') fields = [] for m in metrics_list: fields += m.fields # check metric fields are unique if len(fields) != len(set(fields)): raise TrackEvalException('Code being run with multiple metrics with fields of the same name') return metric_names
def write_summary_results(summaries, cls, output_folder): """ Write summary results to file
:param List[str] summaries: list of all summaries :param List[str] cls: list of classes :param List[str] output_folder: directory to store the summary results
:return: None ::
trackeval.utils.write_summary_results(config, default_config, name) """ fields = sum([list(s.keys()) for s in summaries], []) values = sum([list(s.values()) for s in summaries], [])
# In order to remain consistent upon new fields being adding, for each of the following fields if they are present # they will be output in the summary first in the order below. Any further fields will be output in the order each # metric family is called, and within each family either in the order they were added to the dict (python >= 3.6) or # randomly (python < 3.6). default_order = ['HOTA', 'DetA', 'AssA', 'DetRe', 'DetPr', 'AssRe', 'AssPr', 'LocA', 'OWTA', 'HOTA(0)', 'LocA(0)', 'HOTALocA(0)', 'MOTA', 'MOTP', 'MODA', 'CLR_Re', 'CLR_Pr', 'MTR', 'PTR', 'MLR', 'CLR_TP', 'CLR_FN', 'CLR_FP', 'IDSW', 'MT', 'PT', 'ML', 'Frag', 'sMOTA', 'IDF1', 'IDR', 'IDP', 'IDTP', 'IDFN', 'IDFP', 'Dets', 'GT_Dets', 'IDs', 'GT_IDs'] default_ordered_dict = OrderedDict(zip(default_order, [None for _ in default_order])) for f, v in zip(fields, values): default_ordered_dict[f] = v for df in default_order: if default_ordered_dict[df] is None: del default_ordered_dict[df] fields = list(default_ordered_dict.keys()) values = list(default_ordered_dict.values())
out_file = os.path.join(output_folder, cls + '_summary.txt') os.makedirs(os.path.dirname(out_file), exist_ok=True) with open(out_file, 'w', newline='') as f: writer = csv.writer(f, delimiter=' ') writer.writerow(fields) writer.writerow(values)
def write_detailed_results(details, cls, output_folder): """ Write detailed results to file :param Dict[str, Object] details: dictionary of all trackers :param List[str] cls: list of classes :param List[str] output_folder: directory to store the detailed results
:return: None ::
trackeval.utils.write_detailed_results(config, default_config, name) """ sequences = details[0].keys() fields = ['seq'] + sum([list(s['COMBINED_SEQ'].keys()) for s in details], []) out_file = os.path.join(output_folder, cls + '_detailed.csv') os.makedirs(os.path.dirname(out_file), exist_ok=True) with open(out_file, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(fields) for seq in sorted(sequences): if seq == 'COMBINED_SEQ': continue writer.writerow([seq] + sum([list(s[seq].values()) for s in details], [])) writer.writerow(['COMBINED'] + sum([list(s['COMBINED_SEQ'].values()) for s in details], []))
def load_detail(file): """ Loads detailed data for a tracker. :param Dict[str] file: file to load the detailed results from
:return: Dict[str] :data ::
trackeval.utils.load_detail(config, default_config, name) """ data = {} with open(file) as f: for i, row_text in enumerate(f): row = row_text.replace('\r', '').replace('\n', '').split(',') if i == 0: keys = row[1:] continue current_values = row[1:] seq = row[0] if seq == 'COMBINED': seq = 'COMBINED_SEQ' if (len(current_values) == len(keys)) and seq != '': data[seq] = {} for key, value in zip(keys, current_values): data[seq][key] = float(value) return data
class TrackEvalException(Exception): """Custom exception for catching expected errors.""" ...1"""Utils modules"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217import osimport reimport argparseimport shutilimport jsonimport csvimport numpy as npimport pandas as pdfrom typing import List, Set, Any
class ValidateFile(argparse.Action): """ Module to validate files """ def __call__(self, parser, namespace, values, option_string = None): if not os.path.exists(values): parser.error(f"Please enter a valid file path. Got: {values}") elif not os.access(values, os.R_OK): parser.error(f"File {values} doesn't have read access") setattr(namespace, self.dest, values)
def validate_file_path(input_string: str) -> str: """ Validates whether the input string matches a file path pattern
:param str input_string: input string :return: validated file path :rtype: str ::
file_path = validate_file_path(input_string) """ file_path_pattern = r"^[a-zA-Z0-9_\-\/.#]+$"
if re.match(file_path_pattern, input_string): return input_string else: raise ValueError(f"Invalid file path: {input_string}")
def load_csv_to_dataframe_from_file(file_path: str, column_names: List[str], camera_ids: Set, interval: int = 1) -> pd.DataFrame: """ Loads dataframe from a CSV file
:param str file_path: file path :param List[str] column_names: column names :return: dataframe in the file :rtype: pd.DataFrame ::
dataFrame = load_csv_to_dataframe_from_file(file_path, column_names) """ data: List[List[str]] = list() valid_file_path = validate_file_path(file_path) df = pd.read_csv(valid_file_path, sep=" ", header=None, names=column_names, dtype={"CameraId": int, "Id": int, "FrameId": int}) # Ensure non-negative values for CameraId, Id, FrameId if (df[['CameraId', 'Id', 'FrameId']] < 0).any().any(): raise ValueError("Invalid negative values found for CameraId, Id, or FrameId.")
# Filter by camera_id df = df[df['CameraId'].isin(camera_ids)] # Filter rows where FrameId % interval == 0 df = df[df['FrameId'] % interval == 0] # Round the last two columns (assuming these are 'Xworld' and 'Yworld') df['Xworld'] = df['Xworld'].round(3) df['Yworld'] = df['Yworld'].round(3) if len(df) == 0: raise ValueError("DataFrame is empty after filtering process.")
return df
def write_dataframe_to_csv_to_file(file_path: str, data: pd.DataFrame, delimiter: str = " ") -> None: """ Writes dataframe to a CSV file
:param str file_path: file path :param pd.DataFrame data: dataframe to be written :param str delimiter: delimiter of the CSV file :return: None ::
write_dataframe_to_csv_to_file(file_path, data, delimiter) """ data.to_csv(file_path, sep=delimiter, index=False, header=False)
def make_dir(dir_path: str) -> None: """ Makes a directory without removing other files
:param str dir_path: directory path :return: None ::
make_dir(dir_path) """ valid_dir_path = validate_file_path(dir_path) if not os.path.isdir(valid_dir_path): os.makedirs(validate_file_path(dir_path))
def make_seq_maps_file(file_dir: str, scenes: List[str], benchmark: str, split_to_eval: str) -> None: """ Makes a sequence-maps file used by TrackEval library
:param str file_dir: file path :param Set(str) sensor_ids: names of sensors :param str benchmark: name of the benchmark :param str split_to_eval: name of the split of data :return: None ::
make_seq_maps_file(file_dir, sensor_ids) """ make_clean_dir(file_dir) file_name = benchmark + "-" +split_to_eval + ".txt" seq_maps_file = file_dir + "/" + file_name f = open(seq_maps_file, "w") f.write("name\n") for name in scenes: sensor_name = str(name) + "\n" f.write(sensor_name) # f.write("FINAL") f.close()
def make_seq_ini_file(gt_dir: str, scene: str, seq_length: int) -> None: """ Makes a sequence-ini file used by TrackEval library
:param str gt_dir: file path :param str scene: Name of a single scene :param int seq_length: Number of frames
:return: None ::
make_seq_ini_file(gt_dir, scene, seq_length) """ ini_file_name = gt_dir + "/seqinfo.ini" f = open(ini_file_name, "w") f.write("[Sequence]\n") name= "name=" +str(scene)+ "\n" f.write(name) f.write("imDir=img1\n") f.write("frameRate=30\n") seq = "seqLength=" + str(seq_length) + "\n" f.write(seq) f.write("imWidth=1920\n") f.write("imHeight=1080\n") f.write("imExt=.jpg\n") f.close()
def get_scene_to_camera_id_dict(file_path): """ Loads a mapping of scene names to camera IDs from a JSON file.
:param str file_path: Path to the JSON file containing scenes data. :return: A dictionary where keys are scene names and values are lists of camera IDs. ::
scene_to_camera_id_dict = get_scene_to_camera_id_dict(file_path) """ scene_2_cam_id = dict() valid_file_path = validate_file_path(file_path) with open(valid_file_path, "r") as file: scenes_data = json.load(file) for scene_data in scenes_data: scene_name = scene_data["scene_name"] camera_ids = scene_data["camera_ids"] if scene_name not in scene_2_cam_id: scene_2_cam_id[scene_name] = [] scene_2_cam_id[scene_name].extend(camera_ids) return scene_2_cam_id
def check_file_size(file_path): """ Checks the size of a file and raises an exception if it exceeds 2 GB.
:param str file_path: Path to the file to be checked. :return: None :raises ValueError: If the file size is greater than 2 GB. ::
check_file_size(file_path) """ file_size_bytes = os.path.getsize(file_path) file_size_gb = file_size_bytes / (2**30) if file_size_gb > 2: raise ValueError(f"The size of the file is {file_size_gb:.2f} GB, which is greater than the 2 GB")
def make_clean_dir(dir_path: str) -> None: """ Makes a clean directory :param str dir_path: directory path :return: None :: make_clean_dir(dir_path) """ valid_dir_path = validate_file_path(dir_path) if os.path.exists(valid_dir_path): shutil.rmtree(dir_path, ignore_errors=True) if not os.path.isdir(valid_dir_path): os.makedirs(validate_file_path(dir_path))MTMC_Tracking_2024/eval/3rdParty_Licenses.mdAdded+882
MTMC_Tracking_2024/eval/README.mdAdded+41
MTMC_Tracking_2024/eval/main.pyAdded+228
MTMC_Tracking_2024/eval/sample_file/ground_truth_test_full.txtAdded+3
MTMC_Tracking_2024/eval/sample_file/pred.txtAdded+3
MTMC_Tracking_2024/eval/sample_file/scene_name_2_cam_id_full.jsonAdded+3
MTMC_Tracking_2024/eval/trackeval/__init__.pyAdded+6
MTMC_Tracking_2024/eval/trackeval/_timing.pyAdded+81
MTMC_Tracking_2024/eval/trackeval/datasets/__init__.pyAdded+3
MTMC_Tracking_2024/eval/trackeval/datasets/_base_dataset.pyAdded+362
MTMC_Tracking_2024/eval/trackeval/datasets/mot_challenge_2d_box.pyAdded+471
MTMC_Tracking_2024/eval/trackeval/datasets/mot_challenge_3d_location.pyAdded+475
MTMC_Tracking_2024/eval/trackeval/datasets/test_mot.pyAdded+475
MTMC_Tracking_2024/eval/trackeval/eval.pyAdded+233
MTMC_Tracking_2024/eval/trackeval/metrics/__init__.pyAdded+5
MTMC_Tracking_2024/eval/trackeval/metrics/_base_metric.pyAdded+199
MTMC_Tracking_2024/eval/trackeval/metrics/clear.pyAdded+223
MTMC_Tracking_2024/eval/trackeval/metrics/count.pyAdded+76
MTMC_Tracking_2024/eval/trackeval/metrics/hota.pyAdded+245
MTMC_Tracking_2024/eval/trackeval/metrics/identity.pyAdded+172
MTMC_Tracking_2024/eval/trackeval/plotting.pyAdded+322
MTMC_Tracking_2024/eval/trackeval/utils.pyAdded+204
MTMC_Tracking_2024/eval/utils/__init__.pyAdded+1
MTMC_Tracking_2024/eval/utils/io_utils.pyAdded+217