├── LICENSE
├── README.md
├── base
├── __init__.py
└── base_model.py
├── data
└── .gitignore
├── image_reconstructor.py
├── model
├── __init__.py
├── model.py
├── submodules.py
└── unet.py
├── options
├── __init__.py
└── inference_options.py
├── pretrained
└── .gitignore
├── run_reconstruction.py
├── scripts
├── embed_reconstructed_images_in_rosbag.py
├── extract_events_from_rosbag.py
├── image_folder_to_rosbag.py
└── resample_reconstructions.py
└── utils
├── __init__.py
├── event_readers.py
├── inference_utils.py
├── loading_utils.py
├── path_utils.py
├── timers.py
└── util.py
/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 | # High Speed and High Dynamic Range Video with an Event Camera
2 |
3 | [](https://youtu.be/eomALySSGVU)
4 |
5 | This is the code for the paper **High Speed and High Dynamic Range Video with an Event Camera** by [Henri Rebecq](http://henri.rebecq.fr), Rene Ranftl, [Vladlen Koltun](http://vladlen.info/) and [Davide Scaramuzza](http://rpg.ifi.uzh.ch/people_scaramuzza.html):
6 |
7 | You can find a pdf of the paper [here](http://rpg.ifi.uzh.ch/docs/TPAMI19_Rebecq.pdf).
8 | If you use any of this code, please cite the following publications:
9 |
10 | ```bibtex
11 | @Article{Rebecq19pami,
12 | author = {Henri Rebecq and Ren{\'{e}} Ranftl and Vladlen Koltun and Davide Scaramuzza},
13 | title = {High Speed and High Dynamic Range Video with an Event Camera},
14 | journal = {{IEEE} Trans. Pattern Anal. Mach. Intell. (T-PAMI)},
15 | url = {http://rpg.ifi.uzh.ch/docs/TPAMI19_Rebecq.pdf},
16 | year = 2019
17 | }
18 | ```
19 |
20 |
21 | ```bibtex
22 | @Article{Rebecq19cvpr,
23 | author = {Henri Rebecq and Ren{\'{e}} Ranftl and Vladlen Koltun and Davide Scaramuzza},
24 | title = {Events-to-Video: Bringing Modern Computer Vision to Event Cameras},
25 | journal = {{IEEE} Conf. Comput. Vis. Pattern Recog. (CVPR)},
26 | year = 2019
27 | }
28 | ```
29 |
30 | ## Install
31 |
32 | Dependencies:
33 |
34 | - [PyTorch](https://pytorch.org/get-started/locally/) >= 1.0
35 | - [NumPy](https://www.numpy.org/)
36 | - [Pandas](https://pandas.pydata.org/)
37 | - [OpenCV](https://opencv.org/)
38 |
39 | ### Install with Anaconda
40 |
41 | The installation requires [Anaconda3](https://www.anaconda.com/distribution/).
42 | You can create a new Anaconda environment with the required dependencies as follows (make sure to adapt the CUDA toolkit version according to your setup):
43 |
44 | ```bash
45 | conda create -n E2VID
46 | conda activate E2VID
47 | conda install pytorch torchvision cudatoolkit=10.0 -c pytorch
48 | conda install pandas
49 | conda install -c conda-forge opencv
50 | ```
51 |
52 | ## Run
53 |
54 | - Download the pretrained model:
55 |
56 | ```bash
57 | wget "http://rpg.ifi.uzh.ch/data/E2VID/models/E2VID_lightweight.pth.tar" -O pretrained/E2VID_lightweight.pth.tar
58 | ```
59 |
60 | - Download an example file with event data:
61 |
62 | ```bash
63 | wget "http://rpg.ifi.uzh.ch/data/E2VID/datasets/ECD_IJRR17/dynamic_6dof.zip" -O data/dynamic_6dof.zip
64 | ```
65 |
66 | Before running the reconstruction, make sure the conda environment is sourced:
67 |
68 | ```bash
69 | conda activate E2VID
70 | ```
71 |
72 | - Run reconstruction:
73 |
74 | ```bash
75 | python run_reconstruction.py \
76 | -c pretrained/E2VID_lightweight.pth.tar \
77 | -i data/dynamic_6dof.zip \
78 | --auto_hdr \
79 | --display \
80 | --show_events
81 | ```
82 |
83 | ## Parameters
84 |
85 | Below is a description of the most important parameters:
86 |
87 | #### Main parameters
88 |
89 | - ``--window_size`` / ``-N`` (default: None) Number of events per window. This is the parameter that has the most influence of the image reconstruction quality. If set to None, this number will be automatically computed based on the sensor size, as N = width * height * num_events_per_pixel (see description of that parameter below). Ignored if `--fixed_duration` is set.
90 | - ``--fixed_duration`` (default: False) If True, will use windows of events with a fixed duration (i.e. a fixed output frame rate).
91 | - ``--window_duration`` / ``-T`` (default: 33 ms) Duration of each event window, in milliseconds. The value of this parameter has strong influence on the image reconstruction quality. Its value may need to be adapted to the dynamics of the scene. Ignored if `--fixed_duration` is not set.
92 | - ``--Imin`` (default: 0.0), `--Imax` (default: 1.0): linear tone mapping is performed by normalizing the output image as follows: `I = (I - Imin) / (Imax - Imin)`. If `--auto_hdr` is set to True, `--Imin` and `--Imax` will be automatically computed as the min (resp. max) intensity values.
93 | - ``--auto_hdr`` (default: False) Automatically compute `--Imin` and `--Imax`. Disabled when `--color` is set.
94 | - ``--color`` (default: False): if True, will perform color reconstruction as described in the paper. Only use this with a [color event camera](http://rpg.ifi.uzh.ch/CED.html) such as the Color DAVIS346.
95 |
96 | #### Output parameters
97 |
98 | - ``--output_folder``: path of the output folder. If not set, the image reconstructions will not be saved to disk.
99 | - ``--dataset_name``: name of the output folder directory (default: 'reconstruction').
100 |
101 | #### Display parameters
102 |
103 | - ``--display`` (default: False): display the video reconstruction in real-time in an OpenCV window.
104 | - ``--show_events`` (default: False): show the input events side-by-side with the reconstruction. If ``--output_folder`` is set, the previews will also be saved to disk in ``/path/to/output/folder/events``.
105 |
106 | #### Additional parameters
107 |
108 | - ``--num_events_per_pixel`` (default: 0.35): Parameter used to automatically estimate the window size based on the sensor size. The value of 0.35 was chosen to correspond to ~ 15,000 events on a 240x180 sensor such as the DAVIS240C.
109 | - ``--no-normalize`` (default: False): Disable event tensor normalization: this will improve speed a bit, but might degrade the image quality a bit.
110 | - ``--no-recurrent`` (default: False): Disable the recurrent connection (i.e. do not maintain a state). For experimenting only, the results will be flickering a lot.
111 | - ``--hot_pixels_file`` (default: None): Path to a file specifying the locations of hot pixels (such a file can be obtained with [this tool](https://github.com/cedric-scheerlinck/dvs_tools/tree/master/dvs_hot_pixel_filter) for example). These pixels will be ignored (i.e. zeroed out in the event tensors).
112 |
113 | ## Example datasets
114 |
115 | We provide a list of example (publicly available) event datasets to get started with E2VID.
116 |
117 | - [High Speed (gun shooting!) and HDR Dataset](http://rpg.ifi.uzh.ch/E2VID.html)
118 | - [Event Camera Dataset](http://rpg.ifi.uzh.ch/data/E2VID/datasets/ECD_IJRR17/)
119 | - [Bardow et al., CVPR'16](http://rpg.ifi.uzh.ch/data/E2VID/datasets/SOFIE_CVPR16/)
120 | - [Scherlinck et al., ACCV'18](http://rpg.ifi.uzh.ch/data/E2VID/datasets/HF_ACCV18/)
121 | - [Color event sequences from the CED dataset Scheerlinck et al., CVPR'18](http://rpg.ifi.uzh.ch/data/E2VID/datasets/CED_CVPRW19/)
122 |
123 | ## Working with ROS
124 |
125 | Because PyTorch recommends Python 3 and ROS is only compatible with Python2, it is not straightforward to have the PyTorch reconstruction code and ROS code running in the same environment.
126 | To make things easy, the reconstruction code we provide has no dependency on ROS, and simply read events from a text file or ZIP file.
127 | We provide convenience functions to convert ROS bags (a popular format for event datasets) into event text files.
128 | In addition, we also provide scripts to convert a folder containing image reconstructions back to a rosbag (or to append image reconstructions to an existing rosbag).
129 |
130 | **Note**: it is **not** necessary to have a sourced conda environment to run the following scripts. However, [ROS](https://www.ros.org/) needs to be installed and sourced.
131 |
132 | ### rosbag -> events.txt
133 |
134 | To extract the events from a rosbag to a zip file containing the event data:
135 |
136 | ```bash
137 | python scripts/extract_events_from_rosbag.py /path/to/rosbag.bag \
138 | --output_folder=/path/to/output/folder \
139 | --event_topic=/dvs/events
140 | ```
141 |
142 | ### image reconstruction folder -> rosbag
143 |
144 | ```bash
145 | python scripts/image_folder_to_rosbag.py \
146 | --datasets dynamic_6dof \
147 | --image_folder /path/to/image/folder \
148 | --output_folder /path/to/output_folder \
149 | --image_topic /dvs/image_reconstructed
150 | ```
151 |
152 | ### Append image_reconstruction_folder to an existing rosbag
153 |
154 | ```bash
155 | cd scripts
156 | python embed_reconstructed_images_in_rosbag.py \
157 | --rosbag_folder /path/to/rosbag/folder \
158 | --datasets dynamic_6dof \
159 | --image_folder /path/to/image/folder \
160 | --output_folder /path/to/output_folder \
161 | --image_topic /dvs/image_reconstructed
162 | ```
163 |
164 | ### Generating a video reconstruction (with a fixed framerate)
165 |
166 | It can be convenient to convert an image folder to a video with a fixed framerate (for example for use in a video editing tool).
167 | You can proceed as follows:
168 |
169 | ```bash
170 | export FRAMERATE=30
171 | python resample_reconstructions.py -i /path/to/input_folder -o /tmp/resampled -r $FRAMERATE
172 | ffmpeg -framerate $FRAMERATE -i /tmp/resampled/frame_%010d.png video_"$FRAMERATE"Hz.mp4
173 | ```
174 |
175 | ## Acknowledgements
176 |
177 | This code borrows from the following open source projects, whom we would like to thank:
178 |
179 | - [pytorch-template](https://github.com/victoresque/pytorch-template)
180 |
--------------------------------------------------------------------------------
/base/__init__.py:
--------------------------------------------------------------------------------
1 | from .base_model import *
2 |
--------------------------------------------------------------------------------
/base/base_model.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import torch.nn as nn
3 | import numpy as np
4 |
5 |
6 | class BaseModel(nn.Module):
7 | """
8 | Base class for all models
9 | """
10 | def __init__(self, config):
11 | super(BaseModel, self).__init__()
12 | self.config = config
13 | self.logger = logging.getLogger(self.__class__.__name__)
14 |
15 | def forward(self, *input):
16 | """
17 | Forward pass logic
18 |
19 | :return: Model output
20 | """
21 | raise NotImplementedError
22 |
23 | def summary(self):
24 | """
25 | Model summary
26 | """
27 | model_parameters = filter(lambda p: p.requires_grad, self.parameters())
28 | params = sum([np.prod(p.size()) for p in model_parameters])
29 | self.logger.info('Trainable parameters: {}'.format(params))
30 | self.logger.info(self)
31 |
--------------------------------------------------------------------------------
/data/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cedric-scheerlinck/rpg_e2vid/d0a7c005f460f2422f2a4bf605f70820ea7a1e5f/data/.gitignore
--------------------------------------------------------------------------------
/image_reconstructor.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import cv2
3 | import numpy as np
4 | from model.model import *
5 | from utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter
6 | from utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction
7 | from utils.util import robust_min, robust_max
8 | from utils.timers import CudaTimer, cuda_timers
9 | from os.path import join
10 | from collections import deque
11 | import torch.nn.functional as F
12 |
13 |
14 | class ImageReconstructor:
15 | def __init__(self, model, height, width, num_bins, options):
16 |
17 | self.model = model
18 | self.use_gpu = options.use_gpu
19 | self.device = torch.device('cuda:0') if self.use_gpu else torch.device('cpu')
20 | self.height = height
21 | self.width = width
22 | self.num_bins = num_bins
23 |
24 | self.initialize(self.height, self.width, options)
25 |
26 | def initialize(self, height, width, options):
27 | print('== Image reconstruction == ')
28 | print('Image size: {}x{}'.format(self.height, self.width))
29 |
30 | self.no_recurrent = options.no_recurrent
31 | if self.no_recurrent:
32 | print('!!Recurrent connection disabled!!')
33 |
34 | self.perform_color_reconstruction = options.color # whether to perform color reconstruction (only use this with the DAVIS346color)
35 | if self.perform_color_reconstruction:
36 | if options.auto_hdr:
37 | print('!!Warning: disabling auto HDR for color reconstruction!!')
38 | options.auto_hdr = False # disable auto_hdr for color reconstruction (otherwise, each channel will be normalized independently)
39 |
40 | self.crop = CropParameters(self.width, self.height, self.model.num_encoders)
41 |
42 | self.last_states_for_each_channel = {'grayscale': None}
43 |
44 | if self.perform_color_reconstruction:
45 | self.crop_halfres = CropParameters(int(width / 2), int(height / 2),
46 | self.model.num_encoders)
47 | for channel in ['R', 'G', 'B', 'W']:
48 | self.last_states_for_each_channel[channel] = None
49 |
50 | self.event_preprocessor = EventPreprocessor(options)
51 | self.intensity_rescaler = IntensityRescaler(options)
52 | self.image_filter = ImageFilter(options)
53 | self.unsharp_mask_filter = UnsharpMaskFilter(options, device=self.device)
54 | self.image_writer = ImageWriter(options)
55 | self.image_display = ImageDisplay(options)
56 |
57 | def update_reconstruction(self, event_tensor, event_tensor_id, stamp=None):
58 | with torch.no_grad():
59 |
60 | with CudaTimer('Reconstruction'):
61 |
62 | with CudaTimer('NumPy (CPU) -> Tensor (GPU)'):
63 | events = event_tensor.unsqueeze(dim=0)
64 | events = events.to(self.device)
65 |
66 | events = self.event_preprocessor(events)
67 |
68 | # Resize tensor to [1 x C x crop_size x crop_size] by applying zero padding
69 | events_for_each_channel = {'grayscale': self.crop.pad(events)}
70 | reconstructions_for_each_channel = {}
71 | if self.perform_color_reconstruction:
72 | events_for_each_channel['R'] = self.crop_halfres.pad(events[:, :, 0::2, 0::2])
73 | events_for_each_channel['G'] = self.crop_halfres.pad(events[:, :, 0::2, 1::2])
74 | events_for_each_channel['W'] = self.crop_halfres.pad(events[:, :, 1::2, 0::2])
75 | events_for_each_channel['B'] = self.crop_halfres.pad(events[:, :, 1::2, 1::2])
76 |
77 | # Reconstruct new intensity image for each channel (grayscale + RGBW if color reconstruction is enabled)
78 | for channel in events_for_each_channel.keys():
79 | with CudaTimer('Inference'):
80 | new_predicted_frame, states = self.model(events_for_each_channel[channel],
81 | self.last_states_for_each_channel[channel])
82 |
83 | if self.no_recurrent:
84 | self.last_states_for_each_channel[channel] = None
85 | else:
86 | self.last_states_for_each_channel[channel] = states
87 |
88 | # Output reconstructed image
89 | crop = self.crop if channel == 'grayscale' else self.crop_halfres
90 |
91 | # Unsharp mask (on GPU)
92 | new_predicted_frame = self.unsharp_mask_filter(new_predicted_frame)
93 |
94 | # Intensity rescaler (on GPU)
95 | new_predicted_frame = self.intensity_rescaler(new_predicted_frame)
96 |
97 | with CudaTimer('Tensor (GPU) -> NumPy (CPU)'):
98 | reconstructions_for_each_channel[channel] = new_predicted_frame[0, 0, crop.iy0:crop.iy1,
99 | crop.ix0:crop.ix1].cpu().numpy()
100 |
101 | if self.perform_color_reconstruction:
102 | out = merge_channels_into_color_image(reconstructions_for_each_channel)
103 | else:
104 | out = reconstructions_for_each_channel['grayscale']
105 |
106 | # Post-processing, e.g bilateral filter (on CPU)
107 | out = self.image_filter(out)
108 |
109 | self.image_writer(out, event_tensor_id, stamp, events=events)
110 | self.image_display(out, events)
111 |
--------------------------------------------------------------------------------
/model/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cedric-scheerlinck/rpg_e2vid/d0a7c005f460f2422f2a4bf605f70820ea7a1e5f/model/__init__.py
--------------------------------------------------------------------------------
/model/model.py:
--------------------------------------------------------------------------------
1 | from base import BaseModel
2 | import torch.nn as nn
3 | import torch
4 | from model.unet import UNet, UNetRecurrent
5 | from os.path import join
6 | from model.submodules import ConvLSTM, ResidualBlock, ConvLayer, UpsampleConvLayer, TransposedConvLayer
7 |
8 |
9 | class BaseE2VID(BaseModel):
10 | def __init__(self, config):
11 | super().__init__(config)
12 |
13 | assert('num_bins' in config)
14 | self.num_bins = int(config['num_bins']) # number of bins in the voxel grid event tensor
15 |
16 | try:
17 | self.skip_type = str(config['skip_type'])
18 | except KeyError:
19 | self.skip_type = 'sum'
20 |
21 | try:
22 | self.num_encoders = int(config['num_encoders'])
23 | except KeyError:
24 | self.num_encoders = 4
25 |
26 | try:
27 | self.base_num_channels = int(config['base_num_channels'])
28 | except KeyError:
29 | self.base_num_channels = 32
30 |
31 | try:
32 | self.num_residual_blocks = int(config['num_residual_blocks'])
33 | except KeyError:
34 | self.num_residual_blocks = 2
35 |
36 | try:
37 | self.norm = str(config['norm'])
38 | except KeyError:
39 | self.norm = None
40 |
41 | try:
42 | self.use_upsample_conv = bool(config['use_upsample_conv'])
43 | except KeyError:
44 | self.use_upsample_conv = True
45 |
46 |
47 | class E2VID(BaseE2VID):
48 | def __init__(self, config):
49 | super(E2VID, self).__init__(config)
50 |
51 | self.unet = UNet(num_input_channels=self.num_bins,
52 | num_output_channels=1,
53 | skip_type=self.skip_type,
54 | activation='sigmoid',
55 | num_encoders=self.num_encoders,
56 | base_num_channels=self.base_num_channels,
57 | num_residual_blocks=self.num_residual_blocks,
58 | norm=self.norm,
59 | use_upsample_conv=self.use_upsample_conv)
60 |
61 | def forward(self, event_tensor, prev_states=None):
62 | """
63 | :param event_tensor: N x num_bins x H x W
64 | :return: a predicted image of size N x 1 x H x W, taking values in [0,1].
65 | """
66 | return self.unet.forward(event_tensor), None
67 |
68 |
69 | class E2VIDRecurrent(BaseE2VID):
70 | """
71 | Recurrent, UNet-like architecture where each encoder is followed by a ConvLSTM or ConvGRU.
72 | """
73 |
74 | def __init__(self, config):
75 | super(E2VIDRecurrent, self).__init__(config)
76 |
77 | try:
78 | self.recurrent_block_type = str(config['recurrent_block_type'])
79 | except KeyError:
80 | self.recurrent_block_type = 'convlstm' # or 'convgru'
81 |
82 | self.unetrecurrent = UNetRecurrent(num_input_channels=self.num_bins,
83 | num_output_channels=1,
84 | skip_type=self.skip_type,
85 | recurrent_block_type=self.recurrent_block_type,
86 | activation='sigmoid',
87 | num_encoders=self.num_encoders,
88 | base_num_channels=self.base_num_channels,
89 | num_residual_blocks=self.num_residual_blocks,
90 | norm=self.norm,
91 | use_upsample_conv=self.use_upsample_conv)
92 |
93 | def forward(self, event_tensor, prev_states):
94 | """
95 | :param event_tensor: N x num_bins x H x W
96 | :param prev_states: previous ConvLSTM state for each encoder module
97 | :return: reconstructed image, taking values in [0,1].
98 | """
99 | img_pred, states = self.unetrecurrent.forward(event_tensor, prev_states)
100 | return img_pred, states
101 |
--------------------------------------------------------------------------------
/model/submodules.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as f
4 | from torch.nn import init
5 |
6 |
7 | class ConvLayer(nn.Module):
8 | def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='relu', norm=None):
9 | super(ConvLayer, self).__init__()
10 |
11 | bias = False if norm == 'BN' else True
12 | self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias)
13 | if activation is not None:
14 | self.activation = getattr(torch, activation, 'relu')
15 | else:
16 | self.activation = None
17 |
18 | self.norm = norm
19 | if norm == 'BN':
20 | self.norm_layer = nn.BatchNorm2d(out_channels)
21 | elif norm == 'IN':
22 | self.norm_layer = nn.InstanceNorm2d(out_channels, track_running_stats=True)
23 |
24 | def forward(self, x):
25 | out = self.conv2d(x)
26 |
27 | if self.norm in ['BN', 'IN']:
28 | out = self.norm_layer(out)
29 |
30 | if self.activation is not None:
31 | out = self.activation(out)
32 |
33 | return out
34 |
35 |
36 | class TransposedConvLayer(nn.Module):
37 | def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='relu', norm=None):
38 | super(TransposedConvLayer, self).__init__()
39 |
40 | bias = False if norm == 'BN' else True
41 | self.transposed_conv2d = nn.ConvTranspose2d(
42 | in_channels, out_channels, kernel_size, stride=2, padding=padding, output_padding=1, bias=bias)
43 |
44 | if activation is not None:
45 | self.activation = getattr(torch, activation, 'relu')
46 | else:
47 | self.activation = None
48 |
49 | self.norm = norm
50 | if norm == 'BN':
51 | self.norm_layer = nn.BatchNorm2d(out_channels)
52 | elif norm == 'IN':
53 | self.norm_layer = nn.InstanceNorm2d(out_channels, track_running_stats=True)
54 |
55 | def forward(self, x):
56 | out = self.transposed_conv2d(x)
57 |
58 | if self.norm in ['BN', 'IN']:
59 | out = self.norm_layer(out)
60 |
61 | if self.activation is not None:
62 | out = self.activation(out)
63 |
64 | return out
65 |
66 |
67 | class UpsampleConvLayer(nn.Module):
68 | def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='relu', norm=None):
69 | super(UpsampleConvLayer, self).__init__()
70 |
71 | bias = False if norm == 'BN' else True
72 | self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias)
73 |
74 | if activation is not None:
75 | self.activation = getattr(torch, activation, 'relu')
76 | else:
77 | self.activation = None
78 |
79 | self.norm = norm
80 | if norm == 'BN':
81 | self.norm_layer = nn.BatchNorm2d(out_channels)
82 | elif norm == 'IN':
83 | self.norm_layer = nn.InstanceNorm2d(out_channels, track_running_stats=True)
84 |
85 | def forward(self, x):
86 | x_upsampled = f.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)
87 | out = self.conv2d(x_upsampled)
88 |
89 | if self.norm in ['BN', 'IN']:
90 | out = self.norm_layer(out)
91 |
92 | if self.activation is not None:
93 | out = self.activation(out)
94 |
95 | return out
96 |
97 |
98 | class RecurrentConvLayer(nn.Module):
99 | def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0,
100 | recurrent_block_type='convlstm', activation='relu', norm=None):
101 | super(RecurrentConvLayer, self).__init__()
102 |
103 | assert(recurrent_block_type in ['convlstm', 'convgru'])
104 | self.recurrent_block_type = recurrent_block_type
105 | if self.recurrent_block_type == 'convlstm':
106 | RecurrentBlock = ConvLSTM
107 | else:
108 | RecurrentBlock = ConvGRU
109 | self.conv = ConvLayer(in_channels, out_channels, kernel_size, stride, padding, activation, norm)
110 | self.recurrent_block = RecurrentBlock(input_size=out_channels, hidden_size=out_channels, kernel_size=3)
111 |
112 | def forward(self, x, prev_state):
113 | x = self.conv(x)
114 | state = self.recurrent_block(x, prev_state)
115 | x = state[0] if self.recurrent_block_type == 'convlstm' else state
116 | return x, state
117 |
118 |
119 | class DownsampleRecurrentConvLayer(nn.Module):
120 | def __init__(self, in_channels, out_channels, kernel_size=3, recurrent_block_type='convlstm', padding=0, activation='relu'):
121 | super(DownsampleRecurrentConvLayer, self).__init__()
122 |
123 | self.activation = getattr(torch, activation, 'relu')
124 |
125 | assert(recurrent_block_type in ['convlstm', 'convgru'])
126 | self.recurrent_block_type = recurrent_block_type
127 | if self.recurrent_block_type == 'convlstm':
128 | RecurrentBlock = ConvLSTM
129 | else:
130 | RecurrentBlock = ConvGRU
131 | self.recurrent_block = RecurrentBlock(input_size=in_channels, hidden_size=out_channels, kernel_size=kernel_size)
132 |
133 | def forward(self, x, prev_state):
134 | state = self.recurrent_block(x, prev_state)
135 | x = state[0] if self.recurrent_block_type == 'convlstm' else state
136 | x = f.interpolate(x, scale_factor=0.5, mode='bilinear', align_corners=False)
137 | return self.activation(x), state
138 |
139 |
140 | # Residual block
141 | class ResidualBlock(nn.Module):
142 | def __init__(self, in_channels, out_channels, stride=1, downsample=None, norm=None):
143 | super(ResidualBlock, self).__init__()
144 | bias = False if norm == 'BN' else True
145 | self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=bias)
146 | self.norm = norm
147 | if norm == 'BN':
148 | self.bn1 = nn.BatchNorm2d(out_channels)
149 | self.bn2 = nn.BatchNorm2d(out_channels)
150 | elif norm == 'IN':
151 | self.bn1 = nn.InstanceNorm2d(out_channels)
152 | self.bn2 = nn.InstanceNorm2d(out_channels)
153 |
154 | self.relu = nn.ReLU(inplace=True)
155 | self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=bias)
156 | self.downsample = downsample
157 |
158 | def forward(self, x):
159 | residual = x
160 | out = self.conv1(x)
161 | if self.norm in ['BN', 'IN']:
162 | out = self.bn1(out)
163 | out = self.relu(out)
164 | out = self.conv2(out)
165 | if self.norm in ['BN', 'IN']:
166 | out = self.bn2(out)
167 |
168 | if self.downsample:
169 | residual = self.downsample(x)
170 |
171 | out += residual
172 | out = self.relu(out)
173 | return out
174 |
175 |
176 | class ConvLSTM(nn.Module):
177 | """Adapted from: https://github.com/Atcold/pytorch-CortexNet/blob/master/model/ConvLSTMCell.py """
178 |
179 | def __init__(self, input_size, hidden_size, kernel_size):
180 | super(ConvLSTM, self).__init__()
181 |
182 | self.input_size = input_size
183 | self.hidden_size = hidden_size
184 | pad = kernel_size // 2
185 |
186 | # cache a tensor filled with zeros to avoid reallocating memory at each inference step if --no-recurrent is enabled
187 | self.zero_tensors = {}
188 |
189 | self.Gates = nn.Conv2d(input_size + hidden_size, 4 * hidden_size, kernel_size, padding=pad)
190 |
191 | def forward(self, input_, prev_state=None):
192 |
193 | # get batch and spatial sizes
194 | batch_size = input_.data.size()[0]
195 | spatial_size = input_.data.size()[2:]
196 |
197 | # generate empty prev_state, if None is provided
198 | if prev_state is None:
199 |
200 | # create the zero tensor if it has not been created already
201 | state_size = tuple([batch_size, self.hidden_size] + list(spatial_size))
202 | if state_size not in self.zero_tensors:
203 | # allocate a tensor with size `spatial_size`, filled with zero (if it has not been allocated already)
204 | self.zero_tensors[state_size] = (
205 | torch.zeros(state_size).to(input_.device),
206 | torch.zeros(state_size).to(input_.device)
207 | )
208 |
209 | prev_state = self.zero_tensors[tuple(state_size)]
210 |
211 | prev_hidden, prev_cell = prev_state
212 |
213 | # data size is [batch, channel, height, width]
214 | stacked_inputs = torch.cat((input_, prev_hidden), 1)
215 | gates = self.Gates(stacked_inputs)
216 |
217 | # chunk across channel dimension
218 | in_gate, remember_gate, out_gate, cell_gate = gates.chunk(4, 1)
219 |
220 | # apply sigmoid non linearity
221 | in_gate = torch.sigmoid(in_gate)
222 | remember_gate = torch.sigmoid(remember_gate)
223 | out_gate = torch.sigmoid(out_gate)
224 |
225 | # apply tanh non linearity
226 | cell_gate = torch.tanh(cell_gate)
227 |
228 | # compute current cell and hidden state
229 | cell = (remember_gate * prev_cell) + (in_gate * cell_gate)
230 | hidden = out_gate * torch.tanh(cell)
231 |
232 | return hidden, cell
233 |
234 |
235 | class ConvGRU(nn.Module):
236 | """
237 | Generate a convolutional GRU cell
238 | Adapted from: https://github.com/jacobkimmel/pytorch_convgru/blob/master/convgru.py
239 | """
240 |
241 | def __init__(self, input_size, hidden_size, kernel_size):
242 | super().__init__()
243 | padding = kernel_size // 2
244 | self.input_size = input_size
245 | self.hidden_size = hidden_size
246 | self.reset_gate = nn.Conv2d(input_size + hidden_size, hidden_size, kernel_size, padding=padding)
247 | self.update_gate = nn.Conv2d(input_size + hidden_size, hidden_size, kernel_size, padding=padding)
248 | self.out_gate = nn.Conv2d(input_size + hidden_size, hidden_size, kernel_size, padding=padding)
249 |
250 | init.orthogonal_(self.reset_gate.weight)
251 | init.orthogonal_(self.update_gate.weight)
252 | init.orthogonal_(self.out_gate.weight)
253 | init.constant_(self.reset_gate.bias, 0.)
254 | init.constant_(self.update_gate.bias, 0.)
255 | init.constant_(self.out_gate.bias, 0.)
256 |
257 | def forward(self, input_, prev_state):
258 |
259 | # get batch and spatial sizes
260 | batch_size = input_.data.size()[0]
261 | spatial_size = input_.data.size()[2:]
262 |
263 | # generate empty prev_state, if None is provided
264 | if prev_state is None:
265 | state_size = [batch_size, self.hidden_size] + list(spatial_size)
266 | prev_state = torch.zeros(state_size).to(input_.device)
267 |
268 | # data size is [batch, channel, height, width]
269 | stacked_inputs = torch.cat([input_, prev_state], dim=1)
270 | update = torch.sigmoid(self.update_gate(stacked_inputs))
271 | reset = torch.sigmoid(self.reset_gate(stacked_inputs))
272 | out_inputs = torch.tanh(self.out_gate(torch.cat([input_, prev_state * reset], dim=1)))
273 | new_state = prev_state * (1 - update) + out_inputs * update
274 |
275 | return new_state
276 |
--------------------------------------------------------------------------------
/model/unet.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as f
4 | from torch.nn import init
5 | from .submodules import ConvLayer, UpsampleConvLayer, TransposedConvLayer, RecurrentConvLayer, ResidualBlock, ConvLSTM, ConvGRU
6 |
7 |
8 | def skip_concat(x1, x2):
9 | return torch.cat([x1, x2], dim=1)
10 |
11 |
12 | def skip_sum(x1, x2):
13 | return x1 + x2
14 |
15 |
16 | class BaseUNet(nn.Module):
17 | def __init__(self, num_input_channels, num_output_channels=1, skip_type='sum', activation='sigmoid',
18 | num_encoders=4, base_num_channels=32, num_residual_blocks=2, norm=None, use_upsample_conv=True):
19 | super(BaseUNet, self).__init__()
20 |
21 | self.num_input_channels = num_input_channels
22 | self.num_output_channels = num_output_channels
23 | self.skip_type = skip_type
24 | self.apply_skip_connection = skip_sum if self.skip_type == 'sum' else skip_concat
25 | self.activation = activation
26 | self.norm = norm
27 |
28 | if use_upsample_conv:
29 | print('Using UpsampleConvLayer (slow, but no checkerboard artefacts)')
30 | self.UpsampleLayer = UpsampleConvLayer
31 | else:
32 | print('Using TransposedConvLayer (fast, with checkerboard artefacts)')
33 | self.UpsampleLayer = TransposedConvLayer
34 |
35 | self.num_encoders = num_encoders
36 | self.base_num_channels = base_num_channels
37 | self.num_residual_blocks = num_residual_blocks
38 | self.max_num_channels = self.base_num_channels * pow(2, self.num_encoders)
39 |
40 | assert(self.num_input_channels > 0)
41 | assert(self.num_output_channels > 0)
42 |
43 | self.encoder_input_sizes = []
44 | for i in range(self.num_encoders):
45 | self.encoder_input_sizes.append(self.base_num_channels * pow(2, i))
46 |
47 | self.encoder_output_sizes = [self.base_num_channels * pow(2, i + 1) for i in range(self.num_encoders)]
48 |
49 | self.activation = getattr(torch, self.activation, 'sigmoid')
50 |
51 | def build_resblocks(self):
52 | self.resblocks = nn.ModuleList()
53 | for i in range(self.num_residual_blocks):
54 | self.resblocks.append(ResidualBlock(self.max_num_channels, self.max_num_channels, norm=self.norm))
55 |
56 | def build_decoders(self):
57 | decoder_input_sizes = list(reversed([self.base_num_channels * pow(2, i + 1) for i in range(self.num_encoders)]))
58 |
59 | self.decoders = nn.ModuleList()
60 | for input_size in decoder_input_sizes:
61 | self.decoders.append(self.UpsampleLayer(input_size if self.skip_type == 'sum' else 2 * input_size,
62 | input_size // 2,
63 | kernel_size=5, padding=2, norm=self.norm))
64 |
65 | def build_prediction_layer(self):
66 | self.pred = ConvLayer(self.base_num_channels if self.skip_type == 'sum' else 2 * self.base_num_channels,
67 | self.num_output_channels, 1, activation=None, norm=self.norm)
68 |
69 |
70 | class UNet(BaseUNet):
71 | def __init__(self, num_input_channels, num_output_channels=1, skip_type='sum', activation='sigmoid',
72 | num_encoders=4, base_num_channels=32, num_residual_blocks=2, norm=None, use_upsample_conv=True):
73 | super(UNet, self).__init__(num_input_channels, num_output_channels, skip_type, activation,
74 | num_encoders, base_num_channels, num_residual_blocks, norm, use_upsample_conv)
75 |
76 | self.head = ConvLayer(self.num_input_channels, self.base_num_channels,
77 | kernel_size=5, stride=1, padding=2) # N x C x H x W -> N x 32 x H x W
78 |
79 | self.encoders = nn.ModuleList()
80 | for input_size, output_size in zip(self.encoder_input_sizes, self.encoder_output_sizes):
81 | self.encoders.append(ConvLayer(input_size, output_size, kernel_size=5,
82 | stride=2, padding=2, norm=self.norm))
83 |
84 | self.build_resblocks()
85 | self.build_decoders()
86 | self.build_prediction_layer()
87 |
88 | def forward(self, x):
89 | """
90 | :param x: N x num_input_channels x H x W
91 | :return: N x num_output_channels x H x W
92 | """
93 |
94 | # head
95 | x = self.head(x)
96 | head = x
97 |
98 | # encoder
99 | blocks = []
100 | for i, encoder in enumerate(self.encoders):
101 | x = encoder(x)
102 | blocks.append(x)
103 |
104 | # residual blocks
105 | for resblock in self.resblocks:
106 | x = resblock(x)
107 |
108 | # decoder
109 | for i, decoder in enumerate(self.decoders):
110 | x = decoder(self.apply_skip_connection(x, blocks[self.num_encoders - i - 1]))
111 |
112 | img = self.activation(self.pred(self.apply_skip_connection(x, head)))
113 |
114 | return img
115 |
116 |
117 | class UNetRecurrent(BaseUNet):
118 | """
119 | Recurrent UNet architecture where every encoder is followed by a recurrent convolutional block,
120 | such as a ConvLSTM or a ConvGRU.
121 | Symmetric, skip connections on every encoding layer.
122 | """
123 |
124 | def __init__(self, num_input_channels, num_output_channels=1, skip_type='sum',
125 | recurrent_block_type='convlstm', activation='sigmoid', num_encoders=4, base_num_channels=32,
126 | num_residual_blocks=2, norm=None, use_upsample_conv=True):
127 | super(UNetRecurrent, self).__init__(num_input_channels, num_output_channels, skip_type, activation,
128 | num_encoders, base_num_channels, num_residual_blocks, norm,
129 | use_upsample_conv)
130 |
131 | self.head = ConvLayer(self.num_input_channels, self.base_num_channels,
132 | kernel_size=5, stride=1, padding=2) # N x C x H x W -> N x 32 x H x W
133 |
134 | self.encoders = nn.ModuleList()
135 | for input_size, output_size in zip(self.encoder_input_sizes, self.encoder_output_sizes):
136 | self.encoders.append(RecurrentConvLayer(input_size, output_size,
137 | kernel_size=5, stride=2, padding=2,
138 | recurrent_block_type=recurrent_block_type,
139 | norm=self.norm))
140 |
141 | self.build_resblocks()
142 | self.build_decoders()
143 | self.build_prediction_layer()
144 |
145 | def forward(self, x, prev_states):
146 | """
147 | :param x: N x num_input_channels x H x W
148 | :param prev_states: previous LSTM states for every encoder layer
149 | :return: N x num_output_channels x H x W
150 | """
151 |
152 | # head
153 | x = self.head(x)
154 | head = x
155 |
156 | if prev_states is None:
157 | prev_states = [None] * self.num_encoders
158 |
159 | # encoder
160 | blocks = []
161 | states = []
162 | for i, encoder in enumerate(self.encoders):
163 | x, state = encoder(x, prev_states[i])
164 | blocks.append(x)
165 | states.append(state)
166 |
167 | # residual blocks
168 | for resblock in self.resblocks:
169 | x = resblock(x)
170 |
171 | # decoder
172 | for i, decoder in enumerate(self.decoders):
173 | x = decoder(self.apply_skip_connection(x, blocks[self.num_encoders - i - 1]))
174 |
175 | # tail
176 | img = self.activation(self.pred(self.apply_skip_connection(x, head)))
177 |
178 | return img, states
179 |
--------------------------------------------------------------------------------
/options/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cedric-scheerlinck/rpg_e2vid/d0a7c005f460f2422f2a4bf605f70820ea7a1e5f/options/__init__.py
--------------------------------------------------------------------------------
/options/inference_options.py:
--------------------------------------------------------------------------------
1 | def set_inference_options(parser):
2 |
3 | parser.add_argument('-o', '--output_folder', default=None, type=str) # if None, will not write the images to disk
4 | parser.add_argument('--dataset_name', default='reconstruction', type=str)
5 |
6 | parser.add_argument('--use_gpu', dest='use_gpu', action='store_true')
7 | parser.set_defaults(use_gpu=True)
8 |
9 | """ Display """
10 | parser.add_argument('--display', dest='display', action='store_true')
11 | parser.set_defaults(display=False)
12 |
13 | parser.add_argument('--show_events', dest='show_events', action='store_true')
14 | parser.set_defaults(show_events=False)
15 |
16 | parser.add_argument('--event_display_mode', default='red-blue', type=str,
17 | help="Event display mode ('red-blue' or 'grayscale')")
18 |
19 | parser.add_argument('--num_bins_to_show', default=-1, type=int,
20 | help="Number of bins of the voxel grid to show when displaying events (-1 means show all the bins).")
21 |
22 | parser.add_argument('--display_border_crop', default=0, type=int,
23 | help="Remove the outer border of size display_border_crop before displaying image.")
24 |
25 | parser.add_argument('--display_wait_time', default=1, type=int,
26 | help="Time to wait after each call to cv2.imshow, in milliseconds (default: 1)")
27 |
28 | """ Post-processing / filtering """
29 |
30 | # (optional) path to a text file containing the locations of hot pixels to ignore
31 | parser.add_argument('--hot_pixels_file', default=None, type=str)
32 |
33 | # (optional) unsharp mask
34 | parser.add_argument('--unsharp_mask_amount', default=0.3, type=float)
35 | parser.add_argument('--unsharp_mask_sigma', default=1.0, type=float)
36 |
37 | # (optional) bilateral filter
38 | parser.add_argument('--bilateral_filter_sigma', default=0.0, type=float)
39 |
40 | # (optional) flip the event tensors vertically
41 | parser.add_argument('--flip', dest='flip', action='store_true')
42 | parser.set_defaults(flip=False)
43 |
44 | """ Tone mapping (i.e. rescaling of the image intensities)"""
45 | parser.add_argument('--Imin', default=0.0, type=float,
46 | help="Min intensity for intensity rescaling (linear tone mapping).")
47 | parser.add_argument('--Imax', default=1.0, type=float,
48 | help="Max intensity value for intensity rescaling (linear tone mapping).")
49 | parser.add_argument('--auto_hdr', dest='auto_hdr', action='store_true',
50 | help="If True, will compute Imin and Imax automatically.")
51 | parser.set_defaults(auto_hdr=False)
52 | parser.add_argument('--auto_hdr_median_filter_size', default=10, type=int,
53 | help="Size of the median filter window used to smooth temporally Imin and Imax")
54 |
55 | """ Perform color reconstruction? (only use this flag with the DAVIS346color) """
56 | parser.add_argument('--color', dest='color', action='store_true')
57 | parser.set_defaults(color=False)
58 |
59 | """ Advanced parameters """
60 | # disable normalization of input event tensors (saves a bit of time, but may produce slightly worse results)
61 | parser.add_argument('--no-normalize', dest='no_normalize', action='store_true')
62 | parser.set_defaults(no_normalize=False)
63 |
64 | # disable recurrent connection (will severely degrade the results; for testing purposes only)
65 | parser.add_argument('--no-recurrent', dest='no_recurrent', action='store_true')
66 | parser.set_defaults(no_recurrent=False)
67 |
--------------------------------------------------------------------------------
/pretrained/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cedric-scheerlinck/rpg_e2vid/d0a7c005f460f2422f2a4bf605f70820ea7a1e5f/pretrained/.gitignore
--------------------------------------------------------------------------------
/run_reconstruction.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from utils.loading_utils import load_model, get_device
3 | import numpy as np
4 | import argparse
5 | import pandas as pd
6 | from utils.event_readers import FixedSizeEventReader, FixedDurationEventReader
7 | from utils.inference_utils import events_to_voxel_grid, events_to_voxel_grid_pytorch
8 | from utils.timers import Timer
9 | import time
10 | from image_reconstructor import ImageReconstructor
11 | from options.inference_options import set_inference_options
12 |
13 |
14 | if __name__ == "__main__":
15 |
16 | parser = argparse.ArgumentParser(
17 | description='Evaluating a trained network')
18 | parser.add_argument('-c', '--path_to_model', required=True, type=str,
19 | help='path to model weights')
20 | parser.add_argument('-i', '--input_file', required=True, type=str)
21 | parser.add_argument('--fixed_duration', dest='fixed_duration', action='store_true')
22 | parser.set_defaults(fixed_duration=False)
23 | parser.add_argument('-N', '--window_size', default=None, type=int,
24 | help="Size of each event window, in number of events. Ignored if --fixed_duration=True")
25 | parser.add_argument('-T', '--window_duration', default=33.33, type=float,
26 | help="Duration of each event window, in milliseconds. Ignored if --fixed_duration=False")
27 | parser.add_argument('--num_events_per_pixel', default=0.35, type=float,
28 | help='in case N (window size) is not specified, it will be \
29 | automatically computed as N = width * height * num_events_per_pixel')
30 | parser.add_argument('--skipevents', default=0, type=int)
31 | parser.add_argument('--suboffset', default=0, type=int)
32 | parser.add_argument('--compute_voxel_grid_on_cpu', dest='compute_voxel_grid_on_cpu', action='store_true')
33 | parser.set_defaults(compute_voxel_grid_on_cpu=False)
34 |
35 | set_inference_options(parser)
36 |
37 | args = parser.parse_args()
38 |
39 | # Read sensor size from the first first line of the event file
40 | path_to_events = args.input_file
41 |
42 | header = pd.read_csv(path_to_events, delim_whitespace=True, header=None, names=['width', 'height'],
43 | dtype={'width': np.int, 'height': np.int},
44 | nrows=1)
45 | width, height = header.values[0]
46 | print('Sensor size: {} x {}'.format(width, height))
47 |
48 | # Load model
49 | model = load_model(args.path_to_model)
50 | device = get_device(args.use_gpu)
51 |
52 | model = model.to(device)
53 | model.eval()
54 |
55 | reconstructor = ImageReconstructor(model, height, width, model.num_bins, args)
56 |
57 | """ Read chunks of events using Pandas """
58 |
59 | # Loop through the events and reconstruct images
60 | N = args.window_size
61 | if not args.fixed_duration:
62 | if N is None:
63 | N = int(width * height * args.num_events_per_pixel)
64 | print('Will use {} events per tensor (automatically estimated with num_events_per_pixel={:0.2f}).'.format(
65 | N, args.num_events_per_pixel))
66 | else:
67 | print('Will use {} events per tensor (user-specified)'.format(N))
68 | mean_num_events_per_pixel = float(N) / float(width * height)
69 | if mean_num_events_per_pixel < 0.1:
70 | print('!!Warning!! the number of events used ({}) seems to be low compared to the sensor size. \
71 | The reconstruction results might be suboptimal.'.format(N))
72 | elif mean_num_events_per_pixel > 1.5:
73 | print('!!Warning!! the number of events used ({}) seems to be high compared to the sensor size. \
74 | The reconstruction results might be suboptimal.'.format(N))
75 |
76 | initial_offset = args.skipevents
77 | sub_offset = args.suboffset
78 | start_index = initial_offset + sub_offset
79 |
80 | if args.compute_voxel_grid_on_cpu:
81 | print('Will compute voxel grid on CPU.')
82 |
83 | if args.fixed_duration:
84 | event_window_iterator = FixedDurationEventReader(path_to_events,
85 | duration_ms=args.window_duration,
86 | start_index=start_index)
87 | else:
88 | event_window_iterator = FixedSizeEventReader(path_to_events, num_events=N, start_index=start_index)
89 |
90 | with Timer('Processing entire dataset'):
91 | for event_window in event_window_iterator:
92 |
93 | last_timestamp = event_window[-1, 0]
94 |
95 | with Timer('Building event tensor'):
96 | if args.compute_voxel_grid_on_cpu:
97 | event_tensor = events_to_voxel_grid(event_window,
98 | num_bins=model.num_bins,
99 | width=width,
100 | height=height)
101 | event_tensor = torch.from_numpy(event_tensor)
102 | else:
103 | event_tensor = events_to_voxel_grid_pytorch(event_window,
104 | num_bins=model.num_bins,
105 | width=width,
106 | height=height,
107 | device=device)
108 |
109 | num_events_in_window = event_window.shape[0]
110 | reconstructor.update_reconstruction(event_tensor, start_index + num_events_in_window, last_timestamp)
111 |
112 | start_index += num_events_in_window
113 |
--------------------------------------------------------------------------------
/scripts/embed_reconstructed_images_in_rosbag.py:
--------------------------------------------------------------------------------
1 | import rosbag
2 | import cv2
3 | import numpy as np
4 | from cv_bridge import CvBridge, CvBridgeError
5 | from os.path import join
6 | import rospy
7 | import argparse
8 | import shutil
9 | import os
10 | import glob
11 |
12 |
13 | if __name__ == "__main__":
14 |
15 | parser = argparse.ArgumentParser()
16 | parser.add_argument("--datasets", default='dynamic_6dof', type=lambda s: [str(item) for item in s.split(',')],
17 | help="Delimited list of datasets")
18 | parser.add_argument("--rosbag_folder", required=True,
19 | type=str, help="Path to the base folder containing the rosbags")
20 | parser.add_argument("--image_folder", required=True,
21 | type=str, help="Path to the base folder containing the image reconstructions")
22 | parser.add_argument("--output_folder", default='.',
23 | type=str, help="Path to the output folder")
24 | parser.add_argument("--image_topic", required=True, type=str,
25 | help="Name of the topic which will contain the reconstructed images")
26 | parser.add_argument('--overwrite', dest='overwrite', action='store_true',
27 | help="Whether to overwrite existing rosbags (default: false)")
28 | parser.set_defaults(feature=False)
29 |
30 | args = parser.parse_args()
31 |
32 | print('Datasets to process: {}'.format(args.datasets))
33 |
34 | for dataset in args.datasets:
35 | original_bag_filename = join(
36 | args.rosbag_folder, '{}.bag'.format(dataset))
37 | reconstructed_images_folder = join(
38 | args.image_folder, dataset)
39 |
40 | bridge = CvBridge()
41 | continue_processing = True
42 |
43 | if not os.path.exists(args.output_folder):
44 | os.makedirs(args.output_folder)
45 |
46 | input_bag_filename = join(
47 | args.output_folder, '{}.bag'.format(dataset))
48 |
49 | if os.path.exists(input_bag_filename):
50 | print('Detected existing rosbag: {}.'.format(input_bag_filename))
51 | if args.overwrite:
52 | print('Will overwrite the existing bag.')
53 | else:
54 | print('Will not overwrite. If you want to overwrite, use option --overwrite')
55 | continue_processing = False
56 |
57 | if continue_processing:
58 | # Copy the source bag to the output folder
59 | print('Copying bag: {} to {}'.format(
60 | original_bag_filename, input_bag_filename))
61 | shutil.copyfile(original_bag_filename, input_bag_filename)
62 |
63 | # Now append the reconstructed images to the copied rosbag
64 | stamps = np.loadtxt(
65 | join(reconstructed_images_folder, 'timestamps.txt'))
66 | if len(stamps.shape) == 2:
67 | stamps = stamps[:, 1]
68 |
69 | # list all images in the folder
70 | images = [f for f in glob.glob(join(reconstructed_images_folder, "*.png"))]
71 | images = sorted(images)
72 | print('Found {} images'.format(len(images)))
73 |
74 | with rosbag.Bag(input_bag_filename, 'a') as outbag:
75 |
76 | for i, image_path in enumerate(images):
77 |
78 | stamp = stamps[i]
79 | img = cv2.imread(join(reconstructed_images_folder, image_path), 0)
80 | try:
81 | img_msg = bridge.cv2_to_imgmsg(img, encoding='mono8')
82 | stamp_ros = rospy.Time(stamp)
83 | print(img.shape, stamp_ros)
84 | img_msg.header.stamp = stamp_ros
85 | img_msg.header.seq = i
86 | outbag.write(args.image_topic, img_msg,
87 | img_msg.header.stamp)
88 |
89 | except CvBridgeError, e:
90 | print e
91 |
--------------------------------------------------------------------------------
/scripts/extract_events_from_rosbag.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import argparse
4 | import rosbag
5 | import rospy
6 | import os
7 | import zipfile
8 | import shutil
9 | import sys
10 | from os.path import basename
11 |
12 |
13 | # Function borrowed from: https://stackoverflow.com/a/3041990
14 | def query_yes_no(question, default="yes"):
15 | """Ask a yes/no question via raw_input() and return their answer.
16 |
17 | "question" is a string that is presented to the user.
18 | "default" is the presumed answer if the user just hits .
19 | It must be "yes" (the default), "no" or None (meaning
20 | an answer is required of the user).
21 |
22 | The "answer" return value is True for "yes" or False for "no".
23 | """
24 | valid = {"yes": True, "y": True, "ye": True,
25 | "no": False, "n": False}
26 | if default is None:
27 | prompt = " [y/n] "
28 | elif default == "yes":
29 | prompt = " [Y/n] "
30 | elif default == "no":
31 | prompt = " [y/N] "
32 | else:
33 | raise ValueError("invalid default answer: '%s'" % default)
34 |
35 | while True:
36 | sys.stdout.write(question + prompt)
37 | choice = raw_input().lower()
38 | if default is not None and choice == '':
39 | return valid[default]
40 | elif choice in valid:
41 | return valid[choice]
42 | else:
43 | sys.stdout.write("Please respond with 'yes' or 'no' "
44 | "(or 'y' or 'n').\n")
45 |
46 |
47 | def timestamp_str(ts):
48 | t = ts.secs + ts.nsecs / float(1e9)
49 | return '{:.12f}'.format(t)
50 |
51 |
52 | if __name__ == "__main__":
53 |
54 | # arguments
55 | parser = argparse.ArgumentParser()
56 | parser.add_argument("bag", help="ROS bag file to extract")
57 | parser.add_argument("--output_folder", default="extracted_data", help="Folder where to extract the data")
58 | parser.add_argument("--event_topic", default="/dvs/events", help="Event topic")
59 | parser.add_argument('--no-zip', dest='no_zip', action='store_true')
60 | parser.set_defaults(no_zip=False)
61 | args = parser.parse_args()
62 |
63 | print('Data will be extracted in folder: {}'.format(args.output_folder))
64 |
65 | if not os.path.exists(args.output_folder):
66 | os.makedirs(args.output_folder)
67 |
68 | width, height = None, None
69 | event_sum = 0
70 | event_msg_sum = 0
71 | num_msgs_between_logs = 25
72 | output_name = os.path.basename(args.bag).split('.')[0] # /path/to/mybag.bag -> mybag
73 | path_to_events_file = os.path.join(args.output_folder, '{}.txt'.format(output_name))
74 |
75 | with open(path_to_events_file, 'w') as events_file:
76 |
77 | with rosbag.Bag(args.bag, 'r') as bag:
78 |
79 | # Look for the topics that are available and save the total number of messages for each topic (useful for the progress bar)
80 | total_num_event_msgs = 0
81 | topics = bag.get_type_and_topic_info().topics
82 | for topic_name, topic_info in topics.iteritems():
83 | if topic_name == args.event_topic:
84 | total_num_event_msgs = topic_info.message_count
85 | print('Found events topic: {} with {} messages'.format(topic_name, topic_info.message_count))
86 |
87 | # Extract events to text file
88 | for topic, msg, t in bag.read_messages():
89 | if topic == args.event_topic:
90 |
91 | if width is None:
92 | width = msg.width
93 | height = msg.height
94 | print('Found sensor size: {} x {}'.format(width, height))
95 | events_file.write("{} {}\n".format(width, height))
96 |
97 | if event_msg_sum % num_msgs_between_logs == 0 or event_msg_sum >= total_num_event_msgs - 1:
98 | print('Event messages: {} / {}'.format(event_msg_sum + 1, total_num_event_msgs))
99 | event_msg_sum += 1
100 |
101 | for e in msg.events:
102 | events_file.write(timestamp_str(e.ts) + " ")
103 | events_file.write(str(e.x) + " ")
104 | events_file.write(str(e.y) + " ")
105 | events_file.write(("1" if e.polarity else "0") + "\n")
106 | event_sum += 1
107 |
108 | # statistics
109 | print('All events extracted!')
110 | print('Events:', event_sum)
111 |
112 | # Zip text file
113 | if not args.no_zip:
114 | print('Compressing text file...')
115 | path_to_events_zipfile = os.path.join(args.output_folder, '{}.zip'.format(output_name))
116 | with zipfile.ZipFile(path_to_events_zipfile, 'w') as zip_file:
117 | zip_file.write(path_to_events_file, basename(path_to_events_file), compress_type=zipfile.ZIP_DEFLATED)
118 | print('Finished!')
119 |
120 | # Remove events.txt
121 | if query_yes_no('Remove text file {}?'.format(path_to_events_file)):
122 | if os.path.exists(path_to_events_file):
123 | os.remove(path_to_events_file)
124 | print('Removed {}.'.format(path_to_events_file))
125 |
126 | print('Done extracting events!')
127 |
--------------------------------------------------------------------------------
/scripts/image_folder_to_rosbag.py:
--------------------------------------------------------------------------------
1 | import rosbag
2 | import cv2
3 | import numpy as np
4 | from cv_bridge import CvBridge, CvBridgeError
5 | from os.path import join
6 | import rospy
7 | import argparse
8 | import shutil
9 | import os
10 | import glob
11 |
12 | if __name__ == "__main__":
13 |
14 | parser = argparse.ArgumentParser()
15 | parser.add_argument("--datasets", default='dynamic_6dof', type=lambda s: [str(item) for item in s.split(',')],
16 | help="Delimited list of datasets")
17 | parser.add_argument("--image_folder", required=True,
18 | type=str, help="Path to the base folder containing the image reconstructions")
19 | parser.add_argument("--output_folder", default='.',
20 | type=str, help="Path to the output folder")
21 | parser.add_argument("--image_topic", required=True, type=str,
22 | help="Name of the topic which will contain the reconstructed images")
23 | parser.add_argument('--overwrite', dest='overwrite', action='store_true',
24 | help="Whether to overwrite existing rosbags (default: false)")
25 | parser.set_defaults(feature=False)
26 |
27 | args = parser.parse_args()
28 |
29 | print('Datasets to process: {}'.format(args.datasets))
30 |
31 | for dataset in args.datasets:
32 | reconstructed_images_folder = join(
33 | args.image_folder, dataset)
34 |
35 | bridge = CvBridge()
36 | continue_processing = True
37 |
38 | if not os.path.exists(args.output_folder):
39 | os.makedirs(args.output_folder)
40 |
41 | output_bag_filename = join(
42 | args.output_folder, '{}.bag'.format(dataset))
43 |
44 | if continue_processing:
45 | # Write the images to a rosbag
46 | stamps = np.loadtxt(
47 | join(reconstructed_images_folder, 'timestamps.txt'))
48 | if len(stamps.shape) == 2:
49 | stamps = stamps[:, 1]
50 |
51 | # list all images in the folder
52 | images = [f for f in glob.glob(join(reconstructed_images_folder, "*.png"))]
53 | images = sorted(images)
54 | print('Found {} images'.format(len(images)))
55 |
56 | with rosbag.Bag(output_bag_filename, 'w') as outbag:
57 |
58 | for i, image_path in enumerate(images):
59 |
60 | stamp = stamps[i]
61 | img = cv2.imread(join(reconstructed_images_folder, image_path), 0)
62 |
63 | try:
64 | img_msg = bridge.cv2_to_imgmsg(img, encoding='mono8')
65 | stamp_ros = rospy.Time(stamp)
66 | print(img.shape, stamp_ros)
67 | img_msg.header.stamp = stamp_ros
68 | img_msg.header.seq = i
69 | outbag.write(args.image_topic, img_msg,
70 | img_msg.header.stamp)
71 |
72 | except CvBridgeError, e:
73 | print e
74 |
--------------------------------------------------------------------------------
/scripts/resample_reconstructions.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from matplotlib import pyplot as plt
3 | import argparse
4 | import glob
5 | from os.path import basename, join, exists
6 | from os import makedirs
7 | import math
8 | import shutil
9 |
10 |
11 | def find_nearest(array, value):
12 | idx = np.searchsorted(array, value, side="left")
13 | if idx > 0 and (idx == len(array) or math.fabs(value - array[idx - 1]) < math.fabs(value - array[idx])):
14 | return (idx - 1), array[idx - 1]
15 | else:
16 | return idx, array[idx]
17 |
18 |
19 | if __name__ == "__main__":
20 |
21 | parser = argparse.ArgumentParser(
22 | description='Pick images in a folder containing timestamped images so that the resulting video has a fixed frame rate (used defined)')
23 |
24 | parser.add_argument('-i', '--input_folder', required=True, type=str)
25 | parser.add_argument('-o', '--output_folder', required=True, type=str)
26 | parser.add_argument('-r', '--framerate', default=1000.0, type=float)
27 | args = parser.parse_args()
28 |
29 | output_folder = args.output_folder
30 | if not exists(output_folder):
31 | makedirs(output_folder)
32 |
33 | # list all images in the folder
34 | images = [f for f in glob.glob(join(args.input_folder, "*.png"), recursive=False)]
35 | images = sorted(images)
36 | print('Found {} images'.format(len(images)))
37 |
38 | # read timestamps (and check there is one timestamp per image...)
39 | stamps = np.loadtxt(join(args.input_folder, 'timestamps.txt'))
40 | stamps = np.sort(stamps)
41 | np.savetxt(join(args.input_folder, 'timestamps_sorted.txt'), stamps)
42 | assert(len(stamps) == len(images))
43 |
44 | # find the closest image to each element in [t0, t0 + dt, t0 + 2 * dt, t0 + 3 * dt, ...]
45 | # where t0 = stamps[0]
46 | dt = 1.0 / args.framerate
47 | t = stamps[0]
48 | img_index, _ = find_nearest(stamps, t)
49 |
50 | i = 0
51 | while t <= stamps[-1]:
52 | t += dt
53 | img_index, _ = find_nearest(stamps, t)
54 | path_to_img = images[img_index]
55 | shutil.copyfile(path_to_img, join(output_folder, 'frame_{:010d}.png'.format(i)))
56 | i += 1
57 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cedric-scheerlinck/rpg_e2vid/d0a7c005f460f2422f2a4bf605f70820ea7a1e5f/utils/__init__.py
--------------------------------------------------------------------------------
/utils/event_readers.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import zipfile
3 | from os.path import splitext
4 | import numpy as np
5 | from .timers import Timer
6 |
7 |
8 | class FixedSizeEventReader:
9 | """
10 | Reads events from a '.txt' or '.zip' file, and packages the events into
11 | non-overlapping event windows, each containing a fixed number of events.
12 | """
13 |
14 | def __init__(self, path_to_event_file, num_events=10000, start_index=0):
15 | print('Will use fixed size event windows with {} events'.format(num_events))
16 | print('Output frame rate: variable')
17 | self.iterator = pd.read_csv(path_to_event_file, delim_whitespace=True, header=None,
18 | names=['t', 'x', 'y', 'pol'],
19 | dtype={'t': np.float64, 'x': np.int16, 'y': np.int16, 'pol': np.int16},
20 | engine='c',
21 | skiprows=start_index + 1, chunksize=num_events, nrows=None, memory_map=True)
22 |
23 | def __iter__(self):
24 | return self
25 |
26 | def __next__(self):
27 | with Timer('Reading event window from file'):
28 | event_window = self.iterator.__next__().values
29 | return event_window
30 |
31 |
32 | class FixedDurationEventReader:
33 | """
34 | Reads events from a '.txt' or '.zip' file, and packages the events into
35 | non-overlapping event windows, each of a fixed duration.
36 |
37 | **Note**: This reader is much slower than the FixedSizeEventReader.
38 | The reason is that the latter can use Pandas' very efficient cunk-based reading scheme implemented in C.
39 | """
40 |
41 | def __init__(self, path_to_event_file, duration_ms=50.0, start_index=0):
42 | print('Will use fixed duration event windows of size {:.2f} ms'.format(duration_ms))
43 | print('Output frame rate: {:.1f} Hz'.format(1000.0 / duration_ms))
44 | file_extension = splitext(path_to_event_file)[1]
45 | assert(file_extension in ['.txt', '.zip'])
46 | self.is_zip_file = (file_extension == '.zip')
47 |
48 | if self.is_zip_file: # '.zip'
49 | self.zip_file = zipfile.ZipFile(path_to_event_file)
50 | files_in_archive = self.zip_file.namelist()
51 | assert(len(files_in_archive) == 1) # make sure there is only one text file in the archive
52 | self.event_file = self.zip_file.open(files_in_archive[0], 'r')
53 | else:
54 | self.event_file = open(path_to_event_file, 'r')
55 |
56 | # ignore header + the first start_index lines
57 | for i in range(1 + start_index):
58 | self.event_file.readline()
59 |
60 | self.last_stamp = None
61 | self.duration_s = duration_ms / 1000.0
62 |
63 | def __iter__(self):
64 | return self
65 |
66 | def __del__(self):
67 | if self.is_zip_file:
68 | self.zip_file.close()
69 |
70 | self.event_file.close()
71 |
72 | def __next__(self):
73 | with Timer('Reading event window from file'):
74 | event_list = []
75 | for line in self.event_file:
76 | if self.is_zip_file:
77 | line = line.decode("utf-8")
78 | t, x, y, pol = line.split(' ')
79 | t, x, y, pol = float(t), int(x), int(y), int(pol)
80 | event_list.append([t, x, y, pol])
81 | if self.last_stamp is None:
82 | self.last_stamp = t
83 | if t > self.last_stamp + self.duration_s:
84 | self.last_stamp = t
85 | event_window = np.array(event_list)
86 | return event_window
87 |
88 | raise StopIteration
89 |
--------------------------------------------------------------------------------
/utils/inference_utils.py:
--------------------------------------------------------------------------------
1 | from .util import robust_min, robust_max
2 | from .path_utils import ensure_dir
3 | from .timers import Timer, CudaTimer
4 | from .loading_utils import get_device
5 | from os.path import join
6 | from math import ceil, floor
7 | from torch.nn import ReflectionPad2d
8 | import numpy as np
9 | import torch
10 | import cv2
11 | from collections import deque
12 | import atexit
13 | import scipy.stats as st
14 | import torch.nn.functional as F
15 | from math import sqrt
16 |
17 |
18 | def make_event_preview(events, mode='red-blue', num_bins_to_show=-1):
19 | # events: [1 x C x H x W] event tensor
20 | # mode: 'red-blue' or 'grayscale'
21 | # num_bins_to_show: number of bins of the voxel grid to show. -1 means show all bins.
22 | assert(mode in ['red-blue', 'grayscale'])
23 | if num_bins_to_show < 0:
24 | sum_events = torch.sum(events[0, :, :, :], dim=0).detach().cpu().numpy()
25 | else:
26 | sum_events = torch.sum(events[0, -num_bins_to_show:, :, :], dim=0).detach().cpu().numpy()
27 |
28 | if mode == 'red-blue':
29 | # Red-blue mode
30 | # positive events: blue, negative events: red
31 | event_preview = np.zeros((sum_events.shape[0], sum_events.shape[1], 3), dtype=np.uint8)
32 | b = event_preview[:, :, 0]
33 | r = event_preview[:, :, 2]
34 | b[sum_events > 0] = 255
35 | r[sum_events < 0] = 255
36 | else:
37 | # Grayscale mode
38 | # normalize event image to [0, 255] for display
39 | m, M = -10.0, 10.0
40 | event_preview = np.clip((255.0 * (sum_events - m) / (M - m)).astype(np.uint8), 0, 255)
41 |
42 | return event_preview
43 |
44 |
45 | def gkern(kernlen=5, nsig=1.0):
46 | """Returns a 2D Gaussian kernel array."""
47 | """https://stackoverflow.com/a/29731818"""
48 | interval = (2 * nsig + 1.) / (kernlen)
49 | x = np.linspace(-nsig - interval / 2., nsig + interval / 2., kernlen + 1)
50 | kern1d = np.diff(st.norm.cdf(x))
51 | kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
52 | kernel = kernel_raw / kernel_raw.sum()
53 | return torch.from_numpy(kernel).float()
54 |
55 |
56 | class EventPreprocessor:
57 | """
58 | Utility class to preprocess event tensors.
59 | Can perform operations such as hot pixel removing, event tensor normalization,
60 | or flipping the event tensor.
61 | """
62 |
63 | def __init__(self, options):
64 |
65 | print('== Event preprocessing ==')
66 | self.no_normalize = options.no_normalize
67 | if self.no_normalize:
68 | print('!!Will not normalize event tensors!!')
69 | else:
70 | print('Will normalize event tensors.')
71 |
72 | self.hot_pixel_locations = []
73 | if options.hot_pixels_file:
74 | try:
75 | self.hot_pixel_locations = np.loadtxt(options.hot_pixels_file, delimiter=',').astype(np.int)
76 | print('Will remove {} hot pixels'.format(self.hot_pixel_locations.shape[0]))
77 | except IOError:
78 | print('WARNING: could not load hot pixels file: {}'.format(options.hot_pixels_file))
79 |
80 | self.flip = options.flip
81 | if self.flip:
82 | print('Will flip event tensors.')
83 |
84 | def __call__(self, events):
85 |
86 | # Remove (i.e. zero out) the hot pixels
87 | for x, y in self.hot_pixel_locations:
88 | events[:, :, y, x] = 0
89 |
90 | # Flip tensor vertically and horizontally
91 | if self.flip:
92 | events = torch.flip(events, dims=[2, 3])
93 |
94 | # Normalize the event tensor (voxel grid) so that
95 | # the mean and stddev of the nonzero values in the tensor are equal to (0.0, 1.0)
96 | if not self.no_normalize:
97 | with CudaTimer('Normalization'):
98 | nonzero_ev = (events != 0)
99 | num_nonzeros = nonzero_ev.sum()
100 | if num_nonzeros > 0:
101 | # compute mean and stddev of the **nonzero** elements of the event tensor
102 | # we do not use PyTorch's default mean() and std() functions since it's faster
103 | # to compute it by hand than applying those funcs to a masked array
104 | mean = events.sum() / num_nonzeros
105 | stddev = torch.sqrt((events ** 2).sum() / num_nonzeros - mean ** 2)
106 | mask = nonzero_ev.float()
107 | events = mask * (events - mean) / stddev
108 |
109 | return events
110 |
111 |
112 | class IntensityRescaler:
113 | """
114 | Utility class to rescale image intensities to the range [0, 1],
115 | using (robust) min/max normalization.
116 | Optionally, the min/max bounds can be smoothed over a sliding window to avoid jitter.
117 | """
118 |
119 | def __init__(self, options):
120 | self.auto_hdr = options.auto_hdr
121 | self.intensity_bounds = deque()
122 | self.auto_hdr_median_filter_size = options.auto_hdr_median_filter_size
123 | self.Imin = options.Imin
124 | self.Imax = options.Imax
125 |
126 | def __call__(self, img):
127 | """
128 | param img: [1 x 1 x H x W] Tensor taking values in [0, 1]
129 | """
130 | if self.auto_hdr:
131 | with CudaTimer('Compute Imin/Imax (auto HDR)'):
132 | Imin = torch.min(img).item()
133 | Imax = torch.max(img).item()
134 |
135 | # ensure that the range is at least 0.1
136 | Imin = np.clip(Imin, 0.0, 0.45)
137 | Imax = np.clip(Imax, 0.55, 1.0)
138 |
139 | # adjust image dynamic range (i.e. its contrast)
140 | if len(self.intensity_bounds) > self.auto_hdr_median_filter_size:
141 | self.intensity_bounds.popleft()
142 |
143 | self.intensity_bounds.append((Imin, Imax))
144 | self.Imin = np.median([rmin for rmin, rmax in self.intensity_bounds])
145 | self.Imax = np.median([rmax for rmin, rmax in self.intensity_bounds])
146 |
147 | with CudaTimer('Intensity rescaling'):
148 | img = 255.0 * (img - self.Imin) / (self.Imax - self.Imin)
149 | img.clamp_(0.0, 255.0)
150 | img = img.byte() # convert to 8-bit tensor
151 |
152 | return img
153 |
154 |
155 | class ImageWriter:
156 | """
157 | Utility class to write images to disk.
158 | Also writes the image timestamps into a text file.
159 | """
160 |
161 | def __init__(self, options):
162 |
163 | self.output_folder = options.output_folder
164 | self.dataset_name = options.dataset_name
165 | self.save_events = options.show_events
166 | self.event_display_mode = options.event_display_mode
167 | self.num_bins_to_show = options.num_bins_to_show
168 | print('== Image Writer ==')
169 | if self.output_folder:
170 | ensure_dir(self.output_folder)
171 | ensure_dir(join(self.output_folder, self.dataset_name))
172 | print('Will write images to: {}'.format(join(self.output_folder, self.dataset_name)))
173 | self.timestamps_file = open(join(self.output_folder, self.dataset_name, 'timestamps.txt'), 'a')
174 |
175 | if self.save_events:
176 | self.event_previews_folder = join(self.output_folder, self.dataset_name, 'events')
177 | ensure_dir(self.event_previews_folder)
178 | print('Will write event previews to: {}'.format(self.event_previews_folder))
179 |
180 | atexit.register(self.__cleanup__)
181 | else:
182 | print('Will not write images to disk.')
183 |
184 | def __call__(self, img, event_tensor_id, stamp=None, events=None):
185 | if not self.output_folder:
186 | return
187 |
188 | if self.save_events and events is not None:
189 | event_preview = make_event_preview(events, mode=self.event_display_mode,
190 | num_bins_to_show=self.num_bins_to_show)
191 | cv2.imwrite(join(self.event_previews_folder,
192 | 'events_{:010d}.png'.format(event_tensor_id)), event_preview)
193 |
194 | cv2.imwrite(join(self.output_folder, self.dataset_name,
195 | 'frame_{:010d}.png'.format(event_tensor_id)), img)
196 | if stamp is not None:
197 | self.timestamps_file.write('{:.18f}\n'.format(stamp))
198 |
199 | def __cleanup__(self):
200 | if self.output_folder:
201 | self.timestamps_file.close()
202 |
203 |
204 | class ImageDisplay:
205 | """
206 | Utility class to display image reconstructions
207 | """
208 |
209 | def __init__(self, options):
210 | self.display = options.display
211 | self.show_events = options.show_events
212 | self.color = options.color
213 | self.event_display_mode = options.event_display_mode
214 | self.num_bins_to_show = options.num_bins_to_show
215 |
216 | self.window_name = 'Reconstruction'
217 | if self.show_events:
218 | self.window_name = 'Events | ' + self.window_name
219 |
220 | if self.display:
221 | cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
222 |
223 | self.border = options.display_border_crop
224 | self.wait_time = options.display_wait_time
225 |
226 | def crop_outer_border(self, img, border):
227 | if self.border == 0:
228 | return img
229 | else:
230 | return img[border:-border, border:-border]
231 |
232 | def __call__(self, img, events=None):
233 |
234 | if not self.display:
235 | return
236 |
237 | img = self.crop_outer_border(img, self.border)
238 |
239 | if self.show_events:
240 | assert(events is not None)
241 | event_preview = make_event_preview(events, mode=self.event_display_mode,
242 | num_bins_to_show=self.num_bins_to_show)
243 | event_preview = self.crop_outer_border(event_preview, self.border)
244 |
245 | if self.show_events:
246 | img_is_color = (len(img.shape) == 3)
247 | preview_is_color = (len(event_preview.shape) == 3)
248 |
249 | if(preview_is_color and not img_is_color):
250 | img = np.dstack([img] * 3)
251 | elif(img_is_color and not preview_is_color):
252 | event_preview = np.dstack([event_preview] * 3)
253 |
254 | img = np.hstack([event_preview, img])
255 |
256 | cv2.imshow(self.window_name, img)
257 | cv2.waitKey(self.wait_time)
258 |
259 |
260 | class UnsharpMaskFilter:
261 | """
262 | Utility class to perform unsharp mask filtering on reconstructed images.
263 | """
264 |
265 | def __init__(self, options, device):
266 | self.unsharp_mask_amount = options.unsharp_mask_amount
267 | self.unsharp_mask_sigma = options.unsharp_mask_sigma
268 | self.gaussian_kernel_size = 5
269 | self.gaussian_kernel = gkern(self.gaussian_kernel_size,
270 | self.unsharp_mask_sigma).unsqueeze(0).unsqueeze(0).to(device)
271 |
272 | def __call__(self, img):
273 | if self.unsharp_mask_amount > 0:
274 | with CudaTimer('Unsharp mask'):
275 | blurred = F.conv2d(img, self.gaussian_kernel,
276 | padding=self.gaussian_kernel_size // 2)
277 | img = (1 + self.unsharp_mask_amount) * img - self.unsharp_mask_amount * blurred
278 | return img
279 |
280 |
281 | class ImageFilter:
282 | """
283 | Utility class to perform some basic filtering on reconstructed images.
284 | """
285 |
286 | def __init__(self, options):
287 | self.bilateral_filter_sigma = options.bilateral_filter_sigma
288 |
289 | def __call__(self, img):
290 |
291 | if self.bilateral_filter_sigma:
292 | with Timer('Bilateral filter (sigma={:.2f})'.format(self.bilateral_filter_sigma)):
293 | filtered_img = np.zeros_like(img)
294 | filtered_img = cv2.bilateralFilter(
295 | img, 5, 25.0 * self.bilateral_filter_sigma, 25.0 * self.bilateral_filter_sigma)
296 | img = filtered_img
297 |
298 | return img
299 |
300 |
301 | def optimal_crop_size(max_size, max_subsample_factor):
302 | """ Find the optimal crop size for a given max_size and subsample_factor.
303 | The optimal crop size is the smallest integer which is greater or equal than max_size,
304 | while being divisible by 2^max_subsample_factor.
305 | """
306 | crop_size = int(pow(2, max_subsample_factor) * ceil(max_size / pow(2, max_subsample_factor)))
307 | return crop_size
308 |
309 |
310 | class CropParameters:
311 | """ Helper class to compute and store useful parameters for pre-processing and post-processing
312 | of images in and out of E2VID.
313 | Pre-processing: finding the best image size for the network, and padding the input image with zeros
314 | Post-processing: Crop the output image back to the original image size
315 | """
316 |
317 | def __init__(self, width, height, num_encoders):
318 |
319 | self.height = height
320 | self.width = width
321 | self.num_encoders = num_encoders
322 | self.width_crop_size = optimal_crop_size(self.width, num_encoders)
323 | self.height_crop_size = optimal_crop_size(self.height, num_encoders)
324 |
325 | self.padding_top = ceil(0.5 * (self.height_crop_size - self.height))
326 | self.padding_bottom = floor(0.5 * (self.height_crop_size - self.height))
327 | self.padding_left = ceil(0.5 * (self.width_crop_size - self.width))
328 | self.padding_right = floor(0.5 * (self.width_crop_size - self.width))
329 | self.pad = ReflectionPad2d((self.padding_left, self.padding_right, self.padding_top, self.padding_bottom))
330 |
331 | self.cx = floor(self.width_crop_size / 2)
332 | self.cy = floor(self.height_crop_size / 2)
333 |
334 | self.ix0 = self.cx - floor(self.width / 2)
335 | self.ix1 = self.cx + ceil(self.width / 2)
336 | self.iy0 = self.cy - floor(self.height / 2)
337 | self.iy1 = self.cy + ceil(self.height / 2)
338 |
339 |
340 | def shift_image(X, dx, dy):
341 | X = np.roll(X, dy, axis=0)
342 | X = np.roll(X, dx, axis=1)
343 | if dy > 0:
344 | X[:dy, :] = np.expand_dims(X[dy, :], axis=0)
345 | elif dy < 0:
346 | X[dy:, :] = np.expand_dims(X[dy, :], axis=0)
347 | if dx > 0:
348 | X[:, :dx] = np.expand_dims(X[:, dx], axis=1)
349 | elif dx < 0:
350 | X[:, dx:] = np.expand_dims(X[:, dx], axis=1)
351 | return X
352 |
353 |
354 | def upsample_color_image(grayscale_highres, color_lowres_bgr, colorspace='LAB'):
355 | """
356 | Generate a high res color image from a high res grayscale image, and a low res color image,
357 | using the trick described in:
358 | http://www.planetary.org/blogs/emily-lakdawalla/2013/04231204-image-processing-colorizing-images.html
359 | """
360 | assert(len(grayscale_highres.shape) == 2)
361 | assert(len(color_lowres_bgr.shape) == 3 and color_lowres_bgr.shape[2] == 3)
362 |
363 | if colorspace == 'LAB':
364 | # convert color image to LAB space
365 | lab = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2LAB)
366 | # replace lightness channel with the highres image
367 | lab[:, :, 0] = grayscale_highres
368 | # convert back to BGR
369 | color_highres_bgr = cv2.cvtColor(src=lab, code=cv2.COLOR_LAB2BGR)
370 | elif colorspace == 'HSV':
371 | # convert color image to HSV space
372 | hsv = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2HSV)
373 | # replace value channel with the highres image
374 | hsv[:, :, 2] = grayscale_highres
375 | # convert back to BGR
376 | color_highres_bgr = cv2.cvtColor(src=hsv, code=cv2.COLOR_HSV2BGR)
377 | elif colorspace == 'HLS':
378 | # convert color image to HLS space
379 | hls = cv2.cvtColor(src=color_lowres_bgr, code=cv2.COLOR_BGR2HLS)
380 | # replace lightness channel with the highres image
381 | hls[:, :, 1] = grayscale_highres
382 | # convert back to BGR
383 | color_highres_bgr = cv2.cvtColor(src=hls, code=cv2.COLOR_HLS2BGR)
384 |
385 | return color_highres_bgr
386 |
387 |
388 | def merge_channels_into_color_image(channels):
389 | """
390 | Combine a full resolution grayscale reconstruction and four color channels at half resolution
391 | into a color image at full resolution.
392 |
393 | :param channels: dictionary containing the four color reconstructions (at quarter resolution),
394 | and the full resolution grayscale reconstruction.
395 | :return a color image at full resolution
396 | """
397 |
398 | with Timer('Merge color channels'):
399 |
400 | assert('R' in channels)
401 | assert('G' in channels)
402 | assert('W' in channels)
403 | assert('B' in channels)
404 | assert('grayscale' in channels)
405 |
406 | # upsample each channel independently
407 | for channel in ['R', 'G', 'W', 'B']:
408 | channels[channel] = cv2.resize(channels[channel], dsize=None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
409 |
410 | # Shift the channels so that they all have the same origin
411 | channels['B'] = shift_image(channels['B'], dx=1, dy=1)
412 | channels['G'] = shift_image(channels['G'], dx=1, dy=0)
413 | channels['W'] = shift_image(channels['W'], dx=0, dy=1)
414 |
415 | # reconstruct the color image at half the resolution using the reconstructed channels RGBW
416 | reconstruction_bgr = np.dstack([channels['B'],
417 | cv2.addWeighted(src1=channels['G'], alpha=0.5,
418 | src2=channels['W'], beta=0.5,
419 | gamma=0.0, dtype=cv2.CV_8U),
420 | channels['R']])
421 |
422 | reconstruction_grayscale = channels['grayscale']
423 |
424 | # combine the full res grayscale resolution with the low res to get a full res color image
425 | upsampled_img = upsample_color_image(reconstruction_grayscale, reconstruction_bgr)
426 | return upsampled_img
427 |
428 | return upsampled_img
429 |
430 |
431 | def events_to_voxel_grid(events, num_bins, width, height):
432 | """
433 | Build a voxel grid with bilinear interpolation in the time domain from a set of events.
434 |
435 | :param events: a [N x 4] NumPy array containing one event per row in the form: [timestamp, x, y, polarity]
436 | :param num_bins: number of bins in the temporal axis of the voxel grid
437 | :param width, height: dimensions of the voxel grid
438 | """
439 |
440 | assert(events.shape[1] == 4)
441 | assert(num_bins > 0)
442 | assert(width > 0)
443 | assert(height > 0)
444 |
445 | voxel_grid = np.zeros((num_bins, height, width), np.float32).ravel()
446 |
447 | # normalize the event timestamps so that they lie between 0 and num_bins
448 | last_stamp = events[-1, 0]
449 | first_stamp = events[0, 0]
450 | deltaT = last_stamp - first_stamp
451 |
452 | if deltaT == 0:
453 | deltaT = 1.0
454 |
455 | events[:, 0] = (num_bins - 1) * (events[:, 0] - first_stamp) / deltaT
456 | ts = events[:, 0]
457 | xs = events[:, 1].astype(np.int)
458 | ys = events[:, 2].astype(np.int)
459 | pols = events[:, 3]
460 | pols[pols == 0] = -1 # polarity should be +1 / -1
461 |
462 | tis = ts.astype(np.int)
463 | dts = ts - tis
464 | vals_left = pols * (1.0 - dts)
465 | vals_right = pols * dts
466 |
467 | valid_indices = tis < num_bins
468 | np.add.at(voxel_grid, xs[valid_indices] + ys[valid_indices] * width
469 | + tis[valid_indices] * width * height, vals_left[valid_indices])
470 |
471 | valid_indices = (tis + 1) < num_bins
472 | np.add.at(voxel_grid, xs[valid_indices] + ys[valid_indices] * width
473 | + (tis[valid_indices] + 1) * width * height, vals_right[valid_indices])
474 |
475 | voxel_grid = np.reshape(voxel_grid, (num_bins, height, width))
476 |
477 | return voxel_grid
478 |
479 |
480 | def events_to_voxel_grid_pytorch(events, num_bins, width, height, device):
481 | """
482 | Build a voxel grid with bilinear interpolation in the time domain from a set of events.
483 |
484 | :param events: a [N x 4] NumPy array containing one event per row in the form: [timestamp, x, y, polarity]
485 | :param num_bins: number of bins in the temporal axis of the voxel grid
486 | :param width, height: dimensions of the voxel grid
487 | :param device: device to use to perform computations
488 | :return voxel_grid: PyTorch event tensor (on the device specified)
489 | """
490 |
491 | DeviceTimer = CudaTimer if device.type == 'cuda' else Timer
492 |
493 | assert(events.shape[1] == 4)
494 | assert(num_bins > 0)
495 | assert(width > 0)
496 | assert(height > 0)
497 |
498 | with torch.no_grad():
499 |
500 | events_torch = torch.from_numpy(events)
501 | with DeviceTimer('Events -> Device (voxel grid)'):
502 | events_torch = events_torch.to(device)
503 |
504 | with DeviceTimer('Voxel grid voting'):
505 | voxel_grid = torch.zeros(num_bins, height, width, dtype=torch.float32, device=device).flatten()
506 |
507 | # normalize the event timestamps so that they lie between 0 and num_bins
508 | last_stamp = events_torch[-1, 0]
509 | first_stamp = events_torch[0, 0]
510 | deltaT = last_stamp - first_stamp
511 |
512 | if deltaT == 0:
513 | deltaT = 1.0
514 |
515 | events_torch[:, 0] = (num_bins - 1) * (events_torch[:, 0] - first_stamp) / deltaT
516 | ts = events_torch[:, 0]
517 | xs = events_torch[:, 1].long()
518 | ys = events_torch[:, 2].long()
519 | pols = events_torch[:, 3].float()
520 | pols[pols == 0] = -1 # polarity should be +1 / -1
521 |
522 | tis = torch.floor(ts)
523 | tis_long = tis.long()
524 | dts = ts - tis
525 | vals_left = pols * (1.0 - dts.float())
526 | vals_right = pols * dts.float()
527 |
528 | valid_indices = tis < num_bins
529 | valid_indices &= tis >= 0
530 | voxel_grid.index_add_(dim=0,
531 | index=xs[valid_indices] + ys[valid_indices]
532 | * width + tis_long[valid_indices] * width * height,
533 | source=vals_left[valid_indices])
534 |
535 | valid_indices = (tis + 1) < num_bins
536 | valid_indices &= tis >= 0
537 |
538 | voxel_grid.index_add_(dim=0,
539 | index=xs[valid_indices] + ys[valid_indices] * width
540 | + (tis_long[valid_indices] + 1) * width * height,
541 | source=vals_right[valid_indices])
542 |
543 | voxel_grid = voxel_grid.view(num_bins, height, width)
544 |
545 | return voxel_grid
546 |
--------------------------------------------------------------------------------
/utils/loading_utils.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from model.model import *
3 |
4 |
5 | def load_model(path_to_model):
6 | print('Loading model {}...'.format(path_to_model))
7 | raw_model = torch.load(path_to_model)
8 | arch = raw_model['arch']
9 |
10 | try:
11 | model_type = raw_model['model']
12 | except KeyError:
13 | model_type = raw_model['config']['model']
14 |
15 | # instantiate model
16 | model = eval(arch)(model_type)
17 |
18 | # load model weights
19 | model.load_state_dict(raw_model['state_dict'])
20 |
21 | return model
22 |
23 |
24 | def get_device(use_gpu):
25 | if use_gpu and torch.cuda.is_available():
26 | device = torch.device('cuda:0')
27 | else:
28 | device = torch.device('cpu')
29 | print('Device:', device)
30 |
31 | return device
32 |
--------------------------------------------------------------------------------
/utils/path_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | def ensure_dir(path):
5 | if not os.path.exists(path):
6 | os.makedirs(path)
7 |
--------------------------------------------------------------------------------
/utils/timers.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import time
3 | import numpy as np
4 | import atexit
5 |
6 | cuda_timers = {}
7 | timers = {}
8 |
9 |
10 | class CudaTimer:
11 | def __init__(self, timer_name=''):
12 | self.timer_name = timer_name
13 | if self.timer_name not in cuda_timers:
14 | cuda_timers[self.timer_name] = []
15 |
16 | self.start = torch.cuda.Event(enable_timing=True)
17 | self.end = torch.cuda.Event(enable_timing=True)
18 |
19 | def __enter__(self):
20 | self.start.record()
21 | return self
22 |
23 | def __exit__(self, *args):
24 | self.end.record()
25 | torch.cuda.synchronize()
26 | cuda_timers[self.timer_name].append(self.start.elapsed_time(self.end))
27 |
28 |
29 | class Timer:
30 | def __init__(self, timer_name=''):
31 | self.timer_name = timer_name
32 | if self.timer_name not in timers:
33 | timers[self.timer_name] = []
34 |
35 | def __enter__(self):
36 | self.start = time.time()
37 | return self
38 |
39 | def __exit__(self, *args):
40 | self.end = time.time()
41 | self.interval = self.end - self.start # measured in seconds
42 | self.interval *= 1000.0 # convert to milliseconds
43 | timers[self.timer_name].append(self.interval)
44 |
45 |
46 | def print_timing_info():
47 | print('== Timing statistics ==')
48 | for timer_name, timing_values in [*cuda_timers.items(), *timers.items()]:
49 | timing_value = np.mean(np.array(timing_values))
50 | if timing_value < 1000.0:
51 | print('{}: {:.2f} ms'.format(timer_name, timing_value))
52 | else:
53 | print('{}: {:.2f} s'.format(timer_name, timing_value / 1000.0))
54 |
55 |
56 | # this will print all the timer values upon termination of any program that imported this file
57 | atexit.register(print_timing_info)
58 |
--------------------------------------------------------------------------------
/utils/util.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from math import fabs
3 |
4 |
5 | def robust_min(img, p=5):
6 | return np.percentile(img.ravel(), p)
7 |
8 |
9 | def robust_max(img, p=95):
10 | return np.percentile(img.ravel(), p)
11 |
12 |
13 | def normalize(img, m=10, M=90):
14 | return np.clip((img - robust_min(img, m)) / (robust_max(img, M) - robust_min(img, m)), 0.0, 1.0)
15 |
16 |
17 | def first_element_greater_than(values, req_value):
18 | """Returns the pair (i, values[i]) such that i is the minimum value that satisfies values[i] >= req_value.
19 | Returns (-1, None) if there is no such i.
20 | Note: this function assumes that values is a sorted array!"""
21 | i = np.searchsorted(values, req_value)
22 | val = values[i] if i < len(values) else None
23 | return (i, val)
24 |
25 |
26 | def last_element_less_than(values, req_value):
27 | """Returns the pair (i, values[i]) such that i is the maximum value that satisfies values[i] <= req_value.
28 | Returns (-1, None) if there is no such i.
29 | Note: this function assumes that values is a sorted array!"""
30 | i = np.searchsorted(values, req_value, side='right') - 1
31 | val = values[i] if i >= 0 else None
32 | return (i, val)
33 |
34 |
35 | def closest_element_to(values, req_value):
36 | """Returns the tuple (i, values[i], diff) such that i is the closest value to req_value,
37 | and diff = |values(i) - req_value|
38 | Note: this function assumes that values is a sorted array!"""
39 | assert(len(values) > 0)
40 |
41 | i = np.searchsorted(values, req_value, side='left')
42 | if i > 0 and (i == len(values) or fabs(req_value - values[i - 1]) < fabs(req_value - values[i])):
43 | idx = i - 1
44 | val = values[i - 1]
45 | else:
46 | idx = i
47 | val = values[i]
48 |
49 | diff = fabs(val - req_value)
50 | return (idx, val, diff)
51 |
--------------------------------------------------------------------------------