├── .gitignore ├── LICENCE ├── README.md ├── config ├── boost.pc.example ├── caffe.pc.example ├── cuda.pc.example ├── dlib-1.pc.example └── opencv.pc.example ├── cpp ├── README.md ├── makefile └── src │ ├── ImageTracker.cpp │ ├── ImageTracker.h │ ├── detector │ ├── Detector.cpp │ ├── Detector.h │ ├── RandomDetector.cpp │ ├── RandomDetector.h │ ├── SSDDetector.cpp │ └── SSDDetector.h │ ├── examples │ ├── DetectAndTrackDemo.cpp │ ├── DetectDemo.cpp │ └── TrackDemo.cpp │ ├── tracker │ ├── Affinity.cpp │ ├── Affinity.h │ ├── PAOT.cpp │ ├── PAOT.h │ ├── RandomTracker.cpp │ ├── RandomTracker.h │ ├── Tracker.cpp │ ├── Tracker.h │ └── predictor │ │ ├── Predictor.cpp │ │ ├── Predictor.h │ │ ├── StationaryPredictor.cpp │ │ ├── StationaryPredictor.h │ │ ├── kalman │ │ ├── KalmanPredictor.cpp │ │ └── KalmanPredictor.h │ │ └── particle │ │ ├── Particle.cpp │ │ ├── Particle.h │ │ ├── ParticleFilter.cpp │ │ ├── ParticleFilter.h │ │ ├── ParticlePredictor.cpp │ │ └── ParticlePredictor.h │ └── util │ ├── BoundingBox.cpp │ ├── BoundingBox.h │ ├── Detection.cpp │ ├── Detection.h │ ├── DetectionFileParser.cpp │ ├── DetectionFileParser.h │ ├── Tracking.cpp │ └── Tracking.h ├── data └── seqmaps │ └── seqmap.txt.example ├── makefile ├── models └── config │ └── model_config.txt.example └── python ├── README.md ├── generate_images.py └── generate_video.sh /.gitignore: -------------------------------------------------------------------------------- 1 | #### Project specific #### 2 | data/* 3 | models/* 4 | config/* 5 | external/* 6 | !*.example 7 | 8 | # Python 9 | python/output/ 10 | 11 | #### Language #### 12 | 13 | #### C++ #### 14 | *.o 15 | *.out 16 | *.out.dSYM/ 17 | *.d/ 18 | 19 | #### Python #### 20 | __pycache__/ 21 | *.py[cod] 22 | *$py.class 23 | 24 | #### IDE ##### 25 | # Clion 26 | cmake-build-debug/ 27 | CMakeLists.txt 28 | 29 | # Pycharm 30 | .idea/ -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tracking-by-detection 2 | Code for my master thesis, titled "Real-Time Multiple Object Tracking: A Study on the Importance of Speed". 3 | 4 | ## Introduction 5 | In this project, we implement a multiple object tracker, following the _tracking-by-detection_ paradigm, as an extension of an existing method. It works by modelling the movement of objects by solving the filtering problem, and associating detections with predicted new locations in new frames using the Hungarian algorithm. Three different similarity measures are used, which use the location and shape of the bounding boxes. Compared to other trackers on the [MOTChallenge](https://motchallenge.net/) leaderboard, our method, referred to as _C++SORT_, is the fastest non-anonymous submission, while also achieving decent score on other metrics. By running our model on the [Okutama-Action](http://okutama-action.org/) dataset, sampled at different frame-rates, we show that the performance is greatly reduced when running the model - including detecting objects - in real-time. In most metrics, the score is reduced by 50%, but in certain cases as much as 90%. We argue that this indicates that other, slower methods could not be used for tracking in real-time, but that more research is required specifically on this. 6 | 7 | This work constitutes my master thesis. The thesis is published [on a university portal](http://www.diva-portal.org/smash/record.jsf?pid=diva2:1146388), but is also made avalable [on arXiv](https://arxiv.org/abs/1709.03572). 8 | 9 | ## Citing 10 | If you find the thesis or this repository useful in your research, please consider citing the report: 11 | ``` 12 | @article{murray2017real, 13 | title={Real-Time Multiple Object Tracking - A Study on the Importance of Speed}, 14 | author={Murray, Samuel}, 15 | journal={arXiv preprint arXiv:1709.03572}, 16 | year = {2017} 17 | } 18 | ``` 19 | 20 | ## Dependencies 21 | * Build: 22 | * C++11 23 | * make 24 | * pkg-config 25 | * Tracking: 26 | * dlib (≥19.4) 27 | * Detection: 28 | * OpenCV (≥3.2) 29 | * Caffe\* 30 | * Cuda\* (≥7) 31 | * Run demos: 32 | * Boost (≥1.63) 33 | 34 | \* For instructions on how to install `Caffe` and `Cuda`, see **Configure**. 35 | 36 | #### Mac 37 | Use [Homebrew](https://brew.sh/) to build packages. 38 | 39 | To install `OpenCV`, follow [this tutorial](http://www.pyimagesearch.com/2016/12/19/install-opencv-3-on-macos-with-homebrew-the-easy-way/). 40 | 41 | Remaining dependencies can be installed with: 42 | ``` 43 | $ brew install 44 | ``` 45 | 46 | It might be possible to build all packages yourself, without `Homebrew`. Please refer to the instructions for **Linux** below. 47 | 48 | #### Linux 49 | To install `boost`, see the [official documentation](http://www.boost.org/doc/libs/1_63_0/more/getting_started/unix-variants.html). 50 | 51 | To install `OpenCV`, see the [official documentation](http://docs.opencv.org/master/d7/d9f/tutorial_linux_install.html). 52 | 53 | To install `dlib`, download and unpack it from [here](http://dlib.net/). Build as a shared library with: 54 | ``` 55 | $ cd dlib- 56 | $ mkdir build 57 | $ cd build 58 | $ cmake .. 59 | $ make 60 | $ sudo make install 61 | ``` 62 | 63 | #### Windows 64 | Not tested. Please refer to the instructions for **Linux** above; some packages have similar guides for Windows. 65 | 66 | ## Configure 67 | 68 | #### Directory structure 69 | The following directories should be present in root: 70 | * `config` - `.pc` files for dependencies. 71 | * `cpp` - C++ source code. 72 | * `data` - Data sets and sequence maps for running demos. 73 | * `models` - Caffe models for object detection. 74 | * `python` - Python scripts for generating images. 75 | 76 | #### pkg-config 77 | Make sure `PKG_CONFIG_PATH` includes the paths to the `.pc` files for all dependencies. Alternatively, copy and modify the `.pc.example` files in `config/`. Test if `pkg-config` can find `.pc` files for all dependencies, including custom ones in `config/`: 78 | ``` 79 | $ make test 80 | ``` 81 | 82 | #### Caffe 83 | [This version of Caffe](https://github.com/weiliu89/caffe/tree/ssd) is used, which works with SSD models. Thorough instructions are given there on how to install and configure Caffe. They refer to the [official documentation](http://caffe.berkeleyvision.org/installation.html) on how to install prerequisites. 84 | 85 | #### Cuda 86 | See **Caffe** above. 87 | 88 | ## Demo 89 | #### Directory structure 90 | * `data/` - Put datasets (images and/or detections) here. Images are expected to be in `/images/`, and detections in `/model-type` (this is also where custom detections will be put). Sequence maps should exist in `data/seqmaps` (an example file is given). Tracking output will be in `data/result//.txt`. 91 | * `models/` - To use Caffe, put models in `models/`. Config files for each model should exist in `models/config/` (an example file is given). 92 | 93 | Three example usages are provided: 94 | 1. **Detect** - Detect objects in a provided sequence of images. Objects are detected by a CNN (Caffe). 95 | 1. **Track** - Track objects from provided detections. The detections should be on the format used in [MOTChallenge](https://motchallenge.net/). 96 | 1. **Detect and Track** - Track objects detected in a provided sequence of images. Objects are detected by a CNN (Caffe). 97 | 98 | ## Integrate in other projects 99 | All source code is in `cpp/src/`. 100 | * To track objects from pre-existing detections, create an instance of `MCSORT`. No code in `detector/` is needed. Use function `tracker.track()`. 101 | * To detect and track objects from images, create an instance of `ImageTracker`. Requires Caffe. Use function `tracker.detectAndTrack()`. 102 | -------------------------------------------------------------------------------- /config/boost.pc.example: -------------------------------------------------------------------------------- 1 | # Package Information for pkg-config 2 | 3 | # Path to where Boost is installed 4 | prefix=/path/to/boost 5 | # Path to where libraries are 6 | libdir=${prefix}/lib 7 | # Path to where include files are 8 | includedir=${prefix}/include 9 | 10 | Name: Boost 11 | Description: Boost provides free peer-reviewed portable C++ source libraries 12 | Version: 1.63.0 13 | Libs: -L${libdir} -lboost_filesystem -lboost_system 14 | Cflags: -isystem ${includedir} -------------------------------------------------------------------------------- /config/caffe.pc.example: -------------------------------------------------------------------------------- 1 | # Package Information for pkg-config 2 | 3 | # Path to where Caffe is installed 4 | prefix=/path/to/caffe 5 | # Path to where libraries are 6 | libdir=${prefix}/.build_release/lib 7 | # Path to where include files are 8 | includedir=${prefix}/include 9 | 10 | Name: Caffe 11 | Description: Deep learning framework by the BVLC 12 | Version: 1.0 13 | Libs: -L${libdir} -lcaffe 14 | Cflags: -isystem${includedir} -isystem${prefix}/.build_release/src -------------------------------------------------------------------------------- /config/cuda.pc.example: -------------------------------------------------------------------------------- 1 | # Package Information for pkg-config 2 | 3 | # Path to where CUDA is installed 4 | prefix=/path/to/cuda 5 | # Path to where include files are 6 | includedir=${prefix}/include 7 | 8 | Name: CUDA 9 | Description: A parallel computing platform and programming model invented by NVIDIA 10 | Version: 7.0 11 | Cflags: -isystem ${includedir} 12 | Libs: -lboost_system -lglog -lgflags -------------------------------------------------------------------------------- /config/dlib-1.pc.example: -------------------------------------------------------------------------------- 1 | # Package Information for pkg-config 2 | 3 | # Path to where dlib is installed 4 | prefix=/path/to/dlib 5 | # Path to where libraries are 6 | libdir=${prefix}/lib 7 | # Path to where include files are 8 | includedir=${prefix}/include 9 | 10 | Name: dlib 11 | Description: Numerical and networking C++ library 12 | Version: 19.4.0 13 | Libs: -L${libdir} -ldlib 14 | Cflags: -isystem${includedir} 15 | Requires: libpng -------------------------------------------------------------------------------- /config/opencv.pc.example: -------------------------------------------------------------------------------- 1 | # Package Information for pkg-config 2 | 3 | # Path to where OpenCV is installed 4 | prefix=/path/to/opencv3 5 | # Path to where libraries is 6 | libdir=${prefix}/lib 7 | # Path to where include files are 8 | includedir_old=${prefix}/include/opencv 9 | includedir_new=${prefix}/include 10 | 11 | Name: OpenCV 12 | Description: Open Source Computer Vision Library 13 | Version: 3.2.0 14 | Libs: -L${prefix}/lib -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_dpm -lopencv_fuzzy -lopencv_hdf -lopencv_line_descriptor -lopencv_optflow -lopencv_reg -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_rgbd -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_face -lopencv_plot -lopencv_dnn -lopencv_xfeatures2d -lopencv_shape -lopencv_video -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d -lopencv_flann -lopencv_xobjdetect -lopencv_objdetect -lopencv_ml -lopencv_xphoto -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_photo -lopencv_imgproc -lopencv_core 15 | Cflags: -I${includedir_old} -I${includedir_new} -------------------------------------------------------------------------------- /cpp/README.md: -------------------------------------------------------------------------------- 1 | # C++ 2 | The source code of the project. Code is located in `src/`. 3 | 4 | ## Compile 5 | Compile everything: 6 | ``` 7 | $ make compile [use_caffe=true] [force_rebuild=true] 8 | ``` 9 | 10 | Remove all created files: 11 | ``` 12 | $ make clean 13 | ``` 14 | 15 | Check the value of a makefile variable: 16 | ``` 17 | $ make print- 18 | ``` 19 | 20 | **NOTE:** Calling `make ` without passing `use_caffe=true` will make the preprocessor remove all code that uses Caffe. This is to enable compilation without Caffe installed. However, this can lead to problems when _e.g._ `make detect use_caffe=true` is called after `make track`, since the files that use Caffe will not be rebuilt. To prevent this, either pass `use_caffe=true` every time you compile, or call `force_rebuild=true` to force all `.o` files to be rebuilt. 21 | 22 | ## Demo 23 | Two example usages are provided. Note that the following targets will also compile the code, and so the same variables (`use_caffe` and `force_rebuild`) are used. 24 | Three example usages are provided: 25 | 1. **Detect** - Detect objects in a provided sequence of images. Objects are detected by a CNN (Caffe). 26 | ``` 27 | $ make detect 28 | $ ./detectApp.out [-s sequencesFile] [-m modelConfigFile] 29 | ``` 30 | 2. **Track** - Track objects from provided detections. The detections should be on the format used in [MOTChallenge](https://motchallenge.net/). 31 | ``` 32 | $ make track 33 | $ ./trackApp.out [-s sequencesFile] [-m modelType] \ 34 | [-d detectionFormat] [-i frameInterval] 35 | ``` 36 | 37 | 3. **Detect and Track** - Track objects detected in a provided sequence of images. Objects are detected by a CNN (Caffe). 38 | ``` 39 | $ make detectAndTrack 40 | $ ./trackApp.out [-s sequencesFile] [-m modelConfigFile] 41 | ``` 42 | 43 | ## Integrate in other projects 44 | * To detect objects from images, create an instance of `SSDDetector`. Requires Caffe. Use function `detector.detect()`. 45 | * To track objects from pre-existing detections, create an instance of `PAOT`. No code in `detector/` is needed. Use function `tracker.track()`. 46 | * To detect and track objects from images, create an instance of `ImageTracker`. Requires Caffe. Use function `tracker.detectAndTrack()`. 47 | -------------------------------------------------------------------------------- /cpp/makefile: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | # Compiler options 4 | CXX = g++ 5 | CXXFLAGS = -std=c++11 -g -Wall -pedantic 6 | LDFLAGS = 7 | DEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.Td 8 | 9 | # External libraries 10 | export PKG_CONFIG_PATH := ../config:$(PKG_CONFIG_PATH) 11 | 12 | # OpenCV 13 | CXXFLAGS += `pkg-config --cflags opencv` 14 | LDFLAGS += `pkg-config --libs opencv` 15 | 16 | # dlib 17 | CXXFLAGS += `pkg-config --cflags dlib-1` 18 | LDFLAGS += `pkg-config --libs dlib-1` 19 | 20 | # Boost 21 | CXXFLAGS += `pkg-config --cflags boost` 22 | LDFLAGS += `pkg-config --libs boost` 23 | 24 | # For compilation with Caffe 25 | use_caffe = false 26 | ifeq ($(use_caffe),true) 27 | # Caffe 28 | CXXFLAGS += -DUSE_CAFFE 29 | CXXFLAGS += `pkg-config --cflags caffe` 30 | LDFLAGS += `pkg-config --libs caffe` 31 | 32 | # Cuda 33 | CXXFLAGS += `pkg-config --cflags cuda` 34 | LDFLAGS += `pkg-config --libs cuda` 35 | endif 36 | 37 | # Directories 38 | SOURCEDIR = src 39 | BUILDDIR = build 40 | MAINDIR = examples 41 | DEPDIR = .d 42 | 43 | # Input/Output files 44 | SOURCES := $(shell find $(SOURCEDIR) -name "*.cpp") 45 | OBJECTS := $(patsubst $(SOURCEDIR)/%.cpp,$(BUILDDIR)/%.o,$(SOURCES)) 46 | DEPFILES := $(patsubst $(SOURCEDIR)/%.cpp,$(DEPDIR)/%.d,$(SOURCES)) 47 | TARGET_detect := detectApp.out 48 | TARGET_track := trackApp.out 49 | TARGET_detectAndTrack := detectAndTrackApp.out 50 | TARGETS := $(TARGET_detect) $(TARGET_track) $(TARGET_detectAndTrack) 51 | 52 | # For running DetectDemo.cpp 53 | OBJECTS_detect := $(filter-out $(BUILDDIR)/$(MAINDIR)/%.o,$(OBJECTS)) 54 | OBJECTS_detect += $(BUILDDIR)/$(MAINDIR)/DetectDemo.o 55 | 56 | # For running TrackDemo.cpp 57 | OBJECTS_track := $(filter-out $(BUILDDIR)/$(MAINDIR)/%.o,$(OBJECTS)) 58 | OBJECTS_track += $(BUILDDIR)/$(MAINDIR)/TrackDemo.o 59 | 60 | # For running DetectAndTrackDemo.cpp 61 | OBJECTS_detectAndTrack := $(filter-out $(BUILDDIR)/$(MAINDIR)/%.o,$(OBJECTS)) 62 | OBJECTS_detectAndTrack += $(BUILDDIR)/$(MAINDIR)/DetectAndTrackDemo.o 63 | 64 | # Build instructioncs 65 | MKDIRIFNOTEXIST = @test -d $(@D) || mkdir -p $(@D) 66 | COMPILE = $(CXX) $(DEPFLAGS) $(CXXFLAGS) -c 67 | POSTCOMPILE = mv -f $(DEPDIR)/$*.Td $(DEPDIR)/$*.d 68 | 69 | # Targets 70 | .SECONDEXPANSION: 71 | 72 | # Instructions 73 | all: 74 | @echo 'Call "make compile" to compile everything, or "make " to compile and link a specific target' 75 | 76 | # Print variable 77 | print-% : ; @echo $* = $($*) 78 | 79 | # Compile and link target 80 | detect track detectAndTrack: compile $$(TARGET_$$@) 81 | 82 | # Link target's objects 83 | %App.out: $$(OBJECTS_%) 84 | @echo '(link) CXX $@' 85 | @$(CXX) -o $@ $^ $(LDFLAGS) 86 | 87 | # Compile all files 88 | compile: $(OBJECTS) 89 | 90 | # Crazy alternative: [...]%.d | $(BUILDDIR)/$$(filter-out ./,$$(dir %)).dir --- %.dir: ; $(MKDIRIFNOTEXIST) 91 | $(BUILDDIR)/%.o: $(SOURCEDIR)/%.cpp $(DEPDIR)/%.d 92 | @echo '(compile) CXX $<' 93 | @$(MKDIRIFNOTEXIST) 94 | @$(COMPILE) $< -o $@ 95 | @$(POSTCOMPILE) 96 | 97 | $(DEPDIR)/%.d: 98 | $(MKDIRIFNOTEXIST) 99 | 100 | # Prevent files from being deleted as intermediate files by make 101 | .PRECIOUS: $(OBJECTS) $(DEPFILES) 102 | 103 | # Include dependency files 104 | include $(wildcard $(DEPFILES)) 105 | 106 | # Rebuild all object files 107 | force_rebuild = false 108 | ifeq ($(force_rebuild),true) 109 | $(shell rm $(OBJECTS)) 110 | endif 111 | 112 | # Remove all generated files 113 | .PHONY: clean 114 | clean: 115 | rm -f $(OBJECTS) 116 | rm -f $(DEPFILES) 117 | rm -f $(TARGETS) -------------------------------------------------------------------------------- /cpp/src/ImageTracker.cpp: -------------------------------------------------------------------------------- 1 | #include "ImageTracker.h" 2 | 3 | ImageTracker::ImageTracker(const std::shared_ptr &detector, const std::shared_ptr &tracker) 4 | : detector(detector), tracker(tracker) {} 5 | 6 | std::vector ImageTracker::detectAndTrack(const cv::Mat &image) const { 7 | return tracker->track(detector->detect(image)); 8 | } -------------------------------------------------------------------------------- /cpp/src/ImageTracker.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_IMAGETRACKER_H 2 | #define CPP_IMAGETRACKER_H 3 | 4 | 5 | #include "detector/Detector.h" 6 | #include "tracker/Tracker.h" 7 | 8 | #include 9 | 10 | class ImageTracker { 11 | public: 12 | ImageTracker(const std::shared_ptr &detector, const std::shared_ptr &tracker); 13 | 14 | /** 15 | * For each frame, gets a set of Detections from Detector and tracks them with Tracker. 16 | * Returns the Trackings. 17 | */ 18 | std::vector detectAndTrack(const cv::Mat &image) const; 19 | 20 | private: 21 | std::shared_ptr detector; 22 | std::shared_ptr tracker; 23 | }; 24 | 25 | 26 | #endif //CPP_IMAGETRACKER_H -------------------------------------------------------------------------------- /cpp/src/detector/Detector.cpp: -------------------------------------------------------------------------------- 1 | #include "Detector.h" -------------------------------------------------------------------------------- /cpp/src/detector/Detector.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_DETECTOR_H 2 | #define CPP_DETECTOR_H 3 | 4 | 5 | #include "../util/Detection.h" 6 | 7 | #include 8 | 9 | #include 10 | 11 | class Detector { 12 | public: 13 | Detector() = default; 14 | 15 | virtual ~Detector() = default; 16 | 17 | // Prevent copying and moving 18 | Detector(const Detector &) = delete; 19 | 20 | Detector(Detector &&rhs) = delete; 21 | 22 | Detector &operator=(const Detector &) = delete; 23 | 24 | Detector &operator=(Detector &&rhs) = delete; 25 | 26 | /** 27 | * Detects objects in a given image. 28 | * Returns the Detections. 29 | */ 30 | virtual std::vector detect(const cv::Mat &image) = 0; 31 | }; 32 | 33 | 34 | #endif //CPP_DETECTOR_H -------------------------------------------------------------------------------- /cpp/src/detector/RandomDetector.cpp: -------------------------------------------------------------------------------- 1 | #include "RandomDetector.h" 2 | 3 | // Methods 4 | 5 | std::vector RandomDetector::detect(const cv::Mat &image) { 6 | std::vector detections; 7 | detections.push_back(Detection(0, 1, BoundingBox(0.1 * image.cols + rand() % 10 - 5, 8 | 0.2 * image.rows + rand() % 10 - 5, 9 | 50, 10 | 50 11 | ))); 12 | detections.push_back(Detection(0, 1, BoundingBox(0.4 * image.cols + rand() % 10 - 5, 13 | 0.7 * image.rows + rand() % 10 - 5, 14 | 40, 15 | 100 16 | ))); 17 | detections.push_back(Detection(1, 1, BoundingBox(0.8 * image.cols + rand() % 10 - 5, 18 | 0.8 * image.rows + rand() % 10 - 5, 19 | 90, 20 | 30 21 | ))); 22 | return detections; 23 | } -------------------------------------------------------------------------------- /cpp/src/detector/RandomDetector.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_RANDOMDETECTOR_H 2 | #define CPP_RANDOMDETECTOR_H 3 | 4 | 5 | #include "Detector.h" 6 | 7 | class RandomDetector : public Detector { 8 | public: 9 | RandomDetector() = default; 10 | 11 | /** 12 | * Returns a set of (semi) random Detections, independent of the image. 13 | * Only used as a placeholder for a real Detector, e.g. for debugging. 14 | */ 15 | std::vector detect(const cv::Mat &image) override; 16 | }; 17 | 18 | 19 | #endif //CPP_RANDOMDETECTOR_H -------------------------------------------------------------------------------- /cpp/src/detector/SSDDetector.cpp: -------------------------------------------------------------------------------- 1 | #include "SSDDetector.h" 2 | 3 | #ifdef USE_CAFFE 4 | 5 | #include 6 | #include 7 | 8 | using caffe::Caffe; 9 | using caffe::Net; 10 | using caffe::Blob; 11 | 12 | // Constructors 13 | 14 | SSDDetector::SSDDetector(const std::string &modelFile, const std::string &weightsFile, const std::string &meanValue) 15 | : Detector() { 16 | Caffe::set_mode(Caffe::GPU); 17 | 18 | // Load the network. 19 | net.reset(new Net(modelFile, caffe::TEST)); 20 | net->CopyTrainedLayersFrom(weightsFile); 21 | 22 | Blob *inputLayer = net->input_blobs()[0]; 23 | numChannels = inputLayer->channels(); 24 | inputGeometry = cv::Size(inputLayer->width(), inputLayer->height()); 25 | setMean(meanValue); 26 | } 27 | 28 | // Methods 29 | 30 | std::vector SSDDetector::detect(const cv::Mat &image) { 31 | Blob *inputLayer = net->input_blobs()[0]; 32 | inputLayer->Reshape(1, numChannels, inputGeometry.height, inputGeometry.width); 33 | 34 | // Forward dimension change to all layers. 35 | net->Reshape(); 36 | std::vector inputChannels; 37 | wrapInputLayer(&inputChannels); 38 | preprocess(image, &inputChannels); 39 | net->Forward(); 40 | 41 | // Copy the output layer to a vector 42 | Blob *resultBlob = net->output_blobs()[0]; 43 | 44 | // Result format: [image_id, label, score, xmin, ymin, xmax, ymax]. 45 | const float *result = resultBlob->cpu_data(); 46 | const int numDet = resultBlob->height(); 47 | std::vector detections; 48 | for (int k = 0; k < numDet; ++k) { 49 | if (result[0] == -1 || result[2] < 0.1) { 50 | // Skip invalid detection. 51 | result += 7; 52 | continue; 53 | } 54 | std::vector det(result, result + 7); 55 | 56 | Detection detection(int(det[1]), det[2], BoundingBox((det[3] + det[5]) / 2 * image.cols, 57 | (det[4] + det[6]) / 2 * image.rows, 58 | (det[5] - det[3]) * image.cols, 59 | (det[6] - det[4]) * image.rows 60 | )); 61 | 62 | detections.push_back(detection); 63 | result += 7; 64 | } 65 | return detections; 66 | } 67 | 68 | void SSDDetector::setMean(const std::string &meanValue) { 69 | cv::Scalar channelMean; 70 | std::stringstream ss(meanValue); 71 | std::vector values; 72 | std::string item; 73 | while (getline(ss, item, ',')) { 74 | double value = std::atof(item.c_str()); 75 | values.push_back(value); 76 | } 77 | 78 | std::vector channels; 79 | for (int i = 0; i < numChannels; ++i) { 80 | // Extract an individual channel. 81 | cv::Mat channel(inputGeometry.height, inputGeometry.width, CV_32FC1, cv::Scalar(values[i])); 82 | channels.push_back(channel); 83 | } 84 | cv::merge(channels, mean); 85 | } 86 | 87 | void SSDDetector::wrapInputLayer(std::vector *inputChannels) { 88 | Blob *inputLayer = net->input_blobs()[0]; 89 | 90 | int width = inputLayer->width(); 91 | int height = inputLayer->height(); 92 | float *inputData = inputLayer->mutable_cpu_data(); 93 | for (int i = 0; i < inputLayer->channels(); ++i) { 94 | cv::Mat channel(height, width, CV_32FC1, inputData); 95 | inputChannels->push_back(channel); 96 | inputData += width * height; 97 | } 98 | } 99 | 100 | void SSDDetector::preprocess(const cv::Mat &image, std::vector *inputChannels) { 101 | // Convert the input image to the input image format of the network. 102 | cv::Mat sample; 103 | if (image.channels() == 3 && numChannels == 1) 104 | cv::cvtColor(image, sample, cv::COLOR_BGR2GRAY); 105 | else if (image.channels() == 4 && numChannels == 1) 106 | cv::cvtColor(image, sample, cv::COLOR_BGRA2GRAY); 107 | else if (image.channels() == 4 && numChannels == 3) 108 | cv::cvtColor(image, sample, cv::COLOR_BGRA2BGR); 109 | else if (image.channels() == 1 && numChannels == 3) 110 | cv::cvtColor(image, sample, cv::COLOR_GRAY2BGR); 111 | else 112 | sample = image; 113 | 114 | cv::Mat sampleResized; 115 | if (sample.size() != inputGeometry) 116 | cv::resize(sample, sampleResized, inputGeometry); 117 | else 118 | sampleResized = sample; 119 | 120 | cv::Mat sampleFloat; 121 | if (numChannels == 3) 122 | sampleResized.convertTo(sampleFloat, CV_32FC3); 123 | else 124 | sampleResized.convertTo(sampleFloat, CV_32FC1); 125 | 126 | cv::Mat sampleNormalized; 127 | cv::subtract(sampleFloat, mean, sampleNormalized); 128 | 129 | /* 130 | * This operation will write the separate BGR planes directly to the 131 | * input layer of the network because it is wrapped by the cv::Mat 132 | * objects in inputChannels. 133 | */ 134 | cv::split(sampleNormalized, *inputChannels); 135 | } 136 | 137 | #else //USE_CAFFE 138 | 139 | #include 140 | #include 141 | SSDDetector::SSDDetector() { 142 | std::cerr << "Use of SSDDetector requires Caffe; compile with USE_CAFFE.\n"; 143 | throw std::runtime_error("Use of SSDDetector requires Caffe; compile with USE_CAFFE."); 144 | } 145 | 146 | SSDDetector::SSDDetector(const std::string &model_file, 147 | const std::string &weights_file, 148 | const std::string &mean_value) : SSDDetector() {} 149 | std::vector SSDDetector::detect(const cv::Mat &image) { 150 | throw std::runtime_error("Use of SSDDetector requires Caffe; compile with USE_CAFFE."); 151 | } 152 | 153 | #endif //USE_CAFFE -------------------------------------------------------------------------------- /cpp/src/detector/SSDDetector.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_SSDDETECTOR_H 2 | #define CPP_SSDDETECTOR_H 3 | 4 | 5 | #include "Detector.h" 6 | 7 | #include 8 | 9 | #ifdef USE_CAFFE 10 | 11 | #include 12 | 13 | #endif //USE_CAFFE 14 | 15 | #include 16 | #include 17 | 18 | #ifdef USE_CAFFE 19 | 20 | class SSDDetector : public Detector { 21 | public: 22 | SSDDetector(const std::string &modelFile, const std::string &weightsFile, const std::string &meanValue); 23 | 24 | std::vector detect(const cv::Mat &image) override; 25 | 26 | private: 27 | void setMean(const std::string &meanValue); 28 | 29 | /** 30 | * Wrap the input layer of the network in separate cv::Mat objects 31 | * (one per channel). This way we save one memcpy operation and we 32 | * don't need to rely on cudaMemcpy2D. The last preprocessing operation 33 | * will write the separate channels directly to the input layer. 34 | */ 35 | void wrapInputLayer(std::vector *inputChannels); 36 | 37 | void preprocess(const cv::Mat &image, std::vector *inputChannels); 38 | 39 | std::shared_ptr> net; 40 | cv::Size inputGeometry; 41 | int numChannels; 42 | cv::Mat mean; 43 | }; 44 | 45 | #else // USE_CAFFE 46 | 47 | class SSDDetector : public Detector { 48 | public: 49 | SSDDetector(); 50 | 51 | SSDDetector(const std::string &model_file, const std::string &weights_file, const std::string &mean_value); 52 | 53 | std::vector detect(const cv::Mat &image) override; 54 | }; 55 | 56 | #endif //USE_CAFFE 57 | 58 | 59 | #endif //CPP_SSDDETECTOR_H -------------------------------------------------------------------------------- /cpp/src/examples/DetectAndTrackDemo.cpp: -------------------------------------------------------------------------------- 1 | #include "../ImageTracker.h" 2 | #include "../detector/RandomDetector.h" 3 | #include "../detector/SSDDetector.h" 4 | #include "../tracker/PAOT.h" 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | static const boost::filesystem::path dataDirPath = boost::filesystem::current_path().parent_path() / "data"; 21 | static const boost::filesystem::path modelDirPath = boost::filesystem::current_path().parent_path() / "models"; 22 | static const double originalFrameRate = 30; 23 | 24 | const char *USAGE_MESSAGE = "Usage: %s " 25 | "-s sequenceMap " 26 | "-m modelConfigFile " 27 | "[-r]\n"; 28 | const char *OPEN_FILE_MESSAGE = "Could not open file %s\n"; 29 | const char *OPEN_DIR_MESSAGE = "Could not open directory %s\n"; 30 | const char *FILE_EXISTS_MESSAGE = "Output file %s already exists; don't overwrite\n"; 31 | 32 | std::pair, int> detectAndTrack(const std::shared_ptr &detector, 33 | const boost::filesystem::path &sequencePath, 34 | const std::string &modelType, 35 | const bool realTime) { 36 | typedef std::chrono::duration msduration; 37 | 38 | // Make sure input directory exists 39 | boost::filesystem::path inputDirPath = dataDirPath / sequencePath / "images"; 40 | if (!boost::filesystem::is_directory(inputDirPath)) { 41 | fprintf(stderr, OPEN_DIR_MESSAGE, sequencePath.c_str()); 42 | exit(EXIT_FAILURE); 43 | } 44 | 45 | // Create output directory if not exists 46 | boost::filesystem::path outputDirPath = dataDirPath / "results" / sequencePath.parent_path() / modelType; 47 | if (!boost::filesystem::is_directory(outputDirPath)) { 48 | boost::filesystem::create_directories(outputDirPath); 49 | } 50 | 51 | // Make sure output file does not exist 52 | boost::filesystem::path outputPath = outputDirPath / (sequencePath.filename().string() + ".txt"); 53 | if (boost::filesystem::exists(outputPath)) { 54 | fprintf(stderr, FILE_EXISTS_MESSAGE, outputPath.c_str()); 55 | return std::pair(msduration(0), 0); 56 | } 57 | 58 | // Make sure output file can be opened 59 | std::ofstream outputStream; 60 | outputStream.open(outputPath.string()); 61 | if (!outputStream.is_open()) { 62 | fprintf(stderr, OPEN_FILE_MESSAGE, outputPath.c_str()); 63 | exit(EXIT_FAILURE); 64 | } 65 | 66 | ImageTracker imageTracker(detector, std::make_shared()); 67 | 68 | std::vector imagePaths; 69 | std::copy(boost::filesystem::directory_iterator(inputDirPath), 70 | boost::filesystem::directory_iterator(), 71 | std::back_inserter(imagePaths)); 72 | std::sort(imagePaths.begin(), imagePaths.end()); 73 | 74 | msduration cumulativeDuration = std::chrono::milliseconds::zero(); 75 | int frameCount = 0; 76 | int frame = 0; 77 | for (auto imageIt = imagePaths.begin(); imageIt != imagePaths.end(); ++imageIt) { 78 | std::cout << "Image: " << imageIt->string() << std::endl; 79 | cv::Mat image = cv::imread(imageIt->string(), 1); 80 | 81 | auto startTime = std::chrono::high_resolution_clock::now(); 82 | std::vector trackings = imageTracker.detectAndTrack(image); 83 | auto endTime = std::chrono::high_resolution_clock::now(); 84 | msduration duration = std::chrono::duration_cast( 85 | endTime - startTime); 86 | cumulativeDuration += duration; 87 | 88 | for (auto trackingIt = trackings.begin(); trackingIt != trackings.end(); ++trackingIt) { 89 | outputStream << frame << "," 90 | << trackingIt->ID << "," 91 | << trackingIt->bb.x1() << "," 92 | << trackingIt->bb.y1() << "," 93 | << trackingIt->bb.width << "," 94 | << trackingIt->bb.height << "," 95 | << "1" << "," // Confidence 96 | << "-1,-1,-1" << "," // Unused 97 | << trackingIt->label << "\n"; 98 | } 99 | if (realTime) { 100 | int framesToSkip = int((originalFrameRate * duration.count()) / 1000) - 1; 101 | std::cout << "Skipping " << framesToSkip << " frames" << std::endl; 102 | for (int i = 0; i < framesToSkip; ++i) { 103 | if (imageIt == imagePaths.end()) { 104 | ++frameCount; 105 | outputStream.close(); 106 | return std::pair(cumulativeDuration, frameCount); 107 | } 108 | ++frame; 109 | ++imageIt; 110 | } 111 | } 112 | ++frame; 113 | ++frameCount; 114 | if (frameCount % 100 == 0) { 115 | std::cout << "Processed " << frameCount << " images" << std::endl; 116 | } 117 | } 118 | outputStream.close(); 119 | return std::pair(cumulativeDuration, frameCount); 120 | } 121 | 122 | #ifdef USE_CAFFE 123 | 124 | int main(int argc, char **argv) { 125 | 126 | std::string sequenceMapName; 127 | std::string modelConfigFileName; 128 | std::string modelType; 129 | bool realTime = false; 130 | std::shared_ptr detector; 131 | 132 | int opt; 133 | while ((opt = getopt(argc, argv, "s:m:r")) != -1) { 134 | switch (opt) { 135 | case 's': 136 | sequenceMapName = optarg; 137 | break; 138 | case 'm': 139 | modelConfigFileName = optarg; 140 | break; 141 | case 'r': 142 | realTime = true; 143 | break; 144 | default: 145 | fprintf(stderr, USAGE_MESSAGE, argv[0]); 146 | exit(EXIT_FAILURE); 147 | } 148 | } 149 | if (sequenceMapName == "" || modelConfigFileName == "") { 150 | fprintf(stderr, USAGE_MESSAGE, argv[0]); 151 | exit(EXIT_FAILURE); 152 | } 153 | 154 | boost::filesystem::path modelConfigFilePath = modelDirPath / "config" / modelConfigFileName; 155 | std::ifstream modelConfigFile(modelConfigFilePath.string()); 156 | if (modelConfigFile.is_open()) { 157 | std::string modelFile; 158 | std::string weightsFile; 159 | std::string meanValues; 160 | std::getline(modelConfigFile, modelType); 161 | std::getline(modelConfigFile, modelFile); 162 | std::getline(modelConfigFile, weightsFile); 163 | std::getline(modelConfigFile, meanValues); 164 | boost::filesystem::path modelFilePath = modelDirPath / modelFile; 165 | boost::filesystem::path weightsFilePath = modelDirPath / weightsFile; 166 | detector = std::make_shared(modelFilePath.string(), weightsFilePath.string(), meanValues); 167 | } else { 168 | fprintf(stderr, OPEN_FILE_MESSAGE, modelConfigFilePath.c_str()); 169 | exit(EXIT_FAILURE); 170 | } 171 | 172 | boost::filesystem::path sequenceMapPath = dataDirPath / "seqmaps" / sequenceMapName; 173 | std::ifstream sequenceMap(sequenceMapPath.string()); 174 | if (sequenceMap.is_open()) { 175 | 176 | std::chrono::duration cumulativeDuration; 177 | int cumulativeFrameCount = 0; 178 | 179 | std::string sequencePathString; 180 | while (std::getline(sequenceMap, sequencePathString)) { 181 | std::cout << "Sequence: " << sequencePathString << std::endl; 182 | auto durationFrameCount = detectAndTrack(detector, sequencePathString, modelType, realTime); 183 | auto duration = std::chrono::duration_cast(durationFrameCount.first).count(); 184 | std::cout << "Duration: " << duration << "ms" 185 | << " (" << double(durationFrameCount.second * 1000) / duration << "fps)\n"; 186 | cumulativeDuration += durationFrameCount.first; 187 | cumulativeFrameCount += durationFrameCount.second; 188 | } 189 | sequenceMap.close(); 190 | auto totalDuration = std::chrono::duration_cast(cumulativeDuration).count(); 191 | std::cout << "Total duration: " << double(totalDuration) / 1000 << "s" 192 | << " (" << double(cumulativeFrameCount * 1000) / totalDuration << "fps)\n"; 193 | } else { 194 | fprintf(stderr, OPEN_FILE_MESSAGE, sequenceMapName.c_str()); 195 | exit(EXIT_FAILURE); 196 | } 197 | exit(EXIT_SUCCESS); 198 | } 199 | 200 | #else //USE_CAFFE 201 | int main(int argc, char** argv) { 202 | std::cerr << "This example requires Caffe; compile with USE_CAFFE.\n"; 203 | exit(EXIT_FAILURE); 204 | } 205 | #endif //USE_CAFFE -------------------------------------------------------------------------------- /cpp/src/examples/DetectDemo.cpp: -------------------------------------------------------------------------------- 1 | #include "../detector/RandomDetector.h" 2 | #include "../detector/SSDDetector.h" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | static const boost::filesystem::path dataDirPath = boost::filesystem::current_path().parent_path() / "data"; 19 | static const boost::filesystem::path modelDirPath = boost::filesystem::current_path().parent_path() / "models"; 20 | 21 | const char *USAGE_MESSAGE = "Usage: %s " 22 | "-s sequenceMap " 23 | "-m modelConfigFile\n"; 24 | const char *OPEN_FILE_MESSAGE = "Could not open file %s\n"; 25 | const char *OPEN_DIR_MESSAGE = "Could not open directory %s\n"; 26 | const char *FILE_EXISTS_MESSAGE = "Output file %s already exists; don't overwrite\n"; 27 | 28 | std::pair, int> detect(const std::shared_ptr &detector, 29 | const boost::filesystem::path &sequencePath, 30 | const std::string &modelType) { 31 | typedef std::chrono::duration msduration; 32 | 33 | // Make sure input directory exists 34 | boost::filesystem::path inputDirPath = dataDirPath / sequencePath / "images"; 35 | if (!boost::filesystem::is_directory(inputDirPath)) { 36 | fprintf(stderr, OPEN_DIR_MESSAGE, sequencePath.c_str()); 37 | exit(EXIT_FAILURE); 38 | } 39 | 40 | // Create output directory if not exists 41 | boost::filesystem::path outputDirPath = dataDirPath / sequencePath / modelType; 42 | if (!boost::filesystem::is_directory(outputDirPath)) { 43 | boost::filesystem::create_directories(outputDirPath); 44 | } 45 | 46 | // Make sure output file does not exist 47 | boost::filesystem::path outputPath = outputDirPath / "det.txt"; 48 | if (boost::filesystem::exists(outputPath)) { 49 | fprintf(stderr, FILE_EXISTS_MESSAGE, outputPath.c_str()); 50 | return std::pair(msduration(0), 0); 51 | } 52 | 53 | // Make sure output file can be opened 54 | std::ofstream outputStream; 55 | outputStream.open(outputPath.string()); 56 | if (!outputStream.is_open()) { 57 | fprintf(stderr, OPEN_FILE_MESSAGE, outputPath.c_str()); 58 | exit(EXIT_FAILURE); 59 | } 60 | 61 | std::vector imagePaths; 62 | std::copy(boost::filesystem::directory_iterator(inputDirPath), 63 | boost::filesystem::directory_iterator(), 64 | std::back_inserter(imagePaths)); 65 | std::sort(imagePaths.begin(), imagePaths.end()); 66 | 67 | msduration cumulativeDuration = std::chrono::milliseconds::zero(); 68 | int frameCount = 0; 69 | for (auto imageIt = imagePaths.begin(); imageIt != imagePaths.end(); ++imageIt) { 70 | cv::Mat image = cv::imread(imageIt->string(), 1); 71 | 72 | auto startTime = std::chrono::high_resolution_clock::now(); 73 | std::vector detections = detector->detect(image); 74 | auto endTime = std::chrono::high_resolution_clock::now(); 75 | 76 | cumulativeDuration += std::chrono::duration_cast( 77 | endTime - startTime); 78 | 79 | for (auto detectionIt = detections.begin(); detectionIt != detections.end(); ++detectionIt) { 80 | outputStream << frameCount << "," 81 | << "-1" << "," // ID 82 | << detectionIt->bb.x1() << "," 83 | << detectionIt->bb.y1() << "," 84 | << detectionIt->bb.width << "," 85 | << detectionIt->bb.height << "," 86 | << detectionIt->confidence << "," 87 | << "-1,-1,-1" << "," // Unused 88 | << detectionIt->label << "\n"; 89 | } 90 | ++frameCount; 91 | if (frameCount % 100 == 0) { 92 | std::cout << "Processed " << frameCount << " images" << std::endl; 93 | } 94 | } 95 | outputStream.close(); 96 | return std::pair(cumulativeDuration, frameCount); 97 | } 98 | 99 | #ifdef USE_CAFFE 100 | 101 | int main(int argc, char **argv) { 102 | 103 | std::string sequenceMapName; 104 | std::string modelConfigFileName; 105 | std::string modelType; 106 | std::shared_ptr detector; 107 | 108 | int opt; 109 | while ((opt = getopt(argc, argv, "s:m:")) != -1) { 110 | switch (opt) { 111 | case 's': 112 | sequenceMapName = optarg; 113 | break; 114 | case 'm': 115 | modelConfigFileName = optarg; 116 | break; 117 | default: 118 | fprintf(stderr, USAGE_MESSAGE, argv[0]); 119 | exit(EXIT_FAILURE); 120 | } 121 | } 122 | if (sequenceMapName == "" || modelConfigFileName == "") { 123 | fprintf(stderr, USAGE_MESSAGE, argv[0]); 124 | exit(EXIT_FAILURE); 125 | } 126 | 127 | boost::filesystem::path modelConfigFilePath = modelDirPath / "config" / modelConfigFileName; 128 | std::ifstream modelConfigFile(modelConfigFilePath.string()); 129 | if (modelConfigFile.is_open()) { 130 | std::string modelFile; 131 | std::string weightsFile; 132 | std::string meanValues; 133 | std::getline(modelConfigFile, modelType); 134 | std::getline(modelConfigFile, modelFile); 135 | std::getline(modelConfigFile, weightsFile); 136 | std::getline(modelConfigFile, meanValues); 137 | boost::filesystem::path modelFilePath = modelDirPath / modelFile; 138 | boost::filesystem::path weightsFilePath = modelDirPath / weightsFile; 139 | detector = std::make_shared(modelFilePath.string(), weightsFilePath.string(), meanValues); 140 | } else { 141 | fprintf(stderr, OPEN_FILE_MESSAGE, modelConfigFilePath.c_str()); 142 | exit(EXIT_FAILURE); 143 | } 144 | 145 | boost::filesystem::path sequenceMapPath = dataDirPath / "seqmaps" / sequenceMapName; 146 | std::ifstream sequenceMap(sequenceMapPath.string()); 147 | if (sequenceMap.is_open()) { 148 | 149 | std::chrono::duration cumulativeDuration; 150 | int cumulativeFrameCount = 0; 151 | 152 | std::string sequencePathString; 153 | while (std::getline(sequenceMap, sequencePathString)) { 154 | std::cout << "Sequence: " << sequencePathString << std::endl; 155 | auto durationFrameCount = detect(detector, sequencePathString, modelType); 156 | auto duration = std::chrono::duration_cast(durationFrameCount.first).count(); 157 | std::cout << "Duration: " << duration << "ms" 158 | << " (" << double(durationFrameCount.second * 1000) / duration << "fps)\n"; 159 | cumulativeDuration += durationFrameCount.first; 160 | cumulativeFrameCount += durationFrameCount.second; 161 | } 162 | sequenceMap.close(); 163 | auto totalDuration = std::chrono::duration_cast(cumulativeDuration).count(); 164 | std::cout << "Total duration: " << double(totalDuration) / 1000 << "s" 165 | << " (" << double(cumulativeFrameCount * 1000) / totalDuration << "fps)\n"; 166 | } else { 167 | fprintf(stderr, OPEN_FILE_MESSAGE, sequenceMapName.c_str()); 168 | exit(EXIT_FAILURE); 169 | } 170 | exit(EXIT_SUCCESS); 171 | } 172 | 173 | #else //USE_CAFFE 174 | int main(int argc, char **argv) { 175 | std::cerr << "This example requires Caffe; compile with USE_CAFFE.\n"; 176 | exit(EXIT_FAILURE); 177 | } 178 | #endif //USE_CAFFE -------------------------------------------------------------------------------- /cpp/src/examples/TrackDemo.cpp: -------------------------------------------------------------------------------- 1 | #include "../tracker/Tracker.h" 2 | #include "../tracker/PAOT.h" 3 | #include "../util/DetectionFileParser.h" 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | const boost::filesystem::path dataDirPath = boost::filesystem::current_path().parent_path() / "data"; 14 | 15 | const char *USAGE_MESSAGE = "Usage: %s " 16 | "-s sequenceMap " 17 | "-m modelType " 18 | "-f detectionFormat " 19 | "[-i frameInterval (default 1)] " 20 | "[-x (overwrites result)]\n"; 21 | const char *OPEN_FILE_MESSAGE = "Could not open file %s\n"; 22 | const char *FILE_EXISTS_MESSAGE = "Output file %s already exists; won't overwrite\n"; 23 | 24 | std::pair, int> track(const boost::filesystem::path &sequencePath, 25 | const std::string &modelType, 26 | const std::string &detectionFormat, 27 | const int frameInterval, 28 | const bool doOverwriteResult) { 29 | typedef std::chrono::duration msduration; 30 | 31 | // Make sure input file exists 32 | boost::filesystem::path inputPath = dataDirPath / sequencePath / modelType / "det.txt"; 33 | std::ifstream inputStream(inputPath.string()); 34 | if (!inputStream.is_open()) { 35 | fprintf(stderr, OPEN_FILE_MESSAGE, inputPath.c_str()); 36 | return std::pair(msduration(0), 0); 37 | } 38 | 39 | // Create output directory if not exists 40 | boost::filesystem::path outputDirPath = dataDirPath / "results" / sequencePath.parent_path() / modelType; 41 | if (!boost::filesystem::is_directory(outputDirPath)) { 42 | boost::filesystem::create_directories(outputDirPath); 43 | } 44 | 45 | // Make sure output file does not exist 46 | boost::filesystem::path outputPath = outputDirPath / (sequencePath.filename().string() + ".txt"); 47 | if (boost::filesystem::exists(outputPath) && !doOverwriteResult) { 48 | fprintf(stderr, FILE_EXISTS_MESSAGE, outputPath.c_str()); 49 | return std::pair(msduration(0), 0); 50 | } 51 | 52 | // Make sure output file can be opened 53 | std::ofstream outputStream; 54 | outputStream.open(outputPath.string()); 55 | if (!outputStream.is_open()) { 56 | fprintf(stderr, OPEN_FILE_MESSAGE, outputPath.c_str()); 57 | return std::pair(msduration(0), 0); 58 | } 59 | 60 | PAOT tracker; 61 | 62 | std::map> (*parseFileFunc)(std::ifstream &file); 63 | if (detectionFormat == "okutama") { 64 | parseFileFunc = DetectionFileParser::parseOkutamaFile; 65 | } else if (detectionFormat == "mot") { 66 | parseFileFunc = DetectionFileParser::parseMOTFile; 67 | } else { 68 | throw std::invalid_argument(detectionFormat + " not a valid detectionFormat"); 69 | } 70 | const auto frameToDetections = parseFileFunc(inputStream); 71 | 72 | msduration cumulativeDuration = std::chrono::milliseconds::zero(); 73 | int frameCount = 0; 74 | for (int frame = 0; frame < frameToDetections.rbegin()->first; ++frame) { 75 | if (frame % frameInterval == 0 && frameToDetections.find(frame) != frameToDetections.end()) { 76 | auto startTime = std::chrono::high_resolution_clock::now(); 77 | std::vector trackings = tracker.track(frameToDetections.at(frame)); 78 | auto endTime = std::chrono::high_resolution_clock::now(); 79 | 80 | cumulativeDuration += std::chrono::duration_cast( 81 | endTime - startTime); 82 | 83 | for (auto trackingIt = trackings.begin(); trackingIt != trackings.end(); ++trackingIt) { 84 | outputStream << frame << "," 85 | << trackingIt->ID << "," 86 | << trackingIt->bb.x1() << "," 87 | << trackingIt->bb.y1() << "," 88 | << trackingIt->bb.width << "," 89 | << trackingIt->bb.height << "," 90 | << "1" << "," // Confidence 91 | << "-1,-1,-1" << "," // Unused 92 | << trackingIt->label << "\n"; 93 | } 94 | ++frameCount; 95 | } 96 | } 97 | outputStream.close(); 98 | return std::pair(cumulativeDuration, frameCount); 99 | } 100 | 101 | int main(int argc, char **argv) { 102 | 103 | std::string sequenceMapName; 104 | std::string modelType; 105 | std::string detectionFormat; 106 | int frameInterval = 1; 107 | bool doOverwriteResult = false; 108 | 109 | int opt; 110 | while ((opt = getopt(argc, argv, "s:m:f:i:x")) != -1) { 111 | switch (opt) { 112 | case 's': 113 | sequenceMapName = optarg; 114 | break; 115 | case 'm': 116 | modelType = optarg; 117 | break; 118 | case 'f': 119 | detectionFormat = optarg; 120 | break; 121 | case 'i': 122 | frameInterval = atoi(optarg); 123 | break; 124 | case 'x': 125 | doOverwriteResult = true; 126 | break; 127 | default: 128 | fprintf(stderr, USAGE_MESSAGE, argv[0]); 129 | exit(EXIT_FAILURE); 130 | } 131 | } 132 | 133 | if (sequenceMapName == "" || modelType == "" || detectionFormat == "") { 134 | fprintf(stderr, USAGE_MESSAGE, argv[0]); 135 | exit(EXIT_FAILURE); 136 | } 137 | if (frameInterval < 1) { 138 | fprintf(stderr, "frameInterval must be a positive integer"); 139 | exit(EXIT_FAILURE); 140 | } 141 | 142 | boost::filesystem::path sequenceMapPath = dataDirPath / "seqmaps" / sequenceMapName; 143 | std::ifstream sequenceMap(sequenceMapPath.string()); 144 | if (sequenceMap.is_open()) { 145 | 146 | std::chrono::duration cumulativeDuration; 147 | int cumulativeFrameCount = 0; 148 | 149 | std::string sequencePathString; 150 | while (getline(sequenceMap, sequencePathString)) { 151 | std::cout << "Sequence: " << sequencePathString << std::endl; 152 | auto durationFrameCount = track(sequencePathString, modelType, detectionFormat, frameInterval, 153 | doOverwriteResult); 154 | auto duration = std::chrono::duration_cast(durationFrameCount.first).count(); 155 | std::cout << "Duration: " << duration << "ms" 156 | << " (" << double(durationFrameCount.second * 1000) / duration << "fps)\n"; 157 | cumulativeDuration += durationFrameCount.first; 158 | cumulativeFrameCount += durationFrameCount.second; 159 | } 160 | sequenceMap.close(); 161 | auto totalDuration = std::chrono::duration_cast(cumulativeDuration).count(); 162 | std::cout << "Total duration: " << double(totalDuration) / 1000 << "s" 163 | << " (" << double(cumulativeFrameCount * 1000) / totalDuration << "fps)\n"; 164 | } else { 165 | fprintf(stderr, OPEN_FILE_MESSAGE, sequenceMapName.c_str()); 166 | exit(EXIT_FAILURE); 167 | } 168 | exit(EXIT_SUCCESS); 169 | } -------------------------------------------------------------------------------- /cpp/src/tracker/Affinity.cpp: -------------------------------------------------------------------------------- 1 | #include "Affinity.h" 2 | 3 | #include 4 | 5 | double Affinity::euclDist(const BoundingBox &a, const BoundingBox &b) { 6 | return std::sqrt(std::pow(a.cx - b.cx, 2) + std::pow(a.cy - b.cy, 2)); 7 | } 8 | 9 | double Affinity::iou(const BoundingBox &a, const BoundingBox &b) { 10 | double xx1 = std::max(a.x1(), b.x1()); 11 | double yy1 = std::max(a.y1(), b.y1()); 12 | double xx2 = std::min(a.x2(), b.x2()); 13 | double yy2 = std::min(a.y2(), b.y2()); 14 | double width = std::max(xx2 - xx1, 0.); 15 | double height = std::max(yy2 - yy1, 0.); 16 | double intersection = width * height; 17 | double uni = a.area() + b.area() - intersection; 18 | return intersection / uni; 19 | } 20 | 21 | double Affinity::linCost(const BoundingBox &a, const BoundingBox &b) { 22 | double positionCost = std::sqrt(std::pow(a.cx - b.cx, 2) + std::pow(a.cy - b.cy, 2)); 23 | double shapeCost = std::sqrt(std::pow(a.width - b.width, 2) + std::pow(a.height - b.height, 2)); 24 | return positionCost * shapeCost; 25 | } 26 | 27 | double Affinity::expCost(const BoundingBox &a, const BoundingBox &b) { 28 | // It is expected that a is detection and b is prediction 29 | double positionWeight = 0.5; 30 | double shapeWeight = 1.5; 31 | double positionCost = std::exp(-positionWeight * ( 32 | std::pow((a.cx - b.cx) / a.width, 2) + 33 | std::pow((a.cy - b.cy) / a.height, 2))); 34 | double shapeCost = std::exp(-shapeWeight * ( 35 | std::abs(a.width - b.width) / (a.width + b.width) + 36 | std::abs(a.height - b.height) / (a.height + b.height))); 37 | return positionCost * shapeCost; 38 | } -------------------------------------------------------------------------------- /cpp/src/tracker/Affinity.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_AFFINITY_H 2 | #define CPP_AFFINITY_H 3 | 4 | 5 | #include "../util/BoundingBox.h" 6 | 7 | class Affinity { 8 | public: 9 | /** 10 | * Euclidian distance 11 | * Small value indicates similarity 12 | */ 13 | static double euclDist(const BoundingBox &a, const BoundingBox &b); 14 | 15 | /** 16 | * Intersection over union 17 | * Large value indicates similarity 18 | * From: Simple Online and Realtime Tracking 19 | * (Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos, Ben Upcroft) 20 | */ 21 | static double iou(const BoundingBox &a, const BoundingBox &b); 22 | 23 | /** 24 | * Combination of linear similarity in position and shape 25 | * Small value indicates similarity 26 | * From: Online multi-target tracking with strong and weak detections 27 | * (Ricardo Sanchez-Matilla, Fabio Poiesi, Andrea Cavallaro Centre) 28 | */ 29 | static double linCost(const BoundingBox &a, const BoundingBox &b); 30 | 31 | /** 32 | * Combination of exponential similarity in position and shape 33 | * Large value indicates similarity 34 | * From: POI: Multiple Object Tracking with High Performance Detection and Appearance Feature 35 | * (Fengwei Yu, Wenbo Li, Quanquan Li, Yu Liu, Xiaohua Shi, Junjie Yan) 36 | * @param a BoundingBox from Detection 37 | * @param b BoundingBox from Predictor 38 | */ 39 | static double expCost(const BoundingBox &a, const BoundingBox &b); 40 | 41 | private: 42 | // Prevent instantiation 43 | Affinity() {}; 44 | }; 45 | 46 | 47 | #endif //CPP_AFFINITY_H -------------------------------------------------------------------------------- /cpp/src/tracker/PAOT.cpp: -------------------------------------------------------------------------------- 1 | #include "PAOT.h" 2 | 3 | #include "Affinity.h" 4 | #include "predictor/kalman/KalmanPredictor.h" 5 | #include "predictor/particle/ParticlePredictor.h" 6 | 7 | #include 8 | 9 | // Methods 10 | 11 | std::vector PAOT::track(const std::vector &detections) { 12 | frameCount++; 13 | 14 | // Filter detections on confidence 15 | std::vector strongDetections; 16 | for (const auto &detection : detections) { 17 | if (detection.confidence > detectionThreshold) { 18 | strongDetections.push_back(detection); 19 | } 20 | } 21 | 22 | Association association = associateDetectionsToPredictors(strongDetections, predictors, 23 | Affinity::expCost, affinityThreshold); 24 | 25 | // Update matched predictors with assigned detections 26 | 27 | for (const auto &match : association.matching) { 28 | predictors.at(match.second)->update(strongDetections.at(match.first)); 29 | } 30 | 31 | for (const auto p : association.unmatchedPredictors) { 32 | predictors.at(p)->update(); 33 | } 34 | 35 | // Create and initialise new predictors for unmatched detections 36 | for (const auto id : association.unmatchedDetections) { 37 | auto predictor = std::make_shared(strongDetections.at(id), ++trackCount); 38 | predictors.push_back(predictor); 39 | } 40 | 41 | // Remove predictors that have been inactive for too long 42 | predictors.erase(std::remove_if( 43 | predictors.begin(), predictors.end(), 44 | [this](const std::shared_ptr &predictor) { 45 | return predictor->getTimeSinceUpdate() > maxAge; 46 | }), predictors.end()); 47 | 48 | // Return trackings from active predictors 49 | std::vector trackings; 50 | for (auto it = predictors.begin(); it != predictors.end(); ++it) { 51 | if ((*it)->getTimeSinceUpdate() < 1 && 52 | ((*it)->getHitStreak() >= minHits || frameCount <= minHits)) { 53 | trackings.push_back((*it)->getTracking()); 54 | } 55 | } 56 | return trackings; 57 | } 58 | 59 | PAOT::Association PAOT::associateDetectionsToPredictors( 60 | const std::vector &detections, 61 | const std::vector> &predictors, 62 | double (*affinityMeasure)(const BoundingBox &a, const BoundingBox &b), 63 | double affinityThreshold) { 64 | 65 | const int DOUBLE_PRECISION = 100; 66 | std::vector> matches; 67 | std::vector unmatchedDetections; 68 | std::vector unmatchedPredictors; 69 | 70 | if (predictors.empty()) { 71 | for (int i = 0; i < detections.size(); ++i) 72 | unmatchedDetections.push_back(i); 73 | return PAOT::Association{matches, unmatchedDetections, unmatchedPredictors}; 74 | } 75 | 76 | dlib::matrix cost(detections.size(), predictors.size()); 77 | for (size_t row = 0; row < detections.size(); ++row) { 78 | for (size_t col = 0; col < predictors.size(); ++col) { 79 | cost(row, col) = int(DOUBLE_PRECISION * affinityMeasure( 80 | detections.at(row).bb, 81 | predictors.at(col)->getPredictedNextDetection().bb)); 82 | } 83 | } 84 | 85 | // Zero-pad to make it square 86 | if (cost.nr() > cost.nc()) { 87 | cost = dlib::join_rows(cost, dlib::zeros_matrix(1, cost.nr() - cost.nc())); 88 | } else if (cost.nc() > cost.nr()) { 89 | cost = dlib::join_cols(cost, dlib::zeros_matrix(cost.nc() - cost.nr(), 1)); 90 | } 91 | 92 | std::vector assignment = dlib::max_cost_assignment(cost); 93 | 94 | // Filter out matches with low IoU, including those for indices from padding 95 | for (int d = 0; d < assignment.size(); ++d) { 96 | if (cost(d, assignment[d]) < affinityThreshold * DOUBLE_PRECISION) { 97 | if (d < detections.size()) { 98 | unmatchedDetections.push_back(d); 99 | } 100 | if (assignment[d] < predictors.size()) { 101 | unmatchedPredictors.push_back(int(assignment[d])); 102 | } 103 | } else { 104 | matches.push_back(std::pair(d, assignment[d])); 105 | } 106 | } 107 | return PAOT::Association{matches, unmatchedDetections, unmatchedPredictors}; 108 | } -------------------------------------------------------------------------------- /cpp/src/tracker/PAOT.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_PAOT_H 2 | #define CPP_PAOT_H 3 | 4 | 5 | #include "Tracker.h" 6 | #include "predictor/Predictor.h" 7 | #include "predictor/kalman/KalmanPredictor.h" 8 | 9 | #include 10 | #include 11 | 12 | class PAOT : public Tracker { 13 | struct Association; 14 | 15 | public: 16 | PAOT() = default; 17 | 18 | virtual ~PAOT() = default; 19 | 20 | /** 21 | * Uses a linear velocity Kalman filters to predict locations of objects from previous frame. 22 | * Associates detections to Kalman filters using an Affinity measure and the Hungarian Algorithm. 23 | */ 24 | std::vector track(const std::vector &detections) override; 25 | 26 | private: 27 | const int maxAge = 2; // Original: 1 28 | const int minHits = 0; // Original: 3 29 | const double detectionThreshold = 0.4; 30 | const double affinityThreshold = 0.1; 31 | std::vector> predictors; 32 | int trackCount = 0; 33 | int frameCount = 0; 34 | 35 | /** 36 | * Uses an Affinity measure and Hungarian algorithm to determine which detection corresponds to which Kalman filter. 37 | */ 38 | static Association associateDetectionsToPredictors( 39 | const std::vector &detections, 40 | const std::vector> &predictors, 41 | double (*affinityMeasure)(const BoundingBox &a, const BoundingBox &b), 42 | double affinityThreshold); 43 | 44 | struct Association { 45 | std::vector> matching; 46 | std::vector unmatchedDetections; 47 | std::vector unmatchedPredictors; 48 | }; 49 | }; 50 | 51 | 52 | #endif //CPP_MCSORT_H -------------------------------------------------------------------------------- /cpp/src/tracker/RandomTracker.cpp: -------------------------------------------------------------------------------- 1 | #include "RandomTracker.h" 2 | 3 | #include 4 | 5 | // Methods 6 | 7 | std::vector RandomTracker::track(const std::vector &detections) { 8 | std::vector associatedDetections; 9 | std::map perLabelCount; 10 | for (const auto &det : detections) { 11 | Tracking d(det.label, perLabelCount[det.label]++, det.bb); 12 | associatedDetections.push_back(d); 13 | } 14 | return associatedDetections; 15 | } -------------------------------------------------------------------------------- /cpp/src/tracker/RandomTracker.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_RANDOMTRACKER_H 2 | #define CPP_RANDOMTRACKER_H 3 | 4 | 5 | #include "Tracker.h" 6 | #include "../detector/Detector.h" 7 | 8 | class RandomTracker : public Tracker { 9 | public: 10 | RandomTracker() = default; 11 | 12 | /** 13 | * Assigns IDs to Detections in the same order as they arrive. 14 | * Only used as a placeholder for a real Tracker, e.g. for debugging. 15 | */ 16 | std::vector track(const std::vector &detections) override; 17 | }; 18 | 19 | 20 | #endif //CPP_RANDOMTRACKER_H -------------------------------------------------------------------------------- /cpp/src/tracker/Tracker.cpp: -------------------------------------------------------------------------------- 1 | #include "Tracker.h" -------------------------------------------------------------------------------- /cpp/src/tracker/Tracker.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_TRACKER_H 2 | #define CPP_TRACKER_H 3 | 4 | 5 | #include "../util/Detection.h" 6 | #include "../util/Tracking.h" 7 | 8 | #include 9 | 10 | class Tracker { 11 | public: 12 | Tracker() = default; 13 | 14 | virtual ~Tracker() = default; 15 | 16 | // Prevent copying and moving 17 | Tracker(const Tracker &) = delete; 18 | 19 | Tracker(Tracker &&) = delete; 20 | 21 | Tracker &operator=(const Tracker &) = delete; 22 | 23 | Tracker &operator=(Tracker &&) = delete; 24 | 25 | /** 26 | * For each timestep, tracks the given Detections. 27 | * Returns the Trackings. 28 | */ 29 | virtual std::vector track(const std::vector &detections) = 0; 30 | }; 31 | 32 | 33 | #endif //CPP_TRACKER_H -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/Predictor.cpp: -------------------------------------------------------------------------------- 1 | #include "Predictor.h" 2 | 3 | // Constructors 4 | 5 | Predictor::Predictor(int label, int ID) 6 | : label(label), ID(ID), timeSinceUpdate(0), hitStreak(0) {} 7 | 8 | Predictor::Predictor(Predictor &&rhs) 9 | : label(rhs.label), ID(rhs.ID), timeSinceUpdate(rhs.timeSinceUpdate), hitStreak(rhs.hitStreak) {} 10 | 11 | Predictor &Predictor::operator=(Predictor &&rhs) { 12 | label = rhs.label; 13 | ID = rhs.ID; 14 | timeSinceUpdate = rhs.timeSinceUpdate; 15 | hitStreak = rhs.hitStreak; 16 | return *this; 17 | } 18 | 19 | // Methods 20 | 21 | void Predictor::update() { 22 | timeSinceUpdate++; 23 | hitStreak = 0; 24 | } 25 | 26 | void Predictor::update(const Detection &det) { 27 | timeSinceUpdate = 0; 28 | hitStreak++; 29 | } 30 | 31 | // Getters 32 | 33 | int Predictor::getTimeSinceUpdate() const { 34 | return timeSinceUpdate; 35 | } 36 | 37 | int Predictor::getHitStreak() const { 38 | return hitStreak; 39 | } 40 | 41 | int Predictor::getLabel() const { 42 | return label; 43 | } 44 | 45 | int Predictor::getID() const { 46 | return ID; 47 | } 48 | 49 | // Functions 50 | 51 | BoundingBox Predictor::stateToBoundingBox(const dlib::matrix &state) { 52 | double rectifiedArea = std::max(state(2), 0.); 53 | double width = std::sqrt(rectifiedArea * state(3)); 54 | double height = rectifiedArea / width; 55 | return BoundingBox(state(0), state(1), width, height); 56 | } 57 | 58 | dlib::matrix Predictor::boundingBoxToMeas(const BoundingBox &bb) { 59 | dlib::matrix z; 60 | z = bb.cx, bb.cy, bb.area(), bb.ratio(); 61 | return z; 62 | } 63 | 64 | std::ostream &operator<<(std::ostream &os, const Predictor &p) { 65 | os << p.getPredictedNextDetection(); 66 | return os; 67 | } -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/Predictor.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_PREDICTOR_H 2 | #define CPP_PREDICTOR_H 3 | 4 | 5 | #include "../../util/Detection.h" 6 | #include "../../util/Tracking.h" 7 | 8 | #include 9 | 10 | class Predictor { 11 | public: 12 | static constexpr int numStates = 7; // [x, y, area, ratio, vx, vy, area_change] 13 | static constexpr int numObservations = 4; // [x, y, area, ratio] 14 | 15 | public: 16 | Predictor(int label, int ID); 17 | 18 | virtual ~Predictor() = default; 19 | 20 | Predictor(Predictor &&rhs); 21 | 22 | Predictor &operator=(Predictor &&rhs); 23 | 24 | // Prevent copying 25 | Predictor(const Predictor &) = delete; 26 | 27 | Predictor &operator=(Predictor &) = delete; 28 | 29 | /** 30 | * Advances the state vector using current estimation. 31 | */ 32 | virtual void update() = 0; 33 | 34 | /** 35 | * Updates and advances the state vector using given Detection as observation. 36 | */ 37 | virtual void update(const Detection &det) = 0; 38 | 39 | /** 40 | * Returns the predicted next state as Detection. 41 | */ 42 | virtual Detection getPredictedNextDetection() const = 0; 43 | 44 | /** 45 | * Returns the current state as Tracking. 46 | */ 47 | virtual Tracking getTracking() const = 0; 48 | 49 | int getHitStreak() const; 50 | 51 | int getTimeSinceUpdate() const; 52 | 53 | int getLabel() const; 54 | 55 | int getID() const; 56 | 57 | /** 58 | * Converts a state vector to a BoundingBox. 59 | */ 60 | static BoundingBox stateToBoundingBox(const dlib::matrix &state); 61 | 62 | /** 63 | * Converts a BoundingBox to an observation vector. 64 | */ 65 | static dlib::matrix boundingBoxToMeas(const BoundingBox &bb); 66 | 67 | private: 68 | int label; 69 | int ID; 70 | int timeSinceUpdate; 71 | int hitStreak; 72 | }; 73 | 74 | std::ostream &operator<<(std::ostream &os, const Predictor &kp); 75 | 76 | 77 | #endif //CPP_PREDICTOR_H -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/StationaryPredictor.cpp: -------------------------------------------------------------------------------- 1 | #include "StationaryPredictor.h" 2 | 3 | // Constructors 4 | 5 | StationaryPredictor::StationaryPredictor(const Detection &initialState, int ID) 6 | : Predictor(initialState.label, ID), state(std::make_shared(initialState.bb)) {} 7 | 8 | StationaryPredictor::StationaryPredictor(StationaryPredictor &&rhs) 9 | : Predictor(std::move(rhs)), state(rhs.state) {} 10 | 11 | StationaryPredictor &StationaryPredictor::operator=(StationaryPredictor &&rhs) { 12 | Predictor::operator=(std::move(rhs)); 13 | state = std::move(rhs.state); 14 | return *this; 15 | } 16 | 17 | // Methods 18 | 19 | void StationaryPredictor::update() { 20 | Predictor::update(); 21 | } 22 | 23 | void StationaryPredictor::update(const Detection &det) { 24 | Predictor::update(det); 25 | state = std::make_shared(det.bb); 26 | } 27 | 28 | // Getters 29 | 30 | Detection StationaryPredictor::getPredictedNextDetection() const { 31 | return Detection(getLabel(), 1, *state); 32 | } 33 | 34 | Tracking StationaryPredictor::getTracking() const { 35 | return Tracking(getLabel(), getID(), *state); 36 | } -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/StationaryPredictor.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_STATIONARYPREDICTOR_H 2 | #define CPP_STATIONARYPREDICTOR_H 3 | 4 | 5 | #include "Predictor.h" 6 | 7 | #include 8 | 9 | class StationaryPredictor : public Predictor { 10 | public: 11 | StationaryPredictor(const Detection &initialState, int ID); 12 | 13 | StationaryPredictor(StationaryPredictor &&rhs); 14 | 15 | StationaryPredictor &operator=(StationaryPredictor &&rhs); 16 | 17 | /** 18 | * Does nothing except calling Predictor::update(). 19 | */ 20 | void update() override; 21 | 22 | /** 23 | * Sets state to match the Detection. 24 | */ 25 | void update(const Detection &det) override; 26 | 27 | /** 28 | * Returns state as Detection. 29 | */ 30 | Detection getPredictedNextDetection() const override; 31 | 32 | /** 33 | * Returns state as Tracking. 34 | */ 35 | Tracking getTracking() const override; 36 | 37 | private: 38 | std::shared_ptr state; 39 | }; 40 | 41 | 42 | #endif //CPP_STATIONARYPREDICTOR_H -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/kalman/KalmanPredictor.cpp: -------------------------------------------------------------------------------- 1 | #include "KalmanPredictor.h" 2 | 3 | // Constructors 4 | 5 | KalmanPredictor::KalmanPredictor(const Detection &initialState, int ID) 6 | : Predictor(initialState.label, ID), filter(nullptr) { 7 | dlib::matrix F; // System dynamics matrix 8 | dlib::matrix H; // Output matrix 9 | dlib::matrix Q; // Process noise covariance 10 | dlib::matrix R; // Measurement noise covariance 11 | dlib::matrix P; // Estimate error covariance 12 | 13 | // define constant velocity model 14 | F = 1, 0, 0, 0, 1, 0, 0, 15 | 0, 1, 0, 0, 0, 1, 0, 16 | 0, 0, 1, 0, 0, 0, 1, 17 | 0, 0, 0, 1, 0, 0, 0, 18 | 0, 0, 0, 0, 1, 0, 0, 19 | 0, 0, 0, 0, 0, 1, 0, 20 | 0, 0, 0, 0, 0, 0, 1; 21 | 22 | H = 1, 0, 0, 0, 0, 0, 0, 23 | 0, 1, 0, 0, 0, 0, 0, 24 | 0, 0, 1, 0, 0, 0, 0, 25 | 0, 0, 0, 1, 0, 0, 0; 26 | 27 | // Covariance values from SORT 28 | Q = 1, 0, 0, 0, 0, 0, 0, 29 | 0, 1, 0, 0, 0, 0, 0, 30 | 0, 0, 1, 0, 0, 0, 0, 31 | 0, 0, 0, 1, 0, 0, 0, 32 | 0, 0, 0, 0, .01, 0, 0, 33 | 0, 0, 0, 0, 0, .01, 0, 34 | 0, 0, 0, 0, 0, 0, .0001; 35 | 36 | R = 1, 0, 0, 0, 37 | 0, 1, 0, 0, 38 | 0, 0, 10, 0, 39 | 0, 0, 0, 10; 40 | 41 | P = 10, 0, 0, 0, 0, 0, 0, 42 | 0, 10, 0, 0, 0, 0, 0, 43 | 0, 0, 10, 0, 0, 0, 0, 44 | 0, 0, 0, 10, 0, 0, 0, 45 | 0, 0, 0, 0, 10000, 0, 0, 46 | 0, 0, 0, 0, 0, 10000, 0, 47 | 0, 0, 0, 0, 0, 0, 10000; 48 | 49 | filter = std::make_shared>( 50 | dlib::kalman_filter()); 51 | filter->set_transition_model(F); 52 | filter->set_observation_model(H); 53 | filter->set_process_noise(Q); 54 | filter->set_measurement_noise(R); 55 | filter->set_estimation_error_covariance(P); 56 | dlib::matrix x0(boundingBoxToMeas(initialState.bb)); 57 | filter->update(x0); 58 | } 59 | 60 | KalmanPredictor::KalmanPredictor(KalmanPredictor &&rhs) 61 | : Predictor(std::move(rhs)), filter(std::move(rhs.filter)) {} 62 | 63 | 64 | KalmanPredictor &KalmanPredictor::operator=(KalmanPredictor &&rhs) { 65 | Predictor::operator=(std::move(rhs)); 66 | filter = std::move(rhs.filter); 67 | return *this; 68 | } 69 | 70 | // Methods 71 | 72 | void KalmanPredictor::update() { 73 | Predictor::update(); 74 | filter->update(); 75 | } 76 | 77 | void KalmanPredictor::update(const Detection &det) { 78 | Predictor::update(det); 79 | filter->update(boundingBoxToMeas(det.bb)); 80 | } 81 | 82 | // Getters 83 | 84 | Detection KalmanPredictor::getPredictedNextDetection() const { 85 | return Detection(getLabel(), 1, stateToBoundingBox(filter->get_predicted_next_state())); 86 | } 87 | 88 | Tracking KalmanPredictor::getTracking() const { 89 | return Tracking(getLabel(), getID(), stateToBoundingBox(filter->get_current_state())); 90 | } -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/kalman/KalmanPredictor.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_KALMANPREDICTOR_H 2 | #define CPP_KALMANPREDICTOR_H 3 | 4 | 5 | #include "../Predictor.h" 6 | 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | class KalmanPredictor : public Predictor { 13 | public: 14 | KalmanPredictor(const Detection &initialState, int ID); 15 | 16 | KalmanPredictor(KalmanPredictor &&rhs); 17 | 18 | KalmanPredictor &operator=(KalmanPredictor &&rhs); 19 | 20 | /** 21 | * Advances the state vector using current estimation. 22 | */ 23 | void update() override; 24 | 25 | /** 26 | * Updates and advances the state vector using given Detection as observation. 27 | */ 28 | void update(const Detection &det) override; 29 | 30 | /** 31 | * Returns the predicted next state as Detection. 32 | */ 33 | Detection getPredictedNextDetection() const override; 34 | 35 | /** 36 | * Returns the current state as Tracking. 37 | */ 38 | Tracking getTracking() const override; 39 | 40 | private: 41 | std::shared_ptr> filter; 42 | }; 43 | 44 | 45 | #endif //CPP_KALMANPREDICTOR_H -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/particle/Particle.cpp: -------------------------------------------------------------------------------- 1 | #include "Particle.h" 2 | 3 | Particle::Particle(const dlib::matrix &state, double weight) 4 | : state(state), weight(weight) {} 5 | 6 | Particle::Particle(const Particle &rhs) { 7 | state = rhs.state; 8 | weight = rhs.weight; 9 | } 10 | 11 | Particle &Particle::operator=(const Particle &rhs) { 12 | state = rhs.state; 13 | weight = rhs.weight; 14 | return *this; 15 | } 16 | -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/particle/Particle.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_PARTICLE_H 2 | #define CPP_PARTICLE_H 3 | 4 | 5 | #include 6 | 7 | class Particle { 8 | static constexpr int numStates = 7; 9 | public: 10 | Particle(const dlib::matrix &state, double weight); 11 | 12 | virtual ~Particle() = default; 13 | 14 | Particle(const Particle &rhs); 15 | 16 | Particle &operator=(const Particle &rhs); 17 | 18 | // No move 19 | Particle &operator=(Particle &&rhs) = delete; 20 | 21 | Particle(Particle &&rhs) = delete; 22 | 23 | dlib::matrix state; 24 | double weight; 25 | }; 26 | 27 | 28 | #endif //CPP_PARTICLE_H -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/particle/ParticleFilter.cpp: -------------------------------------------------------------------------------- 1 | #include "ParticleFilter.h" 2 | #include "../Predictor.h" 3 | #include "../../Affinity.h" 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | // Constructors 10 | ParticleFilter::ParticleFilter(const BoundingBox &initialState) 11 | : particles(std::vector>(numParticles)) { 12 | std::default_random_engine generator; 13 | std::normal_distribution norm(0, 1); 14 | for (auto &particle : particles) { 15 | // TODO: Different noise for different fields 16 | dlib::matrix state; 17 | state = initialState.cx, initialState.cy, initialState.area(), initialState.ratio(), 0, 0, 0; 18 | dlib::matrix noise; 19 | noise = 0, 0, 0, 0, norm(generator), norm(generator), norm(generator); 20 | state += noise; 21 | particle = std::make_shared(state, 1. / numParticles); 22 | } 23 | velocityModel = 1, 0, 0, 0, 1, 0, 0, 24 | 0, 1, 0, 0, 0, 1, 0, 25 | 0, 0, 1, 0, 0, 0, 1, 26 | 0, 0, 0, 1, 0, 0, 0, 27 | 0, 0, 0, 0, 1, 0, 0, 28 | 0, 0, 0, 0, 0, 1, 0, 29 | 0, 0, 0, 0, 0, 0, 1; 30 | } 31 | 32 | ParticleFilter::ParticleFilter(ParticleFilter &&rhs) 33 | : particles(std::move(rhs.particles)), 34 | velocityModel(std::move(rhs.velocityModel)) {} 35 | 36 | ParticleFilter &ParticleFilter::operator=(ParticleFilter &&rhs) { 37 | particles = std::move(rhs.particles); 38 | velocityModel = std::move(rhs.velocityModel); 39 | return *this; 40 | } 41 | 42 | // Methods 43 | 44 | void ParticleFilter::update() { 45 | std::default_random_engine generator; 46 | std::normal_distribution norm(0, 1); 47 | for (auto &particle : particles) { 48 | dlib::matrix noise; 49 | noise = 0, 0, 0, 0, norm(generator), norm(generator), norm(generator); 50 | particle->state = velocityModel * (particle->state + noise); 51 | } 52 | } 53 | 54 | void ParticleFilter::update(const BoundingBox &bb) { 55 | std::default_random_engine generator; 56 | std::normal_distribution norm(0, 1); 57 | for (auto &particle : particles) { 58 | dlib::matrix noise; 59 | noise = 0, 0, 0, 0, norm(generator), norm(generator), norm(generator); 60 | particle->state = velocityModel * (particle->state + noise); 61 | } 62 | double weightSum = 0; 63 | for (int i = 0; i < numParticles; ++i) { 64 | particles.at(i)->weight = Affinity::iou(bb, Predictor::stateToBoundingBox(particles.at(i)->state)); 65 | weightSum += particles.at(i)->weight; 66 | } 67 | if (weightSum == 0) { 68 | // If not particle is good, restart with a new filter 69 | ParticleFilter newFilter(bb); 70 | *this = std::move(newFilter); 71 | return; 72 | } 73 | for (int i = 0; i < numParticles; ++i) { 74 | particles.at(i)->weight /= weightSum; 75 | } 76 | resample(); 77 | } 78 | 79 | BoundingBox ParticleFilter::getPrediction() const { 80 | dlib::matrix meanState = dlib::zeros_matrix(numStates, 1); 81 | for (const auto &particle : particles) { 82 | meanState += velocityModel * particle->state; 83 | } 84 | meanState /= numParticles; 85 | return Predictor::stateToBoundingBox(meanState); 86 | } 87 | 88 | BoundingBox ParticleFilter::getCurrentEstimate() const { 89 | dlib::matrix meanState = dlib::zeros_matrix(numStates, 1); 90 | for (const auto &particle : particles) { 91 | meanState += particle->state; 92 | } 93 | meanState /= numParticles; 94 | return Predictor::stateToBoundingBox(meanState); 95 | } 96 | 97 | void ParticleFilter::resample() { 98 | std::vector> newParticles(numParticles); 99 | std::vector weightDistribution; 100 | double weightSum = 0; 101 | for (int i = 0; i < numParticles; ++i) { 102 | weightSum += particles.at(i)->weight; 103 | weightDistribution.push_back(weightSum); 104 | } 105 | double interval = 1. / weightSum; 106 | int weightIdx = 0; 107 | for (int i = 0; i < numParticles; ++i) { 108 | double val = i * interval; 109 | while (val <= weightSum && val > weightDistribution.at(weightIdx)) { 110 | ++weightIdx; 111 | } 112 | newParticles.at(i) = particles.at(weightIdx); 113 | } 114 | particles = newParticles; 115 | /* 116 | for (int i = 0; i < numParticles; ++i) { 117 | double r = ((double) rand() / RAND_MAX); 118 | std::lower_bound(weightDistribution.begin(), weightDistribution.end(), r); 119 | 120 | } 121 | */ 122 | } -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/particle/ParticleFilter.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_PARTICLEFILTER_H 2 | #define CPP_PARTICLEFILTER_H 3 | 4 | 5 | #include "Particle.h" 6 | #include "../../../util/BoundingBox.h" 7 | 8 | #include 9 | 10 | class ParticleFilter { 11 | public: 12 | static constexpr int numStates = 7; // [x, y, area, ratio, vx, vy, area_change] 13 | static constexpr int numParticles = 2000; 14 | public: 15 | ParticleFilter(const BoundingBox &initialState); 16 | 17 | virtual ~ParticleFilter() = default; 18 | 19 | ParticleFilter(ParticleFilter &&rhs); 20 | 21 | ParticleFilter &operator=(ParticleFilter &&rhs); 22 | 23 | // Prevent copying 24 | ParticleFilter(const ParticleFilter &rhs) = delete; 25 | 26 | ParticleFilter &operator=(const ParticleFilter &rhs) = delete; 27 | 28 | /** 29 | * Move all particles using current velocities. 30 | */ 31 | void update(); 32 | 33 | /** 34 | * Move all particles using current velocities. Update weights and resample based on observation 35 | */ 36 | void update(const BoundingBox &bb); 37 | 38 | /** 39 | * Compute the predicted next state by moving all particles one time step and computing the mean. 40 | */ 41 | BoundingBox getPrediction() const; 42 | 43 | /** 44 | * Compute the mean of all particles. 45 | */ 46 | BoundingBox getCurrentEstimate() const; 47 | 48 | private: 49 | std::vector> particles; 50 | dlib::matrix velocityModel; 51 | 52 | void resample(); 53 | }; 54 | 55 | 56 | #endif //CPP_PARTICLEFILTER_H -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/particle/ParticlePredictor.cpp: -------------------------------------------------------------------------------- 1 | #include "ParticlePredictor.h" 2 | 3 | // Constructors 4 | 5 | ParticlePredictor::ParticlePredictor(const Detection &initialState, int ID) 6 | : Predictor(initialState.label, ID), filter(nullptr) { 7 | filter = std::make_shared(initialState.bb); 8 | } 9 | 10 | ParticlePredictor::ParticlePredictor(ParticlePredictor &&rhs) 11 | : Predictor(std::move(rhs)), filter(std::move(rhs.filter)) {} 12 | 13 | ParticlePredictor &ParticlePredictor::operator=(ParticlePredictor &&rhs) { 14 | Predictor::operator=(std::move(rhs)); 15 | filter = std::move(rhs.filter); 16 | return *this; 17 | } 18 | 19 | // Methods 20 | 21 | void ParticlePredictor::update() { 22 | Predictor::update(); 23 | filter->update(); 24 | } 25 | 26 | void ParticlePredictor::update(const Detection &det) { 27 | Predictor::update(det); 28 | filter->update(det.bb); 29 | } 30 | 31 | // Getters 32 | 33 | Detection ParticlePredictor::getPredictedNextDetection() const { 34 | return Detection(getLabel(), 1, filter->getPrediction()); 35 | } 36 | 37 | Tracking ParticlePredictor::getTracking() const { 38 | return Tracking(getLabel(), getID(), filter->getCurrentEstimate()); 39 | } 40 | -------------------------------------------------------------------------------- /cpp/src/tracker/predictor/particle/ParticlePredictor.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_PARTICLEPREDICTOR_H 2 | #define CPP_PARTICLEPREDICTOR_H 3 | 4 | 5 | #include "../Predictor.h" 6 | #include "ParticleFilter.h" 7 | 8 | #include 9 | 10 | class ParticlePredictor : public Predictor { 11 | public: 12 | ParticlePredictor(const Detection &initialState, int ID); 13 | 14 | ParticlePredictor(ParticlePredictor &&rhs); 15 | 16 | ParticlePredictor &operator=(ParticlePredictor &&rhs); 17 | 18 | /** 19 | * Advances the state vector using current estimation. 20 | */ 21 | void update() override; 22 | 23 | /** 24 | * Updates and advances the state vector using given Detection as observation. 25 | */ 26 | void update(const Detection &det) override; 27 | 28 | /** 29 | * Returns the predicted next state as Detection. 30 | */ 31 | Detection getPredictedNextDetection() const override; 32 | 33 | /** 34 | * Returns the current state as Tracking. 35 | */ 36 | Tracking getTracking() const override; 37 | 38 | private: 39 | std::shared_ptr filter; 40 | }; 41 | 42 | 43 | #endif //CPP_PARTICLEPREDICTOR_H -------------------------------------------------------------------------------- /cpp/src/util/BoundingBox.cpp: -------------------------------------------------------------------------------- 1 | #include "BoundingBox.h" 2 | 3 | // Constructors 4 | 5 | BoundingBox::BoundingBox(double cx, double cy, double width, double height) 6 | : cx(cx), cy(cy), width(width), height(height) {} 7 | 8 | // Functions 9 | 10 | std::ostream &operator<<(std::ostream &os, const BoundingBox &bb) { 11 | os << "(" << bb.cx << "," << bb.cy << ") - " << bb.width << "x" << bb.height; 12 | return os; 13 | } -------------------------------------------------------------------------------- /cpp/src/util/BoundingBox.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_BOUNDINGBOX_H 2 | #define CPP_BOUNDINGBOX_H 3 | 4 | 5 | #include 6 | 7 | struct BoundingBox { 8 | BoundingBox(double cx, double cy, double width, double height); 9 | 10 | const double cx; 11 | const double cy; 12 | const double width; 13 | const double height; 14 | 15 | // (x1,y1) - top left 16 | // (x2,y2) - bottom right 17 | inline double x1() const { return cx - width / 2; } 18 | inline double y1() const { return cy - height / 2; } 19 | inline double x2() const { return cx + width / 2; } 20 | inline double y2() const { return cy + height / 2; } 21 | inline double area() const { return width * height; } 22 | inline double ratio() const { return width / height; } 23 | }; 24 | 25 | std::ostream &operator<<(std::ostream &os, const BoundingBox &bb); 26 | 27 | 28 | #endif //CPP_BOUNDINGBOX_H -------------------------------------------------------------------------------- /cpp/src/util/Detection.cpp: -------------------------------------------------------------------------------- 1 | #include "Detection.h" 2 | 3 | // Constructors 4 | 5 | Detection::Detection(int label, double confidence, const BoundingBox &bb) 6 | : label(label), confidence(confidence), bb(bb) {} 7 | 8 | Detection::Detection(const Detection &rhs) 9 | : label(rhs.label), confidence(rhs.confidence), bb(rhs.bb) {} 10 | 11 | Detection::Detection(Detection &&rhs) 12 | : label(rhs.label), confidence(rhs.confidence), bb(std::move(rhs.bb)) {} 13 | 14 | // Functions 15 | 16 | std::ostream &operator<<(std::ostream &os, const Detection &d) { 17 | os << "Label: " << d.label << " Confidence: " << d.confidence << " " << d.bb; 18 | return os; 19 | } -------------------------------------------------------------------------------- /cpp/src/util/Detection.h: -------------------------------------------------------------------------------- 1 | #ifndef CPP_DETECTION_H 2 | #define CPP_DETECTION_H 3 | 4 | 5 | #include "BoundingBox.h" 6 | 7 | #include 8 | 9 | struct Detection { 10 | Detection(int label, double confidence, const BoundingBox &bb); 11 | 12 | Detection(const Detection &rhs); 13 | 14 | Detection(Detection &&rhs); 15 | 16 | // Prevent assignment 17 | Detection &operator=(const Detection &rhs) = delete; 18 | 19 | Detection &operator=(Detection &&rhs) = delete; 20 | 21 | const int label; 22 | const double confidence; 23 | const BoundingBox bb; 24 | }; 25 | 26 | std::ostream &operator<<(std::ostream &os, const Detection &d); 27 | 28 | 29 | #endif //CPP_DETECTION_H -------------------------------------------------------------------------------- /cpp/src/util/DetectionFileParser.cpp: -------------------------------------------------------------------------------- 1 | #include "DetectionFileParser.h" 2 | 3 | #include 4 | 5 | // Functions 6 | 7 | std::map> DetectionFileParser::parseMOTFile(std::ifstream &file) { 8 | return parseFile(file, DetectionFileParser::parseMOTLine); 9 | } 10 | 11 | std::map> DetectionFileParser::parseOkutamaFile(std::ifstream &file) { 12 | return parseFile(file, DetectionFileParser::parseOkutamaLine); 13 | } 14 | 15 | std::map> DetectionFileParser::parseFile( 16 | std::ifstream &file, 17 | std::pair (*parseLineFunc)(const std::string &)) { 18 | std::string line; 19 | std::map> frameToDetections; 20 | if (file.is_open()) { 21 | while (getline(file, line)) { 22 | std::pair frameDet = parseLineFunc(line); 23 | frameToDetections[frameDet.first].push_back(frameDet.second); 24 | } 25 | file.close(); 26 | } 27 | return frameToDetections; 28 | } 29 | 30 | std::pair DetectionFileParser::parseMOTLine(const std::string &line) { 31 | std::istringstream is(line); 32 | int frame; 33 | int id; // Unused 34 | double x1, y1, width, height, confidence; 35 | double x, y, z; // Unused 36 | int label = 1; 37 | if (!(is >> frame && is.ignore() && 38 | is >> id && is.ignore() && 39 | is >> x1 && is.ignore() && 40 | is >> y1 && is.ignore() && 41 | is >> width && is.ignore() && 42 | is >> height && is.ignore() && 43 | is >> confidence && is.ignore() && 44 | is >> x && is.ignore() && 45 | is >> y && is.ignore() && 46 | is >> z)) { 47 | throw std::invalid_argument( 48 | "Each line must be on following format: " 49 | ",,,,,,,,,"); 50 | } 51 | return std::pair(frame, Detection(label, confidence, 52 | BoundingBox(x1 + width / 2.0, y1 + height / 2.0, width, height))); 53 | } 54 | 55 | std::pair DetectionFileParser::parseOkutamaLine(const std::string &line) { 56 | std::istringstream is(line); 57 | int frame, label; 58 | int id; // Unused 59 | double x1, y1, width, height, confidence; 60 | double x, y, z; // Unused 61 | if (!(is >> frame && is.ignore() && 62 | is >> id && is.ignore() && 63 | is >> x1 && is.ignore() && 64 | is >> y1 && is.ignore() && 65 | is >> width && is.ignore() && 66 | is >> height && is.ignore() && 67 | is >> confidence && is.ignore() && 68 | is >> x && is.ignore() && 69 | is >> y && is.ignore() && 70 | is >> z && is.ignore() && 71 | is >> label)) { 72 | throw std::invalid_argument( 73 | "Each line must be on following format: " 74 | ",,,,,,,,,,