├── LICENSE ├── README.md ├── lib ├── .gitignore ├── pydvs.c ├── pydvs.py └── setup.py └── samples ├── .gitignore ├── error_demo.py ├── evimo-gen-exp.py ├── evimo-gen.py ├── extract_npz.py ├── npz_converter.py ├── npz_split.py ├── poster_6dof.npz └── poster_translation.npz /LICENSE: -------------------------------------------------------------------------------- 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 | 635 | Copyright (C) 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 | Copyright (C) 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 | # pydvs 2 | A set of algorithms to work with event-based cameras in Python3 3 | 4 | 5 | ## Installation 6 | The `pydvs` library can be installed via 7 | 8 | ``` 9 | cd lib 10 | sudo python3 setup.py install 11 | ``` 12 | 13 | ## Usage 14 | To see examples of usage, try examples from `samples` directory, or directly check `lib/pydvs.py` file! 15 | -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /lib/pydvs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define abs(x) ((x)<0 ? -(x) : (x)) 6 | 7 | static PyObject* dvs_img(PyObject* self, PyObject* args) 8 | { 9 | PyArrayObject *in_array; 10 | PyArrayObject *out_array; 11 | 12 | PyObject *model; 13 | int scale = 1; 14 | 15 | /* parse arguments */ 16 | if (!PyArg_ParseTuple(args, "O!O!O!i", &PyArray_Type, &in_array, &PyArray_Type, &out_array, 17 | &PyList_Type, &model, &scale)) 18 | return NULL; 19 | 20 | npy_intp dims[3]; 21 | dims[0] = PyArray_DIM(out_array, 0); 22 | dims[1] = PyArray_DIM(out_array, 1); 23 | dims[2] = PyArray_DIM(out_array, 2); 24 | 25 | int num_model_params = PyList_Size(model); 26 | if (num_model_params != 4) 27 | return NULL; 28 | 29 | float dx = PyFloat_AsDouble(PyList_GetItem(model, 1)); 30 | float dy = PyFloat_AsDouble(PyList_GetItem(model, 0)); 31 | float div = PyFloat_AsDouble(PyList_GetItem(model, 2)); 32 | float rot = PyFloat_AsDouble(PyList_GetItem(model, 3)); 33 | 34 | float *in_dataptr = (float *) PyArray_DATA(in_array); 35 | float *out_dataptr = (float *) PyArray_DATA(out_array); 36 | 37 | int n_events = PyArray_SIZE(in_array) / 4; 38 | float t0 = (n_events > 0) ? in_dataptr[0] : 0; 39 | for (unsigned long i = 0; i < n_events; ++i) { 40 | float t = in_dataptr[i * 4 + 0]; 41 | float x = in_dataptr[i * 4 + 1]; 42 | float y = in_dataptr[i * 4 + 2]; 43 | float p_f = in_dataptr[i * 4 + 3]; 44 | float dt = t - t0; 45 | 46 | // Warp the cloud here 47 | float rx = x - (float)dims[1] / (scale * 2.0), ry = y - (float)dims[0] / (scale * 2.0); 48 | float rx_ = cos(rot * dt) * rx - sin(rot * dt) * ry; 49 | float ry_ = sin(rot * dt) * rx + cos(rot * dt) * ry; 50 | float dnx = rx_ * div * dt + (rx_ - rx) + dx * dt; 51 | float dny = ry_ * div * dt + (ry_ - ry) + dy * dt; 52 | 53 | x = x + dnx; y = y + dny; 54 | 55 | if (((int)y * scale >= dims[0]) || ((int)x * scale >= dims[1]) || (y < 0) || (x < 0)) 56 | continue; 57 | 58 | for (int kx = (int)x * scale; kx < ((int)x + 1) * scale; ++kx) { 59 | for (int ky = (int)y * scale; ky < ((int)y + 1) * scale; ++ky) { 60 | unsigned long idx = ky * dims[1] + kx; 61 | // Time image 62 | out_dataptr[idx * 3 + 1] += dt; 63 | // Event-count images 64 | if (p_f > 0.5) { 65 | out_dataptr[idx * 3 + 0] += 1; 66 | } 67 | else { 68 | out_dataptr[idx * 3 + 2] += 1; 69 | } 70 | } 71 | } 72 | } 73 | 74 | // Normalize time image 75 | /* 76 | for (unsigned long i = 0; i < dims[0] * dims[1]; ++i) { 77 | float div = out_dataptr[i * 3 + 0] + out_dataptr[i * 3 + 2]; 78 | if (div > 0.5) // It can actually only be an integer, like 0, 1, 2... 79 | out_dataptr[i * 3 + 1] /= div; 80 | }*/ 81 | 82 | //Py_INCREF(out_array); 83 | return Py_BuildValue(""); 84 | }; 85 | 86 | 87 | static PyObject* dvs_error(PyObject* self, PyObject* args) 88 | { 89 | PyArrayObject *in_array; 90 | PyArrayObject *out_array; 91 | 92 | /* parse single numpy array argument */ 93 | if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &in_array, &PyArray_Type, &out_array)) 94 | return NULL; 95 | 96 | npy_intp idims[3]; 97 | idims[0] = PyArray_DIM(in_array, 0); 98 | idims[1] = PyArray_DIM(in_array, 1); 99 | idims[2] = PyArray_DIM(in_array, 2); 100 | 101 | npy_intp odims[3]; 102 | odims[0] = PyArray_DIM(out_array, 0); 103 | odims[1] = PyArray_DIM(out_array, 1); 104 | 105 | for (int i = 0; i < 2; ++i) if (idims[i] != odims[i]) return NULL; 106 | if (idims[2] != 3) return NULL; 107 | 108 | const float EPS = 0.0001; 109 | 110 | float *in_dataptr = (float *) PyArray_DATA(in_array); 111 | float *out_dataptr = (float *) PyArray_DATA(out_array); 112 | 113 | float dx = 0, dy = 0, rot = 0, div = 0, cnt = 0, nz_avg = 0; 114 | for (unsigned int y = 1; y < idims[0] - 1; ++y) { 115 | for (unsigned int x = 1; x < idims[1] - 1; ++x) { 116 | unsigned long idx0 = (y - 1) * idims[1] + x; 117 | unsigned long idx1 = (y - 0) * idims[1] + x; 118 | unsigned long idx2 = (y + 1) * idims[1] + x; 119 | 120 | out_dataptr[idx1 * 2 + 0] = 0; 121 | out_dataptr[idx1 * 2 + 1] = 0; 122 | 123 | float lcnt = in_dataptr[idx1 * 3 + 0] + in_dataptr[idx1 * 3 + 2]; 124 | if (lcnt < 0.5) 125 | continue; 126 | 127 | float a00 = in_dataptr[(idx0 - 1) * 3 + 1]; 128 | float a01 = in_dataptr[(idx0 - 0) * 3 + 1]; 129 | float a02 = in_dataptr[(idx0 + 1) * 3 + 1]; 130 | 131 | float a10 = in_dataptr[(idx1 - 1) * 3 + 1]; 132 | //float a11 = in_dataptr[(idx1 - 0) * 3 + 1]; 133 | float a12 = in_dataptr[(idx1 + 1) * 3 + 1]; 134 | 135 | float a20 = in_dataptr[(idx2 - 1) * 3 + 1]; 136 | float a21 = in_dataptr[(idx2 - 0) * 3 + 1]; 137 | float a22 = in_dataptr[(idx2 + 1) * 3 + 1]; 138 | 139 | if (a00 < EPS || a01 < EPS || a02 < EPS || 140 | a10 < EPS || a12 < EPS || 141 | a20 < EPS || a21 < EPS || a22 < EPS) 142 | continue; 143 | 144 | float dy_ = 3 * (a00 - a02) + 10 * (a10 - a12) + 3 * (a20 - a22); 145 | float dx_ = 3 * (a00 - a20) + 10 * (a01 - a21) + 3 * (a02 - a22); 146 | 147 | out_dataptr[idx1 * 2 + 0] = dx_; 148 | out_dataptr[idx1 * 2 + 1] = dy_; 149 | 150 | nz_avg += lcnt; 151 | cnt += 1; 152 | 153 | dx += dx_; 154 | dy += dy_; 155 | 156 | float rx = x - idims[1] / 2, ry = y - idims[0] / 2; 157 | 158 | rot += rx * dy_ - ry * dx_; 159 | div += rx * dx_ + ry * dy_; 160 | } 161 | } 162 | 163 | // Another magic number 164 | if (cnt < 100) { 165 | dx = 0; 166 | dy = 0; 167 | rot = 0; 168 | div = 0; 169 | nz_avg = 0; 170 | } else { 171 | dx /= cnt; 172 | dy /= cnt; 173 | rot /= cnt; 174 | div /= cnt; 175 | nz_avg /= cnt; 176 | } 177 | 178 | //Py_INCREF(out_array); 179 | return Py_BuildValue("ffffff", dx, dy, rot, div, cnt, nz_avg); 180 | }; 181 | 182 | 183 | static PyObject* dvs_flow_error(PyObject* self, PyObject* args) 184 | { 185 | PyArrayObject *in_array; 186 | PyArrayObject *out_array; 187 | 188 | /* parse single numpy array argument */ 189 | if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &in_array, &PyArray_Type, &out_array)) 190 | return NULL; 191 | 192 | npy_intp idims[3]; 193 | idims[0] = PyArray_DIM(in_array, 0); 194 | idims[1] = PyArray_DIM(in_array, 1); 195 | idims[2] = PyArray_DIM(in_array, 2); 196 | 197 | npy_intp odims[3]; 198 | odims[0] = PyArray_DIM(out_array, 0); 199 | odims[1] = PyArray_DIM(out_array, 1); 200 | 201 | for (int i = 0; i < 2; ++i) if (idims[i] != odims[i]) return NULL; 202 | if (idims[2] != 3) return NULL; 203 | 204 | const float EPS = 0.0001; 205 | 206 | float *in_dataptr = (float *) PyArray_DATA(in_array); 207 | float *out_dataptr = (float *) PyArray_DATA(out_array); 208 | 209 | float dx = 0, dy = 0, rot = 0, div = 0, cnt = 0, nz_avg = 0; 210 | for (unsigned int y = 1; y < idims[0] - 1; ++y) { 211 | for (unsigned int x = 1; x < idims[1] - 1; ++x) { 212 | unsigned long idx0 = (y - 1) * idims[1] + x; 213 | unsigned long idx1 = (y - 0) * idims[1] + x; 214 | unsigned long idx2 = (y + 1) * idims[1] + x; 215 | 216 | out_dataptr[idx1 * 2 + 0] = 0; 217 | out_dataptr[idx1 * 2 + 1] = 0; 218 | 219 | float lcnt = in_dataptr[idx1 * 3 + 0] + in_dataptr[idx1 * 3 + 2]; 220 | if (lcnt < 0.5) 221 | continue; 222 | 223 | float a00 = in_dataptr[(idx0 - 1) * 3 + 1]; 224 | float a01 = in_dataptr[(idx0 - 0) * 3 + 1]; 225 | float a02 = in_dataptr[(idx0 + 1) * 3 + 1]; 226 | 227 | float a10 = in_dataptr[(idx1 - 1) * 3 + 1]; 228 | //float a11 = in_dataptr[(idx1 - 0) * 3 + 1]; 229 | float a12 = in_dataptr[(idx1 + 1) * 3 + 1]; 230 | 231 | float a20 = in_dataptr[(idx2 - 1) * 3 + 1]; 232 | float a21 = in_dataptr[(idx2 - 0) * 3 + 1]; 233 | float a22 = in_dataptr[(idx2 + 1) * 3 + 1]; 234 | 235 | if (a00 < EPS || a01 < EPS || a02 < EPS || 236 | a10 < EPS || a12 < EPS || 237 | a20 < EPS || a21 < EPS || a22 < EPS) 238 | continue; 239 | 240 | float rx = x - idims[1] / 2, ry = y - idims[0] / 2; 241 | if (abs(rx) < 0.5 || abs(ry) < 0.5) continue; 242 | 243 | float dx_ = 3 * (a00 - a02) + 10 * (a10 - a12) + 3 * (a20 - a22); 244 | float dy_ = 3 * (a00 - a20) + 10 * (a01 - a21) + 3 * (a02 - a22); 245 | 246 | if (abs(dy_) < 0.001 || abs(dx_) < 0.001) continue; 247 | dy_ = -1.0 / dy_; 248 | dx_ = -1.0 / dx_; 249 | 250 | out_dataptr[idx1 * 2 + 0] = -dx_; 251 | out_dataptr[idx1 * 2 + 1] = dy_; 252 | 253 | nz_avg += lcnt; 254 | cnt += 1; 255 | 256 | dx += dx_; 257 | dy += dy_; 258 | 259 | rot += rx * dy_ - ry * dx_; 260 | float len = 5000 * sqrt((dx_ * dx_ + dy_ * dy_) / (rx * rx + ry * ry)); 261 | float divergence = rx * dx_ + ry * dy_; 262 | 263 | //div += rx * dx_ + ry * dy_; 264 | div += (divergence > 0) ? len : -len; 265 | } 266 | } 267 | 268 | // Another magic number 269 | if (cnt < 10) { 270 | dx = 0; 271 | dy = 0; 272 | rot = 0; 273 | div = 0; 274 | nz_avg = 0; 275 | } else { 276 | dx /= cnt; 277 | dy /= cnt; 278 | rot /= cnt; 279 | div /= cnt; 280 | nz_avg /= cnt; 281 | } 282 | 283 | //Py_INCREF(out_array); 284 | return Py_BuildValue("ffffff", dx, dy, rot, div, cnt, nz_avg); 285 | }; 286 | 287 | 288 | 289 | /* define functions in module */ 290 | static PyMethodDef DVSMethods[] = 291 | { 292 | {"dvs_img", dvs_img, METH_VARARGS, 293 | "compute dvs image from event cloud"}, 294 | {"dvs_error", dvs_error, METH_VARARGS, 295 | "compute errors on the dvs image"}, 296 | {"dvs_flow_error", dvs_flow_error, METH_VARARGS, 297 | "compute fast optical flow on the dvs image"}, 298 | {NULL, NULL, 0, NULL} 299 | }; 300 | 301 | 302 | #if 0 // Python 2.x 303 | 304 | 305 | /* module initialization */ 306 | PyMODINIT_FUNC 307 | initpydvs(void) 308 | { 309 | (void) Py_InitModule("pydvs", DVSMethods); 310 | /* IMPORTANT: this must be called */ 311 | import_array(); 312 | } 313 | #endif 314 | 315 | static struct PyModuleDef cModPyDem = 316 | { 317 | PyModuleDef_HEAD_INIT, 318 | "cpydvs", /* name of module */ 319 | "", /* module documentation, may be NULL */ 320 | -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in 321 | global variables. */ 322 | DVSMethods 323 | }; 324 | 325 | 326 | /* module initialization */ 327 | PyMODINIT_FUNC 328 | PyInit_cpydvs(void) 329 | { 330 | /* IMPORTANT: this must be called */ 331 | import_array(); 332 | return PyModule_Create(&cModPyDem); 333 | }; 334 | -------------------------------------------------------------------------------- /lib/pydvs.py: -------------------------------------------------------------------------------- 1 | import sys, os, shutil 2 | import yaml 3 | import cv2 4 | import numpy as np 5 | from math import fabs, sqrt 6 | import pandas as pd 7 | import pyarrow 8 | 9 | with_rosbag = True 10 | try: 11 | import rosbag 12 | except: 13 | with_rosbag = False 14 | 15 | # The dvs-related functionality implemented in C. 16 | import cpydvs 17 | 18 | 19 | class bcolors: 20 | HEADER = '\033[95m' 21 | PLAIN = '\033[37m' 22 | OKBLUE = '\033[94m' 23 | OKGREEN = '\033[92m' 24 | WARNING = '\033[93m' 25 | FAIL = '\033[91m' 26 | ENDC = '\033[0m' 27 | BOLD = '\033[1m' 28 | UNDERLINE = '\033[4m' 29 | 30 | 31 | def offset(str_, p_offset): 32 | for i in range(p_offset): 33 | str_ = '...' + str_ 34 | return str_ 35 | 36 | def hdr(str_, p_offset=0): 37 | return offset(bcolors.HEADER + str_ + bcolors.ENDC, p_offset) 38 | 39 | def wht(str_, p_offset=0): 40 | return offset(bcolors.PLAIN + str_ + bcolors.ENDC, p_offset) 41 | 42 | def okb(str_, p_offset=0): 43 | return offset(bcolors.OKBLUE + str_ + bcolors.ENDC, p_offset) 44 | 45 | def okg(str_, p_offset=0): 46 | return offset(bcolors.OKGREEN + str_ + bcolors.ENDC, p_offset) 47 | 48 | def wrn(str_, p_offset=0): 49 | return offset(bcolors.WARNING + str_ + bcolors.ENDC, p_offset) 50 | 51 | def err(str_, p_offset=0): 52 | return offset(bcolors.FAIL + str_ + bcolors.ENDC, p_offset) 53 | 54 | def bld(str_, p_offset=0): 55 | return offset(bcolors.BOLD + str_ + bcolors.ENDC, p_offset) 56 | 57 | 58 | def ensure_dir(f): 59 | if not os.path.exists(f): 60 | print (okg("Created directory: ") + okb(f)) 61 | os.makedirs(f) 62 | 63 | def replace_dir(f): 64 | if os.path.exists(f): 65 | print (wrn("Removed directory: ") + okb(f)) 66 | shutil.rmtree(f) 67 | os.makedirs(f) 68 | print (okg("Created directory: ") + okb(f)) 69 | 70 | 71 | def read_calib_yaml(fname): 72 | K = np.array([[0.0, 0.0, 0.0], 73 | [0.0, 0.0, 0.0], 74 | [0.0, 0.0, 1.0]]) 75 | D = np.array([0.0, 0.0, 0.0, 0.0]) 76 | 77 | cam_file = open(fname) 78 | cam_data = yaml.safe_load(cam_file) 79 | cam_file.close() 80 | 81 | K[0][0] = cam_data['cam_fx'] 82 | K[1][1] = cam_data['cam_fy'] 83 | K[0][2] = cam_data['cam_cx'] 84 | K[1][2] = cam_data['cam_cy'] 85 | 86 | return K, D 87 | 88 | 89 | def read_calib_txt(fname): 90 | K = np.array([[0.0, 0.0, 0.0], 91 | [0.0, 0.0, 0.0], 92 | [0.0, 0.0, 1.0]]) 93 | D = np.array([0.0, 0.0, 0.0, 0.0]) 94 | 95 | lines = [] 96 | with open(fname) as calib: 97 | lines = calib.readlines() 98 | 99 | # A single line: fx, fy, xc, cy, k1...k4 100 | if (len(lines) == 1): 101 | calib = lines[0].split(' ') 102 | K[0][0] = calib[0] 103 | K[1][1] = calib[1] 104 | K[0][2] = calib[2] 105 | K[1][2] = calib[3] 106 | D[0] = calib[4] 107 | D[1] = calib[5] 108 | D[2] = calib[6] 109 | D[3] = calib[7] 110 | return K, D 111 | 112 | K_txt = lines[0:3] 113 | D_txt = lines[4] 114 | 115 | for i, line in enumerate(K_txt): 116 | for j, num_txt in enumerate(line.split(' ')[0:3]): 117 | K[i][j] = float(num_txt) 118 | 119 | for j, num_txt in enumerate(D_txt.split(' ')[0:4]): 120 | D[j] = float(num_txt) 121 | 122 | return K, D 123 | 124 | 125 | # legacy is for EVIMO1, generation is very slow (ten minutes or more) 126 | # using binary search is much faster (takes maybe 1 second) but gives 127 | # slightly different indices having the exact indices is not a problem 128 | # for the purpose of the discretization 129 | def get_index(cloud, index_w, legacy=False): 130 | print (okb("Indexing...")) 131 | 132 | idx = [0] 133 | if (cloud.shape[0] < 2): 134 | return np.array(idx, dtype=np.uint32) 135 | 136 | if not legacy: 137 | index_times = np.arange(cloud[0, 0], cloud[-1, 0], step=index_w) 138 | idx = np.searchsorted(cloud[:, 0], index_times, side='left') 139 | idx = np.concatenate((idx, (cloud.shape[0]-1,))) 140 | idx = idx.astype(np.uint32) 141 | else: 142 | last_ts = cloud[0][0] 143 | for i, e in enumerate(cloud): 144 | if i % 100000 == 0: 145 | sys.stdout.write("\r" + str(i + 1) + ' / ' +str(len(cloud)) + '\t\t') 146 | while (e[0] - last_ts > index_w): 147 | if (e[0] - last_ts > 1.0): 148 | print (wrn("\nGap in the events:"), e[0] - last_ts, 'sec.') 149 | idx.append(i) 150 | last_ts += index_w 151 | 152 | idx.append(cloud.shape[0] - 1) 153 | idx = np.array(idx, dtype=np.uint32) 154 | return idx 155 | 156 | 157 | def read_event_file_txt(fname, discretization, sort=False, legacy_discretization=False): 158 | print (okb("Reading the event file as a text file...")) 159 | # For a 140M event file (~25 seconds), pandas takes 60 seconds with the C engine 160 | # with pyarrow it takes 23 seconds, pyarrow is considered experimental at the time of writing 161 | # np.loadtxt takes 765 seconds 162 | if os.path.exists(fname): 163 | try: 164 | cloud_pd = pd.read_csv(fname, 165 | dtype=np.float32, 166 | names=['t', 'x', 'y', 'p'], 167 | delimiter=' ', 168 | engine='pyarrow').to_numpy() 169 | 170 | # Something about what panda's to_numpy returns breaks codes that follow 171 | # copying the pandas data into another numpy array fixes it, very strange 172 | cloud = np.zeros(cloud_pd.shape, dtype=np.float32) 173 | cloud[:, :] = cloud_pd[:, :] 174 | 175 | # All these things are identical..... 176 | #print(cloud_pd.shape) 177 | #print(cloud_pd.dtype) 178 | #print(cloud.shape) 179 | #print(cloud.dtype) 180 | #print(type(cloud_pd)) 181 | #print(type(cloud)) 182 | except pyarrow.lib.ArrowInvalid: 183 | # CSV was empty because this is probably a conventional camera sequence 184 | cloud = np.zeros((0,), dtype=np.float32) 185 | else: 186 | cloud = np.zeros((0,), dtype=np.float32) 187 | 188 | if (sort): 189 | cloud = cloud[cloud[:,0].argsort()] 190 | 191 | if (cloud.shape[0] == 0): 192 | print (wrn("Read 0 events from " + fname + "!")) 193 | return np.empty(shape=(0,4), dtype=np.float32), np.empty(shape=(0,), dtype=np.float32) 194 | else: 195 | t0 = cloud[0][0] 196 | if (cloud[0][0] > 1e5): 197 | cloud[:,0] -= t0 198 | print (wrn("Adjusting initial timestamp to 0!")) 199 | 200 | print (okg("Read"), cloud.shape[0], okg("events:"), cloud[0][0], "-", cloud[-1][0], "sec.") 201 | 202 | idx = get_index(cloud, discretization, legacy_discretization) 203 | return cloud.astype(np.float32), idx 204 | 205 | 206 | def read_event_file_bag(fname, discretization, event_topic, sort=True, get_index=True): 207 | if (not with_rosbag): 208 | print (wrn("rosbag not found!")) 209 | return None, None 210 | 211 | print (okb("Reading events from a bag file..."), "topic:", event_topic) 212 | with rosbag.Bag(fname, 'r') as bag: 213 | if (event_topic not in bag.get_type_and_topic_info()[1].keys()): 214 | print (wrn("topic '" + event_topic + "' is not found in bag " + fname)) 215 | print ("Available topics:", bag.get_type_and_topic_info()[1].keys()) 216 | return None, None 217 | 218 | ecount = 0 219 | msg_cnt = 0 220 | first_event_ts = None 221 | with rosbag.Bag(fname, 'r') as bag: 222 | msg_cnt = bag.get_message_count(topic_filters = [event_topic]) 223 | 224 | for i, (topic, msg, t) in enumerate(bag.read_messages(topics = [event_topic])): 225 | if topic == event_topic: 226 | if (ecount == 0 and len(msg.events) > 0): 227 | first_event_ts = msg.events[0].ts 228 | ecount += len(msg.events) 229 | sys.stdout.write("read message " + str(i) + " / " + str(msg_cnt) + "\t\t\r") 230 | 231 | print ("\nFound", ecount, "events") 232 | 233 | cloud = np.zeros((ecount, 4), dtype=np.float32) 234 | eid = 0 235 | 236 | with rosbag.Bag(fname, 'r') as bag: 237 | for i, (topic, msg, t) in enumerate(bag.read_messages(topics = [event_topic])): 238 | if topic == event_topic: 239 | for e in msg.events: 240 | cloud[eid][0] = (e.ts - first_event_ts).to_sec() 241 | cloud[eid][1] = e.x 242 | cloud[eid][2] = e.y 243 | if (e.polarity): 244 | cloud[eid][3] = 1 245 | else: 246 | cloud[eid][3] = 0 247 | eid += 1 248 | if (i % 10 == 0): 249 | sys.stdout.write("convert to npz " + str(i) + " / " + str(msg_cnt) + "\t\t\r") 250 | 251 | print () 252 | if (sort): 253 | print ("Sorting event timestamps") 254 | cloud = cloud[cloud[:,0].argsort()] 255 | 256 | if (cloud.shape[0] == 0): 257 | print (wrn("Read 0 events from " + fname + "!")) 258 | else: 259 | t0 = cloud[0][0] 260 | if (cloud[0][0] > 1e5): 261 | cloud[:,0] -= t0 262 | print (wrn("Adjusting initial timestamp to 0!")) 263 | 264 | if (not get_index): 265 | return cloud.astype(np.float32), None 266 | 267 | print (okb("Indexing...")) 268 | idx = get_index(cloud, discretization) 269 | return cloud.astype(np.float32), idx 270 | 271 | 272 | def undistort_img(img, K, D): 273 | if (K is None): 274 | return img 275 | if (D is None): 276 | D = np.array([0, 0, 0, 0]) 277 | 278 | Knew = K.copy() 279 | Knew[(0,1), (0,1)] = 0.87 * Knew[(0,1), (0,1)] 280 | img_undistorted = cv2.fisheye.undistortImage(img, K, D=D, Knew=Knew) 281 | return img_undistorted 282 | 283 | 284 | def dvs_img(cloud, shape, model=None, scale=None, K=None, D=None): 285 | fcloud = cloud.astype(np.float32) # Important! 286 | 287 | if (model is None): 288 | model = [0, 0, 0, 0] 289 | 290 | if (scale is None): 291 | scale = 1 292 | 293 | cmb = np.zeros((shape[0] * scale, shape[1] * scale, 3), dtype=np.float32) 294 | cpydvs.dvs_img(fcloud, cmb, model, scale) 295 | 296 | cmb = undistort_img(cmb, K, D) 297 | 298 | cnt_img = cmb[:,:,0] + cmb[:,:,2] + 1e-8 299 | timg = cmb[:,:,1] 300 | 301 | timg /= cnt_img 302 | 303 | # Undistortion may affect the event counts 304 | timg[cnt_img < 0.9] = 0 305 | return cmb 306 | 307 | 308 | def dvs_err(tc_img, G_img): 309 | return cpydvs.dvs_error(tc_img, G_img) 310 | 311 | 312 | def dvs_flow_err(tc_img, G_img): 313 | return cpydvs.dvs_flow_error(tc_img, G_img) 314 | 315 | 316 | def get_slice(cloud, idx, ts, width, mode=0, idx_step=0.01): 317 | if (cloud.shape[0] == 0): 318 | return cloud, np.array([0]) 319 | 320 | ts_lo = ts 321 | ts_hi = ts + width 322 | if (mode == 1): 323 | ts_lo = ts - width / 2.0 324 | ts_hi = ts + width / 2.0 325 | if (mode == 2): 326 | ts_lo = ts - width 327 | ts_hi = ts 328 | if (mode > 2 or mode < 0): 329 | print (wrn("get_slice: Wrong mode! Reverting to default...")) 330 | if (ts_lo < 0): ts_lo = 0 331 | 332 | t0 = cloud[0][0] 333 | 334 | idx_lo = int((ts_lo - t0) / idx_step) 335 | idx_hi = int((ts_hi - t0) / idx_step) 336 | if (idx_lo >= len(idx)): idx_lo = -1 337 | if (idx_hi >= len(idx)): idx_hi = -1 338 | 339 | sl = np.copy(cloud[idx[idx_lo]:idx[idx_hi]].astype(np.float32)) 340 | idx_ = np.copy(idx[idx_lo:idx_hi]) 341 | 342 | if (idx_lo == idx_hi): 343 | return sl, np.array([0]) 344 | 345 | if (len(idx_) > 0): 346 | idx_0 = idx_[0] 347 | idx_ -= idx_0 348 | 349 | if (sl.shape[0] > 0): 350 | t0 = sl[0][0] 351 | sl[:,0] -= t0 352 | 353 | return sl, idx_ 354 | -------------------------------------------------------------------------------- /lib/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from distutils.core import setup, Extension 4 | import numpy 5 | 6 | # define the extension module 7 | libdvs = Extension('cpydvs', sources=['pydvs.c'], 8 | include_dirs=[numpy.get_include()]) 9 | 10 | # run the setup 11 | setup(name='pydvs', 12 | version='1.0', 13 | description='Python toolkit to work with event-based sensors', 14 | author='Anton Mitrokhin', 15 | author_email='amitrokh@umd.edu', 16 | url='https://github.com/ncos/pydvs', 17 | py_modules=['pydvs'], 18 | ext_modules=[libdvs] 19 | ) 20 | -------------------------------------------------------------------------------- /samples/.gitignore: -------------------------------------------------------------------------------- 1 | ~* 2 | *.pyc 3 | *.swp 4 | *.txt 5 | -------------------------------------------------------------------------------- /samples/error_demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | import numpy as np 5 | import os, sys, signal, math, time 6 | import matplotlib.colors as colors 7 | 8 | import pydvs, cv2 9 | 10 | 11 | def colorize_image(flow_x, flow_y): 12 | hsv_buffer = np.empty((flow_x.shape[0], flow_x.shape[1], 3)) 13 | hsv_buffer[:,:,1] = 1.0 14 | hsv_buffer[:,:,0] = (np.arctan2(flow_y, flow_x) + np.pi)/(2.0*np.pi) 15 | hsv_buffer[:,:,2] = np.linalg.norm( np.stack((flow_x,flow_y), axis=0), axis=0 ) 16 | hsv_buffer[:,:,2] = np.log(1. + hsv_buffer[:,:,2]) 17 | 18 | flat = hsv_buffer[:,:,2].reshape((-1)) 19 | m = 1 20 | try: 21 | m = np.nanmax(flat[np.isfinite(flat)]) 22 | except: 23 | m = 1 24 | if not np.isclose(m, 0.0): 25 | hsv_buffer[:,:,2] /= m 26 | 27 | return colors.hsv_to_rgb(hsv_buffer) 28 | 29 | 30 | class AlignmentErrorTool: 31 | def __init__(self, cloud, shape, K, D): 32 | self.cloud = np.copy(cloud).astype(np.float32) 33 | if (self.cloud.shape[0] > 0): 34 | t0 = self.cloud[0][0] 35 | self.cloud[:,0] -= t0 36 | 37 | self.scale = 3 38 | 39 | self.K = K 40 | self.D = D 41 | 42 | self.shape = shape 43 | 44 | self.width = 0 45 | if (self.cloud.shape[0] > 0): 46 | self.width = self.cloud[-1][0] - self.cloud[0][0] 47 | 48 | cv2.namedWindow('GUI') 49 | cv2.createTrackbar('X', 'GUI', 127, 255, self.manual_update) 50 | cv2.createTrackbar('Y', 'GUI', 127, 255, self.manual_update) 51 | cv2.createTrackbar('Z', 'GUI', 127, 255, self.manual_update) 52 | cv2.createTrackbar('Yaw','GUI', 127, 255, self.manual_update) 53 | 54 | circle = np.zeros((self.shape[0] * self.scale, self.shape[1] * self.scale, 2)) 55 | for x in range(circle.shape[0]): 56 | for y in range(circle.shape[1]): 57 | circle[x, y] = (np.array([circle.shape[0]/2, circle.shape[1]/2]) - np.array([x, y])) / 100 58 | 59 | self.hsv_circle = colorize_image(circle[:,:,0], circle[:,:,1]) 60 | 61 | self.x_err = 0 62 | self.y_err = 0 63 | self.z_err = 0 64 | self.yaw_err = 0 65 | self.e_count = 0 66 | self.nz_avg = 0 67 | 68 | self.manual_update(None) 69 | while (True): 70 | k = cv2.waitKey(1) & 0xFF 71 | if k == 27: 72 | break 73 | if k == 99: 74 | self.minimize_timg() 75 | 76 | cv2.destroyAllWindows() 77 | 78 | def iteration_step(self): 79 | 80 | # Compute images according to the model 81 | dvs_img = pydvs.dvs_img(self.cloud, self.shape, model=[self.x, self.y, self.z, self.yaw], 82 | scale=self.scale, K=self.K, D=self.D) 83 | 84 | # Compute errors on the images 85 | dgrad = np.zeros((self.shape[0] * self.scale, self.shape[1] * self.scale, 2), dtype=np.float32) 86 | self.x_err, self.y_err, self.yaw_err, self.z_err, self.e_count, self.nz_avg = \ 87 | pydvs.dvs_err(dvs_img, dgrad) 88 | 89 | print ("-------------") 90 | print (self.x, self.y, self.yaw, self.z) 91 | print (self.x_err, self.y_err, self.yaw_err, self.z_err, self.e_count, self.nz_avg) 92 | 93 | # Visualization 94 | c_img = dvs_img[:,:,0] + dvs_img[:,:,2] 95 | c_img = np.dstack((c_img, c_img, c_img)) * 0.5 / (self.nz_avg + 1e-3) 96 | 97 | dvs_img[:,:,1] *= 1.0 / self.width 98 | t_img = np.dstack((dvs_img[:,:,1], dvs_img[:,:,1], dvs_img[:,:,1])) 99 | 100 | G_img = colorize_image(dgrad[:,:,0], dgrad[:,:,1]) 101 | cv2.imshow('GUI', np.hstack((c_img, t_img, G_img, self.hsv_circle))) 102 | 103 | def manual_update(self, x): 104 | self.x = float(cv2.getTrackbarPos('X', 'GUI') - 127) * 10 105 | self.y = float(cv2.getTrackbarPos('Y', 'GUI') - 127) * 10 106 | self.z = float(cv2.getTrackbarPos('Z', 'GUI') - 127) / 10 107 | self.yaw = float(cv2.getTrackbarPos('Yaw','GUI') - 127) / 10 108 | 109 | self.iteration_step() 110 | 111 | def minimize_timg(self): 112 | # Initial errors 113 | self.iteration_step() 114 | divs = [0.0001, 0.0001, 10.0, 10.0] 115 | 116 | old_x_err = self.x_err 117 | old_y_err = self.y_err 118 | old_yaw_err = self.yaw_err 119 | old_z_err = self.z_err 120 | 121 | enabled = False 122 | 123 | while (True): 124 | if (self.x_err * old_x_err < 0): 125 | divs[0] *= 1.5 126 | if (self.y_err * old_y_err < 0): 127 | divs[1] *= 1.5 128 | if (self.yaw_err * old_yaw_err < 0): 129 | divs[2] *= 2 130 | if (self.z_err * old_z_err < 0): 131 | divs[3] *= 2 132 | 133 | ex_step = self.x_err / divs[0] 134 | ey_step = self.y_err / divs[1] 135 | eyaw_step = 0 * self.yaw_err / divs[2] 136 | ez_step = 0 * self.z_err / divs[3] 137 | 138 | if (abs(ex_step) < 1e-2 and abs(ey_step) < 1e-2 and 139 | abs(eyaw_step) < 1e-3 and abs(ez_step) < 1e-3): 140 | break 141 | 142 | self.yaw_err = 0 143 | self.z_err = 0 144 | if (abs(self.x_err) < 1e-4 and abs(self.y_err) < 1e-4 and 145 | abs(self.yaw_err) < 1e-2 and abs(self.z_err) < 1e-2): 146 | break 147 | 148 | self.x += ex_step 149 | self.y += ey_step 150 | 151 | if (abs(self.x_err) < 1e-2 and abs(self.y_err)): 152 | enabled = True 153 | 154 | if (enabled): 155 | self.yaw += eyaw_step 156 | self.z += ez_step 157 | 158 | old_x_err = self.x_err 159 | old_y_err = self.y_err 160 | old_yaw_err = self.yaw_err 161 | old_z_err = self.z_err 162 | 163 | self.iteration_step() 164 | 165 | #cv2.waitKey(0) 166 | 167 | 168 | 169 | if __name__ == '__main__': 170 | parser = argparse.ArgumentParser() 171 | parser.add_argument('--slice', 172 | type=str, 173 | required=True) 174 | parser.add_argument('--bounds', 175 | nargs='+', 176 | type=int, 177 | default=[0, -1], 178 | required=False) 179 | parser.add_argument('--info', 180 | action='store_true', 181 | required=False) 182 | 183 | args = parser.parse_args() 184 | 185 | print ("Opening", args.slice) 186 | 187 | sl_npz = np.load(args.slice) 188 | cloud = sl_npz['events'] 189 | idx = sl_npz['index'] 190 | K = None #sl_npz['K'] 191 | D = None #sl_npz['D'] / 10 192 | 193 | if (len(args.bounds) != 2 or (args.bounds[0] > args.bounds[1] and args.bounds[1] != -1) 194 | or (args.bounds[0] < 0) or (args.bounds[1] < -1)): 195 | print ("Invalid bounds: ", args.bounds) 196 | print ("Bounds have to specify two points in the index array, possible values are 0 -", len(idx) - 1) 197 | exit(0) 198 | 199 | idx = np.append(idx, [cloud.shape[0]]) 200 | sl = cloud[idx[args.bounds[0]]:idx[args.bounds[1]]] 201 | 202 | if (args.info): 203 | width = cloud[-1][0] - cloud[0][0] 204 | print ("Input cloud:") 205 | print ("\tWidth: ", width, "seconds and", len(cloud), "events.") 206 | print ("\tIndex size: ", len(idx), "points, step = ", width / float(len(idx) + 1), "seconds.") 207 | print ("") 208 | width = sl[-1][0] - sl[0][0] 209 | print ("Chosen slice:") 210 | print ("\tWidth: ", width, "seconds and", len(sl), "events.") 211 | print ("") 212 | 213 | 214 | a = AlignmentErrorTool(sl, (180, 240), K, D) 215 | -------------------------------------------------------------------------------- /samples/evimo-gen-exp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | import os, sys, math, signal, glob 7 | import cv2 8 | import pydvs 9 | 10 | from scipy.interpolate import splprep, splev 11 | 12 | def mask_to_color(mask): 13 | colors = [[0,255,0], [0,0,255], [255,0,0], [56,62,43], [26,50,63], [36,55,56]] 14 | cmb = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.float32) 15 | m_ = np.max(mask) + 500 16 | m_ = max(m_, 3500) 17 | 18 | maxoid = int(m_ / 1000) 19 | for i in range(maxoid): 20 | cutoff_lo = 1000.0 * (i + 1.0) - 5 21 | cutoff_hi = 1000.0 * (i + 1.0) + 5 22 | cmb[np.where(np.logical_and(mask>=cutoff_lo, mask<=cutoff_hi))] = np.array(colors[i % len(colors)]) 23 | cmb *= 2.5 24 | return cmb 25 | 26 | 27 | def gen_text_stub(shape_y, meta, step=15, font_scale=0.8): 28 | strings = {} 29 | for key in sorted(meta.keys()): 30 | try: 31 | vel = meta[key]['vel'] 32 | pos = meta[key]['pos'] 33 | except: 34 | continue 35 | strings[key] = {} 36 | strings[key]['vt'] = ("{0:.2f}".format(vel['t']['x']) + " " 37 | "{0:.2f}".format(vel['t']['y']) + " " 38 | "{0:.2f}".format(vel['t']['z'])) 39 | strings[key]['vr'] = ("{0:.2f}".format(vel['rpy']['r']) + " " 40 | "{0:.2f}".format(vel['rpy']['p']) + " " 41 | "{0:.2f}".format(vel['rpy']['y'])) 42 | strings[key]['pt'] = ("{0:.2f}".format(pos['t']['x']) + " " 43 | "{0:.2f}".format(pos['t']['y']) + " " 44 | "{0:.2f}".format(pos['t']['z'])) 45 | strings[key]['pr'] = ("{0:.2f}".format(pos['rpy']['r']) + " " 46 | "{0:.2f}".format(pos['rpy']['p']) + " " 47 | "{0:.2f}".format(pos['rpy']['y'])) 48 | strings['ts'] = "{0:.3f}".format(meta['ts']) 49 | 50 | shape_x = int(len(strings) * step + step / 2) 51 | cmb = np.zeros((shape_x, shape_y, 3), dtype=np.float32) 52 | 53 | offst = {} 54 | offst['vt'] = step * 4 55 | offst['vr'] = offst['vt'] + step * 10 56 | offst['pt'] = offst['vr'] + step * 10 57 | offst['pr'] = offst['pt'] + step * 10 58 | 59 | for i, key in enumerate(sorted(strings.keys())): 60 | if (key == 'ts'): 61 | cv2.putText(cmb, key + ': ' + strings['ts'], (step // 2, step + i * step), 62 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 63 | continue 64 | cv2.putText(cmb, key + ': ', (step // 2, step + i * step), 65 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 66 | cv2.putText(cmb, strings[key]['vt'], (offst['vt'], step + i * step), 67 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 68 | cv2.putText(cmb, '| ' + strings[key]['vr'], (offst['vr'], step + i * step), 69 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 70 | cv2.putText(cmb, '| ' + strings[key]['pt'], (offst['pt'], step + i * step), 71 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 72 | cv2.putText(cmb, '| ' + strings[key]['pr'], (offst['pr'], step + i * step), 73 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 74 | return cmb 75 | 76 | 77 | def dvs_img(cloud, shape, K, D, slice_width, mode=0): 78 | cmb = pydvs.dvs_img(cloud, shape, K=K, D=D) 79 | 80 | ncnt = cmb[:,:,0] 81 | time = cmb[:,:,1] 82 | pcnt = cmb[:,:,2] 83 | cnt = pcnt + ncnt 84 | 85 | # Scale up to be able to save as uint8 86 | # For visualization only. May cause overflow if slice_width is large 87 | cmb[:,:,0] *= 50 88 | cmb[:,:,1] *= 255.0 / slice_width 89 | cmb[:,:,2] *= 50 90 | 91 | if (mode == 1): 92 | cmb = np.dstack((time, pcnt, ncnt)) 93 | return cmb 94 | 95 | 96 | def aos2soa(aos, keys=[]): 97 | # Convert an array of structures (expressed as Python dict) 98 | # to a structure of arrays 99 | if (len(aos) == 0): 100 | return aos 101 | end = aos[0] 102 | for key in keys: 103 | end = end[key] 104 | if (type(end) == type(dict())): 105 | ret = {} 106 | for key in end: 107 | ret[key] = aos2soa(aos, keys + [key]) 108 | return ret 109 | ret = [] 110 | for s in aos: 111 | end = s 112 | for key in keys: 113 | end = end[key] 114 | ret.append(end) 115 | return ret 116 | 117 | 118 | def d(arr): 119 | ret = [0] 120 | for i in range(1, len(arr) - 1): 121 | ret.append((arr[i + 1] - arr[i - 1])) 122 | ret.append(ret[-1]) 123 | ret[0] = ret[1] 124 | return np.array(ret) 125 | 126 | 127 | def angle_to_absolute(angles): 128 | ret = [angles[0]] 129 | offset = 0.0 130 | for i in range(1, len(angles)): 131 | if (angles[i - 1] - angles[i] > 5.5): 132 | offset += 2 * math.pi 133 | if (angles[i] - angles[i - 1] > 5.5): 134 | offset -= 2 * math.pi 135 | ret.append(angles[i] + offset) 136 | return np.array(ret) 137 | 138 | 139 | def smooth(t, x, s=0.001, k=3): 140 | tckp, u = splprep([x, t], s=s, k=k, nest=-1) 141 | x_new, t_new = splev(np.linspace(0, 1, len(t)), tckp) 142 | return t_new, x_new 143 | 144 | 145 | def save_plot(frames_meta, oids, file_name, tp='vel'): 146 | plottable_meta = aos2soa(frames_meta) 147 | plt.rcParams['lines.linewidth'] = 0.8 148 | #fig, axs = plt.subplots(2 * (len(oids) + 1), 1) 149 | 150 | fig, axs = plt.subplots(2 * (len(oids) + 3), 1) 151 | 152 | 153 | 154 | #axs[0].plot(plottable_meta['ts'], 100 * d(plottable_meta['ts']), label='dt') 155 | #axs[0].plot(plottable_meta['ts'], 100 * d(plottable_meta['cam']['pos']['t']['x']), label='dp') 156 | #axs[0].plot(plottable_meta['ts'], d(plottable_meta['cam']['pos']['t']['x']) / d(plottable_meta['ts']), '-', label='vel') 157 | #axs[0].plot(plottable_meta['ts'], plottable_meta['cam']['pos']['t']['x'], '-', label='pos') 158 | #axs[0].plot(t_new, x_new, '-', label='pos_smooth') 159 | #axs[0].plot(plottable_meta['ts'], d(plottable_meta['cam']['pos']['t']['x']) / d(plottable_meta['ts']), '-', label='vel') 160 | #axs[0].plot(t_new, d(x_new) / d(t_new), '-', label='vel_smooth') 161 | 162 | #t, x = smooth(plottable_meta['ts'], plottable_meta['2']['pos']['t']['x']) 163 | 164 | oid = 'cam' 165 | t = plottable_meta['ts'] 166 | p = [plottable_meta[oid]['pos']['t']['x'], plottable_meta[oid]['pos']['t']['y'], plottable_meta[oid]['pos']['t']['z']] 167 | 168 | tckp, u = splprep(p + [t], s=0.001, k=3, nest=-1) 169 | x, y, z, t_new = splev(np.linspace(0, 1, len(t)), tckp) 170 | 171 | axs[0].plot(t_new, x, '-', label='p smooth') 172 | axs[0].plot(plottable_meta['ts'], plottable_meta[oid]['pos']['t']['x'], '-', label='p') 173 | axs[1].plot(t_new, y, '-', label='p smooth') 174 | axs[1].plot(plottable_meta['ts'], plottable_meta[oid]['pos']['t']['y'], '-', label='p') 175 | axs[2].plot(t_new, z, '-', label='p smooth') 176 | axs[2].plot(plottable_meta['ts'], plottable_meta[oid]['pos']['t']['z'], '-', label='p') 177 | 178 | t = plottable_meta['ts'] 179 | plottable_meta[oid]['pos']['rpy']['r'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['r']) 180 | plottable_meta[oid]['pos']['rpy']['p'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['p']) 181 | plottable_meta[oid]['pos']['rpy']['y'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['y']) 182 | 183 | px = [plottable_meta[oid]['pos']['rpy']['r']] 184 | py = [plottable_meta[oid]['pos']['rpy']['p']] 185 | pz = [plottable_meta[oid]['pos']['rpy']['y']] 186 | 187 | tckp, u = splprep(px + [t], s=0.001, k=3, nest=-1) 188 | x, t_new = splev(np.linspace(0, 1, len(t)), tckp) 189 | 190 | axs[3].plot(t_new, x, '-', label='p smooth') 191 | axs[3].plot(plottable_meta['ts'], plottable_meta[oid]['pos']['rpy']['r'], '-', label='p') 192 | 193 | tckp, u = splprep(py + [t], s=0.001, k=3, nest=-1) 194 | y, t_new = splev(np.linspace(0, 1, len(t)), tckp) 195 | 196 | axs[4].plot(t_new, y, '-', label='p smooth') 197 | axs[4].plot(plottable_meta['ts'], plottable_meta[oid]['pos']['rpy']['p'], '-', label='p') 198 | 199 | tckp, u = splprep(pz + [t], s=0.001, k=3, nest=-1) 200 | z, t_new = splev(np.linspace(0, 1, len(t)), tckp) 201 | 202 | axs[5].plot(t_new, z, '-', label='p smooth') 203 | axs[5].plot(plottable_meta['ts'], plottable_meta[oid]['pos']['rpy']['y'], '-', label='p') 204 | 205 | 206 | #axs[0].plot(t, x, '-', label='pos') 207 | #axs[0].plot(t, d(x) / d(t), '-', label='vel_sm') 208 | # __t = '1' 209 | # axs[0].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['t']['x'], '-', label='p(data)') 210 | # axs[0].plot(plottable_meta['ts'], d(plottable_meta[__t]['pos']['t']['x']) / d(plottable_meta['ts']), '-', label='p(diff)') 211 | # axs[1].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['t']['y'], '-', label='p(data)') 212 | # axs[1].plot(plottable_meta['ts'], d(plottable_meta[__t]['pos']['t']['y']) / d(plottable_meta['ts']), '-', label='p(diff)') 213 | # axs[2].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['t']['z'], '-', label='p(data)') 214 | # axs[2].plot(plottable_meta['ts'], d(plottable_meta[__t]['pos']['t']['z']) / d(plottable_meta['ts']), '-', label='p(diff)') 215 | # axs[3].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['rpy']['r'], '-', label='p(data)') 216 | # axs[3].plot(plottable_meta['ts'], d(plottable_meta[__t]['pos']['rpy']['r']) / d(plottable_meta['ts']), '-', label='p(diff)') 217 | # axs[4].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['rpy']['p'], '-', label='p(data)') 218 | # axs[4].plot(plottable_meta['ts'], d(plottable_meta[__t]['pos']['rpy']['p']) / d(plottable_meta['ts']), '-', label='p(diff)') 219 | # axs[5].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['rpy']['y'], '-', label='p(data)') 220 | # axs[5].plot(plottable_meta['ts'], d(plottable_meta[__t]['pos']['rpy']['y']) / d(plottable_meta['ts']), '-', label='p(diff)') 221 | 222 | # axs[0].plot(plottable_meta['ts'], plottable_meta[__t]['pos']['t']['x'], '-', label='p(data)') 223 | # axs[1].plot(plottable_meta['ts'], plottable_meta[__t]['pos']['t']['y'], '-', label='p(data)') 224 | # axs[2].plot(plottable_meta['ts'], plottable_meta[__t]['pos']['t']['z'], '-', label='p(data)') 225 | # axs[0].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['t']['x'], '-', label='v(data)') 226 | # axs[1].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['t']['y'], '-', label='v(data)') 227 | # axs[2].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['t']['z'], '-', label='v(data)') 228 | # axs[3].plot(plottable_meta['ts'], plottable_meta[__t]['pos']['rpy']['r'], '-', label='p(data)') 229 | # axs[4].plot(plottable_meta['ts'], plottable_meta[__t]['pos']['rpy']['p'], '-', label='p(data)') 230 | # axs[5].plot(plottable_meta['ts'], plottable_meta[__t]['pos']['rpy']['y'], '-', label='p(data)') 231 | # axs[3].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['rpy']['r'], '-', label='v(data)') 232 | # axs[4].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['rpy']['p'], '-', label='v(data)') 233 | # axs[5].plot(plottable_meta['ts'], plottable_meta[__t]['vel']['rpy']['y'], '-', label='v(data)') 234 | 235 | 236 | axs[0].grid() 237 | axs[0].legend() 238 | axs[1].grid() 239 | axs[1].legend() 240 | axs[2].grid() 241 | axs[2].legend() 242 | 243 | fig.set_size_inches(0.03 * 50 * (plottable_meta['ts'][-1] - plottable_meta['ts'][0]), 8 * (1 + len(oids))) 244 | plt.savefig(file_name, dpi=400, bbox_inches='tight') 245 | #plt.show() 246 | return 247 | 248 | 249 | #v_new, t_new_ = splev(np.linspace(0, 1, len(t)), tckp, der=1) 250 | #axs[0].plot(t_new, d(v_new)/d(t_new_), '-', label='vel_spl') 251 | 252 | #axs[0].plot(plottable_meta['ts'], plottable_meta['cam']['vel']['t']['x'], 'o-', label='vel') 253 | #axs[0].plot(plottable_meta['ts'], plottable_meta['cam'][tp]['t']['x'], label='X axis (up - down)') 254 | 255 | #axs[0].plot(plottable_meta['ts'], plottable_meta['cam'][tp]['t']['y'], label='Y axis (left - right)') 256 | #axs[0].plot(plottable_meta['ts'], plottable_meta['cam'][tp]['t']['z'], label='Z axis (forward - backward)') 257 | axs[0].set_ylabel('camera linear (m/s)') 258 | axs[0].grid() 259 | axs[0].legend() 260 | axs[1].plot(plottable_meta['ts'], plottable_meta['cam'][tp]['rpy']['r'], label='X axis') 261 | axs[1].plot(plottable_meta['ts'], plottable_meta['cam'][tp]['rpy']['p'], label='Y axis') 262 | axs[1].plot(plottable_meta['ts'], plottable_meta['cam'][tp]['rpy']['y'], label='Z axis') 263 | axs[1].set_xlabel('frame') 264 | axs[1].set_ylabel('camera angular (rad/s)') 265 | axs[1].grid() 266 | axs[1].legend() 267 | 268 | for k, id_ in enumerate(oids): 269 | axs[2 * k + 2].plot(plottable_meta['ts'], plottable_meta[id_][tp]['t']['x'], label='X axis') 270 | axs[2 * k + 2].plot(plottable_meta['ts'], plottable_meta[id_][tp]['t']['y'], label='Y axis') 271 | axs[2 * k + 2].plot(plottable_meta['ts'], plottable_meta[id_][tp]['t']['z'], label='Z axis') 272 | axs[2 * k + 2].set_ylabel('object_' + str(id_) + ' linear (m/s)') 273 | axs[2 * k + 2].grid() 274 | axs[2 * k + 2].legend() 275 | axs[2 * k + 3].plot(plottable_meta['ts'], plottable_meta[id_][tp]['rpy']['r'], label='X axis') 276 | axs[2 * k + 3].plot(plottable_meta['ts'], plottable_meta[id_][tp]['rpy']['p'], label='Y axis') 277 | axs[2 * k + 3].plot(plottable_meta['ts'], plottable_meta[id_][tp]['rpy']['y'], label='Z axis') 278 | axs[2 * k + 3].set_xlabel('frame') 279 | axs[2 * k + 3].set_ylabel('object_' + str(id_) + ' angular (rad/s)') 280 | axs[2 * k + 3].grid() 281 | axs[2 * k + 3].legend() 282 | 283 | fig.set_size_inches(0.03 * 50 * (plottable_meta['ts'][-1] - plottable_meta['ts'][0]), 8 * (1 + len(oids))) 284 | plt.savefig(file_name, dpi=400, bbox_inches='tight') 285 | plt.show() 286 | 287 | 288 | def add_spline_smoothing(dataset_txt, oid): 289 | tj = aos2soa(dataset_txt['full_trajectory']) 290 | t, x = smooth(tj['ts'], tj[oid]['pos']['t']['x']) 291 | 292 | 293 | 294 | 295 | #axs[0].plot(t, x, '-', label='pos') 296 | #axs[0].plot(t, d(x) / d(t), '-', label='vel_sm') 297 | 298 | 299 | #tj['cam'] 300 | 301 | 302 | if __name__ == '__main__': 303 | parser = argparse.ArgumentParser() 304 | parser.add_argument('--base_dir', 305 | type=str, 306 | default='.', 307 | required=False) 308 | parser.add_argument('--discretization', 309 | type=float, 310 | required=False, 311 | default=0.01) 312 | parser.add_argument('--slice_width', 313 | type=float, 314 | required=False, 315 | default=0.05) 316 | 317 | args = parser.parse_args() 318 | print (pydvs.okb("Opening"), args.base_dir) 319 | 320 | dataset_txt = eval(open(os.path.join(args.base_dir, 'meta.txt')).read()) 321 | #add_spline_smoothing(dataset_txt, 'cam') 322 | 323 | K = np.array([[0.0, 0.0, 0.0], 324 | [0.0, 0.0, 0.0], 325 | [0.0, 0.0, 1.0]]) 326 | D = np.array([0.0, 0.0, 0.0, 0.0]) 327 | 328 | K[0][0] = dataset_txt['meta']['fx'] 329 | K[1][1] = dataset_txt['meta']['fy'] 330 | K[0][2] = dataset_txt['meta']['cx'] 331 | K[1][2] = dataset_txt['meta']['cy'] 332 | D[0] = dataset_txt['meta']['k1'] 333 | D[1] = dataset_txt['meta']['k2'] 334 | D[2] = dataset_txt['meta']['k3'] 335 | D[3] = dataset_txt['meta']['k4'] 336 | RES_X = dataset_txt['meta']['res_x'] 337 | RES_Y = dataset_txt['meta']['res_y'] 338 | NUM_FRAMES = len(dataset_txt['frames']) 339 | frames_meta = dataset_txt['frames'] 340 | 341 | D /= 10.0 # FIXME 342 | 343 | # FIXME 344 | oids = [] 345 | for key in frames_meta[0]: 346 | if (key == 'cam'): continue 347 | if (type(frames_meta[0][key]) == type(dict()) and 'vel' in frames_meta[0][key]): 348 | oids.append(key) 349 | 350 | print (pydvs.okb("Resolution:"), RES_Y, 'x', RES_X) 351 | print (pydvs.okb("Frames:"), NUM_FRAMES) 352 | print (pydvs.okb("Object ids:"), oids) 353 | print (pydvs.okb("Calibration:")) 354 | print (K) 355 | print (D) 356 | 357 | # Create a plot 358 | save_plot(frames_meta, oids, os.path.join(args.base_dir, 'velocity_plots.pdf'), tp='vel') 359 | save_plot(dataset_txt['full_trajectory'], oids, os.path.join(args.base_dir, 'velocity_plots_full.pdf'), tp='vel') 360 | 361 | # Read depth / masks 362 | print (pydvs.bld("Reading the depth and masks:")) 363 | depths = np.zeros((NUM_FRAMES,) + (RES_X, RES_Y)) 364 | masks = np.zeros((NUM_FRAMES,) + (RES_X, RES_Y)) 365 | classical = np.zeros((NUM_FRAMES,) + (RES_X, RES_Y)) 366 | classical_read = 0 367 | for i, frame in enumerate(frames_meta): 368 | print ("frame\t", i + 1, "/", NUM_FRAMES, "\t", end='\r') 369 | 370 | gt_frame_name = os.path.join(args.base_dir, frame['gt_frame']) 371 | gt_img = cv2.imread(gt_frame_name, cv2.IMREAD_UNCHANGED).astype(dtype=np.float32) 372 | 373 | depth = gt_img[:,:,0] 374 | mask = gt_img[:,:,2] 375 | 376 | depth[depth <= 10] = np.nan 377 | depths[i,:,:] = depth 378 | masks[i,:,:] = mask 379 | 380 | if ('classical_frame' in frame.keys()): 381 | classical_frame_name = os.path.join(args.base_dir, frame['classical_frame']) 382 | classical[i,:,:] = cv2.imread(classical_frame_name, cv2.IMREAD_GRAYSCALE).astype(dtype=np.float32) 383 | classical_read += 1 384 | print ("\n") 385 | 386 | if (classical_read > 0): 387 | print (pydvs.okb("Read "), classical_read, "/", NUM_FRAMES, pydvs.okb(" classical frames")) 388 | 389 | # Read event cloud 390 | cloud, idx = pydvs.read_event_file_txt(os.path.join(args.base_dir, 'events.txt'), args.discretization) 391 | print (pydvs.okb("The recording range:"), cloud[0][0], "-", cloud[-1][0]) 392 | print (pydvs.okb("The gt range:"), frames_meta[0]['ts'], "-", frames_meta[-1]['ts']) 393 | print (pydvs.okb("Discretization resolution:"), args.discretization) 394 | 395 | # Save .npz file 396 | print (pydvs.bld("Saving...")) 397 | np.savez_compressed(os.path.join(args.base_dir, 'dataset.npz'), events=cloud, index=idx, 398 | discretization=args.discretization, K=K, D=D, depth=depths, mask=masks, meta=dataset_txt) 399 | print ("\n") 400 | 401 | # Generate images: 402 | slice_dir = os.path.join(args.base_dir, 'slices') 403 | vis_dir = os.path.join(args.base_dir, 'vis') 404 | 405 | pydvs.replace_dir(slice_dir) 406 | pydvs.replace_dir(vis_dir) 407 | 408 | for i, frame in enumerate(frames_meta): 409 | print ("Saving sanity check frames\t", i + 1, "/", NUM_FRAMES, "\t", end='\r') 410 | time = frame['ts'] 411 | if (time > cloud[-1][0] or time < cloud[0][0]): 412 | continue 413 | 414 | sl, _ = pydvs.get_slice(cloud, idx, time, args.slice_width, 1, args.discretization) 415 | 416 | depth = depths[i] 417 | mask = masks[i] 418 | eimg = dvs_img(sl, (RES_X, RES_Y), None, None, args.slice_width, mode=0) 419 | 420 | cv2.imwrite(os.path.join(slice_dir, 'frame_' + str(i).rjust(10, '0') + '.png'), eimg) 421 | cv2.imwrite(os.path.join(slice_dir, 'depth_' + str(i).rjust(10, '0') + '.png'), depth.astype(np.uint16)) 422 | cv2.imwrite(os.path.join(slice_dir, 'mask_' + str(i).rjust(10, '0') + '.png'), mask.astype(np.uint16)) 423 | 424 | eimg = dvs_img(sl, (RES_X, RES_Y), None, None, args.slice_width, mode=1) 425 | 426 | nmin = np.nanmin(depth) 427 | nmax = np.nanmax(depth) 428 | 429 | eimg[:,:,2] = (depth - nmin) / (nmax - nmin) * 255 430 | col_mask = mask_to_color(mask) 431 | 432 | rgb_img = np.dstack((classical[i], classical[i], classical[i])) 433 | rgb_img[mask > 10] = rgb_img[mask > 10] * 0.5 + col_mask[mask > 10] * 0.5 434 | eimg = np.hstack((rgb_img, eimg)) 435 | 436 | footer = gen_text_stub(eimg.shape[1], frame) 437 | eimg = np.vstack((eimg, footer)) 438 | 439 | cv2.imwrite(os.path.join(vis_dir, 'frame_' + str(i).rjust(10, '0') + '.png'), eimg) 440 | print (pydvs.okg("\nDone.\n")) 441 | -------------------------------------------------------------------------------- /samples/evimo-gen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | import multiprocessing 5 | from multiprocessing import Pool 6 | import subprocess 7 | import numpy as np 8 | import matplotlib.pyplot as plt 9 | import os, sys, math, signal, glob 10 | import cv2 11 | import pydvs 12 | from tqdm import tqdm 13 | import shutil 14 | 15 | # https://stackoverflow.com/a/57364423 16 | # istarmap.py for Python 3.8+ 17 | import multiprocessing.pool as mpp 18 | def istarmap(self, func, iterable, chunksize=1): 19 | """starmap-version of imap 20 | """ 21 | self._check_running() 22 | if chunksize < 1: 23 | raise ValueError( 24 | "Chunksize must be 1+, not {0:n}".format( 25 | chunksize)) 26 | 27 | task_batches = mpp.Pool._get_tasks(func, iterable, chunksize) 28 | result = mpp.IMapIterator(self) 29 | self._taskqueue.put( 30 | ( 31 | self._guarded_task_generation(result._job, 32 | mpp.starmapstar, 33 | task_batches), 34 | result._set_length 35 | )) 36 | return (item for chunk in result for item in chunk) 37 | mpp.Pool.istarmap = istarmap 38 | 39 | 40 | def mask_to_color(mask): 41 | colors = [[84, 71, 140], [44, 105, 154], [4, 139, 168], 42 | [13, 179, 158], [22, 219, 147], [131, 227, 119], 43 | [185, 231, 105], [239, 234, 90], [241, 196, 83], 44 | [242, 158, 76], [239, 71, 111], [255, 209, 102], 45 | [6, 214, 160], [17, 138, 178], [7, 59, 76], 46 | [6, 123, 194], [132, 188, 218], [236, 195, 11], 47 | [243, 119, 72], [213, 96, 98]] 48 | 49 | cmb = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.float32) 50 | m_ = np.max(mask) + 500 51 | m_ = max(m_, 3500) 52 | 53 | maxoid = int(m_ / 1000) 54 | for i in range(maxoid): 55 | cutoff_lo = 1000.0 * (i + 1.0) - 5 56 | cutoff_hi = 1000.0 * (i + 1.0) + 5 57 | cmb[np.where(np.logical_and(mask>=cutoff_lo, mask<=cutoff_hi))] = np.array(colors[i % len(colors)]) 58 | return cmb 59 | 60 | 61 | def gen_text_stub(shape_y, meta, step=15, font_scale=0.8): 62 | strings = {} 63 | for key in sorted(meta.keys()): 64 | try: 65 | pos = meta[key]['pos'] 66 | except: 67 | continue 68 | strings[key] = {} 69 | strings[key]['pt'] = ("{0:.2f}".format(pos['t']['x']) + " " 70 | "{0:.2f}".format(pos['t']['y']) + " " 71 | "{0:.2f}".format(pos['t']['z'])) 72 | strings[key]['pr'] = ("{0:.2f}".format(pos['rpy']['r']) + " " 73 | "{0:.2f}".format(pos['rpy']['p']) + " " 74 | "{0:.2f}".format(pos['rpy']['y'])) 75 | shape_x = int(len(strings) * step + step / 2) 76 | cmb = np.zeros((shape_x, shape_y, 3), dtype=np.float32) 77 | 78 | offst = {} 79 | offst['pt'] = step * 4 80 | offst['pr'] = offst['pt'] + step * 10 81 | 82 | for i, key in enumerate(sorted(strings.keys())): 83 | cv2.putText(cmb, key + ': ', (step // 2, step + i * step), 84 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 85 | cv2.putText(cmb, '| ' + strings[key]['pt'], (offst['pt'], step + i * step), 86 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 87 | cv2.putText(cmb, '| ' + strings[key]['pr'], (offst['pr'], step + i * step), 88 | cv2.FONT_HERSHEY_PLAIN, font_scale, (255,255,255), 1, cv2.LINE_AA) 89 | return cmb 90 | 91 | 92 | def dvs_img(cloud, shape, K, D, slice_width, mode=0): 93 | cmb = pydvs.dvs_img(cloud, shape, K=K, D=D) 94 | 95 | ncnt = cmb[:,:,0] 96 | time = cmb[:,:,1] 97 | pcnt = cmb[:,:,2] 98 | cnt = pcnt + ncnt 99 | 100 | # Scale up to be able to save as uint8 101 | # For visualization only. May cause overflow if slice_width is large 102 | cmb[:,:,0] *= 50 103 | cmb[:,:,1] *= 255.0 / slice_width 104 | cmb[:,:,2] *= 50 105 | 106 | if (mode == 1): 107 | cmb = np.dstack((time, pcnt, ncnt)) 108 | return cmb 109 | 110 | 111 | # aos2soa does not suffice because there are dropped poses 112 | def frames_meta_to_arrays(all_objects_pose_list): 113 | objects_arrays = {} 114 | 115 | for objects_pose in all_objects_pose_list: 116 | for obj_id in objects_pose: 117 | if obj_id == 'ts': 118 | if 'ts' not in objects_arrays: 119 | objects_arrays['ts'] = [] 120 | objects_arrays['ts'].append(objects_pose['ts']) 121 | 122 | if obj_id == 'cam' or obj_id.isnumeric(): 123 | if obj_id not in objects_arrays: 124 | objects_arrays[obj_id] = {} 125 | objects_arrays[obj_id]['ts'] = [] 126 | objects_arrays[obj_id]['pos'] = {} 127 | objects_arrays[obj_id]['pos']['t'] = {} 128 | objects_arrays[obj_id]['pos']['t']['x'] = [] 129 | objects_arrays[obj_id]['pos']['t']['y'] = [] 130 | objects_arrays[obj_id]['pos']['t']['z'] = [] 131 | objects_arrays[obj_id]['pos']['rpy'] = {} 132 | objects_arrays[obj_id]['pos']['rpy']['r'] = [] 133 | objects_arrays[obj_id]['pos']['rpy']['p'] = [] 134 | objects_arrays[obj_id]['pos']['rpy']['y'] = [] 135 | objects_arrays[obj_id]['pos']['q'] = {} 136 | objects_arrays[obj_id]['pos']['q']['w'] = [] 137 | objects_arrays[obj_id]['pos']['q']['x'] = [] 138 | objects_arrays[obj_id]['pos']['q']['y'] = [] 139 | objects_arrays[obj_id]['pos']['q']['z'] = [] 140 | 141 | objects_arrays[obj_id]['ts'].append(objects_pose[obj_id]['ts']) 142 | objects_arrays[obj_id]['pos']['t']['x'].append(objects_pose[obj_id]['pos']['t']['x']) 143 | objects_arrays[obj_id]['pos']['t']['y'].append(objects_pose[obj_id]['pos']['t']['y']) 144 | objects_arrays[obj_id]['pos']['t']['z'].append(objects_pose[obj_id]['pos']['t']['z']) 145 | objects_arrays[obj_id]['pos']['rpy']['r'].append(objects_pose[obj_id]['pos']['rpy']['r']) 146 | objects_arrays[obj_id]['pos']['rpy']['p'].append(objects_pose[obj_id]['pos']['rpy']['p']) 147 | objects_arrays[obj_id]['pos']['rpy']['y'].append(objects_pose[obj_id]['pos']['rpy']['y']) 148 | objects_arrays[obj_id]['pos']['q']['w'].append(objects_pose[obj_id]['pos']['q']['w']) 149 | objects_arrays[obj_id]['pos']['q']['x'].append(objects_pose[obj_id]['pos']['q']['x']) 150 | objects_arrays[obj_id]['pos']['q']['y'].append(objects_pose[obj_id]['pos']['q']['y']) 151 | objects_arrays[obj_id]['pos']['q']['z'].append(objects_pose[obj_id]['pos']['q']['z']) 152 | return objects_arrays 153 | 154 | def angle_to_absolute(angles): 155 | return np.array(angles) 156 | ret = [angles[0]] 157 | offset = 0.0 158 | for i in range(1, len(angles)): 159 | if (angles[i - 1] - angles[i] > 5.5): 160 | offset += 2 * math.pi 161 | if (angles[i] - angles[i - 1] > 5.5): 162 | offset -= 2 * math.pi 163 | ret.append(angles[i] + offset) 164 | return np.array(ret) 165 | 166 | 167 | def save_plot(frames_meta, oids, file_name, tp='pos'): 168 | plottable_meta = frames_meta_to_arrays(frames_meta) 169 | plt.rcParams['lines.linewidth'] = 0.8 170 | fig, axs = plt.subplots(2 * (len(oids) + 1), 1) 171 | 172 | oid = 'cam' 173 | plottable_meta[oid]['pos']['rpy']['r'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['r']) 174 | plottable_meta[oid]['pos']['rpy']['p'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['p']) 175 | plottable_meta[oid]['pos']['rpy']['y'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['y']) 176 | 177 | axs[0].plot(plottable_meta['cam']['ts'], plottable_meta['cam'][tp]['t']['x'], label='X axis') 178 | axs[0].plot(plottable_meta['cam']['ts'], plottable_meta['cam'][tp]['t']['y'], label='Y axis') 179 | axs[0].plot(plottable_meta['cam']['ts'], plottable_meta['cam'][tp]['t']['z'], label='Z axis') 180 | axs[0].set_ylabel('camera translation (m)') 181 | axs[0].grid() 182 | axs[0].legend() 183 | axs[1].plot(plottable_meta['cam']['ts'], plottable_meta['cam'][tp]['rpy']['r'], label='R') 184 | axs[1].plot(plottable_meta['cam']['ts'], plottable_meta['cam'][tp]['rpy']['p'], label='P') 185 | axs[1].plot(plottable_meta['cam']['ts'], plottable_meta['cam'][tp]['rpy']['y'], label='Y') 186 | axs[1].set_xlabel('frame') 187 | axs[1].set_ylabel('camera rotation (rad)') 188 | axs[1].grid() 189 | axs[1].legend() 190 | 191 | for k, id_ in enumerate(oids): 192 | plottable_meta[oid]['pos']['rpy']['r'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['r']) 193 | plottable_meta[oid]['pos']['rpy']['p'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['p']) 194 | plottable_meta[oid]['pos']['rpy']['y'] = angle_to_absolute(plottable_meta[oid]['pos']['rpy']['y']) 195 | 196 | axs[2 * k + 2].plot(plottable_meta[id_]['ts'], plottable_meta[id_][tp]['t']['x'], label='X axis') 197 | axs[2 * k + 2].plot(plottable_meta[id_]['ts'], plottable_meta[id_][tp]['t']['y'], label='Y axis') 198 | axs[2 * k + 2].plot(plottable_meta[id_]['ts'], plottable_meta[id_][tp]['t']['z'], label='Z axis') 199 | axs[2 * k + 2].set_ylabel('object_' + str(id_) + ' translation (m)') 200 | axs[2 * k + 2].grid() 201 | axs[2 * k + 2].legend() 202 | axs[2 * k + 3].plot(plottable_meta[id_]['ts'], plottable_meta[id_][tp]['rpy']['r'], label='R') 203 | axs[2 * k + 3].plot(plottable_meta[id_]['ts'], plottable_meta[id_][tp]['rpy']['p'], label='P') 204 | axs[2 * k + 3].plot(plottable_meta[id_]['ts'], plottable_meta[id_][tp]['rpy']['y'], label='Y') 205 | axs[2 * k + 3].set_xlabel('frame') 206 | axs[2 * k + 3].set_ylabel('object_' + str(id_) + ' rotation (rad)') 207 | axs[2 * k + 3].grid() 208 | axs[2 * k + 3].legend() 209 | 210 | fig.set_size_inches(0.03 * 50 * (plottable_meta['ts'][-1] - plottable_meta['ts'][0]), 8 * (1 + len(oids))) 211 | plt.savefig(file_name, dpi=400, bbox_inches='tight') 212 | #plt.show() 213 | 214 | if __name__ == '__main__': 215 | parser = argparse.ArgumentParser() 216 | parser.add_argument('--base_dir', 217 | type=str, 218 | default='.', 219 | required=False) 220 | parser.add_argument('--discretization', 221 | type=float, 222 | required=False, 223 | default=0.01) 224 | parser.add_argument('--slice_width', 225 | type=float, 226 | required=False, 227 | default=0.05) 228 | parser.add_argument('--skip_slice_vis', action='store_true') 229 | parser.add_argument('--evimo2_npz', action='store_true') 230 | parser.add_argument('--evimo2_no_compress', action='store_true') 231 | args = parser.parse_args() 232 | 233 | print (pydvs.okb("Opening"), args.base_dir) 234 | 235 | dataset_txt = eval(open(os.path.join(args.base_dir, 'meta.txt')).read()) 236 | 237 | K = np.array([[0.0, 0.0, 0.0], 238 | [0.0, 0.0, 0.0], 239 | [0.0, 0.0, 1.0]]) 240 | D = np.array([0.0, 0.0, 0.0, 0.0]) 241 | 242 | K[0][0] = dataset_txt['meta']['fx'] 243 | K[1][1] = dataset_txt['meta']['fy'] 244 | K[0][2] = dataset_txt['meta']['cx'] 245 | K[1][2] = dataset_txt['meta']['cy'] 246 | D[0] = dataset_txt['meta']['k1'] 247 | D[1] = dataset_txt['meta']['k2'] 248 | D[2] = dataset_txt['meta']['k3'] 249 | D[3] = dataset_txt['meta']['k4'] 250 | RES_X = dataset_txt['meta']['res_x'] 251 | RES_Y = dataset_txt['meta']['res_y'] 252 | NUM_FRAMES = len(dataset_txt['frames']) 253 | frames_meta = dataset_txt['frames'] 254 | 255 | oids = {} 256 | for frame in frames_meta: 257 | for key in frame: 258 | if (key == 'cam'): continue 259 | if (type(frame[key]) == type(dict()) and 'pos' in frame[key]): 260 | if key not in oids: 261 | oids[key] = None 262 | oids = list(oids.keys()) 263 | 264 | print (pydvs.okb("Resolution:"), RES_X, 'x', RES_Y) 265 | print (pydvs.okb("Frames:"), NUM_FRAMES) 266 | print (pydvs.okb("Object ids:"), oids) 267 | print (pydvs.okb("Calibration:")) 268 | print (K) 269 | print (D) 270 | 271 | # Create a plot 272 | #save_plot(frames_meta, oids, os.path.join(args.base_dir, 'position_plots.pdf'), tp='pos') 273 | save_plot(dataset_txt['full_trajectory'], oids, os.path.join(args.base_dir, 'position_plots.pdf'), tp='pos') 274 | 275 | # Read depth / masks 276 | print (pydvs.bld("Reading the depth and masks:")) 277 | 278 | 279 | if args.evimo2_npz: 280 | pydvs.replace_dir(os.path.join(args.base_dir, 'depth_npy')) 281 | pydvs.replace_dir(os.path.join(args.base_dir, 'mask_npy')) 282 | pydvs.replace_dir(os.path.join(args.base_dir, 'classical_npy')) 283 | else: 284 | # For original EVIMO npz format, there is no easy way around these big arrays 285 | # because the entire array needs to be passed to savez_compressed 286 | # however, we can memory map them, so at least we do not run out of RAM 287 | depths = np.memmap(os.path.join(args.base_dir, 'dataset_depth.mm'), mode='w+', shape=(NUM_FRAMES,) + (RES_Y, RES_X), dtype=np.uint16) 288 | masks = np.memmap(os.path.join(args.base_dir, 'dataset_masks.mm'), mode='w+', shape=(NUM_FRAMES,) + (RES_Y, RES_X), dtype=np.uint16) 289 | classical = np.memmap(os.path.join(args.base_dir, 'dataset_classical.mm'), mode='w+', shape=(NUM_FRAMES,) + (RES_Y, RES_X, 3), dtype=np.uint8) 290 | 291 | def load_frame(i, frame): 292 | if 'gt_frame' in frame.keys(): 293 | gt_frame_name = os.path.join(args.base_dir, frame['gt_frame']) 294 | gt_img = cv2.imread(gt_frame_name, cv2.IMREAD_UNCHANGED) 295 | if not args.evimo2_npz: 296 | if (gt_img.dtype != depths.dtype or gt_img.dtype != masks.dtype): 297 | print ("\tType mismatch! Expected", depths.dtype, " but have", gt_img.dtype) 298 | sys.exit(-1) 299 | 300 | if args.evimo2_npz: 301 | depth_name = os.path.join(args.base_dir, 'depth_npy', 'depth_' + str(i).rjust(10, '0') + '.npy') 302 | mask_name = os.path.join(args.base_dir, 'mask_npy', 'mask_' + str(i).rjust(10, '0') + '.npy') 303 | np.save(depth_name, gt_img[:, :, 0], allow_pickle=False) 304 | np.save(mask_name, gt_img[:, :, 2], allow_pickle=False) 305 | else: 306 | depths[i,:,:] = gt_img[:,:,0] # depth is in mm 307 | masks[i,:,:] = gt_img[:,:,2] # mask is object ids * 1000 308 | 309 | if ('classical_frame' in frame.keys()): 310 | classical_frame_name = os.path.join(args.base_dir, frame['classical_frame']) 311 | classical_img = cv2.imread(classical_frame_name, cv2.IMREAD_UNCHANGED) 312 | if args.evimo2_npz: 313 | classical_name = os.path.join(args.base_dir, 'classical_npy', 'classical_' + str(i).rjust(10, '0') + '.npy') 314 | np.save(classical_name, classical_img, allow_pickle=False) 315 | else: 316 | classical[i,:,:,:] = classical_img 317 | 318 | if not args.evimo2_npz: 319 | if (gt_img.dtype != depths.dtype or gt_img.dtype != masks.dtype): 320 | print ("\tType mismatch! Expected", classical.dtype, " but have", classical_img.dtype) 321 | sys.exit(-1) 322 | return 1 323 | return 0 324 | 325 | num_cpu = multiprocessing.cpu_count() 326 | print('Using {} processes'.format(num_cpu)) 327 | with Pool(num_cpu) as p: 328 | classical_read_list = list(tqdm(p.istarmap(load_frame, enumerate(frames_meta)), total=len(frames_meta))) 329 | 330 | classical_read = np.sum(classical_read_list) 331 | 332 | print ("\n") 333 | 334 | if (classical_read > 0): 335 | print (pydvs.okb("Read "), classical_read, "/", NUM_FRAMES, pydvs.okb(" classical frames")) 336 | else: 337 | if not args.evimo2_npz: 338 | print (pydvs.wrn("Removing mmap file: ") + pydvs.okb(os.path.join(args.base_dir, 'dataset_classical.mm'))) 339 | classical._mmap.close() 340 | os.remove(os.path.join(args.base_dir, 'dataset_classical.mm')) 341 | 342 | classical = None 343 | 344 | # Read event cloud 345 | cloud, idx = pydvs.read_event_file_txt(os.path.join(args.base_dir, 'events.txt'), args.discretization) 346 | tmin = frames_meta[0]['ts'] 347 | tmax = frames_meta[-1]['ts'] 348 | if (cloud.shape[0] > 0): 349 | tmin = cloud[0][0] 350 | tmax = cloud[-1][0] 351 | print (pydvs.okb("The recording range:"), tmin, "-", tmax) 352 | print (pydvs.okb("The gt range:"), frames_meta[0]['ts'], "-", frames_meta[-1]['ts']) 353 | print (pydvs.okb("Discretization resolution:"), args.discretization) 354 | 355 | # Save .npz file 356 | print (pydvs.bld("Saving...")) 357 | # Save in EVIMO2 format 358 | if args.evimo2_npz: 359 | np.savez(os.path.join(args.base_dir, 'dataset_info.npz'), 360 | index=idx, discretization=args.discretization, K=K, D=D, meta=dataset_txt) 361 | np.save(os.path.join(args.base_dir, 'dataset_events_t.npy'), cloud[:, 0]) 362 | np.save(os.path.join(args.base_dir, 'dataset_events_xy.npy'), cloud[:, 1:3].astype(np.uint16)) 363 | np.save(os.path.join(args.base_dir, 'dataset_events_p.npy'), cloud[:, 3].astype(np.uint8)) 364 | 365 | # For compatibility when there are no classical frames 366 | if classical_read == 0: 367 | np.save(os.path.join(args.base_dir, 'classical_npy', 'empty.npy'), None) 368 | 369 | # If not compressed, the npy files can be compressed later in batches 370 | # which will greatly increase throughput when processing the entire dataset 371 | if not args.evimo2_no_compress: 372 | npz_pairs = [(os.path.join(args.base_dir, 'dataset_depth.npz'), os.path.join(args.base_dir, 'depth_npy')), 373 | (os.path.join(args.base_dir, 'dataset_mask.npz'), os.path.join(args.base_dir, 'mask_npy')), 374 | (os.path.join(args.base_dir, 'dataset_classical.npz'), os.path.join(args.base_dir, 'classical_npy'))] 375 | 376 | print (pydvs.bld("Compressing .npy into npz:")) 377 | print('Using {} processes'.format(len(npz_pairs))) 378 | compress_processes = [subprocess.Popen(['zip', '-rjq', filename, folder], cwd=args.base_dir) 379 | for filename, folder in npz_pairs] 380 | [p.wait() for p in compress_processes] 381 | 382 | # Save in original EVIMO format (takes a long time) 383 | else: 384 | np.savez_compressed(os.path.join(args.base_dir, 'dataset.npz'), events=cloud, index=idx, classical=classical, 385 | discretization=args.discretization, K=K, D=D, depth=depths, mask=masks, meta=dataset_txt) 386 | print ("\n") 387 | 388 | # Generate images: 389 | slice_dir = os.path.join(args.base_dir, 'slices') 390 | vis_dir = os.path.join(args.base_dir, 'vis') 391 | 392 | pydvs.replace_dir(slice_dir) 393 | pydvs.replace_dir(vis_dir) 394 | 395 | def save_visualization(i, frame): 396 | time = frame['ts'] 397 | if (time > tmax or time < tmin): 398 | return 399 | 400 | if args.evimo2_npz: 401 | depth_name = os.path.join(args.base_dir, 'depth_npy', 'depth_' + str(i).rjust(10, '0') + '.npy') 402 | mask_name = os.path.join(args.base_dir, 'mask_npy', 'mask_' + str(i).rjust(10, '0') + '.npy') 403 | 404 | if os.path.exists(depth_name): 405 | depth = np.load(depth_name) 406 | else: 407 | depth = None 408 | 409 | if os.path.exists(mask_name): 410 | mask = np.load(mask_name) 411 | else: 412 | mask = None 413 | else: 414 | depth = depths[i] 415 | mask = masks[i] 416 | 417 | if not args.skip_slice_vis: 418 | if depth is not None: 419 | cv2.imwrite(os.path.join(slice_dir, 'depth_' + str(i).rjust(10, '0') + '.png'), depth.astype(np.uint16)) 420 | if mask is not None: 421 | cv2.imwrite(os.path.join(slice_dir, 'mask_' + str(i).rjust(10, '0') + '.png'), mask.astype(np.uint16)) 422 | 423 | if (cloud.shape[0] > 0): 424 | sl, _ = pydvs.get_slice(cloud, idx, time, args.slice_width, 1, args.discretization) 425 | if not args.skip_slice_vis: 426 | eimg = dvs_img(sl, (RES_Y, RES_X), None, None, args.slice_width, mode=0) 427 | cv2.imwrite(os.path.join(slice_dir, 'frame_' + str(i).rjust(10, '0') + '.png'), eimg) 428 | 429 | # normalize for visualization 430 | if depth is not None: 431 | depth = depth.astype(np.float32) 432 | depth = (255 * (depth - np.nanmin(depth)) / (np.nanmax(depth) - np.nanmin(depth))).astype(np.uint8) 433 | 434 | if mask is not None: 435 | mask = mask.astype(np.float32) 436 | col_mask = mask_to_color(mask) 437 | mask = (255 * (mask - np.nanmin(mask)) / (np.nanmax(mask) - np.nanmin(mask))).astype(np.uint8) 438 | 439 | if classical_read > 0: 440 | if args.evimo2_npz: 441 | classical_name = os.path.join(args.base_dir, 'classical_npy', 'classical_' + str(i).rjust(10, '0') + '.npy') 442 | rgb_img = np.load(classical_name).astype(np.float32) 443 | else: 444 | rgb_img = classical[i].astype(np.float32) 445 | 446 | if mask is not None: 447 | mask_more_than_0 = mask > 0 448 | rgb_img[mask_more_than_0] = rgb_img[mask_more_than_0] * 0.2 + col_mask[mask_more_than_0] * 0.8 449 | 450 | rgb_img = np.rot90(rgb_img, k=2) 451 | if depth is not None: 452 | depth = np.rot90(depth, k=2) 453 | else: 454 | depth = np.zeros((rgb_img.shape[0], rgb_img.shape[1]), dtype=np.uint8) 455 | eimg = np.hstack((rgb_img.astype(np.uint8), np.dstack((depth,depth,depth)))) 456 | else: 457 | eimg = dvs_img(sl, (RES_Y, RES_X), None, None, args.slice_width, mode=0) 458 | if mask is not None: 459 | eimg[mask > 0] = eimg[mask > 0] * 0.5 + col_mask[mask > 0] * 0.5 460 | if depth is None: 461 | depth = np.zeros((eimg.shape[0], eimg.shape[1]), dtype=np.uint8) 462 | eimg = np.hstack((eimg.astype(np.uint8), np.dstack((depth,depth,depth)))) 463 | cv2.imwrite(os.path.join(vis_dir, 'frame_' + str(i).rjust(10, '0') + '.png'), eimg) 464 | 465 | print (pydvs.bld("Saving sanity and visualization frames:")) 466 | num_cpu = multiprocessing.cpu_count() 467 | print('Using {} processes'.format(num_cpu)) 468 | with Pool(num_cpu) as p: 469 | list(tqdm(p.istarmap(save_visualization, enumerate(frames_meta)), total=len(frames_meta))) 470 | 471 | print (pydvs.bld("Cleaning up intermediate files:")) 472 | if not args.evimo2_npz: 473 | print (pydvs.wrn("Removed mmap file: ") + pydvs.okb(os.path.join(args.base_dir, 'dataset_depth.mm'))) 474 | depths._mmap.close() 475 | os.remove(os.path.join(args.base_dir, 'dataset_depth.mm')) 476 | 477 | print (pydvs.wrn("Removed mmap file: ") + pydvs.okb(os.path.join(args.base_dir, 'dataset_masks.mm'))) 478 | masks._mmap.close() 479 | os.remove(os.path.join(args.base_dir, 'dataset_masks.mm')) 480 | 481 | if (classical_read > 0): 482 | print (pydvs.wrn("Removed mmap file: ") + pydvs.okb(os.path.join(args.base_dir, 'dataset_classical.mm'))) 483 | classical._mmap.close() 484 | os.remove(os.path.join(args.base_dir, 'dataset_classical.mm')) 485 | 486 | elif args.evimo2_npz and not args.evimo2_no_compress: 487 | print (pydvs.wrn("Removed directory: ") + pydvs.okb(os.path.join(args.base_dir, 'depth_npy'))) 488 | shutil.rmtree(os.path.join(args.base_dir, 'depth_npy')) 489 | 490 | print (pydvs.wrn("Removed directory: ") + pydvs.okb(os.path.join(args.base_dir, 'mask_npy'))) 491 | shutil.rmtree(os.path.join(args.base_dir, 'mask_npy')) 492 | 493 | print (pydvs.wrn("Removed directory: ") + pydvs.okb(os.path.join(args.base_dir, 'classical_npy'))) 494 | shutil.rmtree(os.path.join(args.base_dir, 'classical_npy')) 495 | 496 | print (pydvs.okg("\nDone.\n")) 497 | -------------------------------------------------------------------------------- /samples/extract_npz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | import numpy as np 5 | import os, sys, shutil, signal, glob, time 6 | import matplotlib.colors as colors 7 | import pydvs, cv2 8 | 9 | 10 | global_scale_pn = 50 11 | global_scale_pp = 50 12 | global_shape = (260, 346) 13 | slice_width = 1 14 | 15 | 16 | def clear_dir(f): 17 | if os.path.exists(f): 18 | print ("Removed directory: " + f) 19 | shutil.rmtree(f) 20 | os.makedirs(f) 21 | print ("Created directory: " + f) 22 | 23 | 24 | def dvs_img(cloud, shape, K, D): 25 | cmb = pydvs.dvs_img(cloud, shape, K=K, D=D) 26 | 27 | cmb[:,:,0] *= global_scale_pp 28 | cmb[:,:,1] *= 255.0 / slice_width 29 | cmb[:,:,2] *= global_scale_pn 30 | 31 | return cmb 32 | return cmb.astype(np.uint8) 33 | 34 | 35 | def mask_to_color(mask): 36 | colors = [[255,255,0], [0,255,255], [255,0,255], 37 | [0,255,0], [0,0,255], [255,0,0]] 38 | 39 | cmb = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.float32) 40 | m_ = np.max(mask) + 500 41 | m_ = max(m_, 3500) 42 | i = 0 43 | while (m_ > 0): 44 | cmb[mask < m_] = np.array(colors[i % len(colors)]) 45 | i += 1 46 | m_ -= 1000 47 | 48 | cmb[mask < 500] = np.array([0,0,0]) 49 | return cmb 50 | 51 | 52 | if __name__ == '__main__': 53 | parser = argparse.ArgumentParser() 54 | parser.add_argument('--base_dir', 55 | type=str, 56 | default='.', 57 | required=False) 58 | parser.add_argument('--width', 59 | type=float, 60 | required=False, 61 | default=0.05) 62 | parser.add_argument('--fps', 63 | type=float, 64 | required=False, 65 | default=-1) 66 | parser.add_argument('--no_undist', 67 | action='store_true', 68 | required=False, 69 | default=False) 70 | parser.add_argument('--mode', 71 | type=int, 72 | required=False, 73 | default=0) 74 | 75 | args = parser.parse_args() 76 | 77 | print ("Opening", args.base_dir) 78 | 79 | sl_npz = np.load(args.base_dir + '/recording.npz') 80 | cloud = sl_npz['events'] 81 | idx = sl_npz['index'] 82 | discretization = sl_npz['discretization'] 83 | slice_width = args.width 84 | 85 | first_ts = cloud[0][0] 86 | last_ts = cloud[-1][0] 87 | 88 | with_depth = True 89 | try: 90 | depth_gt = sl_npz['depth'] 91 | except: 92 | with_depth = False 93 | 94 | with_mask = True 95 | try: 96 | mask_gt = sl_npz['mask'] 97 | except: 98 | with_mask = False 99 | 100 | with_gt_ts = True 101 | try: 102 | gt_ts = sl_npz['gt_ts'] 103 | except: 104 | with_gt_ts = False 105 | 106 | if (not with_gt_ts): 107 | if (args.fps <= 0.0): 108 | print ("No ground truth timestamps available; please specify framerate from cli!") 109 | sys.exit(0) 110 | gt_ts = np.arange(first_ts, last_ts, 1.0 / args.fps) 111 | with_gt_ts = True 112 | 113 | K = None 114 | D = None 115 | 116 | if (not args.no_undist): 117 | K = sl_npz['K'] 118 | D = sl_npz['D'] 119 | print ("K and D:") 120 | print (K) 121 | print (D) 122 | print ("") 123 | else: 124 | print (pydvs.wrn("Undistortion disabled")) 125 | 126 | slice_dir = os.path.join(args.base_dir, 'slices') 127 | vis_dir = os.path.join(args.base_dir, 'vis') 128 | 129 | pydvs.replace_dir(slice_dir) 130 | pydvs.replace_dir(vis_dir) 131 | 132 | print ("The recording range:", first_ts, "-", last_ts) 133 | print ("The gt range:", gt_ts[0], "-", gt_ts[-1]) 134 | print ("Discretization resolution:", discretization) 135 | 136 | for i, time in enumerate(gt_ts): 137 | if (time > last_ts or time < first_ts): 138 | continue 139 | 140 | if (with_depth): 141 | depth = pydvs.undistort_img(depth_gt[i], K, D) 142 | cv2.imwrite(os.path.join(slice_dir, 'depth_' + str(i).rjust(10, '0') + '.png'), depth.astype(np.uint16)) 143 | 144 | if (with_mask): 145 | mask = pydvs.undistort_img(mask_gt[i], K, D) 146 | cv2.imwrite(os.path.join(slice_dir, 'mask_' + str(i).rjust(10, '0') + '.png'), mask.astype(np.uint16)) 147 | 148 | sl, _ = pydvs.get_slice(cloud, idx, time, args.width, args.mode, discretization) 149 | 150 | eimg = dvs_img(sl, global_shape, K, D) 151 | cv2.imwrite(os.path.join(slice_dir, 'frame_' + str(i).rjust(10, '0') + '.png'), eimg) 152 | 153 | cimg = eimg[:,:,0] + eimg[:,:,2] 154 | 155 | depth = cimg 156 | if (with_depth): 157 | nmin = np.nanmin(depth) 158 | nmax = np.nanmax(depth) 159 | depth = (depth - nmin) / (nmax - nmin) * 255 160 | depth = np.dstack((depth, depth * 0, cimg)) 161 | 162 | eimg = depth 163 | if (with_mask): 164 | col_mask = mask_to_color(mask) 165 | eimg = np.hstack((depth, col_mask)) 166 | 167 | cv2.imwrite(os.path.join(vis_dir, 'frame_' + str(i).rjust(10, '0') + '.png'), eimg) 168 | -------------------------------------------------------------------------------- /samples/npz_converter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | import numpy as np 5 | import os, sys 6 | import pydvs 7 | 8 | 9 | if __name__ == '__main__': 10 | parser = argparse.ArgumentParser() 11 | parser.add_argument('--event_file', 12 | type=str, 13 | required=True) 14 | parser.add_argument('--output_file', 15 | type=str, 16 | required=True) 17 | parser.add_argument('--discretization', 18 | type=float, 19 | required=False, 20 | default=0.01) 21 | parser.add_argument('--calib', 22 | type=str, 23 | required=False, 24 | default='') 25 | 26 | 27 | args = parser.parse_args() 28 | 29 | print ("Opening event file:", pydvs.okg(args.event_file)) 30 | 31 | cloud, idx = pydvs.read_event_file_txt(args.event_file, args.discretization) 32 | 33 | K = None 34 | D = None 35 | if ('txt' in args.calib): 36 | K, D = pydvs.read_calib_txt(args.calib) 37 | elif ('yaml' in args.calib): 38 | K, D = pydvs.read_calib_yaml(args.calib) 39 | elif (args.calib != ''): 40 | print (pydvs.bld(pydvs.err("Error: Unknown calibration file format!")), args.calib) 41 | 42 | print ("Saving...") 43 | np.savez_compressed(args.output_file, events=cloud, index=idx, 44 | discretization=args.discretization, K=K, D=D) 45 | 46 | print ("Done.") 47 | -------------------------------------------------------------------------------- /samples/npz_split.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import argparse 4 | import numpy as np 5 | import os, sys, signal, glob, time 6 | import pydvs 7 | 8 | 9 | if __name__ == '__main__': 10 | parser = argparse.ArgumentParser() 11 | parser.add_argument('--slice_in', 12 | type=str, 13 | required=True) 14 | parser.add_argument('--slice_out', 15 | type=str, 16 | required=True) 17 | parser.add_argument('--t1', 18 | type=float, 19 | required=True) 20 | parser.add_argument('--t2', 21 | type=float, 22 | required=True) 23 | 24 | args = parser.parse_args() 25 | 26 | print "Opening", args.slice_in 27 | 28 | sl_npz = np.load(args.slice_in) 29 | cloud = sl_npz['events'] 30 | idx = sl_npz['index'] 31 | discretization = sl_npz['discretization'] 32 | K = sl_npz['K'] 33 | D = sl_npz['D'] 34 | 35 | first_ts = cloud[0][0] 36 | last_ts = cloud[-1][0] 37 | 38 | print "The recording range:", first_ts, "-", last_ts 39 | print "The gt range:", gt_ts[0], "-", gt_ts[-1] 40 | print "gt frame count:", len(gt_ts) 41 | print "Discretization resolution:", discretization 42 | if (args.t1 < first_ts or args.t2 > last_ts): 43 | print "The time boundaries have to be within range" 44 | exit(0) 45 | 46 | width = args.t2 - args.t1 47 | sl, idx_, t0 = pydvs.get_slice(cloud, idx, args.t1, width, 0, discretization) 48 | t1 = t0 + sl[-1][0] - sl[0][0] # The t1 - t2 ragne can be shifted due to discretization 49 | 50 | idx_lo = 0 51 | for i, t in enumerate(gt_ts): 52 | if t > t0: 53 | idx_lo = i 54 | break 55 | idx_hi = 0 56 | for i, t in enumerate(gt_ts): 57 | if t > t1: 58 | idx_hi = i 59 | break 60 | 61 | print "Saving", depth_gt_.shape[0], "gt slices" 62 | 63 | np.savez_compressed(args.slice_out, events=sl, index=idx_, 64 | discretization=discretization, K=K, D=D) 65 | -------------------------------------------------------------------------------- /samples/poster_6dof.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/better-flow/pydvs/fa12a1434a02133321a1b03929a5383f4ec23009/samples/poster_6dof.npz -------------------------------------------------------------------------------- /samples/poster_translation.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/better-flow/pydvs/fa12a1434a02133321a1b03929a5383f4ec23009/samples/poster_translation.npz --------------------------------------------------------------------------------