Datasets:

ArXiv:
License:
zhengthomastang commited on
Commit
a3341ee
·
1 Parent(s): e7fca21

Include evaluation tools for 2024 edition

Browse files
MTMC_Tracking_2024/eval/3rdParty_Licenses.md ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-Party Licenses
2
+
3
+ This project incorporates components from the following open-source software. We have provided links to the licenses for each component below.
4
+
5
+ | Package / Component Name | Version | License | Link to Component's License |
6
+ |---|---|---|---|
7
+ | pandas | 2.3.1 | GNU General Public License v3.0 | [link](https://github.com/PandasWS/Pandas/blob/master/LICENSE)
8
+ | matplotlib | 3.5.2 | Other (Please describe in Comments) | [link](https://github.com/matplotlib/matplotlib/blob/main/LICENSE/LICENSE) |
9
+ | scipy | 1.15.3 | BSD (any variant) | [link](https://github.com/scipy/scipy/tree/main?tab=BSD-3-Clause-1-ov-file#readme) |
10
+
11
+
12
+
13
+ ### MIT License
14
+ ```
15
+ MIT License
16
+
17
+ Copyright (c) [year] [fullname]
18
+
19
+ Permission is hereby granted, free of charge, to any person obtaining a copy
20
+ of this software and associated documentation files (the "Software"), to deal
21
+ in the Software without restriction, including without limitation the rights
22
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23
+ copies of the Software, and to permit persons to whom the Software is
24
+ furnished to do so, subject to the following conditions:
25
+
26
+ The above copyright notice and this permission notice shall be included in all
27
+ copies or substantial portions of the Software.
28
+
29
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35
+ SOFTWARE.
36
+ ```
37
+
38
+ ### BSD License
39
+ ```
40
+ BSD License
41
+
42
+ Copyright (c) [year] [fullname]
43
+ All rights reserved.
44
+
45
+ Redistribution and use in source and binary forms, with or without
46
+ modification, are permitted provided that the following conditions are met:
47
+
48
+ * Redistributions of source code must retain the above copyright
49
+ notice, this list of conditions and the following disclaimer.
50
+ * Redistributions in binary form must reproduce the above copyright
51
+ notice, this list of conditions and the following disclaimer in the
52
+ documentation and/or other materials provided with the distribution.
53
+ * Neither the name of the copyright holder nor the names of its
54
+ contributors may be used to endorse or promote products derived from
55
+ this software without specific prior written permission.
56
+
57
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
58
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
61
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
62
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
63
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
65
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
66
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
67
+ POSSIBILITY OF SUCH DAMAGE.
68
+ ```
69
+
70
+ ### Other
71
+ Numpy license
72
+ ```
73
+ Copyright (c) 2005-2023, NumPy Developers.
74
+ All rights reserved.
75
+
76
+ Redistribution and use in source and binary forms, with or without
77
+ modification, are permitted provided that the following conditions are
78
+ met:
79
+ * Redistributions of source code must retain the above copyright
80
+ notice, this list of conditions and the following disclaimer.
81
+ * Redistributions in binary form must reproduce the above
82
+ copyright notice, this list of conditions and the following
83
+ disclaimer in the documentation and/or other materials provided
84
+ with the distribution.
85
+ * Neither the name of the NumPy Developers nor the names of any
86
+ contributors may be used to endorse or promote products derived
87
+ from this software without specific prior written permission.
88
+
89
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
90
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
91
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
92
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
93
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
94
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
95
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
96
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
97
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
98
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
99
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
100
+ ```
101
+
102
+
103
+ ### MatplotLib
104
+
105
+ ```
106
+ License agreement for matplotlib versions 1.3.0 and later
107
+ =========================================================
108
+
109
+ 1. This LICENSE AGREEMENT is between the Matplotlib Development Team
110
+ ("MDT"), and the Individual or Organization ("Licensee") accessing and
111
+ otherwise using matplotlib software in source or binary form and its
112
+ associated documentation.
113
+
114
+ 2. Subject to the terms and conditions of this License Agreement, MDT
115
+ hereby grants Licensee a nonexclusive, royalty-free, world-wide license
116
+ to reproduce, analyze, test, perform and/or display publicly, prepare
117
+ derivative works, distribute, and otherwise use matplotlib
118
+ alone or in any derivative version, provided, however, that MDT's
119
+ License Agreement and MDT's notice of copyright, i.e., "Copyright (c)
120
+ 2012- Matplotlib Development Team; All Rights Reserved" are retained in
121
+ matplotlib alone or in any derivative version prepared by
122
+ Licensee.
123
+
124
+ 3. In the event Licensee prepares a derivative work that is based on or
125
+ incorporates matplotlib or any part thereof, and wants to
126
+ make the derivative work available to others as provided herein, then
127
+ Licensee hereby agrees to include in any such work a brief summary of
128
+ the changes made to matplotlib .
129
+
130
+ 4. MDT is making matplotlib available to Licensee on an "AS
131
+ IS" basis. MDT MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
132
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO AND
133
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
134
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB
135
+ WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
136
+
137
+ 5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB
138
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR
139
+ LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING
140
+ MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF
141
+ THE POSSIBILITY THEREOF.
142
+
143
+ 6. This License Agreement will automatically terminate upon a material
144
+ breach of its terms and conditions.
145
+
146
+ 7. Nothing in this License Agreement shall be deemed to create any
147
+ relationship of agency, partnership, or joint venture between MDT and
148
+ Licensee. This License Agreement does not grant permission to use MDT
149
+ trademarks or trade name in a trademark sense to endorse or promote
150
+ products or services of Licensee, or any third party.
151
+
152
+ 8. By copying, installing or otherwise using matplotlib ,
153
+ Licensee agrees to be bound by the terms and conditions of this License
154
+ Agreement.
155
+
156
+ License agreement for matplotlib versions prior to 1.3.0
157
+ ========================================================
158
+
159
+ 1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the
160
+ Individual or Organization ("Licensee") accessing and otherwise using
161
+ matplotlib software in source or binary form and its associated
162
+ documentation.
163
+
164
+ 2. Subject to the terms and conditions of this License Agreement, JDH
165
+ hereby grants Licensee a nonexclusive, royalty-free, world-wide license
166
+ to reproduce, analyze, test, perform and/or display publicly, prepare
167
+ derivative works, distribute, and otherwise use matplotlib
168
+ alone or in any derivative version, provided, however, that JDH's
169
+ License Agreement and JDH's notice of copyright, i.e., "Copyright (c)
170
+ 2002-2011 John D. Hunter; All Rights Reserved" are retained in
171
+ matplotlib alone or in any derivative version prepared by
172
+ Licensee.
173
+
174
+ 3. In the event Licensee prepares a derivative work that is based on or
175
+ incorporates matplotlib or any part thereof, and wants to
176
+ make the derivative work available to others as provided herein, then
177
+ Licensee hereby agrees to include in any such work a brief summary of
178
+ the changes made to matplotlib.
179
+
180
+ 4. JDH is making matplotlib available to Licensee on an "AS
181
+ IS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
182
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND
183
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
184
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB
185
+ WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
186
+
187
+ 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB
188
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR
189
+ LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING
190
+ MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF
191
+ THE POSSIBILITY THEREOF.
192
+
193
+ 6. This License Agreement will automatically terminate upon a material
194
+ breach of its terms and conditions.
195
+
196
+ 7. Nothing in this License Agreement shall be deemed to create any
197
+ relationship of agency, partnership, or joint venture between JDH and
198
+ Licensee. This License Agreement does not grant permission to use JDH
199
+ trademarks or trade name in a trademark sense to endorse or promote
200
+ products or services of Licensee, or any third party.
201
+
202
+ 8. By copying, installing or otherwise using matplotlib,
203
+ Licensee agrees to be bound by the terms and conditions of this License
204
+ Agreement.
205
+ ```
206
+
207
+ ### GNU
208
+
209
+ GNU GENERAL PUBLIC LICENSE
210
+ Version 3, 29 June 2007
211
+
212
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
213
+ Everyone is permitted to copy and distribute verbatim copies
214
+ of this license document, but changing it is not allowed.
215
+
216
+ Preamble
217
+
218
+ The GNU General Public License is a free, copyleft license for
219
+ software and other kinds of works.
220
+
221
+ The licenses for most software and other practical works are designed
222
+ to take away your freedom to share and change the works. By contrast,
223
+ the GNU General Public License is intended to guarantee your freedom to
224
+ share and change all versions of a program--to make sure it remains free
225
+ software for all its users. We, the Free Software Foundation, use the
226
+ GNU General Public License for most of our software; it applies also to
227
+ any other work released this way by its authors. You can apply it to
228
+ your programs, too.
229
+
230
+ When we speak of free software, we are referring to freedom, not
231
+ price. Our General Public Licenses are designed to make sure that you
232
+ have the freedom to distribute copies of free software (and charge for
233
+ them if you wish), that you receive source code or can get it if you
234
+ want it, that you can change the software or use pieces of it in new
235
+ free programs, and that you know you can do these things.
236
+
237
+ To protect your rights, we need to prevent others from denying you
238
+ these rights or asking you to surrender the rights. Therefore, you have
239
+ certain responsibilities if you distribute copies of the software, or if
240
+ you modify it: responsibilities to respect the freedom of others.
241
+
242
+ For example, if you distribute copies of such a program, whether
243
+ gratis or for a fee, you must pass on to the recipients the same
244
+ freedoms that you received. You must make sure that they, too, receive
245
+ or can get the source code. And you must show them these terms so they
246
+ know their rights.
247
+
248
+ Developers that use the GNU GPL protect your rights with two steps:
249
+ (1) assert copyright on the software, and (2) offer you this License
250
+ giving you legal permission to copy, distribute and/or modify it.
251
+
252
+ For the developers' and authors' protection, the GPL clearly explains
253
+ that there is no warranty for this free software. For both users' and
254
+ authors' sake, the GPL requires that modified versions be marked as
255
+ changed, so that their problems will not be attributed erroneously to
256
+ authors of previous versions.
257
+
258
+ Some devices are designed to deny users access to install or run
259
+ modified versions of the software inside them, although the manufacturer
260
+ can do so. This is fundamentally incompatible with the aim of
261
+ protecting users' freedom to change the software. The systematic
262
+ pattern of such abuse occurs in the area of products for individuals to
263
+ use, which is precisely where it is most unacceptable. Therefore, we
264
+ have designed this version of the GPL to prohibit the practice for those
265
+ products. If such problems arise substantially in other domains, we
266
+ stand ready to extend this provision to those domains in future versions
267
+ of the GPL, as needed to protect the freedom of users.
268
+
269
+ Finally, every program is threatened constantly by software patents.
270
+ States should not allow patents to restrict development and use of
271
+ software on general-purpose computers, but in those that do, we wish to
272
+ avoid the special danger that patents applied to a free program could
273
+ make it effectively proprietary. To prevent this, the GPL assures that
274
+ patents cannot be used to render the program non-free.
275
+
276
+ The precise terms and conditions for copying, distribution and
277
+ modification follow.
278
+
279
+ TERMS AND CONDITIONS
280
+
281
+ 0. Definitions.
282
+
283
+ "This License" refers to version 3 of the GNU General Public License.
284
+
285
+ "Copyright" also means copyright-like laws that apply to other kinds of
286
+ works, such as semiconductor masks.
287
+
288
+ "The Program" refers to any copyrightable work licensed under this
289
+ License. Each licensee is addressed as "you". "Licensees" and
290
+ "recipients" may be individuals or organizations.
291
+
292
+ To "modify" a work means to copy from or adapt all or part of the work
293
+ in a fashion requiring copyright permission, other than the making of an
294
+ exact copy. The resulting work is called a "modified version" of the
295
+ earlier work or a work "based on" the earlier work.
296
+
297
+ A "covered work" means either the unmodified Program or a work based
298
+ on the Program.
299
+
300
+ To "propagate" a work means to do anything with it that, without
301
+ permission, would make you directly or secondarily liable for
302
+ infringement under applicable copyright law, except executing it on a
303
+ computer or modifying a private copy. Propagation includes copying,
304
+ distribution (with or without modification), making available to the
305
+ public, and in some countries other activities as well.
306
+
307
+ To "convey" a work means any kind of propagation that enables other
308
+ parties to make or receive copies. Mere interaction with a user through
309
+ a computer network, with no transfer of a copy, is not conveying.
310
+
311
+ An interactive user interface displays "Appropriate Legal Notices"
312
+ to the extent that it includes a convenient and prominently visible
313
+ feature that (1) displays an appropriate copyright notice, and (2)
314
+ tells the user that there is no warranty for the work (except to the
315
+ extent that warranties are provided), that licensees may convey the
316
+ work under this License, and how to view a copy of this License. If
317
+ the interface presents a list of user commands or options, such as a
318
+ menu, a prominent item in the list meets this criterion.
319
+
320
+ 1. Source Code.
321
+
322
+ The "source code" for a work means the preferred form of the work
323
+ for making modifications to it. "Object code" means any non-source
324
+ form of a work.
325
+
326
+ A "Standard Interface" means an interface that either is an official
327
+ standard defined by a recognized standards body, or, in the case of
328
+ interfaces specified for a particular programming language, one that
329
+ is widely used among developers working in that language.
330
+
331
+ The "System Libraries" of an executable work include anything, other
332
+ than the work as a whole, that (a) is included in the normal form of
333
+ packaging a Major Component, but which is not part of that Major
334
+ Component, and (b) serves only to enable use of the work with that
335
+ Major Component, or to implement a Standard Interface for which an
336
+ implementation is available to the public in source code form. A
337
+ "Major Component", in this context, means a major essential component
338
+ (kernel, window system, and so on) of the specific operating system
339
+ (if any) on which the executable work runs, or a compiler used to
340
+ produce the work, or an object code interpreter used to run it.
341
+
342
+ The "Corresponding Source" for a work in object code form means all
343
+ the source code needed to generate, install, and (for an executable
344
+ work) run the object code and to modify the work, including scripts to
345
+ control those activities. However, it does not include the work's
346
+ System Libraries, or general-purpose tools or generally available free
347
+ programs which are used unmodified in performing those activities but
348
+ which are not part of the work. For example, Corresponding Source
349
+ includes interface definition files associated with source files for
350
+ the work, and the source code for shared libraries and dynamically
351
+ linked subprograms that the work is specifically designed to require,
352
+ such as by intimate data communication or control flow between those
353
+ subprograms and other parts of the work.
354
+
355
+ The Corresponding Source need not include anything that users
356
+ can regenerate automatically from other parts of the Corresponding
357
+ Source.
358
+
359
+ The Corresponding Source for a work in source code form is that
360
+ same work.
361
+
362
+ 2. Basic Permissions.
363
+
364
+ All rights granted under this License are granted for the term of
365
+ copyright on the Program, and are irrevocable provided the stated
366
+ conditions are met. This License explicitly affirms your unlimited
367
+ permission to run the unmodified Program. The output from running a
368
+ covered work is covered by this License only if the output, given its
369
+ content, constitutes a covered work. This License acknowledges your
370
+ rights of fair use or other equivalent, as provided by copyright law.
371
+
372
+ You may make, run and propagate covered works that you do not
373
+ convey, without conditions so long as your license otherwise remains
374
+ in force. You may convey covered works to others for the sole purpose
375
+ of having them make modifications exclusively for you, or provide you
376
+ with facilities for running those works, provided that you comply with
377
+ the terms of this License in conveying all material for which you do
378
+ not control copyright. Those thus making or running the covered works
379
+ for you must do so exclusively on your behalf, under your direction
380
+ and control, on terms that prohibit them from making any copies of
381
+ your copyrighted material outside their relationship with you.
382
+
383
+ Conveying under any other circumstances is permitted solely under
384
+ the conditions stated below. Sublicensing is not allowed; section 10
385
+ makes it unnecessary.
386
+
387
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
388
+
389
+ No covered work shall be deemed part of an effective technological
390
+ measure under any applicable law fulfilling obligations under article
391
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
392
+ similar laws prohibiting or restricting circumvention of such
393
+ measures.
394
+
395
+ When you convey a covered work, you waive any legal power to forbid
396
+ circumvention of technological measures to the extent such circumvention
397
+ is effected by exercising rights under this License with respect to
398
+ the covered work, and you disclaim any intention to limit operation or
399
+ modification of the work as a means of enforcing, against the work's
400
+ users, your or third parties' legal rights to forbid circumvention of
401
+ technological measures.
402
+
403
+ 4. Conveying Verbatim Copies.
404
+
405
+ You may convey verbatim copies of the Program's source code as you
406
+ receive it, in any medium, provided that you conspicuously and
407
+ appropriately publish on each copy an appropriate copyright notice;
408
+ keep intact all notices stating that this License and any
409
+ non-permissive terms added in accord with section 7 apply to the code;
410
+ keep intact all notices of the absence of any warranty; and give all
411
+ recipients a copy of this License along with the Program.
412
+
413
+ You may charge any price or no price for each copy that you convey,
414
+ and you may offer support or warranty protection for a fee.
415
+
416
+ 5. Conveying Modified Source Versions.
417
+
418
+ You may convey a work based on the Program, or the modifications to
419
+ produce it from the Program, in the form of source code under the
420
+ terms of section 4, provided that you also meet all of these conditions:
421
+
422
+ a) The work must carry prominent notices stating that you modified
423
+ it, and giving a relevant date.
424
+
425
+ b) The work must carry prominent notices stating that it is
426
+ released under this License and any conditions added under section
427
+ 7. This requirement modifies the requirement in section 4 to
428
+ "keep intact all notices".
429
+
430
+ c) You must license the entire work, as a whole, under this
431
+ License to anyone who comes into possession of a copy. This
432
+ License will therefore apply, along with any applicable section 7
433
+ additional terms, to the whole of the work, and all its parts,
434
+ regardless of how they are packaged. This License gives no
435
+ permission to license the work in any other way, but it does not
436
+ invalidate such permission if you have separately received it.
437
+
438
+ d) If the work has interactive user interfaces, each must display
439
+ Appropriate Legal Notices; however, if the Program has interactive
440
+ interfaces that do not display Appropriate Legal Notices, your
441
+ work need not make them do so.
442
+
443
+ A compilation of a covered work with other separate and independent
444
+ works, which are not by their nature extensions of the covered work,
445
+ and which are not combined with it such as to form a larger program,
446
+ in or on a volume of a storage or distribution medium, is called an
447
+ "aggregate" if the compilation and its resulting copyright are not
448
+ used to limit the access or legal rights of the compilation's users
449
+ beyond what the individual works permit. Inclusion of a covered work
450
+ in an aggregate does not cause this License to apply to the other
451
+ parts of the aggregate.
452
+
453
+ 6. Conveying Non-Source Forms.
454
+
455
+ You may convey a covered work in object code form under the terms
456
+ of sections 4 and 5, provided that you also convey the
457
+ machine-readable Corresponding Source under the terms of this License,
458
+ in one of these ways:
459
+
460
+ a) Convey the object code in, or embodied in, a physical product
461
+ (including a physical distribution medium), accompanied by the
462
+ Corresponding Source fixed on a durable physical medium
463
+ customarily used for software interchange.
464
+
465
+ b) Convey the object code in, or embodied in, a physical product
466
+ (including a physical distribution medium), accompanied by a
467
+ written offer, valid for at least three years and valid for as
468
+ long as you offer spare parts or customer support for that product
469
+ model, to give anyone who possesses the object code either (1) a
470
+ copy of the Corresponding Source for all the software in the
471
+ product that is covered by this License, on a durable physical
472
+ medium customarily used for software interchange, for a price no
473
+ more than your reasonable cost of physically performing this
474
+ conveying of source, or (2) access to copy the
475
+ Corresponding Source from a network server at no charge.
476
+
477
+ c) Convey individual copies of the object code with a copy of the
478
+ written offer to provide the Corresponding Source. This
479
+ alternative is allowed only occasionally and noncommercially, and
480
+ only if you received the object code with such an offer, in accord
481
+ with subsection 6b.
482
+
483
+ d) Convey the object code by offering access from a designated
484
+ place (gratis or for a charge), and offer equivalent access to the
485
+ Corresponding Source in the same way through the same place at no
486
+ further charge. You need not require recipients to copy the
487
+ Corresponding Source along with the object code. If the place to
488
+ copy the object code is a network server, the Corresponding Source
489
+ may be on a different server (operated by you or a third party)
490
+ that supports equivalent copying facilities, provided you maintain
491
+ clear directions next to the object code saying where to find the
492
+ Corresponding Source. Regardless of what server hosts the
493
+ Corresponding Source, you remain obligated to ensure that it is
494
+ available for as long as needed to satisfy these requirements.
495
+
496
+ e) Convey the object code using peer-to-peer transmission, provided
497
+ you inform other peers where the object code and Corresponding
498
+ Source of the work are being offered to the general public at no
499
+ charge under subsection 6d.
500
+
501
+ A separable portion of the object code, whose source code is excluded
502
+ from the Corresponding Source as a System Library, need not be
503
+ included in conveying the object code work.
504
+
505
+ A "User Product" is either (1) a "consumer product", which means any
506
+ tangible personal property which is normally used for personal, family,
507
+ or household purposes, or (2) anything designed or sold for incorporation
508
+ into a dwelling. In determining whether a product is a consumer product,
509
+ doubtful cases shall be resolved in favor of coverage. For a particular
510
+ product received by a particular user, "normally used" refers to a
511
+ typical or common use of that class of product, regardless of the status
512
+ of the particular user or of the way in which the particular user
513
+ actually uses, or expects or is expected to use, the product. A product
514
+ is a consumer product regardless of whether the product has substantial
515
+ commercial, industrial or non-consumer uses, unless such uses represent
516
+ the only significant mode of use of the product.
517
+
518
+ "Installation Information" for a User Product means any methods,
519
+ procedures, authorization keys, or other information required to install
520
+ and execute modified versions of a covered work in that User Product from
521
+ a modified version of its Corresponding Source. The information must
522
+ suffice to ensure that the continued functioning of the modified object
523
+ code is in no case prevented or interfered with solely because
524
+ modification has been made.
525
+
526
+ If you convey an object code work under this section in, or with, or
527
+ specifically for use in, a User Product, and the conveying occurs as
528
+ part of a transaction in which the right of possession and use of the
529
+ User Product is transferred to the recipient in perpetuity or for a
530
+ fixed term (regardless of how the transaction is characterized), the
531
+ Corresponding Source conveyed under this section must be accompanied
532
+ by the Installation Information. But this requirement does not apply
533
+ if neither you nor any third party retains the ability to install
534
+ modified object code on the User Product (for example, the work has
535
+ been installed in ROM).
536
+
537
+ The requirement to provide Installation Information does not include a
538
+ requirement to continue to provide support service, warranty, or updates
539
+ for a work that has been modified or installed by the recipient, or for
540
+ the User Product in which it has been modified or installed. Access to a
541
+ network may be denied when the modification itself materially and
542
+ adversely affects the operation of the network or violates the rules and
543
+ protocols for communication across the network.
544
+
545
+ Corresponding Source conveyed, and Installation Information provided,
546
+ in accord with this section must be in a format that is publicly
547
+ documented (and with an implementation available to the public in
548
+ source code form), and must require no special password or key for
549
+ unpacking, reading or copying.
550
+
551
+ 7. Additional Terms.
552
+
553
+ "Additional permissions" are terms that supplement the terms of this
554
+ License by making exceptions from one or more of its conditions.
555
+ Additional permissions that are applicable to the entire Program shall
556
+ be treated as though they were included in this License, to the extent
557
+ that they are valid under applicable law. If additional permissions
558
+ apply only to part of the Program, that part may be used separately
559
+ under those permissions, but the entire Program remains governed by
560
+ this License without regard to the additional permissions.
561
+
562
+ When you convey a copy of a covered work, you may at your option
563
+ remove any additional permissions from that copy, or from any part of
564
+ it. (Additional permissions may be written to require their own
565
+ removal in certain cases when you modify the work.) You may place
566
+ additional permissions on material, added by you to a covered work,
567
+ for which you have or can give appropriate copyright permission.
568
+
569
+ Notwithstanding any other provision of this License, for material you
570
+ add to a covered work, you may (if authorized by the copyright holders of
571
+ that material) supplement the terms of this License with terms:
572
+
573
+ a) Disclaiming warranty or limiting liability differently from the
574
+ terms of sections 15 and 16 of this License; or
575
+
576
+ b) Requiring preservation of specified reasonable legal notices or
577
+ author attributions in that material or in the Appropriate Legal
578
+ Notices displayed by works containing it; or
579
+
580
+ c) Prohibiting misrepresentation of the origin of that material, or
581
+ requiring that modified versions of such material be marked in
582
+ reasonable ways as different from the original version; or
583
+
584
+ d) Limiting the use for publicity purposes of names of licensors or
585
+ authors of the material; or
586
+
587
+ e) Declining to grant rights under trademark law for use of some
588
+ trade names, trademarks, or service marks; or
589
+
590
+ f) Requiring indemnification of licensors and authors of that
591
+ material by anyone who conveys the material (or modified versions of
592
+ it) with contractual assumptions of liability to the recipient, for
593
+ any liability that these contractual assumptions directly impose on
594
+ those licensors and authors.
595
+
596
+ All other non-permissive additional terms are considered "further
597
+ restrictions" within the meaning of section 10. If the Program as you
598
+ received it, or any part of it, contains a notice stating that it is
599
+ governed by this License along with a term that is a further
600
+ restriction, you may remove that term. If a license document contains
601
+ a further restriction but permits relicensing or conveying under this
602
+ License, you may add to a covered work material governed by the terms
603
+ of that license document, provided that the further restriction does
604
+ not survive such relicensing or conveying.
605
+
606
+ If you add terms to a covered work in accord with this section, you
607
+ must place, in the relevant source files, a statement of the
608
+ additional terms that apply to those files, or a notice indicating
609
+ where to find the applicable terms.
610
+
611
+ Additional terms, permissive or non-permissive, may be stated in the
612
+ form of a separately written license, or stated as exceptions;
613
+ the above requirements apply either way.
614
+
615
+ 8. Termination.
616
+
617
+ You may not propagate or modify a covered work except as expressly
618
+ provided under this License. Any attempt otherwise to propagate or
619
+ modify it is void, and will automatically terminate your rights under
620
+ this License (including any patent licenses granted under the third
621
+ paragraph of section 11).
622
+
623
+ However, if you cease all violation of this License, then your
624
+ license from a particular copyright holder is reinstated (a)
625
+ provisionally, unless and until the copyright holder explicitly and
626
+ finally terminates your license, and (b) permanently, if the copyright
627
+ holder fails to notify you of the violation by some reasonable means
628
+ prior to 60 days after the cessation.
629
+
630
+ Moreover, your license from a particular copyright holder is
631
+ reinstated permanently if the copyright holder notifies you of the
632
+ violation by some reasonable means, this is the first time you have
633
+ received notice of violation of this License (for any work) from that
634
+ copyright holder, and you cure the violation prior to 30 days after
635
+ your receipt of the notice.
636
+
637
+ Termination of your rights under this section does not terminate the
638
+ licenses of parties who have received copies or rights from you under
639
+ this License. If your rights have been terminated and not permanently
640
+ reinstated, you do not qualify to receive new licenses for the same
641
+ material under section 10.
642
+
643
+ 9. Acceptance Not Required for Having Copies.
644
+
645
+ You are not required to accept this License in order to receive or
646
+ run a copy of the Program. Ancillary propagation of a covered work
647
+ occurring solely as a consequence of using peer-to-peer transmission
648
+ to receive a copy likewise does not require acceptance. However,
649
+ nothing other than this License grants you permission to propagate or
650
+ modify any covered work. These actions infringe copyright if you do
651
+ not accept this License. Therefore, by modifying or propagating a
652
+ covered work, you indicate your acceptance of this License to do so.
653
+
654
+ 10. Automatic Licensing of Downstream Recipients.
655
+
656
+ Each time you convey a covered work, the recipient automatically
657
+ receives a license from the original licensors, to run, modify and
658
+ propagate that work, subject to this License. You are not responsible
659
+ for enforcing compliance by third parties with this License.
660
+
661
+ An "entity transaction" is a transaction transferring control of an
662
+ organization, or substantially all assets of one, or subdividing an
663
+ organization, or merging organizations. If propagation of a covered
664
+ work results from an entity transaction, each party to that
665
+ transaction who receives a copy of the work also receives whatever
666
+ licenses to the work the party's predecessor in interest had or could
667
+ give under the previous paragraph, plus a right to possession of the
668
+ Corresponding Source of the work from the predecessor in interest, if
669
+ the predecessor has it or can get it with reasonable efforts.
670
+
671
+ You may not impose any further restrictions on the exercise of the
672
+ rights granted or affirmed under this License. For example, you may
673
+ not impose a license fee, royalty, or other charge for exercise of
674
+ rights granted under this License, and you may not initiate litigation
675
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
676
+ any patent claim is infringed by making, using, selling, offering for
677
+ sale, or importing the Program or any portion of it.
678
+
679
+ 11. Patents.
680
+
681
+ A "contributor" is a copyright holder who authorizes use under this
682
+ License of the Program or a work on which the Program is based. The
683
+ work thus licensed is called the contributor's "contributor version".
684
+
685
+ A contributor's "essential patent claims" are all patent claims
686
+ owned or controlled by the contributor, whether already acquired or
687
+ hereafter acquired, that would be infringed by some manner, permitted
688
+ by this License, of making, using, or selling its contributor version,
689
+ but do not include claims that would be infringed only as a
690
+ consequence of further modification of the contributor version. For
691
+ purposes of this definition, "control" includes the right to grant
692
+ patent sublicenses in a manner consistent with the requirements of
693
+ this License.
694
+
695
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
696
+ patent license under the contributor's essential patent claims, to
697
+ make, use, sell, offer for sale, import and otherwise run, modify and
698
+ propagate the contents of its contributor version.
699
+
700
+ In the following three paragraphs, a "patent license" is any express
701
+ agreement or commitment, however denominated, not to enforce a patent
702
+ (such as an express permission to practice a patent or covenant not to
703
+ sue for patent infringement). To "grant" such a patent license to a
704
+ party means to make such an agreement or commitment not to enforce a
705
+ patent against the party.
706
+
707
+ If you convey a covered work, knowingly relying on a patent license,
708
+ and the Corresponding Source of the work is not available for anyone
709
+ to copy, free of charge and under the terms of this License, through a
710
+ publicly available network server or other readily accessible means,
711
+ then you must either (1) cause the Corresponding Source to be so
712
+ available, or (2) arrange to deprive yourself of the benefit of the
713
+ patent license for this particular work, or (3) arrange, in a manner
714
+ consistent with the requirements of this License, to extend the patent
715
+ license to downstream recipients. "Knowingly relying" means you have
716
+ actual knowledge that, but for the patent license, your conveying the
717
+ covered work in a country, or your recipient's use of the covered work
718
+ in a country, would infringe one or more identifiable patents in that
719
+ country that you have reason to believe are valid.
720
+
721
+ If, pursuant to or in connection with a single transaction or
722
+ arrangement, you convey, or propagate by procuring conveyance of, a
723
+ covered work, and grant a patent license to some of the parties
724
+ receiving the covered work authorizing them to use, propagate, modify
725
+ or convey a specific copy of the covered work, then the patent license
726
+ you grant is automatically extended to all recipients of the covered
727
+ work and works based on it.
728
+
729
+ A patent license is "discriminatory" if it does not include within
730
+ the scope of its coverage, prohibits the exercise of, or is
731
+ conditioned on the non-exercise of one or more of the rights that are
732
+ specifically granted under this License. You may not convey a covered
733
+ work if you are a party to an arrangement with a third party that is
734
+ in the business of distributing software, under which you make payment
735
+ to the third party based on the extent of your activity of conveying
736
+ the work, and under which the third party grants, to any of the
737
+ parties who would receive the covered work from you, a discriminatory
738
+ patent license (a) in connection with copies of the covered work
739
+ conveyed by you (or copies made from those copies), or (b) primarily
740
+ for and in connection with specific products or compilations that
741
+ contain the covered work, unless you entered into that arrangement,
742
+ or that patent license was granted, prior to 28 March 2007.
743
+
744
+ Nothing in this License shall be construed as excluding or limiting
745
+ any implied license or other defenses to infringement that may
746
+ otherwise be available to you under applicable patent law.
747
+
748
+ 12. No Surrender of Others' Freedom.
749
+
750
+ If conditions are imposed on you (whether by court order, agreement or
751
+ otherwise) that contradict the conditions of this License, they do not
752
+ excuse you from the conditions of this License. If you cannot convey a
753
+ covered work so as to satisfy simultaneously your obligations under this
754
+ License and any other pertinent obligations, then as a consequence you may
755
+ not convey it at all. For example, if you agree to terms that obligate you
756
+ to collect a royalty for further conveying from those to whom you convey
757
+ the Program, the only way you could satisfy both those terms and this
758
+ License would be to refrain entirely from conveying the Program.
759
+
760
+ 13. Use with the GNU Affero General Public License.
761
+
762
+ Notwithstanding any other provision of this License, you have
763
+ permission to link or combine any covered work with a work licensed
764
+ under version 3 of the GNU Affero General Public License into a single
765
+ combined work, and to convey the resulting work. The terms of this
766
+ License will continue to apply to the part which is the covered work,
767
+ but the special requirements of the GNU Affero General Public License,
768
+ section 13, concerning interaction through a network will apply to the
769
+ combination as such.
770
+
771
+ 14. Revised Versions of this License.
772
+
773
+ The Free Software Foundation may publish revised and/or new versions of
774
+ the GNU General Public License from time to time. Such new versions will
775
+ be similar in spirit to the present version, but may differ in detail to
776
+ address new problems or concerns.
777
+
778
+ Each version is given a distinguishing version number. If the
779
+ Program specifies that a certain numbered version of the GNU General
780
+ Public License "or any later version" applies to it, you have the
781
+ option of following the terms and conditions either of that numbered
782
+ version or of any later version published by the Free Software
783
+ Foundation. If the Program does not specify a version number of the
784
+ GNU General Public License, you may choose any version ever published
785
+ by the Free Software Foundation.
786
+
787
+ If the Program specifies that a proxy can decide which future
788
+ versions of the GNU General Public License can be used, that proxy's
789
+ public statement of acceptance of a version permanently authorizes you
790
+ to choose that version for the Program.
791
+
792
+ Later license versions may give you additional or different
793
+ permissions. However, no additional obligations are imposed on any
794
+ author or copyright holder as a result of your choosing to follow a
795
+ later version.
796
+
797
+ 15. Disclaimer of Warranty.
798
+
799
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
800
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
801
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
802
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
803
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
804
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
805
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
806
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
807
+
808
+ 16. Limitation of Liability.
809
+
810
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
811
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
812
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
813
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
814
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
815
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
816
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
817
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
818
+ SUCH DAMAGES.
819
+
820
+ 17. Interpretation of Sections 15 and 16.
821
+
822
+ If the disclaimer of warranty and limitation of liability provided
823
+ above cannot be given local legal effect according to their terms,
824
+ reviewing courts shall apply local law that most closely approximates
825
+ an absolute waiver of all civil liability in connection with the
826
+ Program, unless a warranty or assumption of liability accompanies a
827
+ copy of the Program in return for a fee.
828
+
829
+ END OF TERMS AND CONDITIONS
830
+
831
+ How to Apply These Terms to Your New Programs
832
+
833
+ If you develop a new program, and you want it to be of the greatest
834
+ possible use to the public, the best way to achieve this is to make it
835
+ free software which everyone can redistribute and change under these terms.
836
+
837
+ To do so, attach the following notices to the program. It is safest
838
+ to attach them to the start of each source file to most effectively
839
+ state the exclusion of warranty; and each file should have at least
840
+ the "copyright" line and a pointer to where the full notice is found.
841
+
842
+ <one line to give the program's name and a brief idea of what it does.>
843
+ Copyright (C) <year> <name of author>
844
+
845
+ This program is free software: you can redistribute it and/or modify
846
+ it under the terms of the GNU General Public License as published by
847
+ the Free Software Foundation, either version 3 of the License, or
848
+ (at your option) any later version.
849
+
850
+ This program is distributed in the hope that it will be useful,
851
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
852
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
853
+ GNU General Public License for more details.
854
+
855
+ You should have received a copy of the GNU General Public License
856
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
857
+
858
+ Also add information on how to contact you by electronic and paper mail.
859
+
860
+ If the program does terminal interaction, make it output a short
861
+ notice like this when it starts in an interactive mode:
862
+
863
+ <program> Copyright (C) <year> <name of author>
864
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
865
+ This is free software, and you are welcome to redistribute it
866
+ under certain conditions; type `show c' for details.
867
+
868
+ The hypothetical commands `show w' and `show c' should show the appropriate
869
+ parts of the General Public License. Of course, your program's commands
870
+ might be different; for a GUI interface, you would use an "about box".
871
+
872
+ You should also get your employer (if you work as a programmer) or school,
873
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
874
+ For more information on this, and how to apply and follow the GNU GPL, see
875
+ <http://www.gnu.org/licenses/>.
876
+
877
+ The GNU General Public License does not permit incorporating your program
878
+ into proprietary programs. If your program is a subroutine library, you
879
+ may consider it more useful to permit linking proprietary applications with
880
+ the library. If this is what you want to do, use the GNU Lesser General
881
+ Public License instead of this License. But first, please read
882
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
MTMC_Tracking_2024/eval/README.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation Code for - MTMC Tracking 2024 Dataset
2
+
3
+ Evaluation code for the Multi-Target Multi-Camera (MTMC) 2024 dataset.
4
+
5
+ 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.
6
+
7
+ HOTA scores calculated using 3D distance measurements in a multi-camera setting.
8
+
9
+ # Environment setup:
10
+ ```
11
+ - [Optional] conda create -n mtmc_eval_2024 python=3.10
12
+ - [Optional] conda activate mtmc_eval_2024
13
+
14
+ - pip3 install pandas
15
+ - pip3 install matplotlib
16
+ - pip3 install scipy
17
+ ```
18
+
19
+ # Usage:
20
+
21
+ - Set the --prediction_file argument to a valid prediction file.
22
+ - Set the --ground_truth_file argument to a valid test file.
23
+ - Set the --num_cores argument based on your setup.
24
+ - Set the --scene_2_camera_id_file argument
25
+
26
+
27
+ Example below:
28
+ ```
29
+ 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
30
+
31
+ Sample Result:
32
+ Total runtime: 187.0887589454651 seconds.
33
+ HOTA: 49.2825%
34
+ DetA: 49.1998%
35
+ AssA: 49.3655%
36
+ LocA: 77.0546%
37
+ ```
38
+
39
+ ## Acknowledgements
40
+
41
+ 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).
MTMC_Tracking_2024/eval/main.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ """
3
+ Evaluation script for the Multi-Camera People Tracking track in the AI City Challenge, Track 1 in 2024.
4
+
5
+ # Environment setup:
6
+ [Optional] conda create -n aicity24-track1 python=3.10
7
+ [Optional] conda activate aicity24-track1
8
+
9
+ pip3 install pandas
10
+ pip3 install matplotlib
11
+ pip3 install scipy
12
+
13
+ # Usage: Set number of cores based on your cpu core count.
14
+
15
+ 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
16
+
17
+ 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
18
+
19
+
20
+ """
21
+ import os
22
+ import sys
23
+ import time
24
+ import tempfile
25
+ import trackeval
26
+ import pandas as pd
27
+ import numpy as np
28
+
29
+
30
+ from argparse import ArgumentParser, ArgumentTypeError
31
+ from typing import List
32
+ from 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
33
+
34
+
35
+ def get_unique_entry_per_scene(dataframe, scene_name, scene_2_camera_id):
36
+ camera_ids = scene_2_camera_id[scene_name]
37
+ filtered_df = dataframe[dataframe["CameraId"].isin(camera_ids)]
38
+ unique_entries_df = filtered_df.drop_duplicates(subset=["FrameId", "Id"])
39
+ return unique_entries_df
40
+
41
+ def check_positive(value):
42
+ int_value = int(value)
43
+ if int_value <= 0:
44
+ raise ArgumentTypeError(f"{value} is an invalid num of cores")
45
+ return int_value
46
+
47
+ 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:
48
+
49
+
50
+ check_file_size(prediction_file_path)
51
+
52
+ # Create a temp directory if output_dir is not specified
53
+ is_temp_dir = False
54
+ if output_dir is None:
55
+ temp_dir = tempfile.TemporaryDirectory()
56
+ is_temp_dir = True
57
+ output_dir = temp_dir.name
58
+ print(f"Temp files will be created here: {output_dir}")
59
+
60
+ # Create a scene 2 camera_id dict
61
+ scene_2_camera_id = get_scene_to_camera_id_dict(scene_2_cam_id_file)
62
+ camera_ids = {camera_id for camera_ids in scene_2_camera_id.values() for camera_id in camera_ids}
63
+
64
+ # Load ground truth and prediction files in dataframe
65
+ column_names = ["CameraId", "Id", "FrameId", "X", "Y", "Width", "Height", "Xworld", "Yworld"]
66
+ mot_pred_dataframe = load_csv_to_dataframe_from_file(prediction_file_path, column_names, camera_ids)
67
+ ground_truth_dataframe = load_csv_to_dataframe_from_file(ground_truth_path, column_names, camera_ids)
68
+
69
+
70
+ # Create evaluater configs for trackeval lib
71
+ default_eval_config = trackeval.eval.Evaluator.get_default_eval_config()
72
+ default_eval_config["PRINT_CONFIG"] = False
73
+ default_eval_config["USE_PARALLEL"] = True
74
+ default_eval_config["LOG_ON_ERROR"] = None
75
+ default_eval_config["NUM_PARALLEL_CORES"] = num_cores
76
+
77
+ # Create dataset configs for trackeval lib
78
+ default_dataset_config = trackeval.datasets.MotChallenge3DLocation.get_default_dataset_config()
79
+ default_dataset_config["DO_PREPROC"] = False
80
+ default_dataset_config["SPLIT_TO_EVAL"] = "all"
81
+ default_dataset_config["GT_FOLDER"] = os.path.join(output_dir, "evaluation", "gt")
82
+ default_dataset_config["TRACKERS_FOLDER"] = os.path.join(output_dir, "evaluation", "scores")
83
+ default_dataset_config["PRINT_CONFIG"] = False
84
+
85
+ # Make output directory for storing results
86
+ make_dir(default_dataset_config["GT_FOLDER"])
87
+ make_dir(default_dataset_config["TRACKERS_FOLDER"])
88
+
89
+ # Create sequence maps file for evaluation
90
+ seq_maps_file = os.path.join(default_dataset_config["GT_FOLDER"], "seqmaps")
91
+ make_seq_maps_file(seq_maps_file, scene_2_camera_id.keys(), default_dataset_config["BENCHMARK"], default_dataset_config["SPLIT_TO_EVAL"])
92
+
93
+ # Set the metrics to obtain
94
+ default_metrics_config = {"METRICS": ["HOTA"], "THRESHOLD": 0.5}
95
+ default_metrics_config["PRINT_CONFIG"] = False
96
+ config = {**default_eval_config, **default_dataset_config, **default_metrics_config} # Merge default configs
97
+ eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()}
98
+ dataset_config = {k: v for k, v in config.items() if k in default_dataset_config.keys()}
99
+ metrics_config = {k: v for k, v in config.items() if k in default_metrics_config.keys()}
100
+
101
+
102
+ # Create prediction and ground truth list
103
+ for scene_name in scene_2_camera_id.keys():
104
+
105
+ # Convert ground truth multi-camera dataframe to single camera in MOT format
106
+ ground_truth_dataframe_per_scene = get_unique_entry_per_scene(ground_truth_dataframe, scene_name, scene_2_camera_id)
107
+ ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Xworld", "Yworld"]]
108
+ ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene.sort_values(by="FrameId")
109
+
110
+ # Make ground truth frame-ids 1-based
111
+ ground_truth_dataframe_per_scene["FrameId"] += 1
112
+
113
+ # Set other defaults
114
+ ground_truth_dataframe_per_scene["Conf"] = 1
115
+ ground_truth_dataframe_per_scene["Zworld"] = -1
116
+ ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Conf", "Xworld", "Yworld", "Zworld"]]
117
+
118
+ # Remove logs for negative frame ids
119
+ ground_truth_dataframe_per_scene = ground_truth_dataframe_per_scene[ground_truth_dataframe_per_scene["FrameId"] >= 1]
120
+
121
+ # Save single camera ground truth in MOT format as CSV
122
+ mot_version = default_dataset_config["BENCHMARK"] + "-" + default_dataset_config["SPLIT_TO_EVAL"]
123
+ gt_dir = os.path.join(default_dataset_config["GT_FOLDER"], mot_version)
124
+ dir_name = os.path.join(gt_dir, str(scene_name))
125
+ gt_file_dir = os.path.join(gt_dir, str(scene_name), "gt")
126
+ gt_file_name = os.path.join(gt_file_dir, "gt.txt")
127
+ make_dir(gt_file_dir)
128
+ write_dataframe_to_csv_to_file(gt_file_name, ground_truth_dataframe_per_scene)
129
+
130
+ # Convert predicted multi-camera dataframe to MOT format
131
+ mot_pred_dataframe_per_scene = get_unique_entry_per_scene(mot_pred_dataframe, scene_name, scene_2_camera_id)
132
+ mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Xworld", "Yworld"]]
133
+ mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene.sort_values(by="FrameId")
134
+
135
+ # Make MOT prediction frame-ids 1-based
136
+ mot_pred_dataframe_per_scene["FrameId"] += 1
137
+
138
+ # Remove logs for negative frame ids
139
+ mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene[mot_pred_dataframe_per_scene["FrameId"] >= 1]
140
+
141
+ # Set other defaults
142
+ mot_pred_dataframe_per_scene["Conf"] = 1
143
+ mot_pred_dataframe_per_scene["Zworld"] = -1
144
+ mot_pred_dataframe_per_scene = mot_pred_dataframe_per_scene[["FrameId", "Id", "X", "Y", "Width", "Height", "Conf", "Xworld", "Yworld", "Zworld"]]
145
+
146
+ # Save single camera prediction in MOT format as CSV
147
+ mot_file_dir = os.path.join(default_dataset_config["TRACKERS_FOLDER"], mot_version, "data", "data")
148
+ make_dir(mot_file_dir)
149
+ tracker_file_name = str(scene_name) + ".txt"
150
+ mot_file_name = os.path.join(mot_file_dir, tracker_file_name)
151
+ write_dataframe_to_csv_to_file(mot_file_name, mot_pred_dataframe_per_scene)
152
+
153
+ # Make sequence ini file for trackeval library
154
+ if np.isnan(mot_pred_dataframe_per_scene["FrameId"].max()):
155
+ last_frame_id = ground_truth_dataframe_per_scene["FrameId"].max()
156
+ elif np.isnan(ground_truth_dataframe_per_scene["FrameId"].max()):
157
+ last_frame_id = mot_pred_dataframe_per_scene["FrameId"].max()
158
+ else:
159
+ last_frame_id = max(mot_pred_dataframe_per_scene["FrameId"].max(), ground_truth_dataframe_per_scene["FrameId"].max())
160
+ make_seq_ini_file(dir_name, scene=str(scene_name), seq_length=last_frame_id)
161
+
162
+
163
+ # Evaluate ground truth & prediction to get all exhaustive metrics
164
+ evaluator = trackeval.eval.Evaluator(eval_config)
165
+ dataset_list = [trackeval.datasets.MotChallenge3DLocation(dataset_config)]
166
+ temp_metrics_list = [trackeval.metrics.HOTA]
167
+
168
+ metrics_list = []
169
+ for metric in temp_metrics_list:
170
+ if metric.get_name() in metrics_config["METRICS"]:
171
+ metrics_list.append(metric(metrics_config))
172
+
173
+ results = evaluator.evaluate(dataset_list, metrics_list)
174
+
175
+ if is_temp_dir:
176
+ temp_dir.cleanup()
177
+ return results
178
+
179
+ def evaluate(prediction_file: str, ground_truth_file: str, output_dir: str, num_cores: int, scene_2_camera_id_file: str) -> None:
180
+
181
+ # Collect the result
182
+ sequence_result = computes_mot_metrics(prediction_file, ground_truth_file, output_dir, num_cores, scene_2_camera_id_file)
183
+
184
+ # Compute average
185
+ final_result = dict()
186
+ HOTA_scores = []
187
+ DetA_scores = []
188
+ AssA_scores = []
189
+ LocA_scores = []
190
+ for scene_name, result in sequence_result[0]["MotChallenge3DLocation"]["data"].items():
191
+
192
+ if scene_name == "COMBINED_SEQ":
193
+ continue
194
+ result = result["pedestrian"]["HOTA"]
195
+ HOTA_scores.append(np.mean(result["HOTA"]))
196
+ DetA_scores.append(np.mean(result["DetA"]))
197
+ AssA_scores.append(np.mean(result["AssA"]))
198
+ LocA_scores.append(np.mean(result["LocA"]))
199
+
200
+ final_result["FINAL"] = dict()
201
+ final_result["FINAL"]["HOTA"] = np.mean(np.array(HOTA_scores))
202
+ final_result["FINAL"]["DetA"] = np.mean(np.array(DetA_scores))
203
+ final_result["FINAL"]["AssA"] = np.mean(np.array(AssA_scores))
204
+ final_result["FINAL"]["LocA"] = np.mean(np.array(LocA_scores))
205
+ return final_result
206
+
207
+ if __name__ == '__main__':
208
+ start = time.time()
209
+ # Parse arguments
210
+ parser = ArgumentParser()
211
+ parser.add_argument('--prediction_file', required=True)
212
+ parser.add_argument('--ground_truth_file', required=True)
213
+ parser.add_argument('--output_dir')
214
+ parser.add_argument('--num_cores', type=check_positive, default=1)
215
+ parser.add_argument('--scene_2_camera_id_file', required=True)
216
+ args = parser.parse_args()
217
+
218
+ # Run evaluation
219
+ final_result = evaluate(args.prediction_file, args.ground_truth_file, args.output_dir, args.num_cores, args.scene_2_camera_id_file)
220
+
221
+ end = time.time()
222
+
223
+ print(f"Total runtime: {end-start} seconds.")
224
+ print(f"HOTA: {float(final_result['FINAL']['HOTA'] * 100):.4f}%")
225
+ print(f"DetA: {float(final_result['FINAL']['DetA'] * 100):.4f}%")
226
+ print(f"AssA: {float(final_result['FINAL']['AssA'] * 100):.4f}%")
227
+ print(f"LocA: {float(final_result['FINAL']['LocA'] * 100):.4f}%")
228
+
MTMC_Tracking_2024/eval/sample_file/ground_truth_test_full.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76fc83dae03807622ef62246ba7ebdf43f8109f5a99a2447e681fd8c94955c14
3
+ size 1508235913
MTMC_Tracking_2024/eval/sample_file/pred.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a51d3f9ff529cfcc1ed7c7e5dbe65307f05ce1e634b369cfedb4d23f5c83fcc3
3
+ size 1341211632
MTMC_Tracking_2024/eval/sample_file/scene_name_2_cam_id_full.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1f1c873d40a50e075d85a364554d902968b2c6717f16ebd5e63d43300f50bac
3
+ size 9555
MTMC_Tracking_2024/eval/trackeval/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """MTMC analytics trackeval modules"""
2
+ from .eval import Evaluator
3
+ from . import datasets
4
+ from . import metrics
5
+ from . import plotting
6
+ from . import utils
MTMC_Tracking_2024/eval/trackeval/_timing.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ from time import perf_counter
3
+ import inspect
4
+
5
+ DO_TIMING = False
6
+ DISPLAY_LESS_PROGRESS = False
7
+ timer_dict = {}
8
+ counter = 0
9
+
10
+
11
+ def time(f):
12
+ """
13
+ Decorator function for timing the execution of a function.
14
+
15
+ :param f: The function to be timed.
16
+ :type f: function
17
+ :return: A wrapped function that measures the execution time of the original function.
18
+ :rtype: function
19
+
20
+ The wrapped function measures the execution time of the original function `f`. If the `DO_TIMING` flag is set to
21
+ `True`, the wrapped function records the accumulated time for each function and provides timing analysis when the
22
+ code is finished. If the flag is set to `False` or certain conditions are met, the wrapped function runs the
23
+ original function without timing.
24
+
25
+ Note that the timing analysis is printed to the console. Modify the implementation to save the timing information
26
+ in a different format or location if desired.
27
+ """
28
+ @wraps(f)
29
+ def wrap(*args, **kw):
30
+ if DO_TIMING:
31
+ # Run function with timing
32
+ ts = perf_counter()
33
+ result = f(*args, **kw)
34
+ te = perf_counter()
35
+ tt = te-ts
36
+
37
+ # Get function name
38
+ arg_names = inspect.getfullargspec(f)[0]
39
+ if arg_names[0] == 'self' and DISPLAY_LESS_PROGRESS:
40
+ return result
41
+ elif arg_names[0] == 'self':
42
+ method_name = type(args[0]).__name__ + '.' + f.__name__
43
+ else:
44
+ method_name = f.__name__
45
+
46
+ # Record accumulative time in each function for analysis
47
+ if method_name in timer_dict.keys():
48
+ timer_dict[method_name] += tt
49
+ else:
50
+ timer_dict[method_name] = tt
51
+
52
+ # If code is finished, display timing summary
53
+ if method_name == "Evaluator.evaluate":
54
+ print("")
55
+ print("Timing analysis:")
56
+ for key, value in timer_dict.items():
57
+ print('%-70s %2.4f sec' % (key, value))
58
+ else:
59
+ # Get function argument values for printing special arguments of interest
60
+ arg_titles = ['tracker', 'seq', 'cls']
61
+ arg_vals = []
62
+ for i, a in enumerate(arg_names):
63
+ if a in arg_titles:
64
+ arg_vals.append(args[i])
65
+ arg_text = '(' + ', '.join(arg_vals) + ')'
66
+
67
+ # Display methods and functions with different indentation.
68
+ if arg_names[0] == 'self':
69
+ print('%-74s %2.4f sec' % (' '*4 + method_name + arg_text, tt))
70
+ elif arg_names[0] == 'test':
71
+ pass
72
+ else:
73
+ global counter
74
+ counter += 1
75
+ print('%i %-70s %2.4f sec' % (counter, method_name + arg_text, tt))
76
+
77
+ return result
78
+ else:
79
+ # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
80
+ return f(*args, **kw)
81
+ return wrap
MTMC_Tracking_2024/eval/trackeval/datasets/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """MTMC analytics datasets modules"""
2
+ from .mot_challenge_2d_box import MotChallenge2DBox
3
+ from .mot_challenge_3d_location import MotChallenge3DLocation
MTMC_Tracking_2024/eval/trackeval/datasets/_base_dataset.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import io
3
+ import zipfile
4
+ import os
5
+ import traceback
6
+ import numpy as np
7
+ from copy import deepcopy
8
+ from abc import ABC, abstractmethod
9
+ from trackeval import _timing
10
+ from trackeval.utils import TrackEvalException
11
+
12
+
13
+ class _BaseDataset(ABC):
14
+ """
15
+ Module to create a skeleton of dataset formats
16
+ """
17
+ @abstractmethod
18
+ def __init__(self):
19
+ self.tracker_list = None
20
+ self.seq_list = None
21
+ self.class_list = None
22
+ self.output_fol = None
23
+ self.output_sub_fol = None
24
+ self.should_classes_combine = True
25
+ self.use_super_categories = False
26
+
27
+ @staticmethod
28
+ @abstractmethod
29
+ def get_default_dataset_config():
30
+ ...
31
+
32
+ @abstractmethod
33
+ def _load_raw_file(self, tracker, seq, is_gt):
34
+ ...
35
+
36
+ @_timing.time
37
+ @abstractmethod
38
+ def get_preprocessed_seq_data(self, raw_data, cls):
39
+ ...
40
+
41
+ @abstractmethod
42
+ def _calculate_similarities(self, gt_dets_t, tracker_dets_t):
43
+ ...
44
+
45
+ @classmethod
46
+ def get_class_name(cls):
47
+ return cls.__name__
48
+
49
+ def get_name(self):
50
+ return self.get_class_name()
51
+
52
+ def get_output_fol(self, tracker):
53
+ return os.path.join(self.output_fol, tracker, self.output_sub_fol)
54
+
55
+ def get_display_name(self, tracker):
56
+ """
57
+ Can be overwritten if the trackers name (in files) is different to how it should be displayed.
58
+ By default this method just returns the trackers name as is.
59
+
60
+ :param tracker: name of tracker
61
+ :return: None
62
+ """
63
+ return tracker
64
+
65
+ def get_eval_info(self):
66
+ """Return info about the dataset needed for the Evaluator
67
+
68
+ :return: List[str] tracker_list: list of all trackers
69
+ :return: List[str] seq_list: list of all sequences
70
+ :return: List[str] class_list: list of all classes
71
+ """
72
+ return self.tracker_list, self.seq_list, self.class_list
73
+
74
+ @_timing.time
75
+ def get_raw_seq_data(self, tracker, seq):
76
+ """ Loads raw data (tracker and ground-truth) for a single tracker on a single sequence.
77
+ Raw data includes all of the information needed for both preprocessing and evaluation, for all classes.
78
+ A later function (get_processed_seq_data) will perform such preprocessing and extract relevant information for
79
+ the evaluation of each class.
80
+
81
+ This returns a dict which contains the fields:
82
+ [num_timesteps]: integer
83
+ [gt_ids, tracker_ids, gt_classes, tracker_classes, tracker_confidences]:
84
+ list (for each timestep) of 1D NDArrays (for each det).
85
+ [gt_dets, tracker_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections.
86
+ [similarity_scores]: list (for each timestep) of 2D NDArrays.
87
+ [gt_extras]: dict (for each extra) of lists (for each timestep) of 1D NDArrays (for each det).
88
+
89
+ gt_extras contains dataset specific information used for preprocessing such as occlusion and truncation levels.
90
+
91
+ Note that similarities are extracted as part of the dataset and not the metric, because almost all metrics are
92
+ independent of the exact method of calculating the similarity. However datasets are not (e.g. segmentation
93
+ masks vs 2D boxes vs 3D boxes).
94
+ We calculate the similarity before preprocessing because often both preprocessing and evaluation require it and
95
+ we don't wish to calculate this twice.
96
+ We calculate similarity between all gt and tracker classes (not just each class individually) to allow for
97
+ calculation of metrics such as class confusion matrices. Typically the impact of this on performance is low.
98
+
99
+ :param: str tracker: name of tracker
100
+ :param: str sequence: name of sequence
101
+ :return: raw_data: similarity scores among all gt & tracker classes
102
+ """
103
+ # Load raw data.
104
+ raw_gt_data = self._load_raw_file(tracker, seq, is_gt=True)
105
+ raw_tracker_data = self._load_raw_file(tracker, seq, is_gt=False)
106
+ raw_data = {**raw_tracker_data, **raw_gt_data} # Merges dictionaries
107
+
108
+ # Calculate similarities for each timestep.
109
+ similarity_scores = []
110
+ for t, (gt_dets_t, tracker_dets_t) in enumerate(zip(raw_data['gt_dets'], raw_data['tracker_dets'])):
111
+ ious = self._calculate_similarities(gt_dets_t, tracker_dets_t)
112
+ similarity_scores.append(ious)
113
+ raw_data['similarity_scores'] = similarity_scores
114
+ return raw_data
115
+
116
+ @staticmethod
117
+ def _load_simple_text_file(file, time_col=0, id_col=None, remove_negative_ids=False, valid_filter=None,
118
+ crowd_ignore_filter=None, convert_filter=None, is_zipped=False, zip_file=None,
119
+ force_delimiters=None):
120
+ """ Function that loads data which is in a commonly used text file format.
121
+ Assumes each det is given by one row of a text file.
122
+ There is no limit to the number or meaning of each column,
123
+ however one column needs to give the timestep of each det (time_col) which is default col 0.
124
+
125
+ The file dialect (deliminator, num cols, etc) is determined automatically.
126
+ This function automatically separates dets by timestep,
127
+ and is much faster than alternatives such as np.loadtext or pandas.
128
+
129
+ If remove_negative_ids is True and id_col is not None, dets with negative values in id_col are excluded.
130
+ These are not excluded from ignore data.
131
+
132
+ valid_filter can be used to only include certain classes.
133
+ It is a dict with ints as keys, and lists as values,
134
+ such that a row is included if "row[key].lower() is in value" for all key/value pairs in the dict.
135
+ If None, all classes are included.
136
+
137
+ crowd_ignore_filter can be used to read crowd_ignore regions separately. It has the same format as valid filter.
138
+
139
+ convert_filter can be used to convert value read to another format.
140
+ This is used most commonly to convert classes given as string to a class id.
141
+ This is a dict such that the key is the column to convert, and the value is another dict giving the mapping.
142
+
143
+ Optionally, input files could be a zip of multiple text files for storage efficiency.
144
+
145
+ Returns read_data and ignore_data.
146
+ Each is a dict (with keys as timesteps as strings) of lists (over dets) of lists (over column values).
147
+ Note that all data is returned as strings, and must be converted to float/int later if needed.
148
+ Note that timesteps will not be present in the returned dict keys if there are no dets for them
149
+
150
+ :param str file: Path to the input text file or the name of the file within the zip file (if is_zipped is True).
151
+ :param int time_col: Index of the column containing the timestep of each detection, defaults to 0.
152
+ :param int id_col: Index of the column containing the ID of each detection, defaults to None.
153
+ :param bool remove_negative_ids: Whether to exclude dets with negative IDs, defaults to False.
154
+ :param dict valid_filter: Dictionary to include only certain classes, defaults to None.
155
+ :param dict crowd_ignore_filter: Dictionary to read crowd_ignore regions separately, defaults to None.
156
+ :param dict convert_filter: Dictionary to convert values read to another format, defaults to None.
157
+ :param bool is_zipped: Whether the input file is a zip file, defaults to False.
158
+ :param str zip_file: Path to the zip file (if is_zipped is True), defaults to None.
159
+ :param list force_delimiters: List of potential delimiters to override the automatic delimiter detection, defaults to None.
160
+ :raises TrackEvalException: If remove_negative_ids is True but id_col is not given, or if there's an error reading the file.
161
+ :return: A tuple containing read_data and crowd_ignore_data dictionaries.
162
+ read_data: dictionary with timesteps as keys (strings) and lists (over detections) of lists (over column values).
163
+ crowd_ignore_data: dictionary with timesteps as keys (strings) and lists (over detections) of lists (over column values).
164
+ :rtype: tuple
165
+ """
166
+
167
+ if remove_negative_ids and id_col is None:
168
+ raise TrackEvalException('remove_negative_ids is True, but id_col is not given.')
169
+ if crowd_ignore_filter is None:
170
+ crowd_ignore_filter = {}
171
+ if convert_filter is None:
172
+ convert_filter = {}
173
+ try:
174
+ if is_zipped: # Either open file directly or within a zip.
175
+ if zip_file is None:
176
+ raise TrackEvalException('is_zipped set to True, but no zip_file is given.')
177
+ archive = zipfile.ZipFile(os.path.join(zip_file), 'r')
178
+ fp = io.TextIOWrapper(archive.open(file, 'r'))
179
+ else:
180
+ fp = open(file)
181
+ read_data = {}
182
+ crowd_ignore_data = {}
183
+ fp.seek(0, os.SEEK_END)
184
+ # check if file is empty
185
+ if fp.tell():
186
+ fp.seek(0)
187
+ dialect = csv.Sniffer().sniff(fp.readline(), delimiters=force_delimiters) # Auto determine structure.
188
+ dialect.skipinitialspace = True # Deal with extra spaces between columns
189
+ fp.seek(0)
190
+ reader = csv.reader(fp, dialect)
191
+ for row in reader:
192
+ try:
193
+ # Deal with extra trailing spaces at the end of rows
194
+ if row[-1] in '':
195
+ row = row[:-1]
196
+ timestep = str(int(float(row[time_col])))
197
+ # Read ignore regions separately.
198
+ is_ignored = False
199
+ for ignore_key, ignore_value in crowd_ignore_filter.items():
200
+ if row[ignore_key].lower() in ignore_value:
201
+ # Convert values in one column (e.g. string to id)
202
+ for convert_key, convert_value in convert_filter.items():
203
+ row[convert_key] = convert_value[row[convert_key].lower()]
204
+ # Save data separated by timestep.
205
+ if timestep in crowd_ignore_data.keys():
206
+ crowd_ignore_data[timestep].append(row)
207
+ else:
208
+ crowd_ignore_data[timestep] = [row]
209
+ is_ignored = True
210
+ if is_ignored: # if det is an ignore region, it cannot be a normal det.
211
+ continue
212
+ # Exclude some dets if not valid.
213
+ if valid_filter is not None:
214
+ for key, value in valid_filter.items():
215
+ if row[key].lower() not in value:
216
+ continue
217
+ if remove_negative_ids:
218
+ if int(float(row[id_col])) < 0:
219
+ continue
220
+ # Convert values in one column (e.g. string to id)
221
+ for convert_key, convert_value in convert_filter.items():
222
+ row[convert_key] = convert_value[row[convert_key].lower()]
223
+ # Save data separated by timestep.
224
+ if timestep in read_data.keys():
225
+ read_data[timestep].append(row)
226
+ else:
227
+ read_data[timestep] = [row]
228
+ except Exception:
229
+ exc_str_init = 'In file %s the following line cannot be read correctly: \n' % os.path.basename(
230
+ file)
231
+ exc_str = ' '.join([exc_str_init]+row)
232
+ raise TrackEvalException(exc_str)
233
+ fp.close()
234
+ except Exception:
235
+ print('Error loading file: %s, printing traceback.' % file)
236
+ traceback.print_exc()
237
+ raise TrackEvalException(
238
+ 'File %s cannot be read because it is either not present or invalidly formatted' % os.path.basename(
239
+ file))
240
+ return read_data, crowd_ignore_data
241
+
242
+ @staticmethod
243
+ def _calculate_mask_ious(masks1, masks2, is_encoded=False, do_ioa=False):
244
+ """ Calculates the IOU (intersection over union) between two arrays of segmentation masks.
245
+ If is_encoded a run length encoding with pycocotools is assumed as input format, otherwise an input of numpy
246
+ arrays of the shape (num_masks, height, width) is assumed and the encoding is performed.
247
+ If do_ioa (intersection over area) , then calculates the intersection over the area of masks1 - this is commonly
248
+ used to determine if detections are within crowd ignore region.
249
+ :param masks1: first set of masks (numpy array of shape (num_masks, height, width) if not encoded,
250
+ else pycocotools rle encoded format)
251
+ :param masks2: second set of masks (numpy array of shape (num_masks, height, width) if not encoded,
252
+ else pycocotools rle encoded format)
253
+ :param is_encoded: whether the input is in pycocotools rle encoded format
254
+ :param do_ioa: whether to perform IoA computation
255
+ :return: the IoU/IoA scores
256
+ """
257
+
258
+ # Only loaded when run to reduce minimum requirements
259
+ from pycocotools import mask as mask_utils
260
+
261
+ # use pycocotools for run length encoding of masks
262
+ if not is_encoded:
263
+ masks1 = mask_utils.encode(np.array(np.transpose(masks1, (1, 2, 0)), order='F'))
264
+ masks2 = mask_utils.encode(np.array(np.transpose(masks2, (1, 2, 0)), order='F'))
265
+
266
+ # use pycocotools for iou computation of rle encoded masks
267
+ ious = mask_utils.iou(masks1, masks2, [do_ioa]*len(masks2))
268
+ if len(masks1) == 0 or len(masks2) == 0:
269
+ ious = np.asarray(ious).reshape(len(masks1), len(masks2))
270
+ assert (ious >= 0 - np.finfo('float').eps).all()
271
+ assert (ious <= 1 + np.finfo('float').eps).all()
272
+
273
+ return ious
274
+
275
+ @staticmethod
276
+ def _calculate_box_ious(bboxes1, bboxes2, box_format='xywh', do_ioa=False):
277
+ """ Calculates the IOU (intersection over union) between two arrays of boxes.
278
+ Allows variable box formats ('xywh' and 'x0y0x1y1').
279
+ If do_ioa (intersection over area) , then calculates the intersection over the area of boxes1 - this is commonly
280
+ used to determine if detections are within crowd ignore region.
281
+
282
+ :param bboxes1: first list of bounding boxes
283
+ :param bboxes2: second list of bounding boxes
284
+ :return: ious: the IoU/IoA scores
285
+ """
286
+ if box_format in 'xywh':
287
+ # layout: (x0, y0, w, h)
288
+ bboxes1 = deepcopy(bboxes1)
289
+ bboxes2 = deepcopy(bboxes2)
290
+
291
+ bboxes1[:, 2] = bboxes1[:, 0] + bboxes1[:, 2]
292
+ bboxes1[:, 3] = bboxes1[:, 1] + bboxes1[:, 3]
293
+ bboxes2[:, 2] = bboxes2[:, 0] + bboxes2[:, 2]
294
+ bboxes2[:, 3] = bboxes2[:, 1] + bboxes2[:, 3]
295
+ elif box_format not in 'x0y0x1y1':
296
+ raise (TrackEvalException('box_format %s is not implemented' % box_format))
297
+
298
+ # layout: (x0, y0, x1, y1)
299
+ min_ = np.minimum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :])
300
+ max_ = np.maximum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :])
301
+ intersection = np.maximum(min_[..., 2] - max_[..., 0], 0) * np.maximum(min_[..., 3] - max_[..., 1], 0)
302
+ area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
303
+
304
+ if do_ioa:
305
+ ioas = np.zeros_like(intersection)
306
+ valid_mask = area1 > 0 + np.finfo('float').eps
307
+ ioas[valid_mask, :] = intersection[valid_mask, :] / area1[valid_mask][:, np.newaxis]
308
+
309
+ return ioas
310
+ else:
311
+ area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1])
312
+ union = area1[:, np.newaxis] + area2[np.newaxis, :] - intersection
313
+ intersection[area1 <= 0 + np.finfo('float').eps, :] = 0
314
+ intersection[:, area2 <= 0 + np.finfo('float').eps] = 0
315
+ intersection[union <= 0 + np.finfo('float').eps] = 0
316
+ union[union <= 0 + np.finfo('float').eps] = 1
317
+ ious = intersection / union
318
+ return ious
319
+
320
+ @staticmethod
321
+ def _calculate_euclidean_similarity(dets1, dets2, zero_distance):
322
+ """ Calculates the euclidean distance between two sets of detections, and then converts this into a similarity
323
+ measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance).
324
+ The default zero_distance of 2.0, corresponds to the default used in MOT15_3D, such that a 0.5 similarity
325
+ threshold corresponds to a 1m distance threshold for TPs.
326
+
327
+ :param dets1: first list of detections
328
+ :param dets2: second list of detections
329
+ :return: sim: the similarity score
330
+ """
331
+ dist = np.linalg.norm(dets1[:, np.newaxis]-dets2[np.newaxis, :], axis=2)
332
+ sim = np.maximum(0, 1 - dist/zero_distance)
333
+ return sim
334
+
335
+ @staticmethod
336
+ def _check_unique_ids(data, after_preproc=False):
337
+ """Check the requirement that the tracker_ids and gt_ids are unique per timestep"""
338
+ gt_ids = data['gt_ids']
339
+ tracker_ids = data['tracker_ids']
340
+ for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(gt_ids, tracker_ids)):
341
+ if len(tracker_ids_t) > 0:
342
+ unique_ids, counts = np.unique(tracker_ids_t, return_counts=True)
343
+ if np.max(counts) != 1:
344
+ duplicate_ids = unique_ids[counts > 1]
345
+ exc_str_init = 'Tracker predicts the same ID more than once in a single timestep ' \
346
+ '(seq: %s, frame: %i, ids:' % (data['seq'], t+1)
347
+ exc_str = ' '.join([exc_str_init] + [str(d) for d in duplicate_ids]) + ')'
348
+ if after_preproc:
349
+ exc_str_init += '\n Note that this error occurred after preprocessing (but not before), ' \
350
+ 'so ids may not be as in file, and something seems wrong with preproc.'
351
+ raise TrackEvalException(exc_str)
352
+ if len(gt_ids_t) > 0:
353
+ unique_ids, counts = np.unique(gt_ids_t, return_counts=True)
354
+ if np.max(counts) != 1:
355
+ duplicate_ids = unique_ids[counts > 1]
356
+ exc_str_init = 'Ground-truth has the same ID more than once in a single timestep ' \
357
+ '(seq: %s, frame: %i, ids:' % (data['seq'], t+1)
358
+ exc_str = ' '.join([exc_str_init] + [str(d) for d in duplicate_ids]) + ')'
359
+ if after_preproc:
360
+ exc_str_init += '\n Note that this error occurred after preprocessing (but not before), ' \
361
+ 'so ids may not be as in file, and something seems wrong with preproc.'
362
+ raise TrackEvalException(exc_str)
MTMC_Tracking_2024/eval/trackeval/datasets/mot_challenge_2d_box.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import configparser
4
+ import numpy as np
5
+ from scipy.optimize import linear_sum_assignment
6
+ from trackeval import utils
7
+ from trackeval import _timing
8
+ from trackeval.utils import TrackEvalException
9
+ from trackeval.datasets._base_dataset import _BaseDataset
10
+
11
+
12
+ class MotChallenge2DBox(_BaseDataset):
13
+ """
14
+ Dataset class for MOT Challenge 2D bounding box tracking
15
+
16
+ :param dict config: configuration for the app
17
+ ::
18
+
19
+ default_dataset = trackeeval.datasets.MotChallenge2DBox(config)
20
+ """
21
+ @staticmethod
22
+ def get_default_dataset_config():
23
+ """Default class config values"""
24
+ code_path = utils.get_code_path()
25
+ default_config = {
26
+ 'GT_FOLDER': os.path.join(code_path, 'data/gt/mot_challenge/'), # Location of GT data
27
+ 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/mot_challenge/'), # Trackers location
28
+ 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
29
+ 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder)
30
+ 'CLASSES_TO_EVAL': ['pedestrian'], # Valid: ['pedestrian']
31
+ 'BENCHMARK': 'MOT17', # Valid: 'MOT17', 'MOT16', 'MOT20', 'MOT15'
32
+ 'SPLIT_TO_EVAL': 'train', # Valid: 'train', 'test', 'all'
33
+ 'INPUT_AS_ZIP': False, # Whether tracker input files are zipped
34
+ 'PRINT_CONFIG': True, # Whether to print current config
35
+ 'DO_PREPROC': True, # Whether to perform preprocessing (never done for MOT15)
36
+ 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
37
+ 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
38
+ 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
39
+ 'SEQMAP_FOLDER': None, # Where seqmaps are found (if None, GT_FOLDER/seqmaps)
40
+ 'SEQMAP_FILE': None, # Directly specify seqmap file (if none use seqmap_folder/benchmark-split_to_eval)
41
+ 'SEQ_INFO': None, # If not None, directly specify sequences to eval and their number of timesteps
42
+ 'GT_LOC_FORMAT': '{gt_folder}/{seq}/gt/gt.txt', # '{gt_folder}/{seq}/gt/gt.txt'
43
+ 'SKIP_SPLIT_FOL': False, # If False, data is in GT_FOLDER/BENCHMARK-SPLIT_TO_EVAL/ and in
44
+ # TRACKERS_FOLDER/BENCHMARK-SPLIT_TO_EVAL/tracker/
45
+ # If True, then the middle 'benchmark-split' folder is skipped for both.
46
+ }
47
+ return default_config
48
+
49
+ def __init__(self, config=None):
50
+ """Initialise dataset, checking that all required files are present"""
51
+ super().__init__()
52
+ # Fill non-given config values with defaults
53
+ self.config = utils.init_config(config, self.get_default_dataset_config(), self.get_name())
54
+
55
+ self.benchmark = self.config['BENCHMARK']
56
+ gt_set = self.config['BENCHMARK'] + '-' + self.config['SPLIT_TO_EVAL']
57
+ self.gt_set = gt_set
58
+ if not self.config['SKIP_SPLIT_FOL']:
59
+ split_fol = gt_set
60
+ else:
61
+ split_fol = ''
62
+ self.gt_fol = os.path.join(self.config['GT_FOLDER'], split_fol)
63
+ self.tracker_fol = os.path.join(self.config['TRACKERS_FOLDER'], split_fol)
64
+ self.should_classes_combine = False
65
+ self.use_super_categories = False
66
+ self.data_is_zipped = self.config['INPUT_AS_ZIP']
67
+ self.do_preproc = self.config['DO_PREPROC']
68
+
69
+ self.output_fol = self.config['OUTPUT_FOLDER']
70
+ if self.output_fol is None:
71
+ self.output_fol = self.tracker_fol
72
+
73
+ self.tracker_sub_fol = self.config['TRACKER_SUB_FOLDER']
74
+ self.output_sub_fol = self.config['OUTPUT_SUB_FOLDER']
75
+
76
+ # Get classes to eval
77
+ self.valid_classes = ['pedestrian']
78
+ self.class_list = [cls.lower() if cls.lower() in self.valid_classes else None
79
+ for cls in self.config['CLASSES_TO_EVAL']]
80
+ if not all(self.class_list):
81
+ raise TrackEvalException('Attempted to evaluate an invalid class. Only pedestrian class is valid.')
82
+ self.class_name_to_class_id = {'pedestrian': 1, 'person_on_vehicle': 2, 'car': 3, 'bicycle': 4, 'motorbike': 5,
83
+ 'non_mot_vehicle': 6, 'static_person': 7, 'distractor': 8, 'occluder': 9,
84
+ 'occluder_on_ground': 10, 'occluder_full': 11, 'reflection': 12, 'crowd': 13}
85
+ self.valid_class_numbers = list(self.class_name_to_class_id.values())
86
+
87
+ # Get sequences to eval and check gt files exist
88
+ self.seq_list, self.seq_lengths = self._get_seq_info()
89
+ if len(self.seq_list) < 1:
90
+ raise TrackEvalException('No sequences are selected to be evaluated.')
91
+
92
+ # Check gt files exist
93
+ for seq in self.seq_list:
94
+ if not self.data_is_zipped:
95
+ curr_file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq)
96
+ if not os.path.isfile(curr_file):
97
+ print('GT file not found ' + curr_file)
98
+ raise TrackEvalException('GT file not found for sequence: ' + seq)
99
+ if self.data_is_zipped:
100
+ curr_file = os.path.join(self.gt_fol, 'data.zip')
101
+ if not os.path.isfile(curr_file):
102
+ print('GT file not found ' + curr_file)
103
+ raise TrackEvalException('GT file not found: ' + os.path.basename(curr_file))
104
+
105
+ # Get trackers to eval
106
+ if self.config['TRACKERS_TO_EVAL'] is None:
107
+ self.tracker_list = os.listdir(self.tracker_fol)
108
+ else:
109
+ self.tracker_list = self.config['TRACKERS_TO_EVAL']
110
+
111
+ if self.config['TRACKER_DISPLAY_NAMES'] is None:
112
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list))
113
+ elif (self.config['TRACKERS_TO_EVAL'] is not None) and (
114
+ len(self.config['TRACKER_DISPLAY_NAMES']) == len(self.tracker_list)):
115
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.config['TRACKER_DISPLAY_NAMES']))
116
+ else:
117
+ raise TrackEvalException('List of tracker files and tracker display names do not match.')
118
+
119
+ for tracker in self.tracker_list:
120
+ if self.data_is_zipped:
121
+ curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip')
122
+ if not os.path.isfile(curr_file):
123
+ print('Tracker file not found: ' + curr_file)
124
+ raise TrackEvalException('Tracker file not found: ' + tracker + '/' + os.path.basename(curr_file))
125
+ else:
126
+ for seq in self.seq_list:
127
+ curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
128
+ if not os.path.isfile(curr_file):
129
+ print('Tracker file not found: ' + curr_file)
130
+ raise TrackEvalException(
131
+ 'Tracker file not found: ' + tracker + '/' + self.tracker_sub_fol + '/' + os.path.basename(
132
+ curr_file))
133
+
134
+ def get_display_name(self, tracker):
135
+ """
136
+ Gets the display name of the tracker
137
+
138
+ :param str tracker: Class of tracker
139
+ :return: str
140
+ ::
141
+
142
+ dataset.get_display_name(tracker)
143
+ """
144
+
145
+ return self.tracker_to_disp[tracker]
146
+
147
+ def _get_seq_info(self):
148
+ seq_list = []
149
+ seq_lengths = {}
150
+ if self.config["SEQ_INFO"]:
151
+ seq_list = list(self.config["SEQ_INFO"].keys())
152
+ seq_lengths = self.config["SEQ_INFO"]
153
+
154
+ # If sequence length is 'None' tries to read sequence length from .ini files.
155
+ for seq, seq_length in seq_lengths.items():
156
+ if seq_length is None:
157
+ ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini')
158
+ if not os.path.isfile(ini_file):
159
+ raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file))
160
+ ini_data = configparser.ConfigParser()
161
+ ini_data.read(ini_file)
162
+ seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
163
+
164
+ else:
165
+ if self.config["SEQMAP_FILE"]:
166
+ seqmap_file = self.config["SEQMAP_FILE"]
167
+ else:
168
+ if self.config["SEQMAP_FOLDER"] is None:
169
+ seqmap_file = os.path.join(self.config['GT_FOLDER'], 'seqmaps', self.gt_set + '.txt')
170
+ else:
171
+ seqmap_file = os.path.join(self.config["SEQMAP_FOLDER"], self.gt_set + '.txt')
172
+ if not os.path.isfile(seqmap_file):
173
+ print('no seqmap found: ' + seqmap_file)
174
+ raise TrackEvalException('no seqmap found: ' + os.path.basename(seqmap_file))
175
+ with open(seqmap_file) as fp:
176
+ reader = csv.reader(fp)
177
+ for i, row in enumerate(reader):
178
+ if i == 0 or row[0] == '':
179
+ continue
180
+ seq = row[0]
181
+ seq_list.append(seq)
182
+ ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini')
183
+ if not os.path.isfile(ini_file):
184
+ raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file))
185
+ ini_data = configparser.ConfigParser()
186
+ ini_data.read(ini_file)
187
+ seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
188
+ return seq_list, seq_lengths
189
+
190
+ def _load_raw_file(self, tracker, seq, is_gt):
191
+ """Load a file (gt or tracker) in the MOT Challenge 2D box format
192
+
193
+ If is_gt, this returns a dict which contains the fields:
194
+ [gt_ids, gt_classes] : list (for each timestep) of 1D NDArrays (for each det).
195
+ [gt_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections.
196
+ [gt_extras] : list (for each timestep) of dicts (for each extra) of 1D NDArrays (for each det).
197
+
198
+ if not is_gt, this returns a dict which contains the fields:
199
+ [tracker_ids, tracker_classes, tracker_confidences] : list (for each timestep) of 1D NDArrays (for each det).
200
+ [tracker_dets]: list (for each timestep) of lists of detections.
201
+
202
+ :param str tracker: Name of the tracker.
203
+ :param str seq: Sequence identifier.
204
+ :param bool is_gt: Indicates whether the file is ground truth or from a tracker.
205
+ :raises TrackEvalException: If there's an error loading the file or if the data is corrupted.
206
+ :return: dictionary containing the loaded data.
207
+ :rtype: dict
208
+ """
209
+ # File location
210
+ if self.data_is_zipped:
211
+ if is_gt:
212
+ zip_file = os.path.join(self.gt_fol, 'data.zip')
213
+ else:
214
+ zip_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip')
215
+ file = seq + '.txt'
216
+ else:
217
+ zip_file = None
218
+ if is_gt:
219
+ file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq)
220
+ else:
221
+ file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
222
+
223
+ # Load raw data from text file
224
+ read_data, ignore_data = self._load_simple_text_file(file, is_zipped=self.data_is_zipped, zip_file=zip_file)
225
+
226
+ # Convert data to required format
227
+ num_timesteps = self.seq_lengths[seq]
228
+ data_keys = ['ids', 'classes', 'dets']
229
+ if is_gt:
230
+ data_keys += ['gt_crowd_ignore_regions', 'gt_extras']
231
+ else:
232
+ data_keys += ['tracker_confidences']
233
+ raw_data = {key: [None] * num_timesteps for key in data_keys}
234
+
235
+ # Check for any extra time keys
236
+ current_time_keys = [str( t+ 1) for t in range(num_timesteps)]
237
+ extra_time_keys = [x for x in read_data.keys() if x not in current_time_keys]
238
+ if len(extra_time_keys) > 0:
239
+ if is_gt:
240
+ text = 'Ground-truth'
241
+ else:
242
+ text = 'Tracking'
243
+ raise TrackEvalException(
244
+ text + ' data contains the following invalid timesteps in seq %s: ' % seq + ', '.join(
245
+ [str(x) + ', ' for x in extra_time_keys]))
246
+
247
+ for t in range(num_timesteps):
248
+ time_key = str(t+1)
249
+ if time_key in read_data.keys():
250
+ try:
251
+ time_data = np.asarray(read_data[time_key], dtype=float)
252
+ except ValueError:
253
+ if is_gt:
254
+ raise TrackEvalException(
255
+ 'Cannot convert gt data for sequence %s to float. Is data corrupted?' % seq)
256
+ else:
257
+ raise TrackEvalException(
258
+ 'Cannot convert tracking data from tracker %s, sequence %s to float. Is data corrupted?' % (
259
+ tracker, seq))
260
+ try:
261
+ raw_data['dets'][t] = np.atleast_2d(time_data[:, 2:6])
262
+ raw_data['ids'][t] = np.atleast_1d(time_data[:, 1]).astype(int)
263
+ except IndexError:
264
+ if is_gt:
265
+ err = 'Cannot load gt data from sequence %s, because there is not enough ' \
266
+ 'columns in the data.' % seq
267
+ raise TrackEvalException(err)
268
+ else:
269
+ err = 'Cannot load tracker data from tracker %s, sequence %s, because there is not enough ' \
270
+ 'columns in the data.' % (tracker, seq)
271
+ raise TrackEvalException(err)
272
+ if time_data.shape[1] >= 8:
273
+ raw_data['classes'][t] = np.atleast_1d(time_data[:, 7]).astype(int)
274
+ else:
275
+ if not is_gt:
276
+ raw_data['classes'][t] = np.ones_like(raw_data['ids'][t])
277
+ else:
278
+ raise TrackEvalException(
279
+ 'GT data is not in a valid format, there is not enough rows in seq %s, timestep %i.' % (
280
+ seq, t))
281
+ if is_gt:
282
+ gt_extras_dict = {'zero_marked': np.atleast_1d(time_data[:, 6].astype(int))}
283
+ raw_data['gt_extras'][t] = gt_extras_dict
284
+ else:
285
+ raw_data['tracker_confidences'][t] = np.atleast_1d(time_data[:, 6])
286
+ else:
287
+ raw_data['dets'][t] = np.empty((0, 4))
288
+ raw_data['ids'][t] = np.empty(0).astype(int)
289
+ raw_data['classes'][t] = np.empty(0).astype(int)
290
+ if is_gt:
291
+ gt_extras_dict = {'zero_marked': np.empty(0)}
292
+ raw_data['gt_extras'][t] = gt_extras_dict
293
+ else:
294
+ raw_data['tracker_confidences'][t] = np.empty(0)
295
+ if is_gt:
296
+ raw_data['gt_crowd_ignore_regions'][t] = np.empty((0, 4))
297
+
298
+ if is_gt:
299
+ key_map = {'ids': 'gt_ids',
300
+ 'classes': 'gt_classes',
301
+ 'dets': 'gt_dets'}
302
+ else:
303
+ key_map = {'ids': 'tracker_ids',
304
+ 'classes': 'tracker_classes',
305
+ 'dets': 'tracker_dets'}
306
+ for k, v in key_map.items():
307
+ raw_data[v] = raw_data.pop(k)
308
+ raw_data['num_timesteps'] = num_timesteps
309
+ raw_data['seq'] = seq
310
+ return raw_data
311
+
312
+ @_timing.time
313
+ def get_preprocessed_seq_data(self, raw_data, cls):
314
+ """ Preprocess data for a single sequence for a single class ready for evaluation.
315
+ Inputs:
316
+ - raw_data is a dict containing the data for the sequence already read in by get_raw_seq_data().
317
+ - cls is the class to be evaluated.
318
+ Outputs:
319
+ - data is a dict containing all of the information that metrics need to perform evaluation.
320
+ It contains the following fields:
321
+ [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets] : integers.
322
+ [gt_ids, tracker_ids, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det).
323
+ [gt_dets, tracker_dets]: list (for each timestep) of lists of detections.
324
+ [similarity_scores]: list (for each timestep) of 2D NDArrays.
325
+ Notes:
326
+ General preprocessing (preproc) occurs in 4 steps. Some datasets may not use all of these steps.
327
+ 1) Extract only detections relevant for the class to be evaluated (including distractor detections).
328
+ 2) Match gt dets and tracker dets. Remove tracker dets that are matched to a gt det that is of a
329
+ distractor class, or otherwise marked as to be removed.
330
+ 3) Remove unmatched tracker dets if they fall within a crowd ignore region or don't meet a certain
331
+ other criteria (e.g. are too small).
332
+ 4) Remove gt dets that were only useful for preprocessing and not for actual evaluation.
333
+ After the above preprocessing steps, this function also calculates the number of gt and tracker detections
334
+ and unique track ids. It also relabels gt and tracker ids to be contiguous and checks that ids are
335
+ unique within each timestep.
336
+
337
+ MOT Challenge:
338
+ In MOT Challenge, the 4 preproc steps are as follow:
339
+ 1) There is only one class (pedestrian) to be evaluated, but all other classes are used for preproc.
340
+ 2) Predictions are matched against all gt boxes (regardless of class), those matching with distractor
341
+ objects are removed.
342
+ 3) There is no crowd ignore regions.
343
+ 4) All gt dets except pedestrian are removed, also removes pedestrian gt dets marked with zero_marked.
344
+
345
+ :param raw_data: A dict containing the data for the sequence already read in by `get_raw_seq_data()`.
346
+ :param cls: The class to be evaluated.
347
+
348
+ :return: A dict containing all of the information that metrics need to perform evaluation.
349
+ It contains the following fields:
350
+ - [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets]: Integers.
351
+ - [gt_ids, tracker_ids, tracker_confidences]: List (for each timestep) of 1D NDArrays (for each detection).
352
+ - [gt_dets, tracker_dets]: List (for each timestep) of lists of detections.
353
+ - [similarity_scores]: List (for each timestep) of 2D NDArrays.
354
+
355
+ """
356
+ # Check that input data has unique ids
357
+ self._check_unique_ids(raw_data)
358
+
359
+ distractor_class_names = ['person_on_vehicle', 'static_person', 'distractor', 'reflection']
360
+ if self.benchmark == 'MOT20':
361
+ distractor_class_names.append('non_mot_vehicle')
362
+ distractor_classes = [self.class_name_to_class_id[x] for x in distractor_class_names]
363
+ cls_id = self.class_name_to_class_id[cls]
364
+
365
+ data_keys = ['gt_ids', 'tracker_ids', 'gt_dets', 'tracker_dets', 'tracker_confidences', 'similarity_scores']
366
+ data = {key: [None] * raw_data['num_timesteps'] for key in data_keys}
367
+ unique_gt_ids = []
368
+ unique_tracker_ids = []
369
+ num_gt_dets = 0
370
+ num_tracker_dets = 0
371
+ for t in range(raw_data['num_timesteps']):
372
+
373
+ # Get all data
374
+ gt_ids = raw_data['gt_ids'][t]
375
+ gt_dets = raw_data['gt_dets'][t]
376
+ gt_classes = raw_data['gt_classes'][t]
377
+ gt_zero_marked = raw_data['gt_extras'][t]['zero_marked']
378
+
379
+ tracker_ids = raw_data['tracker_ids'][t]
380
+ tracker_dets = raw_data['tracker_dets'][t]
381
+ tracker_classes = raw_data['tracker_classes'][t]
382
+ tracker_confidences = raw_data['tracker_confidences'][t]
383
+ similarity_scores = raw_data['similarity_scores'][t]
384
+
385
+ # Evaluation is ONLY valid for pedestrian class
386
+ if len(tracker_classes) > 0 and np.max(tracker_classes) > 1:
387
+ raise TrackEvalException(
388
+ 'Evaluation is only valid for pedestrian class. Non pedestrian class (%i) found in sequence %s at '
389
+ 'timestep %i.' % (np.max(tracker_classes), raw_data['seq'], t))
390
+
391
+ # Match tracker and gt dets (with hungarian algorithm) and remove tracker dets which match with gt dets
392
+ # which are labeled as belonging to a distractor class.
393
+ to_remove_tracker = np.array([], int)
394
+ if self.do_preproc and self.benchmark != 'MOT15' and gt_ids.shape[0] > 0 and tracker_ids.shape[0] > 0:
395
+
396
+ # Check all classes are valid:
397
+ invalid_classes = np.setdiff1d(np.unique(gt_classes), self.valid_class_numbers)
398
+ if len(invalid_classes) > 0:
399
+ print(' '.join([str(x) for x in invalid_classes]))
400
+ raise(TrackEvalException('Attempting to evaluate using invalid gt classes. '
401
+ 'This warning only triggers if preprocessing is performed, '
402
+ 'e.g. not for MOT15 or where prepropressing is explicitly disabled. '
403
+ 'Please either check your gt data, or disable preprocessing. '
404
+ 'The following invalid classes were found in timestep ' + str(t) + ': ' +
405
+ ' '.join([str(x) for x in invalid_classes])))
406
+
407
+ matching_scores = similarity_scores.copy()
408
+ matching_scores[matching_scores < 0.5 - np.finfo('float').eps] = 0
409
+ match_rows, match_cols = linear_sum_assignment(-matching_scores)
410
+ actually_matched_mask = matching_scores[match_rows, match_cols] > 0 + np.finfo('float').eps
411
+ match_rows = match_rows[actually_matched_mask]
412
+ match_cols = match_cols[actually_matched_mask]
413
+
414
+ is_distractor_class = np.isin(gt_classes[match_rows], distractor_classes)
415
+ to_remove_tracker = match_cols[is_distractor_class]
416
+
417
+ # Apply preprocessing to remove all unwanted tracker dets.
418
+ data['tracker_ids'][t] = np.delete(tracker_ids, to_remove_tracker, axis=0)
419
+ data['tracker_dets'][t] = np.delete(tracker_dets, to_remove_tracker, axis=0)
420
+ data['tracker_confidences'][t] = np.delete(tracker_confidences, to_remove_tracker, axis=0)
421
+ similarity_scores = np.delete(similarity_scores, to_remove_tracker, axis=1)
422
+
423
+ # Remove gt detections marked as to remove (zero marked), and also remove gt detections not in pedestrian
424
+ # class (not applicable for MOT15)
425
+ if self.do_preproc and self.benchmark != 'MOT15':
426
+ gt_to_keep_mask = (np.not_equal(gt_zero_marked, 0)) & \
427
+ (np.equal(gt_classes, cls_id))
428
+ else:
429
+ # There are no classes for MOT15
430
+ gt_to_keep_mask = np.not_equal(gt_zero_marked, 0)
431
+ data['gt_ids'][t] = gt_ids[gt_to_keep_mask]
432
+ data['gt_dets'][t] = gt_dets[gt_to_keep_mask, :]
433
+ data['similarity_scores'][t] = similarity_scores[gt_to_keep_mask]
434
+
435
+ unique_gt_ids += list(np.unique(data['gt_ids'][t]))
436
+ unique_tracker_ids += list(np.unique(data['tracker_ids'][t]))
437
+ num_tracker_dets += len(data['tracker_ids'][t])
438
+ num_gt_dets += len(data['gt_ids'][t])
439
+
440
+ # Re-label IDs such that there are no empty IDs
441
+ if len(unique_gt_ids) > 0:
442
+ unique_gt_ids = np.unique(unique_gt_ids)
443
+ gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1))
444
+ gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids))
445
+ for t in range(raw_data['num_timesteps']):
446
+ if len(data['gt_ids'][t]) > 0:
447
+ data['gt_ids'][t] = gt_id_map[data['gt_ids'][t]].astype(int)
448
+ if len(unique_tracker_ids) > 0:
449
+ unique_tracker_ids = np.unique(unique_tracker_ids)
450
+ tracker_id_map = np.nan * np.ones((np.max(unique_tracker_ids) + 1))
451
+ tracker_id_map[unique_tracker_ids] = np.arange(len(unique_tracker_ids))
452
+ for t in range(raw_data['num_timesteps']):
453
+ if len(data['tracker_ids'][t]) > 0:
454
+ data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(int)
455
+
456
+ # Record overview statistics.
457
+ data['num_tracker_dets'] = num_tracker_dets
458
+ data['num_gt_dets'] = num_gt_dets
459
+ data['num_tracker_ids'] = len(unique_tracker_ids)
460
+ data['num_gt_ids'] = len(unique_gt_ids)
461
+ data['num_timesteps'] = raw_data['num_timesteps']
462
+ data['seq'] = raw_data['seq']
463
+
464
+ # Ensure again that ids are unique per timestep after preproc.
465
+ self._check_unique_ids(data, after_preproc=True)
466
+
467
+ return data
468
+
469
+ def _calculate_similarities(self, gt_dets_t, tracker_dets_t):
470
+ similarity_scores = self._calculate_box_ious(gt_dets_t, tracker_dets_t, box_format='xywh')
471
+ return similarity_scores
MTMC_Tracking_2024/eval/trackeval/datasets/mot_challenge_3d_location.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import configparser
4
+ import numpy as np
5
+ from scipy.optimize import linear_sum_assignment
6
+ from trackeval import utils
7
+ from trackeval import _timing
8
+ from trackeval.utils import TrackEvalException
9
+ from trackeval.datasets._base_dataset import _BaseDataset
10
+
11
+
12
+ class MotChallenge3DLocation(_BaseDataset):
13
+ """
14
+ Dataset class for MOT Challenge 3D tracking
15
+
16
+ :param dict config: configuration for the app
17
+ ::
18
+
19
+ default_dataset = trackeeval.datasets.MotChallenge2DBox(config)
20
+ """
21
+ @staticmethod
22
+ def get_default_dataset_config():
23
+ """Default class config values"""
24
+ code_path = utils.get_code_path()
25
+ default_config = {
26
+ 'GT_FOLDER': os.path.join(code_path, 'data/gt/mot_challenge/'), # Location of GT data
27
+ 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/mot_challenge/'), # Trackers location
28
+ 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
29
+ 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder)
30
+ 'CLASSES_TO_EVAL': ['pedestrian'], # Valid: ['pedestrian']
31
+ 'BENCHMARK': 'MOT17', # Valid: 'MOT17', 'MOT16', 'MOT20', 'MOT15'
32
+ 'SPLIT_TO_EVAL': 'train', # Valid: 'train', 'test', 'all'
33
+ 'INPUT_AS_ZIP': False, # Whether tracker input files are zipped
34
+ 'PRINT_CONFIG': True, # Whether to print current config
35
+ 'DO_PREPROC': True, # Whether to perform preprocessing (never done for MOT15)
36
+ 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
37
+ 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
38
+ 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
39
+ 'SEQMAP_FOLDER': None, # Where seqmaps are found (if None, GT_FOLDER/seqmaps)
40
+ 'SEQMAP_FILE': None, # Directly specify seqmap file (if none use seqmap_folder/benchmark-split_to_eval)
41
+ 'SEQ_INFO': None, # If not None, directly specify sequences to eval and their number of timesteps
42
+ 'GT_LOC_FORMAT': '{gt_folder}/{seq}/gt/gt.txt', # '{gt_folder}/{seq}/gt/gt.txt'
43
+ 'SKIP_SPLIT_FOL': False, # If False, data is in GT_FOLDER/BENCHMARK-SPLIT_TO_EVAL/ and in
44
+ # TRACKERS_FOLDER/BENCHMARK-SPLIT_TO_EVAL/tracker/
45
+ # If True, then the middle 'benchmark-split' folder is skipped for both.
46
+ }
47
+ return default_config
48
+
49
+ def __init__(self, config=None, zd=2.0):
50
+ """Initialise dataset, checking that all required files are present"""
51
+ super().__init__()
52
+ # Fill non-given config values with defaults
53
+ self.config = utils.init_config(config, self.get_default_dataset_config(), self.get_name())
54
+ self.zero_distance = zd
55
+ self.benchmark = self.config['BENCHMARK']
56
+ gt_set = self.config['BENCHMARK'] + '-' + self.config['SPLIT_TO_EVAL']
57
+ self.gt_set = gt_set
58
+ if not self.config['SKIP_SPLIT_FOL']:
59
+ split_fol = gt_set
60
+ else:
61
+ split_fol = ''
62
+ self.gt_fol = os.path.join(self.config['GT_FOLDER'], split_fol)
63
+ self.tracker_fol = os.path.join(self.config['TRACKERS_FOLDER'], split_fol)
64
+ self.should_classes_combine = False
65
+ self.use_super_categories = False
66
+ self.data_is_zipped = self.config['INPUT_AS_ZIP']
67
+ self.do_preproc = self.config['DO_PREPROC']
68
+
69
+ self.output_fol = self.config['OUTPUT_FOLDER']
70
+ if self.output_fol is None:
71
+ self.output_fol = self.tracker_fol
72
+
73
+ self.tracker_sub_fol = self.config['TRACKER_SUB_FOLDER']
74
+ self.output_sub_fol = self.config['OUTPUT_SUB_FOLDER']
75
+
76
+ # Get classes to eval
77
+ self.valid_classes = ['pedestrian']
78
+ self.class_list = [cls.lower() if cls.lower() in self.valid_classes else None
79
+ for cls in self.config['CLASSES_TO_EVAL']]
80
+ if not all(self.class_list):
81
+ raise TrackEvalException('Attempted to evaluate an invalid class. Only pedestrian class is valid.')
82
+ self.class_name_to_class_id = {'pedestrian': 1, 'person_on_vehicle': 2, 'car': 3, 'bicycle': 4, 'motorbike': 5,
83
+ 'non_mot_vehicle': 6, 'static_person': 7, 'distractor': 8, 'occluder': 9,
84
+ 'occluder_on_ground': 10, 'occluder_full': 11, 'reflection': 12, 'crowd': 13}
85
+ self.valid_class_numbers = list(self.class_name_to_class_id.values())
86
+
87
+ # Get sequences to eval and check gt files exist
88
+ self.seq_list, self.seq_lengths = self._get_seq_info()
89
+ if len(self.seq_list) < 1:
90
+ raise TrackEvalException('No sequences are selected to be evaluated.')
91
+
92
+ # Check gt files exist
93
+ for seq in self.seq_list:
94
+ if not self.data_is_zipped:
95
+ curr_file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq)
96
+ if not os.path.isfile(curr_file):
97
+ print('GT file not found ' + curr_file)
98
+ raise TrackEvalException('GT file not found for sequence: ' + seq)
99
+ if self.data_is_zipped:
100
+ curr_file = os.path.join(self.gt_fol, 'data.zip')
101
+ if not os.path.isfile(curr_file):
102
+ print('GT file not found ' + curr_file)
103
+ raise TrackEvalException('GT file not found: ' + os.path.basename(curr_file))
104
+
105
+ # Get trackers to eval
106
+ if self.config['TRACKERS_TO_EVAL'] is None:
107
+ self.tracker_list = os.listdir(self.tracker_fol)
108
+ else:
109
+ self.tracker_list = self.config['TRACKERS_TO_EVAL']
110
+
111
+ if self.config['TRACKER_DISPLAY_NAMES'] is None:
112
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list))
113
+ elif (self.config['TRACKERS_TO_EVAL'] is not None) and (
114
+ len(self.config['TRACKER_DISPLAY_NAMES']) == len(self.tracker_list)):
115
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.config['TRACKER_DISPLAY_NAMES']))
116
+ else:
117
+ raise TrackEvalException('List of tracker files and tracker display names do not match.')
118
+
119
+ for tracker in self.tracker_list:
120
+ if self.data_is_zipped:
121
+ curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip')
122
+ if not os.path.isfile(curr_file):
123
+ print('Tracker file not found: ' + curr_file)
124
+ raise TrackEvalException('Tracker file not found: ' + tracker + '/' + os.path.basename(curr_file))
125
+ else:
126
+ for seq in self.seq_list:
127
+ curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
128
+ if not os.path.isfile(curr_file):
129
+ print('Tracker file not found: ' + curr_file)
130
+ raise TrackEvalException(
131
+ 'Tracker file not found: ' + tracker + '/' + self.tracker_sub_fol + '/' + os.path.basename(
132
+ curr_file))
133
+
134
+ def get_display_name(self, tracker):
135
+ """
136
+ Gets the display name of the tracker
137
+
138
+ :param str tracker: Class of tracker
139
+ :return: str
140
+ ::
141
+
142
+ dataset.get_display_name(tracker)
143
+ """
144
+
145
+ return self.tracker_to_disp[tracker]
146
+
147
+ def _get_seq_info(self):
148
+ seq_list = []
149
+ seq_lengths = {}
150
+ if self.config["SEQ_INFO"]:
151
+ seq_list = list(self.config["SEQ_INFO"].keys())
152
+ seq_lengths = self.config["SEQ_INFO"]
153
+
154
+ # If sequence length is 'None' tries to read sequence length from .ini files.
155
+ for seq, seq_length in seq_lengths.items():
156
+ if seq_length is None:
157
+ ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini')
158
+ if not os.path.isfile(ini_file):
159
+ raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file))
160
+ ini_data = configparser.ConfigParser()
161
+ ini_data.read(ini_file)
162
+ seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
163
+
164
+ else:
165
+ if self.config["SEQMAP_FILE"]:
166
+ seqmap_file = self.config["SEQMAP_FILE"]
167
+ else:
168
+ if self.config["SEQMAP_FOLDER"] is None:
169
+ seqmap_file = os.path.join(self.config['GT_FOLDER'], 'seqmaps', self.gt_set + '.txt')
170
+ else:
171
+ seqmap_file = os.path.join(self.config["SEQMAP_FOLDER"], self.gt_set + '.txt')
172
+ if not os.path.isfile(seqmap_file):
173
+ print('no seqmap found: ' + seqmap_file)
174
+ raise TrackEvalException('no seqmap found: ' + os.path.basename(seqmap_file))
175
+ with open(seqmap_file) as fp:
176
+ reader = csv.reader(fp)
177
+ for i, row in enumerate(reader):
178
+ if i == 0 or row[0] == '':
179
+ continue
180
+ seq = row[0]
181
+ seq_list.append(seq)
182
+ ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini')
183
+ if not os.path.isfile(ini_file):
184
+ raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file))
185
+ ini_data = configparser.ConfigParser()
186
+ ini_data.read(ini_file)
187
+ seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
188
+ return seq_list, seq_lengths
189
+
190
+ def _load_raw_file(self, tracker, seq, is_gt):
191
+ """Load a file (gt or tracker) in the MOT Challenge 3D location format
192
+
193
+ If is_gt, this returns a dict which contains the fields:
194
+ [gt_ids, gt_classes] : list (for each timestep) of 1D NDArrays (for each det).
195
+ [gt_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections.
196
+ [gt_extras] : list (for each timestep) of dicts (for each extra) of 1D NDArrays (for each det).
197
+
198
+ if not is_gt, this returns a dict which contains the fields:
199
+ [tracker_ids, tracker_classes, tracker_confidences] : list (for each timestep) of 1D NDArrays (for each det).
200
+ [tracker_dets]: list (for each timestep) of lists of detections.
201
+
202
+ :param str tracker: Name of the tracker.
203
+ :param str seq: Sequence identifier.
204
+ :param bool is_gt: Indicates whether the file is ground truth or from a tracker.
205
+ :raises TrackEvalException: If there's an error loading the file or if the data is corrupted.
206
+ :return: dictionary containing the loaded data.
207
+ :rtype: dict
208
+ """
209
+ # File location
210
+ if self.data_is_zipped:
211
+ if is_gt:
212
+ zip_file = os.path.join(self.gt_fol, 'data.zip')
213
+ else:
214
+ zip_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip')
215
+ file = seq + '.txt'
216
+ else:
217
+ zip_file = None
218
+ if is_gt:
219
+ file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq)
220
+ else:
221
+ file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
222
+
223
+ # Load raw data from text file
224
+ read_data, ignore_data = self._load_simple_text_file(file, is_zipped=self.data_is_zipped, zip_file=zip_file)
225
+
226
+ # Convert data to required format
227
+ num_timesteps = self.seq_lengths[seq]
228
+ data_keys = ['ids', 'classes', 'dets']
229
+ if is_gt:
230
+ data_keys += ['gt_crowd_ignore_regions', 'gt_extras']
231
+ else:
232
+ data_keys += ['tracker_confidences']
233
+ raw_data = {key: [None] * num_timesteps for key in data_keys}
234
+
235
+ # Check for any extra time keys
236
+ current_time_keys = [str( t+ 1) for t in range(num_timesteps)]
237
+ extra_time_keys = [x for x in read_data.keys() if x not in current_time_keys]
238
+ if len(extra_time_keys) > 0:
239
+ if is_gt:
240
+ text = 'Ground-truth'
241
+ else:
242
+ text = 'Tracking'
243
+ raise TrackEvalException(
244
+ text + ' data contains the following invalid timesteps in seq %s: ' % seq + ', '.join(
245
+ [str(x) + ', ' for x in extra_time_keys]))
246
+
247
+ for t in range(num_timesteps):
248
+ time_key = str(t+1)
249
+ if time_key in read_data.keys():
250
+ try:
251
+ time_data = np.asarray(read_data[time_key], dtype=float)
252
+ except ValueError:
253
+ if is_gt:
254
+ raise TrackEvalException(
255
+ 'Cannot convert gt data for sequence %s to float. Is data corrupted?' % seq)
256
+ else:
257
+ raise TrackEvalException(
258
+ 'Cannot convert tracking data from tracker %s, sequence %s to float. Is data corrupted?' % (
259
+ tracker, seq))
260
+ try:
261
+ if is_gt:
262
+ raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9])
263
+ else:
264
+ raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9])
265
+ raw_data['ids'][t] = np.atleast_1d(time_data[:, 1]).astype(int)
266
+ except IndexError:
267
+ if is_gt:
268
+ err = 'Cannot load gt data from sequence %s, because there is not enough ' \
269
+ 'columns in the data.' % seq
270
+ raise TrackEvalException(err)
271
+ else:
272
+ err = 'Cannot load tracker data from tracker %s, sequence %s, because there is not enough ' \
273
+ 'columns in the data.' % (tracker, seq)
274
+ raise TrackEvalException(err)
275
+ if time_data.shape[1] >= 8:
276
+ raw_data['classes'][t] = np.ones_like(raw_data['ids'][t])
277
+ # raw_data['classes'][t] = np.atleast_1d(time_data[:, 7]).astype(int)
278
+ else:
279
+ if not is_gt:
280
+ raw_data['classes'][t] = np.ones_like(raw_data['ids'][t])
281
+ else:
282
+ raise TrackEvalException(
283
+ 'GT data is not in a valid format, there is not enough rows in seq %s, timestep %i.' % (
284
+ seq, t))
285
+ if is_gt:
286
+ gt_extras_dict = {'zero_marked': np.atleast_1d(time_data[:, 6].astype(int))}
287
+ raw_data['gt_extras'][t] = gt_extras_dict
288
+ else:
289
+ raw_data['tracker_confidences'][t] = np.atleast_1d(time_data[:, 6])
290
+ else:
291
+ raw_data['dets'][t] = np.empty((0, 2))
292
+ raw_data['ids'][t] = np.empty(0).astype(int)
293
+ raw_data['classes'][t] = np.empty(0).astype(int)
294
+ if is_gt:
295
+ gt_extras_dict = {'zero_marked': np.empty(0)}
296
+ raw_data['gt_extras'][t] = gt_extras_dict
297
+ else:
298
+ raw_data['tracker_confidences'][t] = np.empty(0)
299
+ if is_gt:
300
+ raw_data['gt_crowd_ignore_regions'][t] = np.empty((0, 2))
301
+
302
+ if is_gt:
303
+ key_map = {'ids': 'gt_ids',
304
+ 'classes': 'gt_classes',
305
+ 'dets': 'gt_dets'}
306
+ else:
307
+ key_map = {'ids': 'tracker_ids',
308
+ 'classes': 'tracker_classes',
309
+ 'dets': 'tracker_dets'}
310
+ for k, v in key_map.items():
311
+ raw_data[v] = raw_data.pop(k)
312
+ raw_data['num_timesteps'] = num_timesteps
313
+ raw_data['seq'] = seq
314
+ return raw_data
315
+
316
+ @_timing.time
317
+ def get_preprocessed_seq_data(self, raw_data, cls):
318
+ """ Preprocess data for a single sequence for a single class ready for evaluation.
319
+ Inputs:
320
+ - raw_data is a dict containing the data for the sequence already read in by get_raw_seq_data().
321
+ - cls is the class to be evaluated.
322
+ Outputs:
323
+ - data is a dict containing all of the information that metrics need to perform evaluation.
324
+ It contains the following fields:
325
+ [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets] : integers.
326
+ [gt_ids, tracker_ids, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det).
327
+ [gt_dets, tracker_dets]: list (for each timestep) of lists of detections.
328
+ [similarity_scores]: list (for each timestep) of 2D NDArrays.
329
+ Notes:
330
+ General preprocessing (preproc) occurs in 4 steps. Some datasets may not use all of these steps.
331
+ 1) Extract only detections relevant for the class to be evaluated (including distractor detections).
332
+ 2) Match gt dets and tracker dets. Remove tracker dets that are matched to a gt det that is of a
333
+ distractor class, or otherwise marked as to be removed.
334
+ 3) Remove unmatched tracker dets if they fall within a crowd ignore region or don't meet a certain
335
+ other criteria (e.g. are too small).
336
+ 4) Remove gt dets that were only useful for preprocessing and not for actual evaluation.
337
+ After the above preprocessing steps, this function also calculates the number of gt and tracker detections
338
+ and unique track ids. It also relabels gt and tracker ids to be contiguous and checks that ids are
339
+ unique within each timestep.
340
+
341
+ MOT Challenge:
342
+ In MOT Challenge, the 4 preproc steps are as follow:
343
+ 1) There is only one class (pedestrian) to be evaluated, but all other classes are used for preproc.
344
+ 2) Predictions are matched against all gt boxes (regardless of class), those matching with distractor
345
+ objects are removed.
346
+ 3) There is no crowd ignore regions.
347
+ 4) All gt dets except pedestrian are removed, also removes pedestrian gt dets marked with zero_marked.
348
+
349
+ :param raw_data: A dict containing the data for the sequence already read in by `get_raw_seq_data()`.
350
+ :param cls: The class to be evaluated.
351
+
352
+ :return: A dict containing all of the information that metrics need to perform evaluation.
353
+ It contains the following fields:
354
+ - [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets]: Integers.
355
+ - [gt_ids, tracker_ids, tracker_confidences]: List (for each timestep) of 1D NDArrays (for each detection).
356
+ - [gt_dets, tracker_dets]: List (for each timestep) of lists of detections.
357
+ - [similarity_scores]: List (for each timestep) of 2D NDArrays.
358
+
359
+ """
360
+ # Check that input data has unique ids
361
+ self._check_unique_ids(raw_data)
362
+
363
+ distractor_class_names = ['person_on_vehicle', 'static_person', 'distractor', 'reflection']
364
+ if self.benchmark == 'MOT20':
365
+ distractor_class_names.append('non_mot_vehicle')
366
+ distractor_classes = [self.class_name_to_class_id[x] for x in distractor_class_names]
367
+ cls_id = self.class_name_to_class_id[cls]
368
+
369
+ data_keys = ['gt_ids', 'tracker_ids', 'gt_dets', 'tracker_dets', 'tracker_confidences', 'similarity_scores']
370
+ data = {key: [None] * raw_data['num_timesteps'] for key in data_keys}
371
+ unique_gt_ids = []
372
+ unique_tracker_ids = []
373
+ num_gt_dets = 0
374
+ num_tracker_dets = 0
375
+ for t in range(raw_data['num_timesteps']):
376
+
377
+ # Get all data
378
+ gt_ids = raw_data['gt_ids'][t]
379
+ gt_dets = raw_data['gt_dets'][t]
380
+ gt_classes = raw_data['gt_classes'][t]
381
+ gt_zero_marked = raw_data['gt_extras'][t]['zero_marked']
382
+
383
+ tracker_ids = raw_data['tracker_ids'][t]
384
+ tracker_dets = raw_data['tracker_dets'][t]
385
+ tracker_classes = raw_data['tracker_classes'][t]
386
+ tracker_confidences = raw_data['tracker_confidences'][t]
387
+ similarity_scores = raw_data['similarity_scores'][t]
388
+
389
+ # Evaluation is ONLY valid for pedestrian class
390
+ if len(tracker_classes) > 0 and np.max(tracker_classes) > 1:
391
+ raise TrackEvalException(
392
+ 'Evaluation is only valid for pedestrian class. Non pedestrian class (%i) found in sequence %s at '
393
+ 'timestep %i.' % (np.max(tracker_classes), raw_data['seq'], t))
394
+
395
+ # Match tracker and gt dets (with hungarian algorithm) and remove tracker dets which match with gt dets
396
+ # which are labeled as belonging to a distractor class.
397
+ to_remove_tracker = np.array([], int)
398
+ if self.do_preproc and self.benchmark != 'MOT15' and gt_ids.shape[0] > 0 and tracker_ids.shape[0] > 0:
399
+
400
+ # Check all classes are valid:
401
+ invalid_classes = np.setdiff1d(np.unique(gt_classes), self.valid_class_numbers)
402
+ if len(invalid_classes) > 0:
403
+ print(' '.join([str(x) for x in invalid_classes]))
404
+ raise(TrackEvalException('Attempting to evaluate using invalid gt classes. '
405
+ 'This warning only triggers if preprocessing is performed, '
406
+ 'e.g. not for MOT15 or where prepropressing is explicitly disabled. '
407
+ 'Please either check your gt data, or disable preprocessing. '
408
+ 'The following invalid classes were found in timestep ' + str(t) + ': ' +
409
+ ' '.join([str(x) for x in invalid_classes])))
410
+
411
+ matching_scores = similarity_scores.copy()
412
+ matching_scores[matching_scores < 0.5 - np.finfo('float').eps] = 0
413
+ match_rows, match_cols = linear_sum_assignment(-matching_scores)
414
+ actually_matched_mask = matching_scores[match_rows, match_cols] > 0 + np.finfo('float').eps
415
+ match_rows = match_rows[actually_matched_mask]
416
+ match_cols = match_cols[actually_matched_mask]
417
+
418
+ is_distractor_class = np.isin(gt_classes[match_rows], distractor_classes)
419
+ to_remove_tracker = match_cols[is_distractor_class]
420
+
421
+ # Apply preprocessing to remove all unwanted tracker dets.
422
+ data['tracker_ids'][t] = np.delete(tracker_ids, to_remove_tracker, axis=0)
423
+ data['tracker_dets'][t] = np.delete(tracker_dets, to_remove_tracker, axis=0)
424
+ data['tracker_confidences'][t] = np.delete(tracker_confidences, to_remove_tracker, axis=0)
425
+ similarity_scores = np.delete(similarity_scores, to_remove_tracker, axis=1)
426
+
427
+ # Remove gt detections marked as to remove (zero marked), and also remove gt detections not in pedestrian
428
+ # class (not applicable for MOT15)
429
+ if self.do_preproc and self.benchmark != 'MOT15':
430
+ gt_to_keep_mask = (np.not_equal(gt_zero_marked, 0)) & \
431
+ (np.equal(gt_classes, cls_id))
432
+ else:
433
+ # There are no classes for MOT15
434
+ gt_to_keep_mask = np.not_equal(gt_zero_marked, 0)
435
+ data['gt_ids'][t] = gt_ids[gt_to_keep_mask]
436
+ data['gt_dets'][t] = gt_dets[gt_to_keep_mask, :]
437
+ data['similarity_scores'][t] = similarity_scores[gt_to_keep_mask]
438
+
439
+ unique_gt_ids += list(np.unique(data['gt_ids'][t]))
440
+ unique_tracker_ids += list(np.unique(data['tracker_ids'][t]))
441
+ num_tracker_dets += len(data['tracker_ids'][t])
442
+ num_gt_dets += len(data['gt_ids'][t])
443
+
444
+ # Re-label IDs such that there are no empty IDs
445
+ if len(unique_gt_ids) > 0:
446
+ unique_gt_ids = np.unique(unique_gt_ids)
447
+ gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1))
448
+ gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids))
449
+ for t in range(raw_data['num_timesteps']):
450
+ if len(data['gt_ids'][t]) > 0:
451
+ data['gt_ids'][t] = gt_id_map[data['gt_ids'][t]].astype(int)
452
+ if len(unique_tracker_ids) > 0:
453
+ unique_tracker_ids = np.unique(unique_tracker_ids)
454
+ tracker_id_map = np.nan * np.ones((np.max(unique_tracker_ids) + 1))
455
+ tracker_id_map[unique_tracker_ids] = np.arange(len(unique_tracker_ids))
456
+ for t in range(raw_data['num_timesteps']):
457
+ if len(data['tracker_ids'][t]) > 0:
458
+ data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(int)
459
+
460
+ # Record overview statistics.
461
+ data['num_tracker_dets'] = num_tracker_dets
462
+ data['num_gt_dets'] = num_gt_dets
463
+ data['num_tracker_ids'] = len(unique_tracker_ids)
464
+ data['num_gt_ids'] = len(unique_gt_ids)
465
+ data['num_timesteps'] = raw_data['num_timesteps']
466
+ data['seq'] = raw_data['seq']
467
+
468
+ # Ensure again that ids are unique per timestep after preproc.
469
+ self._check_unique_ids(data, after_preproc=True)
470
+
471
+ return data
472
+
473
+ def _calculate_similarities(self, gt_dets_t, tracker_dets_t):
474
+ similarity_scores = self._calculate_euclidean_similarity(gt_dets_t, tracker_dets_t, zero_distance=self.zero_distance)
475
+ return similarity_scores
MTMC_Tracking_2024/eval/trackeval/datasets/test_mot.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import configparser
4
+ import numpy as np
5
+ from scipy.optimize import linear_sum_assignment
6
+ from trackeval import utils
7
+ from trackeval import _timing
8
+ from trackeval.utils import TrackEvalException
9
+ from trackeval.datasets._base_dataset import _BaseDataset
10
+
11
+
12
+ class MotChallenge2DLocation(_BaseDataset):
13
+ """
14
+ Dataset class for MOT Challenge 2D bounding box tracking
15
+
16
+ :param dict config: configuration for the app
17
+ ::
18
+
19
+ default_dataset = trackeeval.datasets.MotChallenge2DBox(config)
20
+ """
21
+ @staticmethod
22
+ def get_default_dataset_config():
23
+ """Default class config values"""
24
+ code_path = utils.get_code_path()
25
+ default_config = {
26
+ 'GT_FOLDER': os.path.join(code_path, 'data/gt/mot_challenge/'), # Location of GT data
27
+ 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/mot_challenge/'), # Trackers location
28
+ 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
29
+ 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder)
30
+ 'CLASSES_TO_EVAL': ['pedestrian'], # Valid: ['pedestrian']
31
+ 'BENCHMARK': 'MOT17', # Valid: 'MOT17', 'MOT16', 'MOT20', 'MOT15'
32
+ 'SPLIT_TO_EVAL': 'train', # Valid: 'train', 'test', 'all'
33
+ 'INPUT_AS_ZIP': False, # Whether tracker input files are zipped
34
+ 'PRINT_CONFIG': True, # Whether to print current config
35
+ 'DO_PREPROC': True, # Whether to perform preprocessing (never done for MOT15)
36
+ 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
37
+ 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
38
+ 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
39
+ 'SEQMAP_FOLDER': None, # Where seqmaps are found (if None, GT_FOLDER/seqmaps)
40
+ 'SEQMAP_FILE': None, # Directly specify seqmap file (if none use seqmap_folder/benchmark-split_to_eval)
41
+ 'SEQ_INFO': None, # If not None, directly specify sequences to eval and their number of timesteps
42
+ 'GT_LOC_FORMAT': '{gt_folder}/{seq}/gt/gt.txt', # '{gt_folder}/{seq}/gt/gt.txt'
43
+ 'SKIP_SPLIT_FOL': False, # If False, data is in GT_FOLDER/BENCHMARK-SPLIT_TO_EVAL/ and in
44
+ # TRACKERS_FOLDER/BENCHMARK-SPLIT_TO_EVAL/tracker/
45
+ # If True, then the middle 'benchmark-split' folder is skipped for both.
46
+ }
47
+ return default_config
48
+
49
+ def __init__(self, config=None):
50
+ """Initialise dataset, checking that all required files are present"""
51
+ super().__init__()
52
+ # Fill non-given config values with defaults
53
+ self.config = utils.init_config(config, self.get_default_dataset_config(), self.get_name())
54
+
55
+ self.benchmark = self.config['BENCHMARK']
56
+ gt_set = self.config['BENCHMARK'] + '-' + self.config['SPLIT_TO_EVAL']
57
+ self.gt_set = gt_set
58
+ if not self.config['SKIP_SPLIT_FOL']:
59
+ split_fol = gt_set
60
+ else:
61
+ split_fol = ''
62
+ self.gt_fol = os.path.join(self.config['GT_FOLDER'], split_fol)
63
+ self.tracker_fol = os.path.join(self.config['TRACKERS_FOLDER'], split_fol)
64
+ self.should_classes_combine = False
65
+ self.use_super_categories = False
66
+ self.data_is_zipped = self.config['INPUT_AS_ZIP']
67
+ self.do_preproc = self.config['DO_PREPROC']
68
+
69
+ self.output_fol = self.config['OUTPUT_FOLDER']
70
+ if self.output_fol is None:
71
+ self.output_fol = self.tracker_fol
72
+
73
+ self.tracker_sub_fol = self.config['TRACKER_SUB_FOLDER']
74
+ self.output_sub_fol = self.config['OUTPUT_SUB_FOLDER']
75
+
76
+ # Get classes to eval
77
+ self.valid_classes = ['pedestrian']
78
+ self.class_list = [cls.lower() if cls.lower() in self.valid_classes else None
79
+ for cls in self.config['CLASSES_TO_EVAL']]
80
+ if not all(self.class_list):
81
+ raise TrackEvalException('Attempted to evaluate an invalid class. Only pedestrian class is valid.')
82
+ self.class_name_to_class_id = {'pedestrian': 1, 'person_on_vehicle': 2, 'car': 3, 'bicycle': 4, 'motorbike': 5,
83
+ 'non_mot_vehicle': 6, 'static_person': 7, 'distractor': 8, 'occluder': 9,
84
+ 'occluder_on_ground': 10, 'occluder_full': 11, 'reflection': 12, 'crowd': 13}
85
+ self.valid_class_numbers = list(self.class_name_to_class_id.values())
86
+
87
+ # Get sequences to eval and check gt files exist
88
+ self.seq_list, self.seq_lengths = self._get_seq_info()
89
+ if len(self.seq_list) < 1:
90
+ raise TrackEvalException('No sequences are selected to be evaluated.')
91
+
92
+ # Check gt files exist
93
+ for seq in self.seq_list:
94
+ if not self.data_is_zipped:
95
+ curr_file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq)
96
+ if not os.path.isfile(curr_file):
97
+ print('GT file not found ' + curr_file)
98
+ raise TrackEvalException('GT file not found for sequence: ' + seq)
99
+ if self.data_is_zipped:
100
+ curr_file = os.path.join(self.gt_fol, 'data.zip')
101
+ if not os.path.isfile(curr_file):
102
+ print('GT file not found ' + curr_file)
103
+ raise TrackEvalException('GT file not found: ' + os.path.basename(curr_file))
104
+
105
+ # Get trackers to eval
106
+ if self.config['TRACKERS_TO_EVAL'] is None:
107
+ self.tracker_list = os.listdir(self.tracker_fol)
108
+ else:
109
+ self.tracker_list = self.config['TRACKERS_TO_EVAL']
110
+
111
+ if self.config['TRACKER_DISPLAY_NAMES'] is None:
112
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list))
113
+ elif (self.config['TRACKERS_TO_EVAL'] is not None) and (
114
+ len(self.config['TRACKER_DISPLAY_NAMES']) == len(self.tracker_list)):
115
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.config['TRACKER_DISPLAY_NAMES']))
116
+ else:
117
+ raise TrackEvalException('List of tracker files and tracker display names do not match.')
118
+
119
+ for tracker in self.tracker_list:
120
+ if self.data_is_zipped:
121
+ curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip')
122
+ if not os.path.isfile(curr_file):
123
+ print('Tracker file not found: ' + curr_file)
124
+ raise TrackEvalException('Tracker file not found: ' + tracker + '/' + os.path.basename(curr_file))
125
+ else:
126
+ for seq in self.seq_list:
127
+ curr_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
128
+ if not os.path.isfile(curr_file):
129
+ print('Tracker file not found: ' + curr_file)
130
+ raise TrackEvalException(
131
+ 'Tracker file not found: ' + tracker + '/' + self.tracker_sub_fol + '/' + os.path.basename(
132
+ curr_file))
133
+
134
+ def get_display_name(self, tracker):
135
+ """
136
+ Gets the display name of the tracker
137
+
138
+ :param str tracker: Class of tracker
139
+ :return: str
140
+ ::
141
+
142
+ dataset.get_display_name(tracker)
143
+ """
144
+
145
+ return self.tracker_to_disp[tracker]
146
+
147
+ def _get_seq_info(self):
148
+ seq_list = []
149
+ seq_lengths = {}
150
+ if self.config["SEQ_INFO"]:
151
+ seq_list = list(self.config["SEQ_INFO"].keys())
152
+ seq_lengths = self.config["SEQ_INFO"]
153
+
154
+ # If sequence length is 'None' tries to read sequence length from .ini files.
155
+ for seq, seq_length in seq_lengths.items():
156
+ if seq_length is None:
157
+ ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini')
158
+ if not os.path.isfile(ini_file):
159
+ raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file))
160
+ ini_data = configparser.ConfigParser()
161
+ ini_data.read(ini_file)
162
+ seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
163
+
164
+ else:
165
+ if self.config["SEQMAP_FILE"]:
166
+ seqmap_file = self.config["SEQMAP_FILE"]
167
+ else:
168
+ if self.config["SEQMAP_FOLDER"] is None:
169
+ seqmap_file = os.path.join(self.config['GT_FOLDER'], 'seqmaps', self.gt_set + '.txt')
170
+ else:
171
+ seqmap_file = os.path.join(self.config["SEQMAP_FOLDER"], self.gt_set + '.txt')
172
+ if not os.path.isfile(seqmap_file):
173
+ print('no seqmap found: ' + seqmap_file)
174
+ raise TrackEvalException('no seqmap found: ' + os.path.basename(seqmap_file))
175
+ with open(seqmap_file) as fp:
176
+ reader = csv.reader(fp)
177
+ for i, row in enumerate(reader):
178
+ if i == 0 or row[0] == '':
179
+ continue
180
+ seq = row[0]
181
+ seq_list.append(seq)
182
+ ini_file = os.path.join(self.gt_fol, seq, 'seqinfo.ini')
183
+ if not os.path.isfile(ini_file):
184
+ raise TrackEvalException('ini file does not exist: ' + seq + '/' + os.path.basename(ini_file))
185
+ ini_data = configparser.ConfigParser()
186
+ ini_data.read(ini_file)
187
+ seq_lengths[seq] = int(float(ini_data['Sequence']['seqLength']))
188
+ return seq_list, seq_lengths
189
+
190
+ def _load_raw_file(self, tracker, seq, is_gt):
191
+ """Load a file (gt or tracker) in the MOT Challenge 2D box format
192
+
193
+ If is_gt, this returns a dict which contains the fields:
194
+ [gt_ids, gt_classes] : list (for each timestep) of 1D NDArrays (for each det).
195
+ [gt_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections.
196
+ [gt_extras] : list (for each timestep) of dicts (for each extra) of 1D NDArrays (for each det).
197
+
198
+ if not is_gt, this returns a dict which contains the fields:
199
+ [tracker_ids, tracker_classes, tracker_confidences] : list (for each timestep) of 1D NDArrays (for each det).
200
+ [tracker_dets]: list (for each timestep) of lists of detections.
201
+
202
+ :param str tracker: Name of the tracker.
203
+ :param str seq: Sequence identifier.
204
+ :param bool is_gt: Indicates whether the file is ground truth or from a tracker.
205
+ :raises TrackEvalException: If there's an error loading the file or if the data is corrupted.
206
+ :return: dictionary containing the loaded data.
207
+ :rtype: dict
208
+ """
209
+ # File location
210
+ if self.data_is_zipped:
211
+ if is_gt:
212
+ zip_file = os.path.join(self.gt_fol, 'data.zip')
213
+ else:
214
+ zip_file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol + '.zip')
215
+ file = seq + '.txt'
216
+ else:
217
+ zip_file = None
218
+ if is_gt:
219
+ file = self.config["GT_LOC_FORMAT"].format(gt_folder=self.gt_fol, seq=seq)
220
+ else:
221
+ file = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol, seq + '.txt')
222
+
223
+ # Load raw data from text file
224
+ read_data, ignore_data = self._load_simple_text_file(file, is_zipped=self.data_is_zipped, zip_file=zip_file)
225
+
226
+ # Convert data to required format
227
+ num_timesteps = self.seq_lengths[seq]
228
+ data_keys = ['ids', 'classes', 'dets']
229
+ if is_gt:
230
+ data_keys += ['gt_crowd_ignore_regions', 'gt_extras']
231
+ else:
232
+ data_keys += ['tracker_confidences']
233
+ raw_data = {key: [None] * num_timesteps for key in data_keys}
234
+
235
+ # Check for any extra time keys
236
+ current_time_keys = [str( t+ 1) for t in range(num_timesteps)]
237
+ extra_time_keys = [x for x in read_data.keys() if x not in current_time_keys]
238
+ if len(extra_time_keys) > 0:
239
+ if is_gt:
240
+ text = 'Ground-truth'
241
+ else:
242
+ text = 'Tracking'
243
+ raise TrackEvalException(
244
+ text + ' data contains the following invalid timesteps in seq %s: ' % seq + ', '.join(
245
+ [str(x) + ', ' for x in extra_time_keys]))
246
+
247
+ for t in range(num_timesteps):
248
+ time_key = str(t+1)
249
+ if time_key in read_data.keys():
250
+ try:
251
+ time_data = np.asarray(read_data[time_key], dtype=float)
252
+ except ValueError:
253
+ if is_gt:
254
+ raise TrackEvalException(
255
+ 'Cannot convert gt data for sequence %s to float. Is data corrupted?' % seq)
256
+ else:
257
+ raise TrackEvalException(
258
+ 'Cannot convert tracking data from tracker %s, sequence %s to float. Is data corrupted?' % (
259
+ tracker, seq))
260
+ try:
261
+ if is_gt:
262
+ raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9])
263
+ else:
264
+ raw_data['dets'][t] = np.atleast_2d(time_data[:, 7:9])
265
+ raw_data['ids'][t] = np.atleast_1d(time_data[:, 1]).astype(int)
266
+ except IndexError:
267
+ if is_gt:
268
+ err = 'Cannot load gt data from sequence %s, because there is not enough ' \
269
+ 'columns in the data.' % seq
270
+ raise TrackEvalException(err)
271
+ else:
272
+ err = 'Cannot load tracker data from tracker %s, sequence %s, because there is not enough ' \
273
+ 'columns in the data.' % (tracker, seq)
274
+ raise TrackEvalException(err)
275
+ if time_data.shape[1] >= 8:
276
+ raw_data['classes'][t] = np.ones_like(raw_data['ids'][t])
277
+ # raw_data['classes'][t] = np.atleast_1d(time_data[:, 7]).astype(int)
278
+ else:
279
+ if not is_gt:
280
+ raw_data['classes'][t] = np.ones_like(raw_data['ids'][t])
281
+ else:
282
+ raise TrackEvalException(
283
+ 'GT data is not in a valid format, there is not enough rows in seq %s, timestep %i.' % (
284
+ seq, t))
285
+ if is_gt:
286
+ gt_extras_dict = {'zero_marked': np.atleast_1d(time_data[:, 6].astype(int))}
287
+ raw_data['gt_extras'][t] = gt_extras_dict
288
+ else:
289
+ raw_data['tracker_confidences'][t] = np.atleast_1d(time_data[:, 6])
290
+ else:
291
+ raw_data['dets'][t] = np.empty((0, 4))
292
+ raw_data['ids'][t] = np.empty(0).astype(int)
293
+ raw_data['classes'][t] = np.empty(0).astype(int)
294
+ if is_gt:
295
+ gt_extras_dict = {'zero_marked': np.empty(0)}
296
+ raw_data['gt_extras'][t] = gt_extras_dict
297
+ else:
298
+ raw_data['tracker_confidences'][t] = np.empty(0)
299
+ if is_gt:
300
+ raw_data['gt_crowd_ignore_regions'][t] = np.empty((0, 4))
301
+
302
+ if is_gt:
303
+ key_map = {'ids': 'gt_ids',
304
+ 'classes': 'gt_classes',
305
+ 'dets': 'gt_dets'}
306
+ else:
307
+ key_map = {'ids': 'tracker_ids',
308
+ 'classes': 'tracker_classes',
309
+ 'dets': 'tracker_dets'}
310
+ for k, v in key_map.items():
311
+ raw_data[v] = raw_data.pop(k)
312
+ raw_data['num_timesteps'] = num_timesteps
313
+ raw_data['seq'] = seq
314
+ return raw_data
315
+
316
+ @_timing.time
317
+ def get_preprocessed_seq_data(self, raw_data, cls):
318
+ """ Preprocess data for a single sequence for a single class ready for evaluation.
319
+ Inputs:
320
+ - raw_data is a dict containing the data for the sequence already read in by get_raw_seq_data().
321
+ - cls is the class to be evaluated.
322
+ Outputs:
323
+ - data is a dict containing all of the information that metrics need to perform evaluation.
324
+ It contains the following fields:
325
+ [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets] : integers.
326
+ [gt_ids, tracker_ids, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det).
327
+ [gt_dets, tracker_dets]: list (for each timestep) of lists of detections.
328
+ [similarity_scores]: list (for each timestep) of 2D NDArrays.
329
+ Notes:
330
+ General preprocessing (preproc) occurs in 4 steps. Some datasets may not use all of these steps.
331
+ 1) Extract only detections relevant for the class to be evaluated (including distractor detections).
332
+ 2) Match gt dets and tracker dets. Remove tracker dets that are matched to a gt det that is of a
333
+ distractor class, or otherwise marked as to be removed.
334
+ 3) Remove unmatched tracker dets if they fall within a crowd ignore region or don't meet a certain
335
+ other criteria (e.g. are too small).
336
+ 4) Remove gt dets that were only useful for preprocessing and not for actual evaluation.
337
+ After the above preprocessing steps, this function also calculates the number of gt and tracker detections
338
+ and unique track ids. It also relabels gt and tracker ids to be contiguous and checks that ids are
339
+ unique within each timestep.
340
+
341
+ MOT Challenge:
342
+ In MOT Challenge, the 4 preproc steps are as follow:
343
+ 1) There is only one class (pedestrian) to be evaluated, but all other classes are used for preproc.
344
+ 2) Predictions are matched against all gt boxes (regardless of class), those matching with distractor
345
+ objects are removed.
346
+ 3) There is no crowd ignore regions.
347
+ 4) All gt dets except pedestrian are removed, also removes pedestrian gt dets marked with zero_marked.
348
+
349
+ :param raw_data: A dict containing the data for the sequence already read in by `get_raw_seq_data()`.
350
+ :param cls: The class to be evaluated.
351
+
352
+ :return: A dict containing all of the information that metrics need to perform evaluation.
353
+ It contains the following fields:
354
+ - [num_timesteps, num_gt_ids, num_tracker_ids, num_gt_dets, num_tracker_dets]: Integers.
355
+ - [gt_ids, tracker_ids, tracker_confidences]: List (for each timestep) of 1D NDArrays (for each detection).
356
+ - [gt_dets, tracker_dets]: List (for each timestep) of lists of detections.
357
+ - [similarity_scores]: List (for each timestep) of 2D NDArrays.
358
+
359
+ """
360
+ # Check that input data has unique ids
361
+ self._check_unique_ids(raw_data)
362
+
363
+ distractor_class_names = ['person_on_vehicle', 'static_person', 'distractor', 'reflection']
364
+ if self.benchmark == 'MOT20':
365
+ distractor_class_names.append('non_mot_vehicle')
366
+ distractor_classes = [self.class_name_to_class_id[x] for x in distractor_class_names]
367
+ cls_id = self.class_name_to_class_id[cls]
368
+
369
+ data_keys = ['gt_ids', 'tracker_ids', 'gt_dets', 'tracker_dets', 'tracker_confidences', 'similarity_scores']
370
+ data = {key: [None] * raw_data['num_timesteps'] for key in data_keys}
371
+ unique_gt_ids = []
372
+ unique_tracker_ids = []
373
+ num_gt_dets = 0
374
+ num_tracker_dets = 0
375
+ for t in range(raw_data['num_timesteps']):
376
+
377
+ # Get all data
378
+ gt_ids = raw_data['gt_ids'][t]
379
+ gt_dets = raw_data['gt_dets'][t]
380
+ gt_classes = raw_data['gt_classes'][t]
381
+ gt_zero_marked = raw_data['gt_extras'][t]['zero_marked']
382
+
383
+ tracker_ids = raw_data['tracker_ids'][t]
384
+ tracker_dets = raw_data['tracker_dets'][t]
385
+ tracker_classes = raw_data['tracker_classes'][t]
386
+ tracker_confidences = raw_data['tracker_confidences'][t]
387
+ similarity_scores = raw_data['similarity_scores'][t]
388
+
389
+ # Evaluation is ONLY valid for pedestrian class
390
+ if len(tracker_classes) > 0 and np.max(tracker_classes) > 1:
391
+ raise TrackEvalException(
392
+ 'Evaluation is only valid for pedestrian class. Non pedestrian class (%i) found in sequence %s at '
393
+ 'timestep %i.' % (np.max(tracker_classes), raw_data['seq'], t))
394
+
395
+ # Match tracker and gt dets (with hungarian algorithm) and remove tracker dets which match with gt dets
396
+ # which are labeled as belonging to a distractor class.
397
+ to_remove_tracker = np.array([], int)
398
+ if self.do_preproc and self.benchmark != 'MOT15' and gt_ids.shape[0] > 0 and tracker_ids.shape[0] > 0:
399
+
400
+ # Check all classes are valid:
401
+ invalid_classes = np.setdiff1d(np.unique(gt_classes), self.valid_class_numbers)
402
+ if len(invalid_classes) > 0:
403
+ print(' '.join([str(x) for x in invalid_classes]))
404
+ raise(TrackEvalException('Attempting to evaluate using invalid gt classes. '
405
+ 'This warning only triggers if preprocessing is performed, '
406
+ 'e.g. not for MOT15 or where prepropressing is explicitly disabled. '
407
+ 'Please either check your gt data, or disable preprocessing. '
408
+ 'The following invalid classes were found in timestep ' + str(t) + ': ' +
409
+ ' '.join([str(x) for x in invalid_classes])))
410
+
411
+ matching_scores = similarity_scores.copy()
412
+ matching_scores[matching_scores < 0.5 - np.finfo('float').eps] = 0
413
+ match_rows, match_cols = linear_sum_assignment(-matching_scores)
414
+ actually_matched_mask = matching_scores[match_rows, match_cols] > 0 + np.finfo('float').eps
415
+ match_rows = match_rows[actually_matched_mask]
416
+ match_cols = match_cols[actually_matched_mask]
417
+
418
+ is_distractor_class = np.isin(gt_classes[match_rows], distractor_classes)
419
+ to_remove_tracker = match_cols[is_distractor_class]
420
+
421
+ # Apply preprocessing to remove all unwanted tracker dets.
422
+ data['tracker_ids'][t] = np.delete(tracker_ids, to_remove_tracker, axis=0)
423
+ data['tracker_dets'][t] = np.delete(tracker_dets, to_remove_tracker, axis=0)
424
+ data['tracker_confidences'][t] = np.delete(tracker_confidences, to_remove_tracker, axis=0)
425
+ similarity_scores = np.delete(similarity_scores, to_remove_tracker, axis=1)
426
+
427
+ # Remove gt detections marked as to remove (zero marked), and also remove gt detections not in pedestrian
428
+ # class (not applicable for MOT15)
429
+ if self.do_preproc and self.benchmark != 'MOT15':
430
+ gt_to_keep_mask = (np.not_equal(gt_zero_marked, 0)) & \
431
+ (np.equal(gt_classes, cls_id))
432
+ else:
433
+ # There are no classes for MOT15
434
+ gt_to_keep_mask = np.not_equal(gt_zero_marked, 0)
435
+ data['gt_ids'][t] = gt_ids[gt_to_keep_mask]
436
+ data['gt_dets'][t] = gt_dets[gt_to_keep_mask, :]
437
+ data['similarity_scores'][t] = similarity_scores[gt_to_keep_mask]
438
+
439
+ unique_gt_ids += list(np.unique(data['gt_ids'][t]))
440
+ unique_tracker_ids += list(np.unique(data['tracker_ids'][t]))
441
+ num_tracker_dets += len(data['tracker_ids'][t])
442
+ num_gt_dets += len(data['gt_ids'][t])
443
+
444
+ # Re-label IDs such that there are no empty IDs
445
+ if len(unique_gt_ids) > 0:
446
+ unique_gt_ids = np.unique(unique_gt_ids)
447
+ gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1))
448
+ gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids))
449
+ for t in range(raw_data['num_timesteps']):
450
+ if len(data['gt_ids'][t]) > 0:
451
+ data['gt_ids'][t] = gt_id_map[data['gt_ids'][t]].astype(int)
452
+ if len(unique_tracker_ids) > 0:
453
+ unique_tracker_ids = np.unique(unique_tracker_ids)
454
+ tracker_id_map = np.nan * np.ones((np.max(unique_tracker_ids) + 1))
455
+ tracker_id_map[unique_tracker_ids] = np.arange(len(unique_tracker_ids))
456
+ for t in range(raw_data['num_timesteps']):
457
+ if len(data['tracker_ids'][t]) > 0:
458
+ data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(int)
459
+
460
+ # Record overview statistics.
461
+ data['num_tracker_dets'] = num_tracker_dets
462
+ data['num_gt_dets'] = num_gt_dets
463
+ data['num_tracker_ids'] = len(unique_tracker_ids)
464
+ data['num_gt_ids'] = len(unique_gt_ids)
465
+ data['num_timesteps'] = raw_data['num_timesteps']
466
+ data['seq'] = raw_data['seq']
467
+
468
+ # Ensure again that ids are unique per timestep after preproc.
469
+ self._check_unique_ids(data, after_preproc=True)
470
+
471
+ return data
472
+
473
+ def _calculate_similarities(self, gt_dets_t, tracker_dets_t):
474
+ similarity_scores = self._calculate_euclidean_similarity(gt_dets_t, tracker_dets_t)
475
+ return similarity_scores
MTMC_Tracking_2024/eval/trackeval/eval.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import logging
3
+ import traceback
4
+ from multiprocessing.pool import Pool
5
+ from functools import partial
6
+ import os
7
+ from . import utils
8
+ from .utils import TrackEvalException
9
+ from . import _timing
10
+ from .metrics import Count
11
+
12
+
13
+ class Evaluator:
14
+ """
15
+ Evaluator class for evaluating different metrics for different datasets
16
+
17
+ :param dict config: configuration for the app
18
+ ::
19
+
20
+ evaluator = Evaluator(config)
21
+ """
22
+
23
+ @staticmethod
24
+ def get_default_eval_config():
25
+ """Returns the default config values for evaluation"""
26
+ code_path = utils.get_code_path()
27
+ default_config = {
28
+ 'USE_PARALLEL': False,
29
+ 'NUM_PARALLEL_CORES': 8,
30
+ 'BREAK_ON_ERROR': True, # Raises exception and exits with error
31
+ 'RETURN_ON_ERROR': False, # if not BREAK_ON_ERROR, then returns from function on error
32
+ 'LOG_ON_ERROR': os.path.join(code_path, 'error_log.txt'), # if not None, save any errors into a log file.
33
+
34
+ 'PRINT_RESULTS': True,
35
+ 'PRINT_ONLY_COMBINED': False,
36
+ 'PRINT_CONFIG': True,
37
+ 'TIME_PROGRESS': True,
38
+ 'DISPLAY_LESS_PROGRESS': True,
39
+
40
+ 'OUTPUT_SUMMARY': True,
41
+ 'OUTPUT_EMPTY_CLASSES': True, # If False, summary files are not output for classes with no detections
42
+ 'OUTPUT_DETAILED': True,
43
+ 'PLOT_CURVES': True,
44
+ }
45
+ return default_config
46
+
47
+ def __init__(self, config=None):
48
+ self.config = utils.init_config(config, self.get_default_eval_config(), 'Eval')
49
+ # Only run timing analysis if not run in parallel.
50
+ if self.config['TIME_PROGRESS'] and not self.config['USE_PARALLEL']:
51
+ _timing.DO_TIMING = True
52
+ if self.config['DISPLAY_LESS_PROGRESS']:
53
+ _timing.DISPLAY_LESS_PROGRESS = True
54
+
55
+ @_timing.time
56
+ def evaluate(self, dataset_list, metrics_list):
57
+ """
58
+ Evaluate a list of datasets with a list of metrics
59
+
60
+ :param List[str] dataset_list: list of all datasets
61
+ :param List[str] metrics_list: list of all metrics
62
+
63
+ :return: str output_res: results of the evaluation
64
+ :return: str output_msg: status of the evaluation
65
+
66
+ ::
67
+
68
+ trackeval.eval.evaluate(dataset_list, metrics_list)
69
+ """
70
+ config = self.config
71
+ metrics_list = metrics_list + [Count()] # Count metrics are always run
72
+ metric_names = utils.validate_metrics_list(metrics_list)
73
+ dataset_names = [dataset.get_name() for dataset in dataset_list]
74
+ output_res = {}
75
+ output_msg = {}
76
+
77
+ for dataset, dataset_name in zip(dataset_list, dataset_names):
78
+ # Get dataset info about what to evaluate
79
+ output_res[dataset_name] = {}
80
+ output_msg[dataset_name] = {}
81
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
82
+ logging.info('Evaluating %i tracker(s) on %i sequence(s) for %i class(es) on %s dataset using the following '
83
+ 'metrics: %s\n' % (len(tracker_list), len(seq_list), len(class_list), dataset_name,
84
+ ', '.join(metric_names)))
85
+
86
+ # Evaluate each tracker
87
+ for tracker in tracker_list:
88
+ # if not config['BREAK_ON_ERROR'] then go to next tracker without breaking
89
+ try:
90
+ # Evaluate each sequence in parallel or in series.
91
+ # returns a nested dict (res), indexed like: res[seq][class][metric_name][sub_metric field]
92
+ # e.g. res[seq_0001][pedestrian][hota][DetA]
93
+ logging.info('Evaluating %s\n' % tracker)
94
+ time_start = time.time()
95
+ if config['USE_PARALLEL']:
96
+ with Pool(config['NUM_PARALLEL_CORES']) as pool:
97
+ _eval_sequence = partial(eval_sequence, dataset=dataset, tracker=tracker,
98
+ class_list=class_list, metrics_list=metrics_list,
99
+ metric_names=metric_names)
100
+ results = pool.map(_eval_sequence, seq_list)
101
+ res = dict(zip(seq_list, results))
102
+ else:
103
+ res = {}
104
+ for curr_seq in sorted(seq_list):
105
+ res[curr_seq] = eval_sequence(curr_seq, dataset, tracker, class_list, metrics_list,
106
+ metric_names)
107
+
108
+ # Combine results over all sequences and then over all classes
109
+
110
+ # collecting combined cls keys (cls averaged, det averaged, super classes)
111
+ combined_cls_keys = []
112
+ res['COMBINED_SEQ'] = {}
113
+ # combine sequences for each class
114
+ for c_cls in class_list:
115
+ res['COMBINED_SEQ'][c_cls] = {}
116
+ for metric, metric_name in zip(metrics_list, metric_names):
117
+ curr_res = {seq_key: seq_value[c_cls][metric_name] for seq_key, seq_value in res.items() if
118
+ seq_key != 'COMBINED_SEQ'}
119
+ # print(curr_res)
120
+ res['COMBINED_SEQ'][c_cls][metric_name] = metric.combine_sequences(curr_res)
121
+ # print(res['COMBINED_SEQ'][c_cls][metric_name])
122
+ # combine classes
123
+ if dataset.should_classes_combine:
124
+ combined_cls_keys += ['cls_comb_cls_av', 'cls_comb_det_av', 'all']
125
+ res['COMBINED_SEQ']['cls_comb_cls_av'] = {}
126
+ res['COMBINED_SEQ']['cls_comb_det_av'] = {}
127
+ for metric, metric_name in zip(metrics_list, metric_names):
128
+ cls_res = {cls_key: cls_value[metric_name] for cls_key, cls_value in
129
+ res['COMBINED_SEQ'].items() if cls_key not in combined_cls_keys}
130
+ res['COMBINED_SEQ']['cls_comb_cls_av'][metric_name] = \
131
+ metric.combine_classes_class_averaged(cls_res)
132
+ res['COMBINED_SEQ']['cls_comb_det_av'][metric_name] = \
133
+ metric.combine_classes_det_averaged(cls_res)
134
+ # combine classes to super classes
135
+ if dataset.use_super_categories:
136
+ for cat, sub_cats in dataset.super_categories.items():
137
+ combined_cls_keys.append(cat)
138
+ res['COMBINED_SEQ'][cat] = {}
139
+ for metric, metric_name in zip(metrics_list, metric_names):
140
+ cat_res = {cls_key: cls_value[metric_name] for cls_key, cls_value in
141
+ res['COMBINED_SEQ'].items() if cls_key in sub_cats}
142
+ res['COMBINED_SEQ'][cat][metric_name] = metric.combine_classes_det_averaged(cat_res)
143
+
144
+ # Print and output results in various formats
145
+ if config['TIME_PROGRESS']:
146
+ logging.info('All sequences for %s finished in %.2f seconds' % (tracker, time.time() - time_start))
147
+ output_fol = dataset.get_output_fol(tracker)
148
+ tracker_display_name = dataset.get_display_name(tracker)
149
+ for c_cls in res['COMBINED_SEQ'].keys(): # class_list + combined classes if calculated
150
+ summaries = []
151
+ details = []
152
+ num_dets = res['COMBINED_SEQ'][c_cls]['Count']['Dets']
153
+ if config['OUTPUT_EMPTY_CLASSES'] or num_dets > 0:
154
+ for metric, metric_name in zip(metrics_list, metric_names):
155
+ # for combined classes there is no per sequence evaluation
156
+ if c_cls in combined_cls_keys:
157
+ table_res = {'COMBINED_SEQ': res['COMBINED_SEQ'][c_cls][metric_name]}
158
+ else:
159
+ table_res = {seq_key: seq_value[c_cls][metric_name] for seq_key, seq_value
160
+ in res.items()}
161
+
162
+ if config['PRINT_RESULTS'] and config['PRINT_ONLY_COMBINED']:
163
+ dont_print = dataset.should_classes_combine and c_cls not in combined_cls_keys
164
+ if not dont_print:
165
+ metric.print_table({'COMBINED_SEQ': table_res['COMBINED_SEQ']},
166
+ tracker_display_name, c_cls)
167
+ elif config['PRINT_RESULTS']:
168
+ # print(table_res['FINAL'])
169
+ metric.print_table(table_res, tracker_display_name, c_cls)
170
+ if config['OUTPUT_SUMMARY']:
171
+ summaries.append(metric.summary_results(table_res))
172
+ if config['OUTPUT_DETAILED']:
173
+ details.append(metric.detailed_results(table_res))
174
+ if config['PLOT_CURVES']:
175
+ metric.plot_single_tracker_results(table_res, tracker_display_name, c_cls,
176
+ output_fol)
177
+ if config['OUTPUT_SUMMARY']:
178
+ utils.write_summary_results(summaries, c_cls, output_fol)
179
+ if config['OUTPUT_DETAILED']:
180
+ utils.write_detailed_results(details, c_cls, output_fol)
181
+
182
+ # Output for returning from function
183
+ output_res[dataset_name][tracker] = res
184
+ output_msg[dataset_name][tracker] = 'Success'
185
+
186
+ except Exception as err:
187
+ output_res[dataset_name][tracker] = None
188
+ if type(err) == TrackEvalException:
189
+ output_msg[dataset_name][tracker] = str(err)
190
+ else:
191
+ output_msg[dataset_name][tracker] = 'Unknown error occurred.'
192
+ logging.info('Tracker %s was unable to be evaluated.' % tracker)
193
+ logging.error(err)
194
+ traceback.print_exc()
195
+ if config['LOG_ON_ERROR'] is not None:
196
+ with open(config['LOG_ON_ERROR'], 'a') as f:
197
+ logging.info(dataset_name, file=f)
198
+ logging.info(tracker, file=f)
199
+ logging.info(traceback.format_exc(), file=f)
200
+ logging.info('\n\n\n', file=f)
201
+ if config['BREAK_ON_ERROR']:
202
+ raise err
203
+ elif config['RETURN_ON_ERROR']:
204
+ return output_res, output_msg
205
+
206
+ return output_res, output_msg
207
+
208
+
209
+ @_timing.time
210
+ def eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names):
211
+ """
212
+ Function for evaluating a single sequence
213
+
214
+ :param str seq: name of the sequence
215
+ :param str dataset: name of the dataset
216
+ :param str tracker: name of the tracker
217
+ :param List[str] class_list: list of all classes to be evaluated
218
+ :param List[str] metrics_list: list of all metrics
219
+ :param List[str] metric_names: list of all metrics names
220
+
221
+ :return: Dict[str] seq_res: results of the eval sequence
222
+ ::
223
+
224
+ trackeval.eval.eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names)
225
+ """
226
+ raw_data = dataset.get_raw_seq_data(tracker, seq)
227
+ seq_res = {}
228
+ for cls in class_list:
229
+ seq_res[cls] = {}
230
+ data = dataset.get_preprocessed_seq_data(raw_data, cls)
231
+ for metric, met_name in zip(metrics_list, metric_names):
232
+ seq_res[cls][met_name] = metric.eval_sequence(data)
233
+ return seq_res
MTMC_Tracking_2024/eval/trackeval/metrics/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """MTMC analytics hota-metrics submodules"""
2
+ from .hota import HOTA
3
+ from .clear import CLEAR
4
+ from .identity import Identity
5
+ from .count import Count
MTMC_Tracking_2024/eval/trackeval/metrics/_base_metric.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from abc import ABC, abstractmethod
3
+ from trackeval import _timing
4
+ from trackeval.utils import TrackEvalException
5
+
6
+
7
+ class _BaseMetric(ABC):
8
+ @abstractmethod
9
+ def __init__(self):
10
+ self.plottable = False
11
+ self.integer_fields = []
12
+ self.float_fields = []
13
+ self.array_labels = []
14
+ self.integer_array_fields = []
15
+ self.float_array_fields = []
16
+ self.fields = []
17
+ self.summary_fields = []
18
+ self.registered = False
19
+
20
+ #####################################################################
21
+ # Abstract functions for subclasses to implement
22
+
23
+ @_timing.time
24
+ @abstractmethod
25
+ def eval_sequence(self, data):
26
+ ...
27
+
28
+ @abstractmethod
29
+ def combine_sequences(self, all_res):
30
+ ...
31
+
32
+ @abstractmethod
33
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False):
34
+ ...
35
+
36
+ @ abstractmethod
37
+ def combine_classes_det_averaged(self, all_res):
38
+ ...
39
+
40
+ def plot_single_tracker_results(self, all_res, tracker, output_folder, cls):
41
+ """
42
+ Plot results of metrics, only valid for metrics with self.plottable
43
+
44
+ :param Dict all_res: dictionary containing all results
45
+ :param str tracker: The tracker to plot results for
46
+ :param str output_folder: The output folder for saving the plots
47
+ :param str cls: The class to plot results for
48
+
49
+ :raises NotImplementedError: If the metric does not have self.plottable
50
+
51
+ """
52
+ if self.plottable:
53
+ raise NotImplementedError('plot_results is not implemented for metric %s' % self.get_name())
54
+ else:
55
+ pass
56
+
57
+ #####################################################################
58
+ # Helper functions which are useful for all metrics:
59
+
60
+ @classmethod
61
+ def get_name(cls):
62
+ return cls.__name__
63
+
64
+ @staticmethod
65
+ def _combine_sum(all_res, field):
66
+ """
67
+ Combine sequence results via sum
68
+
69
+ :param Dict all_res: dictionary containing sequence results
70
+ :param str field: The field to be combined
71
+ :return: The sum of the combined results
72
+ :rtype: float
73
+ """
74
+ return sum([all_res[k][field] for k in all_res.keys()])
75
+
76
+ @staticmethod
77
+ def _combine_weighted_av(all_res, field, comb_res, weight_field):
78
+ """
79
+ Combine sequence results via weighted average
80
+
81
+ :param Dict all_res: dictionary containing sequence results
82
+ :param str field: The field to be combined
83
+ :param Dict comb_res: dictionary containing combined results
84
+ :param str weight_field: The field representing the weight
85
+ :return: The weighted average of the combined results
86
+ :rtype: float
87
+ """
88
+ return sum([all_res[k][field] * all_res[k][weight_field] for k in all_res.keys()]) / np.maximum(1.0, comb_res[
89
+ weight_field])
90
+
91
+ def print_table(self, table_res, tracker, cls):
92
+ """
93
+ Prints table of results for all sequences
94
+
95
+ :param Dict table_res: dictionary containing the results for each sequence.
96
+ :param str tracker: The name of the tracker.
97
+ :param str cls: The name of the class.
98
+ :return None
99
+ """
100
+ print('')
101
+ metric_name = self.get_name()
102
+ self._row_print([metric_name + ': ' + tracker + '-' + cls] + self.summary_fields)
103
+ for seq, results in sorted(table_res.items()):
104
+ if seq == 'COMBINED_SEQ':
105
+ continue
106
+ # if seq == 'FINAL':
107
+ summary_res = self._summary_row(results)
108
+ self._row_print([seq] + summary_res)
109
+ summary_res = self._summary_row(table_res['COMBINED_SEQ'])
110
+ # self._row_print(['COMBINED'] + summary_res)
111
+
112
+ def _summary_row(self, results_):
113
+ """
114
+ Generate a summary row of values based on the provided results.
115
+ :param Dict results_: dictionary containing the metric results.
116
+
117
+ :return: A list of formatted values for the summary row.
118
+ :rtype: list
119
+ :raises NotImplementedError: If the summary function is not implemented for a field type.
120
+ """
121
+ vals = []
122
+ for h in self.summary_fields:
123
+ if h in self.float_array_fields:
124
+ vals.append("{0:1.5g}".format(100 * np.mean(results_[h])))
125
+ elif h in self.float_fields:
126
+ vals.append("{0:1.5g}".format(100 * float(results_[h])))
127
+ elif h in self.integer_fields:
128
+ vals.append("{0:d}".format(int(results_[h])))
129
+ else:
130
+ raise NotImplementedError("Summary function not implemented for this field type.")
131
+ return vals
132
+
133
+ @staticmethod
134
+ def _row_print(*argv):
135
+ """
136
+ Prints results in an evenly spaced rows, with more space in first row
137
+
138
+ :param argv: The values to be printed in each column of the row.
139
+ :type argv: tuple or list
140
+ """
141
+ if len(argv) == 1:
142
+ argv = argv[0]
143
+ to_print = '%-35s' % argv[0]
144
+ for v in argv[1:]:
145
+ to_print += '%-10s' % str(v)
146
+ print(to_print)
147
+
148
+ def summary_results(self, table_res):
149
+ """
150
+ Returns a simple summary of final results for a tracker
151
+
152
+ :param Dict table_res: The table of results containing per-sequence and combined sequence results.
153
+ :return: dictionary representing the summary of final results.
154
+ :rtype: Dict
155
+ """
156
+ return dict(zip(self.summary_fields, self._summary_row(table_res['COMBINED_SEQ'])))
157
+
158
+ def detailed_results(self, table_res):
159
+ """
160
+ Returns detailed final results for a tracker
161
+
162
+ :param Dict table_res: The table of results containing per-sequence and combined sequence results.
163
+ :return: Detailed results for each sequence as a dictionary of dictionaries.
164
+ :rtype: Dict
165
+ :raises TrackEvalException: If the field names and data have different sizes.
166
+ """
167
+ # Get detailed field information
168
+ detailed_fields = self.float_fields + self.integer_fields
169
+ for h in self.float_array_fields + self.integer_array_fields:
170
+ for alpha in [int(100*x) for x in self.array_labels]:
171
+ detailed_fields.append(h + '___' + str(alpha))
172
+ detailed_fields.append(h + '___AUC')
173
+
174
+ # Get detailed results
175
+ detailed_results = {}
176
+ for seq, res in table_res.items():
177
+ detailed_row = self._detailed_row(res)
178
+ if len(detailed_row) != len(detailed_fields):
179
+ raise TrackEvalException(
180
+ 'Field names and data have different sizes (%i and %i)' % (len(detailed_row), len(detailed_fields)))
181
+ detailed_results[seq] = dict(zip(detailed_fields, detailed_row))
182
+ return detailed_results
183
+
184
+ def _detailed_row(self, res):
185
+ """
186
+ Calculates a detailed row of results for a given set of metrics.
187
+
188
+ :param Dict res: The results containing the metrics.
189
+ :return: Detailed row of results.
190
+ :rtype: list
191
+ """
192
+ detailed_row = []
193
+ for h in self.float_fields + self.integer_fields:
194
+ detailed_row.append(res[h])
195
+ for h in self.float_array_fields + self.integer_array_fields:
196
+ for i, alpha in enumerate([int(100 * x) for x in self.array_labels]):
197
+ detailed_row.append(res[h][i])
198
+ detailed_row.append(np.mean(res[h]))
199
+ return detailed_row
MTMC_Tracking_2024/eval/trackeval/metrics/clear.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linear_sum_assignment
3
+ from ._base_metric import _BaseMetric
4
+ from trackeval import _timing
5
+ from trackeval import utils
6
+
7
+
8
+ class CLEAR(_BaseMetric):
9
+ """
10
+ Class which implements the CLEAR metrics
11
+
12
+ :param Dict config: configuration for the app
13
+ ::
14
+
15
+ identity = trackeval.metrics.CLEAR(config)
16
+ """
17
+
18
+ @staticmethod
19
+ def get_default_config():
20
+ """Default class config values"""
21
+ default_config = {
22
+ 'THRESHOLD': 0.5, # Similarity score threshold required for a TP match. Default 0.5.
23
+ 'PRINT_CONFIG': True, # Whether to print the config information on init. Default: False.
24
+ }
25
+ return default_config
26
+
27
+ def __init__(self, config=None):
28
+ super().__init__()
29
+ main_integer_fields = ['CLR_TP', 'CLR_FN', 'CLR_FP', 'IDSW', 'MT', 'PT', 'ML', 'Frag']
30
+ extra_integer_fields = ['CLR_Frames']
31
+ self.integer_fields = main_integer_fields + extra_integer_fields
32
+ main_float_fields = ['MOTA', 'MOTP', 'MODA', 'CLR_Re', 'CLR_Pr', 'MTR', 'PTR', 'MLR', 'sMOTA']
33
+ extra_float_fields = ['CLR_F1', 'FP_per_frame', 'MOTAL', 'MOTP_sum']
34
+ self.float_fields = main_float_fields + extra_float_fields
35
+ self.fields = self.float_fields + self.integer_fields
36
+ self.summed_fields = self.integer_fields + ['MOTP_sum']
37
+ self.summary_fields = main_float_fields + main_integer_fields
38
+
39
+ # Configuration options:
40
+ self.config = utils.init_config(config, self.get_default_config(), self.get_name())
41
+ self.threshold = float(self.config['THRESHOLD'])
42
+
43
+
44
+ @_timing.time
45
+ def eval_sequence(self, data):
46
+ """
47
+ Calculates CLEAR metrics for one sequence
48
+
49
+ :param Dict[str, float] data: dictionary containing the data for the sequence
50
+
51
+ :return: dictionary containing the calculated count metrics
52
+ :rtype: Dict[str, float]
53
+ """
54
+ # Initialise results
55
+ res = {}
56
+ for field in self.fields:
57
+ res[field] = 0
58
+
59
+ # Return result quickly if tracker or gt sequence is empty
60
+ if data['num_tracker_dets'] == 0:
61
+ res['CLR_FN'] = data['num_gt_dets']
62
+ res['ML'] = data['num_gt_ids']
63
+ res['MLR'] = 1.0
64
+ return res
65
+ if data['num_gt_dets'] == 0:
66
+ res['CLR_FP'] = data['num_tracker_dets']
67
+ res['MLR'] = 1.0
68
+ return res
69
+
70
+ # Variables counting global association
71
+ num_gt_ids = data['num_gt_ids']
72
+ gt_id_count = np.zeros(num_gt_ids) # For MT/ML/PT
73
+ gt_matched_count = np.zeros(num_gt_ids) # For MT/ML/PT
74
+ gt_frag_count = np.zeros(num_gt_ids) # For Frag
75
+
76
+ # Note that IDSWs are counted based on the last time each gt_id was present (any number of frames previously),
77
+ # but are only used in matching to continue current tracks based on the gt_id in the single previous timestep.
78
+ prev_tracker_id = np.nan * np.zeros(num_gt_ids) # For scoring IDSW
79
+ prev_timestep_tracker_id = np.nan * np.zeros(num_gt_ids) # For matching IDSW
80
+
81
+ # Calculate scores for each timestep
82
+ for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])):
83
+ # Deal with the case that there are no gt_det/tracker_det in a timestep.
84
+ if len(gt_ids_t) == 0:
85
+ res['CLR_FP'] += len(tracker_ids_t)
86
+ continue
87
+ if len(tracker_ids_t) == 0:
88
+ res['CLR_FN'] += len(gt_ids_t)
89
+ gt_id_count[gt_ids_t] += 1
90
+ continue
91
+
92
+ # Calc score matrix to first minimise IDSWs from previous frame, and then maximise MOTP secondarily
93
+ similarity = data['similarity_scores'][t]
94
+ score_mat = (tracker_ids_t[np.newaxis, :] == prev_timestep_tracker_id[gt_ids_t[:, np.newaxis]])
95
+ score_mat = 1000 * score_mat + similarity
96
+ score_mat[similarity < self.threshold - np.finfo('float').eps] = 0
97
+
98
+ # Hungarian algorithm to find best matches
99
+ match_rows, match_cols = linear_sum_assignment(-score_mat)
100
+ actually_matched_mask = score_mat[match_rows, match_cols] > 0 + np.finfo('float').eps
101
+ match_rows = match_rows[actually_matched_mask]
102
+ match_cols = match_cols[actually_matched_mask]
103
+
104
+ matched_gt_ids = gt_ids_t[match_rows]
105
+ matched_tracker_ids = tracker_ids_t[match_cols]
106
+
107
+ # Calc IDSW for MOTA
108
+ prev_matched_tracker_ids = prev_tracker_id[matched_gt_ids]
109
+ is_idsw = (np.logical_not(np.isnan(prev_matched_tracker_ids))) & (
110
+ np.not_equal(matched_tracker_ids, prev_matched_tracker_ids))
111
+ res['IDSW'] += np.sum(is_idsw)
112
+
113
+ # Update counters for MT/ML/PT/Frag and record for IDSW/Frag for next timestep
114
+ gt_id_count[gt_ids_t] += 1
115
+ gt_matched_count[matched_gt_ids] += 1
116
+ not_previously_tracked = np.isnan(prev_timestep_tracker_id)
117
+ prev_tracker_id[matched_gt_ids] = matched_tracker_ids
118
+ prev_timestep_tracker_id[:] = np.nan
119
+ prev_timestep_tracker_id[matched_gt_ids] = matched_tracker_ids
120
+ currently_tracked = np.logical_not(np.isnan(prev_timestep_tracker_id))
121
+ gt_frag_count += np.logical_and(not_previously_tracked, currently_tracked)
122
+
123
+ # Calculate and accumulate basic statistics
124
+ num_matches = len(matched_gt_ids)
125
+ res['CLR_TP'] += num_matches
126
+ res['CLR_FN'] += len(gt_ids_t) - num_matches
127
+ res['CLR_FP'] += len(tracker_ids_t) - num_matches
128
+ if num_matches > 0:
129
+ res['MOTP_sum'] += sum(similarity[match_rows, match_cols])
130
+
131
+ # Calculate MT/ML/PT/Frag/MOTP
132
+ tracked_ratio = gt_matched_count[gt_id_count > 0] / gt_id_count[gt_id_count > 0]
133
+ res['MT'] = np.sum(np.greater(tracked_ratio, 0.8))
134
+ res['PT'] = np.sum(np.greater_equal(tracked_ratio, 0.2)) - res['MT']
135
+ res['ML'] = num_gt_ids - res['MT'] - res['PT']
136
+ res['Frag'] = np.sum(np.subtract(gt_frag_count[gt_frag_count > 0], 1))
137
+ res['MOTP'] = res['MOTP_sum'] / np.maximum(1.0, res['CLR_TP'])
138
+
139
+ res['CLR_Frames'] = data['num_timesteps']
140
+
141
+ # Calculate final CLEAR scores
142
+ res = self._compute_final_fields(res)
143
+ return res
144
+
145
+ def combine_sequences(self, all_res):
146
+ """
147
+ Combines metrics across all sequences
148
+
149
+ :param Dict[str, float] all_res: dictionary containing the metrics for each sequence
150
+ :return: dictionary containing the combined metrics across sequences
151
+ :rtype: Dict[str, float]
152
+ """
153
+ res = {}
154
+ for field in self.summed_fields:
155
+ res[field] = self._combine_sum(all_res, field)
156
+ res = self._compute_final_fields(res)
157
+ return res
158
+
159
+ def combine_classes_det_averaged(self, all_res):
160
+ """
161
+ Combines metrics across all classes by averaging over the detection values
162
+
163
+ :param Dict[str, float] all_res: dictionary containing the metrics for each class
164
+ :return: dictionary containing the combined metrics averaged over detections
165
+ :rtype: Dict[str, float]
166
+ """
167
+ res = {}
168
+ for field in self.summed_fields:
169
+ res[field] = self._combine_sum(all_res, field)
170
+ res = self._compute_final_fields(res)
171
+ return res
172
+
173
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False):
174
+ """
175
+ Combines metrics across all classes by averaging over the class values.
176
+ If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection.
177
+
178
+ :param Dict[str, float] all_res: dictionary containing the ID metrics for each class
179
+ :param bool ignore_empty_classes: Flag to ignore empty classes, defaults to False
180
+ :return: dictionary containing the combined metrics averaged over classes
181
+ :rtype: Dict[str, float]
182
+ """
183
+ res = {}
184
+ for field in self.integer_fields:
185
+ if ignore_empty_classes:
186
+ res[field] = self._combine_sum(
187
+ {k: v for k, v in all_res.items() if v['CLR_TP'] + v['CLR_FN'] + v['CLR_FP'] > 0}, field)
188
+ else:
189
+ res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field)
190
+ for field in self.float_fields:
191
+ if ignore_empty_classes:
192
+ res[field] = np.mean(
193
+ [v[field] for v in all_res.values() if v['CLR_TP'] + v['CLR_FN'] + v['CLR_FP'] > 0], axis=0)
194
+ else:
195
+ res[field] = np.mean([v[field] for v in all_res.values()], axis=0)
196
+ return res
197
+
198
+ @staticmethod
199
+ def _compute_final_fields(res):
200
+ """
201
+ Calculate sub-metric ('field') values which only depend on other sub-metric values.
202
+ This function is used both for both per-sequence calculation, and in combining values across sequences.
203
+
204
+ :param Dict[str, float] res: dictionary containing the sub-metric values
205
+ :return: dictionary containing the updated sub-metric values
206
+ :rtype: Dict[str, float]
207
+ """
208
+ num_gt_ids = res['MT'] + res['ML'] + res['PT']
209
+ res['MTR'] = res['MT'] / np.maximum(1.0, num_gt_ids)
210
+ res['MLR'] = res['ML'] / np.maximum(1.0, num_gt_ids)
211
+ res['PTR'] = res['PT'] / np.maximum(1.0, num_gt_ids)
212
+ res['CLR_Re'] = res['CLR_TP'] / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN'])
213
+ res['CLR_Pr'] = res['CLR_TP'] / np.maximum(1.0, res['CLR_TP'] + res['CLR_FP'])
214
+ res['MODA'] = (res['CLR_TP'] - res['CLR_FP']) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN'])
215
+ res['MOTA'] = (res['CLR_TP'] - res['CLR_FP'] - res['IDSW']) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN'])
216
+ res['MOTP'] = res['MOTP_sum'] / np.maximum(1.0, res['CLR_TP'])
217
+ res['sMOTA'] = (res['MOTP_sum'] - res['CLR_FP'] - res['IDSW']) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN'])
218
+
219
+ res['CLR_F1'] = res['CLR_TP'] / np.maximum(1.0, res['CLR_TP'] + 0.5*res['CLR_FN'] + 0.5*res['CLR_FP'])
220
+ res['FP_per_frame'] = res['CLR_FP'] / np.maximum(1.0, res['CLR_Frames'])
221
+ safe_log_idsw = np.log10(res['IDSW']) if res['IDSW'] > 0 else res['IDSW']
222
+ res['MOTAL'] = (res['CLR_TP'] - res['CLR_FP'] - safe_log_idsw) / np.maximum(1.0, res['CLR_TP'] + res['CLR_FN'])
223
+ return res
MTMC_Tracking_2024/eval/trackeval/metrics/count.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._base_metric import _BaseMetric
2
+ from trackeval import _timing
3
+
4
+
5
+ class Count(_BaseMetric):
6
+ """
7
+ Class which simply counts the number of tracker and gt detections and ids.
8
+
9
+ :param Dict config: configuration for the app
10
+ ::
11
+
12
+ identity = trackeval.metrics.Count(config)
13
+ """
14
+ def __init__(self, config=None):
15
+ super().__init__()
16
+ self.integer_fields = ['Dets', 'GT_Dets', 'IDs', 'GT_IDs']
17
+ self.fields = self.integer_fields
18
+ self.summary_fields = self.fields
19
+
20
+ @_timing.time
21
+ def eval_sequence(self, data):
22
+ """
23
+ Returns counts for one sequence
24
+
25
+ :param Dict data: dictionary containing the data for the sequence
26
+
27
+ :return: dictionary containing the calculated count metrics
28
+ :rtype: Dict[str, Dict[str]]
29
+ """
30
+ # Get results
31
+ res = {'Dets': data['num_tracker_dets'],
32
+ 'GT_Dets': data['num_gt_dets'],
33
+ 'IDs': data['num_tracker_ids'],
34
+ 'GT_IDs': data['num_gt_ids'],
35
+ 'Frames': data['num_timesteps']}
36
+ return res
37
+
38
+ def combine_sequences(self, all_res):
39
+ """
40
+ Combines metrics across all sequences
41
+
42
+ :param Dict[str, float] all_res: dictionary containing the metrics for each sequence
43
+ :return: dictionary containing the combined metrics across sequences
44
+ :rtype: Dict[str, float]
45
+ """
46
+ res = {}
47
+ for field in self.integer_fields:
48
+ res[field] = self._combine_sum(all_res, field)
49
+ return res
50
+
51
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=None):
52
+ """
53
+ Combines metrics across all classes by averaging over the class values
54
+
55
+ :param Dict[str, float] all_res: dictionary containing the ID metrics for each class
56
+ :param bool ignore_empty_classes: Flag to ignore empty classes, defaults to False
57
+ :return: dictionary containing the combined metrics averaged over classes
58
+ :rtype: Dict[str, float]
59
+ """
60
+ res = {}
61
+ for field in self.integer_fields:
62
+ res[field] = self._combine_sum(all_res, field)
63
+ return res
64
+
65
+ def combine_classes_det_averaged(self, all_res):
66
+ """
67
+ Combines metrics across all classes by averaging over the detection values
68
+
69
+ :param Dict[str, float] all_res: dictionary containing the metrics for each class
70
+ :return: dictionary containing the combined metrics averaged over detections
71
+ :rtype: Dict[str, float]
72
+ """
73
+ res = {}
74
+ for field in self.integer_fields:
75
+ res[field] = self._combine_sum(all_res, field)
76
+ return res
MTMC_Tracking_2024/eval/trackeval/metrics/hota.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from trackeval import _timing
4
+ from scipy.optimize import linear_sum_assignment
5
+ from trackeval.metrics._base_metric import _BaseMetric
6
+
7
+
8
+ class HOTA(_BaseMetric):
9
+ """
10
+ Class which implements the HOTA metrics.
11
+ See: https://link.springer.com/article/10.1007/s11263-020-01375-2
12
+
13
+ :param Dict config: configuration for the app
14
+ ::
15
+
16
+ identity = trackeval.metrics.HOTA(config)
17
+ """
18
+
19
+ def __init__(self, config=None):
20
+ super().__init__()
21
+ self.plottable = True
22
+ self.array_labels = np.arange(0.05, 0.99, 0.05)
23
+ self.integer_array_fields = ['HOTA_TP', 'HOTA_FN', 'HOTA_FP']
24
+ self.float_array_fields = ['HOTA', 'DetA', 'AssA', 'DetRe', 'DetPr', 'AssRe', 'AssPr', 'LocA', 'OWTA']
25
+ self.float_fields = ['HOTA(0)', 'LocA(0)', 'HOTALocA(0)']
26
+ self.fields = self.float_array_fields + self.integer_array_fields + self.float_fields
27
+ self.summary_fields = self.float_array_fields + self.float_fields
28
+
29
+ @_timing.time
30
+ def eval_sequence(self, data):
31
+ """
32
+ Calculates the HOTA metrics for one sequence
33
+
34
+ :param Dict data: dictionary containing the data for the sequence
35
+
36
+ :return: dictionary containing the calculated hota metrics
37
+ :rtype: Dict
38
+ """
39
+
40
+ # Initialise results
41
+ res = {}
42
+ for field in self.float_array_fields + self.integer_array_fields:
43
+ res[field] = np.zeros((len(self.array_labels)), dtype=float)
44
+ for field in self.float_fields:
45
+ res[field] = 0
46
+
47
+ # Return result quickly if tracker or gt sequence is empty
48
+ if data['num_tracker_dets'] == 0:
49
+ res['HOTA_FN'] = data['num_gt_dets'] * np.ones((len(self.array_labels)), dtype=float)
50
+ res['LocA'] = np.ones((len(self.array_labels)), dtype=float)
51
+ res['LocA(0)'] = 1.0
52
+ return res
53
+ if data['num_gt_dets'] == 0:
54
+ res['HOTA_FP'] = data['num_tracker_dets'] * np.ones((len(self.array_labels)), dtype=float)
55
+ res['LocA'] = np.ones((len(self.array_labels)), dtype=float)
56
+ res['LocA(0)'] = 1.0
57
+ return res
58
+
59
+ # Variables counting global association
60
+ potential_matches_count = np.zeros((data['num_gt_ids'], data['num_tracker_ids']))
61
+ gt_id_count = np.zeros((data['num_gt_ids'], 1))
62
+ tracker_id_count = np.zeros((1, data['num_tracker_ids']))
63
+
64
+ # First loop through each timestep and accumulate global track information.
65
+ for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])):
66
+ # Count the potential matches between ids in each timestep
67
+ # These are normalised, weighted by the match similarity.
68
+ similarity = data['similarity_scores'][t]
69
+ sim_iou_denom = similarity.sum(0)[np.newaxis, :] + similarity.sum(1)[:, np.newaxis] - similarity
70
+ sim_iou = np.zeros_like(similarity)
71
+ sim_iou_mask = sim_iou_denom > 0 + np.finfo('float').eps
72
+ sim_iou[sim_iou_mask] = similarity[sim_iou_mask] / sim_iou_denom[sim_iou_mask]
73
+ potential_matches_count[gt_ids_t[:, np.newaxis], tracker_ids_t[np.newaxis, :]] += sim_iou
74
+
75
+ # Calculate the total number of dets for each gt_id and tracker_id.
76
+ gt_id_count[gt_ids_t] += 1
77
+ tracker_id_count[0, tracker_ids_t] += 1
78
+
79
+ # Calculate overall jaccard alignment score (before unique matching) between IDs
80
+ global_alignment_score = potential_matches_count / (gt_id_count + tracker_id_count - potential_matches_count)
81
+ matches_counts = [np.zeros_like(potential_matches_count) for _ in self.array_labels]
82
+
83
+ # Calculate scores for each timestep
84
+ for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])):
85
+ # Deal with the case that there are no gt_det/tracker_det in a timestep.
86
+ if len(gt_ids_t) == 0:
87
+ for a, alpha in enumerate(self.array_labels):
88
+ res['HOTA_FP'][a] += len(tracker_ids_t)
89
+ continue
90
+ if len(tracker_ids_t) == 0:
91
+ for a, alpha in enumerate(self.array_labels):
92
+ res['HOTA_FN'][a] += len(gt_ids_t)
93
+ continue
94
+
95
+ # Get matching scores between pairs of dets for optimizing HOTA
96
+ similarity = data['similarity_scores'][t]
97
+ score_mat = global_alignment_score[gt_ids_t[:, np.newaxis], tracker_ids_t[np.newaxis, :]] * similarity
98
+
99
+ # Hungarian algorithm to find best matches
100
+ match_rows, match_cols = linear_sum_assignment(-score_mat)
101
+
102
+ # Calculate and accumulate basic statistics
103
+ for a, alpha in enumerate(self.array_labels):
104
+ actually_matched_mask = similarity[match_rows, match_cols] >= alpha - np.finfo('float').eps
105
+ alpha_match_rows = match_rows[actually_matched_mask]
106
+ alpha_match_cols = match_cols[actually_matched_mask]
107
+ num_matches = len(alpha_match_rows)
108
+ res['HOTA_TP'][a] += num_matches
109
+ res['HOTA_FN'][a] += len(gt_ids_t) - num_matches
110
+ res['HOTA_FP'][a] += len(tracker_ids_t) - num_matches
111
+ if num_matches > 0:
112
+ res['LocA'][a] += sum(similarity[alpha_match_rows, alpha_match_cols])
113
+ matches_counts[a][gt_ids_t[alpha_match_rows], tracker_ids_t[alpha_match_cols]] += 1
114
+
115
+ # Calculate association scores (AssA, AssRe, AssPr) for the alpha value.
116
+ # First calculate scores per gt_id/tracker_id combo and then average over the number of detections.
117
+ for a, alpha in enumerate(self.array_labels):
118
+ matches_count = matches_counts[a]
119
+ ass_a = matches_count / np.maximum(1, gt_id_count + tracker_id_count - matches_count)
120
+ res['AssA'][a] = np.sum(matches_count * ass_a) / np.maximum(1, res['HOTA_TP'][a])
121
+ ass_re = matches_count / np.maximum(1, gt_id_count)
122
+ res['AssRe'][a] = np.sum(matches_count * ass_re) / np.maximum(1, res['HOTA_TP'][a])
123
+ ass_pr = matches_count / np.maximum(1, tracker_id_count)
124
+ res['AssPr'][a] = np.sum(matches_count * ass_pr) / np.maximum(1, res['HOTA_TP'][a])
125
+
126
+ # Calculate final scores
127
+ res['LocA'] = np.maximum(0, res['LocA']) / np.maximum(1e-10, res['HOTA_TP'])
128
+ res = self._compute_final_fields(res)
129
+ return res
130
+
131
+ def combine_sequences(self, all_res):
132
+ """
133
+ Combines metrics across all sequences
134
+
135
+ :param Dict[str, float] all_res: dictionary containing the metrics for each sequence
136
+ :return: dictionary containing the combined metrics across sequences
137
+ :rtype: Dict[str, float]
138
+ """
139
+ res = {}
140
+ for field in self.integer_array_fields:
141
+ res[field] = self._combine_sum(all_res, field)
142
+ for field in ['AssRe', 'AssPr', 'AssA']:
143
+ res[field] = self._combine_weighted_av(all_res, field, res, weight_field='HOTA_TP')
144
+ loca_weighted_sum = sum([all_res[k]['LocA'] * all_res[k]['HOTA_TP'] for k in all_res.keys()])
145
+ res['LocA'] = np.maximum(1e-10, loca_weighted_sum) / np.maximum(1e-10, res['HOTA_TP'])
146
+ res = self._compute_final_fields(res)
147
+ return res
148
+
149
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False):
150
+ """
151
+ Combines metrics across all classes by averaging over the class values.
152
+ If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection.
153
+
154
+ :param Dict[str, float] all_res: dictionary containing the ID metrics for each class
155
+ :param bool ignore_empty_classes: Flag to ignore empty classes, defaults to False
156
+ :return: dictionary containing the combined metrics averaged over classes
157
+ :rtype: Dict[str, float]
158
+ """
159
+ res = {}
160
+ for field in self.integer_array_fields:
161
+ if ignore_empty_classes:
162
+ res[field] = self._combine_sum(
163
+ {k: v for k, v in all_res.items()
164
+ if (v['HOTA_TP'] + v['HOTA_FN'] + v['HOTA_FP'] > 0 + np.finfo('float').eps).any()}, field)
165
+ else:
166
+ res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field)
167
+
168
+ for field in self.float_fields + self.float_array_fields:
169
+ if ignore_empty_classes:
170
+ res[field] = np.mean([v[field] for v in all_res.values() if
171
+ (v['HOTA_TP'] + v['HOTA_FN'] + v['HOTA_FP'] > 0 + np.finfo('float').eps).any()],
172
+ axis=0)
173
+ else:
174
+ res[field] = np.mean([v[field] for v in all_res.values()], axis=0)
175
+ return res
176
+
177
+ def combine_classes_det_averaged(self, all_res):
178
+ """
179
+ Combines metrics across all classes by averaging over the detection values
180
+
181
+ :param Dict[str, float] all_res: dictionary containing the metrics for each class
182
+ :return: dictionary containing the combined metrics averaged over detections
183
+ :rtype: Dict[str, float]
184
+ """
185
+ res = {}
186
+ for field in self.integer_array_fields:
187
+ res[field] = self._combine_sum(all_res, field)
188
+ for field in ['AssRe', 'AssPr', 'AssA']:
189
+ res[field] = self._combine_weighted_av(all_res, field, res, weight_field='HOTA_TP')
190
+ loca_weighted_sum = sum([all_res[k]['LocA'] * all_res[k]['HOTA_TP'] for k in all_res.keys()])
191
+ res['LocA'] = np.maximum(1e-10, loca_weighted_sum) / np.maximum(1e-10, res['HOTA_TP'])
192
+ res = self._compute_final_fields(res)
193
+ return res
194
+
195
+ @staticmethod
196
+ def _compute_final_fields(res):
197
+ """
198
+ Calculate sub-metric ('field') values which only depend on other sub-metric values.
199
+ This function is used both for both per-sequence calculation, and in combining values across sequences.
200
+
201
+ :param Dict[str, float] res: dictionary containing the sub-metric values
202
+ :return: dictionary containing the updated sub-metric values
203
+ :rtype: Dict[str, float]
204
+ """
205
+ res['DetRe'] = res['HOTA_TP'] / np.maximum(1, res['HOTA_TP'] + res['HOTA_FN'])
206
+ res['DetPr'] = res['HOTA_TP'] / np.maximum(1, res['HOTA_TP'] + res['HOTA_FP'])
207
+ res['DetA'] = res['HOTA_TP'] / np.maximum(1, res['HOTA_TP'] + res['HOTA_FN'] + res['HOTA_FP'])
208
+ res['HOTA'] = np.sqrt(res['DetA'] * res['AssA'])
209
+ res['OWTA'] = np.sqrt(res['DetRe'] * res['AssA'])
210
+
211
+ res['HOTA(0)'] = res['HOTA'][0]
212
+ res['LocA(0)'] = res['LocA'][0]
213
+ res['HOTALocA(0)'] = res['HOTA(0)']*res['LocA(0)']
214
+ return res
215
+
216
+ def plot_single_tracker_results(self, table_res, tracker, cls, output_folder):
217
+ """
218
+ Create plot of results
219
+
220
+ :param Dict table_res: dictionary containing the evaluation results
221
+ :param str tracker: The name of the tracker
222
+ :param str cls: The class name
223
+ :param str output_folder: The output folder path for saving the plot
224
+ """
225
+
226
+ # Only loaded when run to reduce minimum requirements
227
+ from matplotlib import pyplot as plt
228
+
229
+ res = table_res['COMBINED_SEQ']
230
+ styles_to_plot = ['r', 'b', 'g', 'b--', 'b:', 'g--', 'g:', 'm']
231
+ for name, style in zip(self.float_array_fields, styles_to_plot):
232
+ plt.plot(self.array_labels, res[name], style)
233
+ plt.xlabel('alpha')
234
+ plt.ylabel('score')
235
+ plt.title(tracker + ' - ' + cls)
236
+ plt.axis([0, 1, 0, 1])
237
+ legend = []
238
+ for name in self.float_array_fields:
239
+ legend += [name + ' (' + str(np.round(np.mean(res[name]), 2)) + ')']
240
+ plt.legend(legend, loc='lower left')
241
+ out_file = os.path.join(output_folder, cls + '_plot.pdf')
242
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
243
+ plt.savefig(out_file)
244
+ plt.savefig(out_file.replace('.pdf', '.png'))
245
+ plt.clf()
MTMC_Tracking_2024/eval/trackeval/metrics/identity.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linear_sum_assignment
3
+ from trackeval import _timing
4
+ from trackeval import utils
5
+ from trackeval.metrics._base_metric import _BaseMetric
6
+
7
+
8
+ class Identity(_BaseMetric):
9
+ """
10
+ Class which implements the Identity metrics
11
+
12
+ :param Dict config: configuration for the app
13
+ ::
14
+
15
+ identity = trackeval.metrics.Identity(config)
16
+ """
17
+
18
+ @staticmethod
19
+ def get_default_config():
20
+ """Default class config values"""
21
+ default_config = {
22
+ 'THRESHOLD': 0.5, # Similarity score threshold required for a IDTP match. Default 0.5.
23
+ 'PRINT_CONFIG': True, # Whether to print the config information on init. Default: False.
24
+ }
25
+ return default_config
26
+
27
+ def __init__(self, config=None):
28
+ super().__init__()
29
+ self.integer_fields = ['IDTP', 'IDFN', 'IDFP']
30
+ self.float_fields = ['IDF1', 'IDR', 'IDP']
31
+ self.fields = self.float_fields + self.integer_fields
32
+ self.summary_fields = self.fields
33
+
34
+ # Configuration options:
35
+ self.config = utils.init_config(config, self.get_default_config(), self.get_name())
36
+ self.threshold = float(self.config['THRESHOLD'])
37
+
38
+ @_timing.time
39
+ def eval_sequence(self, data):
40
+ """
41
+ Calculates ID metrics for one sequence
42
+
43
+ :param Dict[str, float] data: dictionary containing the data for the sequence
44
+
45
+ :return: dictionary containing the calculated ID metrics
46
+ :rtype: Dict[str, float]
47
+ """
48
+ # Initialise results
49
+ res = {}
50
+ for field in self.fields:
51
+ res[field] = 0
52
+
53
+ # Return result quickly if tracker or gt sequence is empty
54
+ if data['num_tracker_dets'] == 0:
55
+ res['IDFN'] = data['num_gt_dets']
56
+ return res
57
+ if data['num_gt_dets'] == 0:
58
+ res['IDFP'] = data['num_tracker_dets']
59
+ return res
60
+
61
+ # Variables counting global association
62
+ potential_matches_count = np.zeros((data['num_gt_ids'], data['num_tracker_ids']))
63
+ gt_id_count = np.zeros(data['num_gt_ids'])
64
+ tracker_id_count = np.zeros(data['num_tracker_ids'])
65
+
66
+ # First loop through each timestep and accumulate global track information.
67
+ for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])):
68
+ # Count the potential matches between ids in each timestep
69
+ matches_mask = np.greater_equal(data['similarity_scores'][t], self.threshold)
70
+ match_idx_gt, match_idx_tracker = np.nonzero(matches_mask)
71
+ potential_matches_count[gt_ids_t[match_idx_gt], tracker_ids_t[match_idx_tracker]] += 1
72
+
73
+ # Calculate the total number of dets for each gt_id and tracker_id.
74
+ gt_id_count[gt_ids_t] += 1
75
+ tracker_id_count[tracker_ids_t] += 1
76
+
77
+ # Calculate optimal assignment cost matrix for ID metrics
78
+ num_gt_ids = data['num_gt_ids']
79
+ num_tracker_ids = data['num_tracker_ids']
80
+ fp_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids))
81
+ fn_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids))
82
+ fp_mat[num_gt_ids:, :num_tracker_ids] = 1e10
83
+ fn_mat[:num_gt_ids, num_tracker_ids:] = 1e10
84
+ for gt_id in range(num_gt_ids):
85
+ fn_mat[gt_id, :num_tracker_ids] = gt_id_count[gt_id]
86
+ fn_mat[gt_id, num_tracker_ids + gt_id] = gt_id_count[gt_id]
87
+ for tracker_id in range(num_tracker_ids):
88
+ fp_mat[:num_gt_ids, tracker_id] = tracker_id_count[tracker_id]
89
+ fp_mat[tracker_id + num_gt_ids, tracker_id] = tracker_id_count[tracker_id]
90
+ fn_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count
91
+ fp_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count
92
+
93
+ # Hungarian algorithm
94
+ match_rows, match_cols = linear_sum_assignment(fn_mat + fp_mat)
95
+
96
+ # Accumulate basic statistics
97
+ res['IDFN'] = fn_mat[match_rows, match_cols].sum().astype(int)
98
+ res['IDFP'] = fp_mat[match_rows, match_cols].sum().astype(int)
99
+ res['IDTP'] = (gt_id_count.sum() - res['IDFN']).astype(int)
100
+
101
+ # Calculate final ID scores
102
+ res = self._compute_final_fields(res)
103
+ return res
104
+
105
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False):
106
+ """
107
+ Combines metrics across all classes by averaging over the class values.
108
+ If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection.
109
+
110
+ :param Dict[str, float] all_res: dictionary containing the ID metrics for each class
111
+ :param bool ignore_empty_classes: flag to ignore empty classes, defaults to False
112
+ :return: dictionary containing the combined metrics averaged over classes
113
+ :rtype: Dict[str, float]
114
+ """
115
+ res = {}
116
+ for field in self.integer_fields:
117
+ if ignore_empty_classes:
118
+ res[field] = self._combine_sum({k: v for k, v in all_res.items()
119
+ if v['IDTP'] + v['IDFN'] + v['IDFP'] > 0 + np.finfo('float').eps},
120
+ field)
121
+ else:
122
+ res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field)
123
+ for field in self.float_fields:
124
+ if ignore_empty_classes:
125
+ res[field] = np.mean([v[field] for v in all_res.values()
126
+ if v['IDTP'] + v['IDFN'] + v['IDFP'] > 0 + np.finfo('float').eps], axis=0)
127
+ else:
128
+ res[field] = np.mean([v[field] for v in all_res.values()], axis=0)
129
+ return res
130
+
131
+ def combine_classes_det_averaged(self, all_res):
132
+ """
133
+ Combines metrics across all classes by averaging over the detection values
134
+
135
+ :param Dict[str, float] all_res: dictionary containing the metrics for each class
136
+ :return: dictionary containing the combined metrics averaged over detections
137
+ :rtype: Dict[str, float]
138
+ """
139
+ res = {}
140
+ for field in self.integer_fields:
141
+ res[field] = self._combine_sum(all_res, field)
142
+ res = self._compute_final_fields(res)
143
+ return res
144
+
145
+ def combine_sequences(self, all_res):
146
+ """
147
+ Combines metrics across all sequences
148
+
149
+ :param Dict[str, float] all_res: dictionary containing the metrics for each sequence
150
+ :return: dictionary containing the combined metrics across sequences
151
+ :rtype: Dict[str, float][str, float]
152
+ """
153
+ res = {}
154
+ for field in self.integer_fields:
155
+ res[field] = self._combine_sum(all_res, field)
156
+ res = self._compute_final_fields(res)
157
+ return res
158
+
159
+ @staticmethod
160
+ def _compute_final_fields(res):
161
+ """
162
+ Calculate sub-metric ('field') values which only depend on other sub-metric values.
163
+ This function is used both for both per-sequence calculation, and in combining values across sequences.
164
+
165
+ :param Dict[str, float] res: dictionary containing the sub-metric values
166
+ :return: dictionary containing the updated sub-metric values
167
+ :rtype: Dict[str, float]
168
+ """
169
+ res['IDR'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + res['IDFN'])
170
+ res['IDP'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + res['IDFP'])
171
+ res['IDF1'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + 0.5 * res['IDFP'] + 0.5 * res['IDFN'])
172
+ return res
MTMC_Tracking_2024/eval/trackeval/plotting.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import numpy as np
4
+ from .utils import TrackEvalException
5
+
6
+
7
+ def plot_compare_trackers(tracker_folder, tracker_list, cls, output_folder, plots_list=None):
8
+ """
9
+ Create plots which compare metrics across different trackers
10
+
11
+ :param str tracker_folder: root tracker folder
12
+ :param str tracker_list: names of all trackers
13
+ :param List[cls] cls: names of classes
14
+ :param str output_folder: root folder to save the plots in
15
+ :param List[str] plots_list: list of all plots to generate
16
+ :return: None
17
+ ::
18
+
19
+ plotting.plot_compare_trackers(tracker_folder, tracker_list, cls, output_folder, plots_list)
20
+ """
21
+ if plots_list is None:
22
+ plots_list = get_default_plots_list()
23
+
24
+ # Load data
25
+ data = load_multiple_tracker_summaries(tracker_folder, tracker_list, cls)
26
+ out_loc = os.path.join(output_folder, cls)
27
+
28
+ # Plot
29
+ print("\n")
30
+ for args in plots_list:
31
+ create_comparison_plot(data, out_loc, *args)
32
+
33
+
34
+ def get_default_plots_list():
35
+ """
36
+ Create a intermediate config to define the type of plots.
37
+ The plot uses the following order to generate the charts:
38
+ y_label, x_label, sort_label, bg_label, bg_function
39
+
40
+ :param None
41
+ :return: List[List[str]] plots_list: detailed description of the plots
42
+ ::
43
+
44
+ plotting.get_default_plots_list(tracker_folder, tracker_list, cls, output_folder, plots_list)
45
+ """
46
+ plots_list = [
47
+ ['AssA', 'DetA', 'HOTA', 'HOTA', 'geometric_mean'],
48
+ ['AssPr', 'AssRe', 'HOTA', 'AssA', 'jaccard'],
49
+ ['DetPr', 'DetRe', 'HOTA', 'DetA', 'jaccard'],
50
+ ['HOTA(0)', 'LocA(0)', 'HOTA', 'HOTALocA(0)', 'multiplication'],
51
+ ['HOTA', 'LocA', 'HOTA', None, None],
52
+
53
+ ['HOTA', 'MOTA', 'HOTA', None, None],
54
+ ['HOTA', 'IDF1', 'HOTA', None, None],
55
+ ['IDF1', 'MOTA', 'HOTA', None, None],
56
+ ]
57
+ return plots_list
58
+
59
+
60
+ def load_multiple_tracker_summaries(tracker_folder, tracker_list, cls):
61
+ """
62
+ Loads summary data for multiple trackers
63
+
64
+ :param str tracker_folder: directory of the tracker folder
65
+ :param str tracker_list: names of the trackers
66
+ :param str cls: names of all classes
67
+
68
+ :return: Dict[str] data: summaried data of the trackers
69
+ ::
70
+
71
+ plotting.load_multiple_tracker_summaries(tracker_folder, tracker_list, cls, output_folder, plots_list)
72
+ """
73
+ data = {}
74
+ for tracker in tracker_list:
75
+ with open(os.path.join(tracker_folder, tracker, cls + '_summary.txt')) as f:
76
+ keys = next(f).split(' ')
77
+ done = False
78
+ while not done:
79
+ values = next(f).split(' ')
80
+ if len(values) == len(keys):
81
+ done = True
82
+ data[tracker] = dict(zip(keys, map(float, values)))
83
+ return data
84
+
85
+
86
+ def create_comparison_plot(data, out_loc, y_label, x_label, sort_label, bg_label=None, bg_function=None, settings=None):
87
+ """
88
+ Creates a scatter plot comparing multiple trackers between two metric fields, with one on the x-axis and the
89
+ other on the y axis. Adds pareto optical lines and (optionally) a background contour.
90
+
91
+ :param data: dict of dicts such that data[tracker_name][metric_field_name] = float
92
+ :param str y_label: the metric_field_name to be plotted on the y-axis
93
+ :param strx_label: the metric_field_name to be plotted on the x-axis
94
+ :param str sort_label: the metric_field_name by which trackers are ordered and ranked
95
+ :param str bg_label: the metric_field_name by which (optional) background contours are plotted
96
+ :param str bg_function: the (optional) function bg_function(x,y) which converts the x_label / y_label values into bg_label.
97
+ :param Dict[str] settings: dict of plot settings with keys:
98
+ 'gap_val': gap between axis ticks and bg curves.
99
+ 'num_to_plot': maximum number of trackers to plot
100
+
101
+ :return: None
102
+ ::
103
+
104
+ plotting.create_comparison_plot(x_values, y_values)
105
+ """
106
+
107
+ # Only loaded when run to reduce minimum requirements
108
+ from matplotlib import pyplot as plt
109
+
110
+ # Get plot settings
111
+ if settings is None:
112
+ gap_val = 2
113
+ num_to_plot = 20
114
+ else:
115
+ gap_val = settings['gap_val']
116
+ num_to_plot = settings['num_to_plot']
117
+
118
+ if (bg_label is None) != (bg_function is None):
119
+ raise TrackEvalException('bg_function and bg_label must either be both given or neither given.')
120
+
121
+ # Extract data
122
+ tracker_names = np.array(list(data.keys()))
123
+ sort_index = np.array([data[t][sort_label] for t in tracker_names]).argsort()[::-1]
124
+ x_values = np.array([data[t][x_label] for t in tracker_names])[sort_index][:num_to_plot]
125
+ y_values = np.array([data[t][y_label] for t in tracker_names])[sort_index][:num_to_plot]
126
+
127
+ # Print info on what is being plotted
128
+ tracker_names = tracker_names[sort_index][:num_to_plot]
129
+ logging.info('Plotting %s vs %s...' % (y_label, x_label))
130
+ #for i, name in enumerate(tracker_names):
131
+ #print('%i: %s' % (i+1, name))
132
+
133
+ # Find best fitting boundaries for data
134
+ boundaries = _get_boundaries(x_values, y_values, round_val=gap_val/2)
135
+
136
+ fig = plt.figure()
137
+
138
+ # Plot background contour
139
+ if bg_function is not None:
140
+ _plot_bg_contour(bg_function, boundaries, gap_val)
141
+
142
+ # Plot pareto optimal lines
143
+ _plot_pareto_optimal_lines(x_values, y_values)
144
+
145
+ # Plot data points with number labels
146
+ labels = np.arange(len(y_values)) + 1
147
+ plt.plot(x_values, y_values, 'b.', markersize=15)
148
+ for xx, yy, l in zip(x_values, y_values, labels):
149
+ plt.text(xx, yy, str(l), color="red", fontsize=15)
150
+
151
+ # Add extra explanatory text to plots
152
+ plt.text(0, -0.11, 'label order:\nHOTA', horizontalalignment='left', verticalalignment='center',
153
+ transform=fig.axes[0].transAxes, color="red", fontsize=12)
154
+ if bg_label is not None:
155
+ plt.text(1, -0.11, 'curve values:\n' + bg_label, horizontalalignment='right', verticalalignment='center',
156
+ transform=fig.axes[0].transAxes, color="grey", fontsize=12)
157
+
158
+ plt.xlabel(x_label, fontsize=15)
159
+ plt.ylabel(y_label, fontsize=15)
160
+ title = y_label + ' vs ' + x_label
161
+ if bg_label is not None:
162
+ title += ' (' + bg_label + ')'
163
+ plt.title(title, fontsize=17)
164
+ plt.xticks(np.arange(0, 100, gap_val))
165
+ plt.yticks(np.arange(0, 100, gap_val))
166
+ min_x, max_x, min_y, max_y = boundaries
167
+ plt.xlim(min_x, max_x)
168
+ plt.ylim(min_y, max_y)
169
+ plt.gca().set_aspect('equal', adjustable='box')
170
+ plt.tight_layout()
171
+
172
+ os.makedirs(out_loc, exist_ok=True)
173
+ filename = os.path.join(out_loc, title.replace(' ', '_'))
174
+ plt.savefig(filename + '.pdf', bbox_inches='tight', pad_inches=0.05)
175
+ plt.savefig(filename + '.png', bbox_inches='tight', pad_inches=0.05)
176
+
177
+
178
+ def _get_boundaries(x_values, y_values, round_val):
179
+ """
180
+ Computes boundaries of a plot
181
+
182
+ :param List[Float] x_values: x values
183
+ :param List[Float] y_values: y values
184
+ :param Float round_val: interval
185
+
186
+ :return: Float, Float, Float, Float: boundaries of the plot
187
+ ::
188
+
189
+ plotting._get_boundaries(x_values, y_values)
190
+ """
191
+ x1 = np.min(np.floor((x_values - 0.5) / round_val) * round_val)
192
+ x2 = np.max(np.ceil((x_values + 0.5) / round_val) * round_val)
193
+ y1 = np.min(np.floor((y_values - 0.5) / round_val) * round_val)
194
+ y2 = np.max(np.ceil((y_values + 0.5) / round_val) * round_val)
195
+ x_range = x2 - x1
196
+ y_range = y2 - y1
197
+ max_range = max(x_range, y_range)
198
+ x_center = (x1 + x2) / 2
199
+ y_center = (y1 + y2) / 2
200
+ min_x = max(x_center - max_range / 2, 0)
201
+ max_x = min(x_center + max_range / 2, 100)
202
+ min_y = max(y_center - max_range / 2, 0)
203
+ max_y = min(y_center + max_range / 2, 100)
204
+ return min_x, max_x, min_y, max_y
205
+
206
+
207
+ def geometric_mean(x, y):
208
+ """
209
+ Computes geometric mean
210
+
211
+ :param Float x: x values
212
+ :param Float y: y values
213
+
214
+ :return: Float: geometric mean value
215
+ ::
216
+
217
+ plotting.geometric_mean(x_values, y_values)
218
+ """
219
+ return np.sqrt(x * y)
220
+
221
+
222
+ def jaccard(x, y):
223
+ x = x / 100
224
+ y = y / 100
225
+ return 100 * (x * y) / (x + y - x * y)
226
+
227
+
228
+ def multiplication(x, y):
229
+ """
230
+ Computes multiplication for plots
231
+
232
+ :param Float x: x values
233
+ :param Float y: y values
234
+
235
+ :return: Float: multiplied value
236
+ ::
237
+
238
+ plotting.multiplication(x_values, y_values)
239
+ """
240
+ return x * y / 100
241
+
242
+
243
+ bg_function_dict = {
244
+ "geometric_mean": geometric_mean,
245
+ "jaccard": jaccard,
246
+ "multiplication": multiplication,
247
+ }
248
+
249
+
250
+ def _plot_bg_contour(bg_function, plot_boundaries, gap_val):
251
+ """
252
+ Plot background contour
253
+
254
+ :param Dict[str:func()] bg_function: sort order function
255
+ :param List[float] plot_boundaries: limit values for the plot
256
+ :param int gap_val: interval value
257
+
258
+ :return: None
259
+ ::
260
+
261
+ plotting._plot_bg_contour(x_values, y_values)
262
+ """
263
+ # Only loaded when run to reduce minimum requirements
264
+ from matplotlib import pyplot as plt
265
+
266
+ # Plot background contour
267
+ min_x, max_x, min_y, max_y = plot_boundaries
268
+ x = np.arange(min_x, max_x, 0.1)
269
+ y = np.arange(min_y, max_y, 0.1)
270
+ x_grid, y_grid = np.meshgrid(x, y)
271
+ if bg_function in bg_function_dict.keys():
272
+ z_grid = bg_function_dict[bg_function](x_grid, y_grid)
273
+ else:
274
+ raise TrackEvalException("background plotting function '%s' is not defined." % bg_function)
275
+ levels = np.arange(0, 100, gap_val)
276
+ con = plt.contour(x_grid, y_grid, z_grid, levels, colors='grey')
277
+
278
+ def bg_format(val):
279
+ s = '{:1f}'.format(val)
280
+ return '{:.0f}'.format(val) if s[-1] == '0' else s
281
+
282
+ con.levels = [bg_format(val) for val in con.levels]
283
+ plt.clabel(con, con.levels, inline=True, fmt='%r', fontsize=8)
284
+
285
+
286
+ def _plot_pareto_optimal_lines(x_values, y_values):
287
+ """
288
+ Plot pareto optimal lines
289
+
290
+ :param List[float] x_values: values to plot on x axis
291
+ :param List[float] y_values: values to plot on y axis
292
+
293
+ :return: None
294
+ ::
295
+
296
+ plotting._plot_pareto_optimal_lines(x_values, y_values)
297
+ """
298
+
299
+ # Only loaded when run to reduce minimum requirements
300
+ from matplotlib import pyplot as plt
301
+
302
+ # Plot pareto optimal lines
303
+ cxs = x_values
304
+ cys = y_values
305
+ best_y = np.argmax(cys)
306
+ x_pareto = [0, cxs[best_y]]
307
+ y_pareto = [cys[best_y], cys[best_y]]
308
+ t = 2
309
+ remaining = cxs > x_pareto[t - 1]
310
+ cys = cys[remaining]
311
+ cxs = cxs[remaining]
312
+ while len(cxs) > 0 and len(cys) > 0:
313
+ best_y = np.argmax(cys)
314
+ x_pareto += [x_pareto[t - 1], cxs[best_y]]
315
+ y_pareto += [cys[best_y], cys[best_y]]
316
+ t += 2
317
+ remaining = cxs > x_pareto[t - 1]
318
+ cys = cys[remaining]
319
+ cxs = cxs[remaining]
320
+ x_pareto.append(x_pareto[t - 1])
321
+ y_pareto.append(0)
322
+ plt.plot(np.array(x_pareto), np.array(y_pareto), '--r')
MTMC_Tracking_2024/eval/trackeval/utils.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import argparse
4
+ from collections import OrderedDict
5
+
6
+
7
+ def init_config(config, default_config, name=None):
8
+ """
9
+ Initialise non-given config values with defaults
10
+
11
+ :param str config: config
12
+ :param str default_config: default config
13
+ :param str name: name of dataset/metric
14
+ :return: None
15
+ ::
16
+
17
+ trackeval.utils.init_config(config, default_config, name)
18
+ """
19
+ if config is None:
20
+ config = default_config
21
+ else:
22
+ for k in default_config.keys():
23
+ if k not in config.keys():
24
+ config[k] = default_config[k]
25
+ if name and config['PRINT_CONFIG']:
26
+ print('\n%s Config:' % name)
27
+ for c in config.keys():
28
+ print('%-20s : %-30s' % (c, config[c]))
29
+ return config
30
+
31
+
32
+ def update_config(config):
33
+ """
34
+ Parse the arguments of a script and updates the config values for a given value if specified in the arguments.
35
+
36
+ :param str config: the config to update
37
+ :return: the updated config
38
+ ::
39
+
40
+ trackeval.utils.update_config(config, default_config, name)
41
+ """
42
+ parser = argparse.ArgumentParser()
43
+ for setting in config.keys():
44
+ if type(config[setting]) == list or type(config[setting]) == type(None):
45
+ parser.add_argument("--" + setting, nargs='+')
46
+ else:
47
+ parser.add_argument("--" + setting)
48
+ args = parser.parse_args().__dict__
49
+ for setting in args.keys():
50
+ if args[setting] is not None:
51
+ if type(config[setting]) == type(True):
52
+ if args[setting] == 'True':
53
+ x = True
54
+ elif args[setting] == 'False':
55
+ x = False
56
+ else:
57
+ raise Exception('Command line parameter ' + setting + 'must be True or False')
58
+ elif type(config[setting]) == type(1):
59
+ x = int(args[setting])
60
+ elif type(args[setting]) == type(None):
61
+ x = None
62
+ else:
63
+ x = args[setting]
64
+ config[setting] = x
65
+ return config
66
+
67
+
68
+ def get_code_path():
69
+ """
70
+ Get base path where the trackeval library is located
71
+
72
+ :param None
73
+ :return: str: base path of trackeval library
74
+ ::
75
+
76
+ trackeval.utils.get_code_path(config, default_config, name)
77
+ """
78
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
79
+
80
+
81
+ def validate_metrics_list(metrics_list):
82
+ """
83
+ Get names of metric class and ensures they are unique, further checks that the fields within each metric class
84
+ do not have overlapping names.
85
+
86
+ :param List[str] metrics_list: list of all metrics to test
87
+ :return: List[str] metric_names: valid list of all metrics to test
88
+ ::
89
+
90
+ trackeval.utils.get_code_path(config, default_config, name)
91
+ """
92
+ metric_names = [metric.get_name() for metric in metrics_list]
93
+ # check metric names are unique
94
+ if len(metric_names) != len(set(metric_names)):
95
+ raise TrackEvalException('Code being run with multiple metrics of the same name')
96
+ fields = []
97
+ for m in metrics_list:
98
+ fields += m.fields
99
+ # check metric fields are unique
100
+ if len(fields) != len(set(fields)):
101
+ raise TrackEvalException('Code being run with multiple metrics with fields of the same name')
102
+ return metric_names
103
+
104
+
105
+ def write_summary_results(summaries, cls, output_folder):
106
+ """
107
+ Write summary results to file
108
+
109
+ :param List[str] summaries: list of all summaries
110
+ :param List[str] cls: list of classes
111
+ :param List[str] output_folder: directory to store the summary results
112
+
113
+ :return: None
114
+ ::
115
+
116
+ trackeval.utils.write_summary_results(config, default_config, name)
117
+ """
118
+ fields = sum([list(s.keys()) for s in summaries], [])
119
+ values = sum([list(s.values()) for s in summaries], [])
120
+
121
+ # In order to remain consistent upon new fields being adding, for each of the following fields if they are present
122
+ # they will be output in the summary first in the order below. Any further fields will be output in the order each
123
+ # metric family is called, and within each family either in the order they were added to the dict (python >= 3.6) or
124
+ # randomly (python < 3.6).
125
+ default_order = ['HOTA', 'DetA', 'AssA', 'DetRe', 'DetPr', 'AssRe', 'AssPr', 'LocA', 'OWTA', 'HOTA(0)', 'LocA(0)',
126
+ 'HOTALocA(0)', 'MOTA', 'MOTP', 'MODA', 'CLR_Re', 'CLR_Pr', 'MTR', 'PTR', 'MLR', 'CLR_TP', 'CLR_FN',
127
+ 'CLR_FP', 'IDSW', 'MT', 'PT', 'ML', 'Frag', 'sMOTA', 'IDF1', 'IDR', 'IDP', 'IDTP', 'IDFN', 'IDFP',
128
+ 'Dets', 'GT_Dets', 'IDs', 'GT_IDs']
129
+ default_ordered_dict = OrderedDict(zip(default_order, [None for _ in default_order]))
130
+ for f, v in zip(fields, values):
131
+ default_ordered_dict[f] = v
132
+ for df in default_order:
133
+ if default_ordered_dict[df] is None:
134
+ del default_ordered_dict[df]
135
+ fields = list(default_ordered_dict.keys())
136
+ values = list(default_ordered_dict.values())
137
+
138
+ out_file = os.path.join(output_folder, cls + '_summary.txt')
139
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
140
+ with open(out_file, 'w', newline='') as f:
141
+ writer = csv.writer(f, delimiter=' ')
142
+ writer.writerow(fields)
143
+ writer.writerow(values)
144
+
145
+
146
+ def write_detailed_results(details, cls, output_folder):
147
+ """
148
+ Write detailed results to file
149
+
150
+ :param Dict[str, Object] details: dictionary of all trackers
151
+ :param List[str] cls: list of classes
152
+ :param List[str] output_folder: directory to store the detailed results
153
+
154
+ :return: None
155
+ ::
156
+
157
+ trackeval.utils.write_detailed_results(config, default_config, name)
158
+ """
159
+ sequences = details[0].keys()
160
+ fields = ['seq'] + sum([list(s['COMBINED_SEQ'].keys()) for s in details], [])
161
+ out_file = os.path.join(output_folder, cls + '_detailed.csv')
162
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
163
+ with open(out_file, 'w', newline='') as f:
164
+ writer = csv.writer(f)
165
+ writer.writerow(fields)
166
+ for seq in sorted(sequences):
167
+ if seq == 'COMBINED_SEQ':
168
+ continue
169
+ writer.writerow([seq] + sum([list(s[seq].values()) for s in details], []))
170
+ writer.writerow(['COMBINED'] + sum([list(s['COMBINED_SEQ'].values()) for s in details], []))
171
+
172
+
173
+ def load_detail(file):
174
+ """
175
+ Loads detailed data for a tracker.
176
+
177
+ :param Dict[str] file: file to load the detailed results from
178
+
179
+ :return: Dict[str] :data
180
+ ::
181
+
182
+ trackeval.utils.load_detail(config, default_config, name)
183
+ """
184
+ data = {}
185
+ with open(file) as f:
186
+ for i, row_text in enumerate(f):
187
+ row = row_text.replace('\r', '').replace('\n', '').split(',')
188
+ if i == 0:
189
+ keys = row[1:]
190
+ continue
191
+ current_values = row[1:]
192
+ seq = row[0]
193
+ if seq == 'COMBINED':
194
+ seq = 'COMBINED_SEQ'
195
+ if (len(current_values) == len(keys)) and seq != '':
196
+ data[seq] = {}
197
+ for key, value in zip(keys, current_values):
198
+ data[seq][key] = float(value)
199
+ return data
200
+
201
+
202
+ class TrackEvalException(Exception):
203
+ """Custom exception for catching expected errors."""
204
+ ...
MTMC_Tracking_2024/eval/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Utils modules"""
MTMC_Tracking_2024/eval/utils/io_utils.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import argparse
4
+ import shutil
5
+ import json
6
+ import csv
7
+ import numpy as np
8
+ import pandas as pd
9
+ from typing import List, Set, Any
10
+
11
+
12
+ class ValidateFile(argparse.Action):
13
+ """
14
+ Module to validate files
15
+ """
16
+ def __call__(self, parser, namespace, values, option_string = None):
17
+
18
+ if not os.path.exists(values):
19
+ parser.error(f"Please enter a valid file path. Got: {values}")
20
+ elif not os.access(values, os.R_OK):
21
+ parser.error(f"File {values} doesn't have read access")
22
+ setattr(namespace, self.dest, values)
23
+
24
+
25
+ def validate_file_path(input_string: str) -> str:
26
+ """
27
+ Validates whether the input string matches a file path pattern
28
+
29
+ :param str input_string: input string
30
+ :return: validated file path
31
+ :rtype: str
32
+ ::
33
+
34
+ file_path = validate_file_path(input_string)
35
+ """
36
+ file_path_pattern = r"^[a-zA-Z0-9_\-\/.#]+$"
37
+
38
+ if re.match(file_path_pattern, input_string):
39
+ return input_string
40
+ else:
41
+ raise ValueError(f"Invalid file path: {input_string}")
42
+
43
+
44
+ def load_csv_to_dataframe_from_file(file_path: str, column_names: List[str], camera_ids: Set, interval: int = 1) -> pd.DataFrame:
45
+ """
46
+ Loads dataframe from a CSV file
47
+
48
+ :param str file_path: file path
49
+ :param List[str] column_names: column names
50
+ :return: dataframe in the file
51
+ :rtype: pd.DataFrame
52
+ ::
53
+
54
+ dataFrame = load_csv_to_dataframe_from_file(file_path, column_names)
55
+ """
56
+ data: List[List[str]] = list()
57
+ valid_file_path = validate_file_path(file_path)
58
+
59
+ df = pd.read_csv(valid_file_path, sep=" ", header=None, names=column_names, dtype={"CameraId": int, "Id": int, "FrameId": int})
60
+
61
+ # Ensure non-negative values for CameraId, Id, FrameId
62
+ if (df[['CameraId', 'Id', 'FrameId']] < 0).any().any():
63
+ raise ValueError("Invalid negative values found for CameraId, Id, or FrameId.")
64
+
65
+
66
+ # Filter by camera_id
67
+ df = df[df['CameraId'].isin(camera_ids)]
68
+
69
+ # Filter rows where FrameId % interval == 0
70
+ df = df[df['FrameId'] % interval == 0]
71
+
72
+ # Round the last two columns (assuming these are 'Xworld' and 'Yworld')
73
+ df['Xworld'] = df['Xworld'].round(3)
74
+ df['Yworld'] = df['Yworld'].round(3)
75
+
76
+ if len(df) == 0:
77
+ raise ValueError("DataFrame is empty after filtering process.")
78
+
79
+ return df
80
+
81
+
82
+ def write_dataframe_to_csv_to_file(file_path: str, data: pd.DataFrame, delimiter: str = " ") -> None:
83
+ """
84
+ Writes dataframe to a CSV file
85
+
86
+ :param str file_path: file path
87
+ :param pd.DataFrame data: dataframe to be written
88
+ :param str delimiter: delimiter of the CSV file
89
+ :return: None
90
+ ::
91
+
92
+ write_dataframe_to_csv_to_file(file_path, data, delimiter)
93
+ """
94
+ data.to_csv(file_path, sep=delimiter, index=False, header=False)
95
+
96
+
97
+ def make_dir(dir_path: str) -> None:
98
+ """
99
+ Makes a directory without removing other files
100
+
101
+ :param str dir_path: directory path
102
+ :return: None
103
+ ::
104
+
105
+ make_dir(dir_path)
106
+ """
107
+ valid_dir_path = validate_file_path(dir_path)
108
+ if not os.path.isdir(valid_dir_path):
109
+ os.makedirs(validate_file_path(dir_path))
110
+
111
+
112
+ def make_seq_maps_file(file_dir: str, scenes: List[str], benchmark: str, split_to_eval: str) -> None:
113
+ """
114
+ Makes a sequence-maps file used by TrackEval library
115
+
116
+ :param str file_dir: file path
117
+ :param Set(str) sensor_ids: names of sensors
118
+ :param str benchmark: name of the benchmark
119
+ :param str split_to_eval: name of the split of data
120
+ :return: None
121
+ ::
122
+
123
+ make_seq_maps_file(file_dir, sensor_ids)
124
+ """
125
+ make_clean_dir(file_dir)
126
+ file_name = benchmark + "-" +split_to_eval + ".txt"
127
+ seq_maps_file = file_dir + "/" + file_name
128
+ f = open(seq_maps_file, "w")
129
+ f.write("name\n")
130
+ for name in scenes:
131
+ sensor_name = str(name) + "\n"
132
+ f.write(sensor_name)
133
+ # f.write("FINAL")
134
+ f.close()
135
+
136
+
137
+ def make_seq_ini_file(gt_dir: str, scene: str, seq_length: int) -> None:
138
+ """
139
+ Makes a sequence-ini file used by TrackEval library
140
+
141
+ :param str gt_dir: file path
142
+ :param str scene: Name of a single scene
143
+ :param int seq_length: Number of frames
144
+
145
+ :return: None
146
+ ::
147
+
148
+ make_seq_ini_file(gt_dir, scene, seq_length)
149
+ """
150
+ ini_file_name = gt_dir + "/seqinfo.ini"
151
+ f = open(ini_file_name, "w")
152
+ f.write("[Sequence]\n")
153
+ name= "name=" +str(scene)+ "\n"
154
+ f.write(name)
155
+ f.write("imDir=img1\n")
156
+ f.write("frameRate=30\n")
157
+ seq = "seqLength=" + str(seq_length) + "\n"
158
+ f.write(seq)
159
+ f.write("imWidth=1920\n")
160
+ f.write("imHeight=1080\n")
161
+ f.write("imExt=.jpg\n")
162
+ f.close()
163
+
164
+
165
+ def get_scene_to_camera_id_dict(file_path):
166
+ """
167
+ Loads a mapping of scene names to camera IDs from a JSON file.
168
+
169
+ :param str file_path: Path to the JSON file containing scenes data.
170
+ :return: A dictionary where keys are scene names and values are lists of camera IDs.
171
+ ::
172
+
173
+ scene_to_camera_id_dict = get_scene_to_camera_id_dict(file_path)
174
+ """
175
+ scene_2_cam_id = dict()
176
+ valid_file_path = validate_file_path(file_path)
177
+ with open(valid_file_path, "r") as file:
178
+ scenes_data = json.load(file)
179
+ for scene_data in scenes_data:
180
+ scene_name = scene_data["scene_name"]
181
+ camera_ids = scene_data["camera_ids"]
182
+ if scene_name not in scene_2_cam_id:
183
+ scene_2_cam_id[scene_name] = []
184
+ scene_2_cam_id[scene_name].extend(camera_ids)
185
+ return scene_2_cam_id
186
+
187
+
188
+ def check_file_size(file_path):
189
+ """
190
+ Checks the size of a file and raises an exception if it exceeds 2 GB.
191
+
192
+ :param str file_path: Path to the file to be checked.
193
+ :return: None
194
+ :raises ValueError: If the file size is greater than 2 GB.
195
+ ::
196
+
197
+ check_file_size(file_path)
198
+ """
199
+ file_size_bytes = os.path.getsize(file_path)
200
+ file_size_gb = file_size_bytes / (2**30)
201
+ if file_size_gb > 2:
202
+ raise ValueError(f"The size of the file is {file_size_gb:.2f} GB, which is greater than the 2 GB")
203
+
204
+
205
+ def make_clean_dir(dir_path: str) -> None:
206
+ """
207
+ Makes a clean directory
208
+ :param str dir_path: directory path
209
+ :return: None
210
+ ::
211
+ make_clean_dir(dir_path)
212
+ """
213
+ valid_dir_path = validate_file_path(dir_path)
214
+ if os.path.exists(valid_dir_path):
215
+ shutil.rmtree(dir_path, ignore_errors=True)
216
+ if not os.path.isdir(valid_dir_path):
217
+ os.makedirs(validate_file_path(dir_path))