├── LICENCE
├── README.md
├── dataset
├── README.md
├── depthEstimator.py
├── gsImgRectifier.py
├── gtFlowGenerator.py
├── poseHandler.py
├── pwcnet.py
├── stereoRectifier.py
└── tum_process.py
├── images
├── data_gen.png
├── dso.jpg
├── networks.png
├── res_img.png
└── rs_pose_net.png
└── network
├── DataLoader.py
├── README.md
├── RsDepthNet.py
├── RsPoseNet.py
├── helpers.py
├── test.py
├── train_rsdepthnet.py
└── train_rsposenet.py
/LICENCE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # IMU-Assisted Learning of Single-View Rolling Shutter Correction
2 | Follow the README in *dataset/* for dataset information and in *network/* for network training and testing.
3 |
4 | ## Samples
5 |
6 |
7 | ## DSO on resulting images
8 |
--------------------------------------------------------------------------------
/dataset/README.md:
--------------------------------------------------------------------------------
1 | # Dataset Process
2 | * Overview
3 |
4 |
5 |
6 | * Usage
7 | * Option a: Process data from raw TUM dataset.
8 | * Dependencies (version we use)
9 | * [numpy(1.17.4)](https://numpy.org/)
10 | * [cv2](https://pypi.org/project/opencv-python/), [csv](https://docs.python.org/3/library/csv.html), [yaml](https://pyyaml.org/wiki/PyYAMLDocumentation) for reading TUM dataset
11 | * [Tensorflow(2.3.0)](https://www.tensorflow.org/) for pwcnet
12 | * [scipy(1.4.1)](https://www.scipy.org/) for pose interpolation
13 | * [pandas(1.2.3)](https://pandas.pydata.org/) for image post-processing (interpolation)
14 | * [tqdm](https://pypi.org/project/tqdm/) for progress visualization
15 |
16 | * Download [TUM Rolling Shutter Dataset](https://vision.in.tum.de/data/datasets/rolling-shutter-dataset) with Euroc/DSO format, modify **data_path** in **tum_process.py** accordingly.
17 | * Download [PWC-Net weights](https://drive.google.com/file/d/1hB5nCbBJf6I06dL5VX4aiAdTYUzlLCsi/view?usp=sharing) (thank Igor Slinko for shaing the weights), modify **ckpt_path** in **pwcnet.py** accordingly.
18 | * Specify **save_path** in **tum_process.py** if needed; otherwise, save to *../data/* by default.
19 | * Process the dataset.
20 | ```
21 | python3 tum_process.py
22 | ```
23 | * Option b: Download the [processed data](https://drive.google.com/file/d/16GJnkvVX1t6cU7lUOvpoc8L-cKy-R55-/view?usp=sharing) directly.
24 |
25 | # Dataset Format
26 | * Network input:
27 | * **seq\*/cam1/images/**: input RS images.
28 | * **seq\*/cam1/imu_cam1_v1.npy**: input row-wise IMU data rotated to cam1 frame, with a shape of [image_count, image_height, 6], the last dimension represents [gryo_x, gryo_y, gryo_z, acc_x, acc_y, acc_z].
29 | * **seq\*/cam1/camera.npy**: global camera intrinsic parameters, [fx, fy, cx, cy].
30 | * **seq\*/cam1/v1_lut.npy**: global lens distortion look-up table, with a shape of [image_height, image_width], the value represents the original scan-line of that pixel.
31 |
32 | * Network training ground-truth:
33 | * **seq\*/cam1/depth/**: depth maps.
34 | * **seq\*/cam1/flows_rs2gs/**: RS correction flow mapping from RS image to GS image.
35 | * **seq\*/cam1/pose_cam1_v1.npy**: row-wise pose for cam1, with a shape of [image_count, image_height, 6], the last dimension represents [t_x, t_y, t_z, r_x, r_y, r_z], the rotation uses angle-axis representation.
36 |
37 | * Other data for testing:
38 | * **seq\*/cam1/images_gs/**: ground-truth GS images.
39 | * **seq\*/cam1/pose_w_cam1.txt**: ground-truth pose of cam1 in world frame, with a shape of [image_count, 8], the last dimension represents [image_index, t_x, t_y, t_z, q_x, q_y, q_z, q_w], the rotation uses quaternion representation; we use it to benchmark visual SLAM systems on resulting images.
40 |
41 | # Code Citations
42 | * The implementation of PWC-Net in this work (**pwcnet.py**) is written by [Phil Ferriere](https://github.com/philferriere/tfoptflow/blob/master/tfoptflow/model_pwcnet.py).
--------------------------------------------------------------------------------
/dataset/depthEstimator.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import absolute_import, division, print_function
18 | import numpy as np
19 | import os
20 | import cv2
21 | from tqdm import tqdm
22 | from numpy import linalg as LA
23 |
24 | from pwcnet import ModelPWCNet
25 |
26 | pwc_net = ModelPWCNet()
27 |
28 |
29 | def getFlowBD(img0, img1, windowName=''):
30 | FLOW_THRES = 2 # threshold to accept a flow by bi-directional matching
31 | h, w = img0.shape[:2]
32 |
33 | img_pairs = [(img0, img1), (img1, img0)]
34 | flow01, flow10 = pwc_net.predict_from_img_pairs(img_pairs, batch_size=2)
35 |
36 | flow01_filtered = np.full_like(flow01, np.nan)
37 | for v0 in range(h):
38 | for u0 in range(w):
39 | fu01, fv01 = flow01[v0, u0, :]
40 | u1, v1 = u0+fu01, v0+fv01
41 | u1i, v1i = int(u1+0.5), int(v1+0.5)
42 | if 0 <= v1i < h and 0 <= u1i < w:
43 | fu10, fv10 = flow10[v1i, u1i, :]
44 | du, dv = u1+fu10-u0, v1+fv10-v0
45 | if (du*du+dv*dv) < FLOW_THRES: # bi-directional filtering
46 | flow01_filtered[v0, u0, 0] = flow01[v0, u0, 0]
47 | flow01_filtered[v0, u0, 1] = flow01[v0, u0, 1]
48 | return flow01_filtered
49 |
50 |
51 | def getRay(cam, uv):
52 | ray_uv = np.ones(3, dtype=np.float32)
53 | ray_uv[0] = (uv[0]-cam[2]) / cam[0]
54 | ray_uv[1] = (uv[1]-cam[3]) / cam[1]
55 | return np.expand_dims(ray_uv / LA.norm(ray_uv), -1)
56 |
57 |
58 | def depthFromTriangulation(cam_ref, cam_cur, T_cur_ref, uv_ref, uv_cur):
59 | R_cur_ref = T_cur_ref[0:3, 0:3]
60 | t_cur_ref = T_cur_ref[0:3, 3]
61 | ray_uv_ref = getRay(cam_ref, uv_ref)
62 | ray_uv_cur = getRay(cam_cur, uv_cur)
63 |
64 | A = np.hstack((np.matmul(R_cur_ref, ray_uv_ref), ray_uv_cur))
65 | AtA = np.matmul(A.T, A)
66 | if LA.det(AtA) < 1e-5:
67 | return -1
68 | depth2 = - np.matmul(np.matmul(LA.inv(AtA), A.T), t_cur_ref)
69 | depth = np.fabs(depth2[0])
70 |
71 | return depth*ray_uv_ref[-1]
72 |
73 |
74 | def calculateCurDepth(cam0, img0, cam1, img1, T_cam0_v1, v1_lut):
75 | h, w = img0.shape[:2]
76 |
77 | depth1 = np.full([h, w], np.nan, dtype=float)
78 |
79 | flow10 = getFlowBD(img1, img0, 'Match')
80 | for v1 in range(h):
81 | for u1 in range(w):
82 | fu, fv = flow10[v1, u1, :]
83 | if not np.isnan(fu):
84 | uv0 = [u1+fu, v1+fv]
85 | depth1[v1, u1] = depthFromTriangulation(
86 | cam1, cam0, T_cam0_v1[v1_lut[v1, u1]], [u1, v1], uv0)
87 |
88 | return depth1
89 |
90 |
91 | def getDepth(save_path):
92 | img0_path = save_path+"cam0/images/"
93 | img1_path = save_path+"cam1/images/"
94 | depth1_path = save_path+"cam1/depth/"
95 | if not os.path.exists(depth1_path):
96 | os.makedirs(depth1_path)
97 |
98 | # Load cameras
99 | cam0 = np.load(save_path+"cam0/camera.npy")
100 | cam1 = np.load(save_path+"cam1/camera.npy")
101 |
102 | # Load poses
103 | T_cam0_v1 = np.load(save_path+"T_cam0_v1.npy")
104 | v1_lut = np.load(save_path+"cam1/v1_lut.npy")
105 | img_count = T_cam0_v1.shape[0]
106 |
107 | # Get depth
108 | for i in tqdm(range(img_count)):
109 | img0 = cv2.imread('{}{}.png'.format(img0_path, i))
110 | img1 = cv2.imread('{}{}.png'.format(img1_path, i))
111 | depth1 = calculateCurDepth(
112 | cam0, img0, cam1, img1, T_cam0_v1[i], v1_lut)
113 | fname = os.path.join(depth1_path, str(i))
114 | np.save(fname, depth1)
115 |
--------------------------------------------------------------------------------
/dataset/gsImgRectifier.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import print_function, division
18 | import os
19 | from tqdm import tqdm
20 | import numpy as np
21 | import pandas as pd
22 | import cv2
23 |
24 |
25 | def rectify_gs_imgs(save_path, resolution):
26 | gs_img_path = save_path+"cam1/images_gs/"
27 | if not os.path.exists(gs_img_path):
28 | os.makedirs(gs_img_path)
29 |
30 | cols, rows = resolution
31 | rs_img_path = save_path+"cam1/images/"
32 | flows_rs2gs_path = save_path+"cam1/flows_rs2gs/"
33 | count = len(os.listdir(flows_rs2gs_path))
34 | for i in tqdm(range(count)):
35 | fi = str(i)
36 | flow_rs2gs = np.load(flows_rs2gs_path + fi + '.npy')
37 | size_1d = rows*cols
38 | ind_v, ind_u = np.indices((rows, cols), dtype='float32')
39 |
40 | # map: rs to gs
41 | uv_rs = np.stack((ind_u, ind_v), axis=-1)
42 | uv_gs = np.array(uv_rs + flow_rs2gs + 0.5, dtype='int')
43 | u_gs = np.clip(uv_gs[:, :, 0], 0, cols-1)
44 | v_gs = np.clip(uv_gs[:, :, 1], 0, rows-1)
45 | uv_gs_1d = v_gs * cols + u_gs
46 | uv_gs_1d = np.reshape(uv_gs_1d, (size_1d))
47 |
48 | # reverse the map: gs to rs
49 | flow_gs2rs_1d_u = np.full((size_1d), np.nan, dtype='float32')
50 | flow_gs2rs_1d_v = np.full((size_1d), np.nan, dtype='float32')
51 | flow_gs2rs_1d_u[uv_gs_1d] = np.reshape(-flow_rs2gs[:, :, 0], (size_1d))
52 | flow_gs2rs_1d_v[uv_gs_1d] = np.reshape(-flow_rs2gs[:, :, 1], (size_1d))
53 | flow_gs2rs = np.stack([np.reshape(flow_gs2rs_1d_u, (rows, cols)),
54 | np.reshape(flow_gs2rs_1d_v, (rows, cols))], axis=-1)
55 |
56 | # 2d interpolation
57 | flow_gs2rs[:, :, 0] = pd.DataFrame(flow_gs2rs[:, :, 0]).interpolate()
58 | flow_gs2rs[:, :, 1] = pd.DataFrame(flow_gs2rs[:, :, 1]).interpolate()
59 |
60 | # reconstruct gs image
61 | map_u = ind_u + flow_gs2rs[:, :, 0]
62 | map_v = ind_v + flow_gs2rs[:, :, 1]
63 | img_rs = cv2.imread(rs_img_path + fi + '.png')
64 | img_gs = cv2.remap(img_rs, map_u, map_v, cv2.INTER_LINEAR)
65 | cv2.imwrite('{}{}.png'.format(gs_img_path, i), img_gs)
66 |
--------------------------------------------------------------------------------
/dataset/gtFlowGenerator.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import absolute_import, division, print_function
18 | import numpy as np
19 | import os
20 | from tqdm import tqdm
21 | from numpy import linalg as LA
22 |
23 |
24 | def projectPoint(ua, va, da, cam_a, T_b_a, cam_b):
25 | Xa = np.ones([3, 1], dtype=np.float32)
26 | Xa[0] = (ua-cam_a[2]) / cam_a[0]
27 | Xa[1] = (va-cam_a[3]) / cam_a[1]
28 | Xa = Xa*da
29 | Xb = np.matmul(T_b_a[0:3, 0:3], Xa)+np.expand_dims(T_b_a[0:3, 3], -1)
30 | ub = Xb[0, 0]/Xb[2, 0]*cam_b[0] + cam_b[2]
31 | vb = Xb[1, 0]/Xb[2, 0]*cam_b[1] + cam_b[3]
32 | return [ub, vb]
33 |
34 |
35 | def getRS2GSFlow(depth_rs, cam1, T_cam0_v1, v1_lut):
36 | h, w = depth_rs.shape[:2]
37 | flow_rs2gs = np.full([h, w, 2], np.nan, dtype=np.float32)
38 |
39 | T_gs_rs = np.empty_like(T_cam0_v1)
40 | for v1 in range(h):
41 | T_gs_rs[v1] = np.matmul(LA.inv(T_cam0_v1[0]), T_cam0_v1[v1])
42 |
43 | # Project from rs to gs
44 | for v1rs in range(h):
45 | for u1rs in range(w):
46 | if np.isnan(depth_rs[v1rs, u1rs]):
47 | continue
48 |
49 | [u1gs, v1gs] = projectPoint(
50 | u1rs, v1rs, depth_rs[v1rs, u1rs], cam1, T_gs_rs[v1_lut[v1rs, u1rs]], cam1)
51 | if not np.isnan(u1gs):
52 | flow_rs2gs[v1rs, u1rs, 0] = u1gs - u1rs
53 | flow_rs2gs[v1rs, u1rs, 1] = v1gs - v1rs
54 |
55 | return flow_rs2gs
56 |
57 |
58 | def getRS2GSFlows(save_path, ns_per_v):
59 | depth1_path = save_path+"cam1/depth/"
60 | cam1 = np.load(save_path+"cam1/camera.npy")
61 | flows_rs2gs_path = save_path+"cam1/flows_rs2gs/"
62 | if not os.path.exists(flows_rs2gs_path):
63 | os.makedirs(flows_rs2gs_path)
64 |
65 | # Load poses
66 | T_cam0_v1 = np.load(save_path+"T_cam0_v1.npy")
67 | v1_lut = np.load(save_path+"cam1/v1_lut.npy")
68 |
69 | img_count = T_cam0_v1.shape[0]
70 | for i in tqdm(range(img_count)):
71 | depth1 = np.load('{}{}.npy'.format(depth1_path, i))
72 | flow_rs2gs = getRS2GSFlow(depth1, cam1, T_cam0_v1[i], v1_lut)
73 | rs2gs_name = os.path.join(flows_rs2gs_path, str(i))
74 | np.save(rs2gs_name, flow_rs2gs)
75 |
--------------------------------------------------------------------------------
/dataset/poseHandler.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import absolute_import, division, print_function
18 | from scipy.spatial.transform import Rotation, RotationSpline
19 | from scipy.interpolate import interp1d, CubicSpline
20 | import numpy as np
21 | import os
22 | import csv
23 | from tqdm import tqdm
24 | from numpy import linalg as LA
25 |
26 |
27 | class Imu:
28 | def __init__(self, imu_file, R_cam1_imu):
29 | imu_reader = csv.reader(open(imu_file), delimiter=" ")
30 | next(imu_reader) # skip the header line
31 | imu_ns_w_a = np.array(list(imu_reader))
32 | imu_ns = np.array(imu_ns_w_a[:, 0], dtype=np.long)
33 | imu_w_a = np.array(imu_ns_w_a[:, 1:], dtype=np.float)
34 | self.first_ns = imu_ns[1]
35 | self.last_ns = imu_ns[-2]
36 |
37 | cam1_w_a = np.zeros((len(imu_ns), 6))
38 | for i in range(len(imu_ns)):
39 | cam1_w_a[i, :3] = np.matmul(R_cam1_imu, imu_w_a[i, :3])
40 | cam1_w_a[i, 3:] = np.matmul(R_cam1_imu, imu_w_a[i, 3:])
41 |
42 | self.imu_interp = interp1d(imu_ns, cam1_w_a, axis=0)
43 |
44 | def isValidNs(self, query_ns):
45 | return self.first_ns <= query_ns <= self.last_ns
46 |
47 | def getImuAt(self, query_ns):
48 | return self.imu_interp(query_ns)
49 |
50 |
51 | class Pose:
52 | def __init__(self, gt_file, T_imu_cam1):
53 | gt_reader = csv.reader(open(gt_file), delimiter=",")
54 | next(gt_reader) # skip the header line
55 | gt_ns_t_q = np.array(list(gt_reader))
56 | gt_ns = np.array(gt_ns_t_q[:, 0], dtype=np.long)
57 | gt_t_q = np.array(gt_ns_t_q[:, 1:], dtype=np.float)
58 | self.first_ns = gt_ns[1]
59 | self.last_ns = gt_ns[-2]
60 |
61 | # transfer to target coordinate
62 | ts, Rs = [], []
63 | for i in range(len(gt_ns)):
64 | T_w_gt = np.identity(4)
65 | T_w_gt[0:3, 3] = gt_t_q[i, :3]
66 | # convert to qx qy qz qw for from_quat
67 | gt_q = gt_t_q[i, np.ix_([4, 5, 6, 3])]
68 | T_w_gt[0:3, 0:3] = Rotation.from_quat(gt_q).as_matrix()
69 | T_w_cam1 = np.matmul(T_w_gt, T_imu_cam1)
70 | ts.append(T_w_cam1[0:3, 3])
71 | Rs.append(T_w_cam1[0:3, 0:3])
72 |
73 | # splines
74 | self.t_spline = CubicSpline(gt_ns, ts)
75 | self.R_spline = RotationSpline(gt_ns, Rotation.from_matrix(Rs))
76 |
77 | def isValidNs(self, query_ns):
78 | return self.first_ns <= query_ns <= self.last_ns
79 |
80 | def getPoseAt(self, query_ns):
81 | T = np.identity(4)
82 | T[0:3, 0:3] = self.R_spline(query_ns).as_matrix()
83 | T[0:3, 3] = self.t_spline(query_ns)
84 | return T
85 |
86 |
87 | def getPoses(data_path, save_path, img_h, ns_per_v):
88 | # image name/time_ns
89 | img_ns = []
90 | times = open(data_path+'cam0/times.txt').read().splitlines()
91 | for i in range(1, len(times)):
92 | cur_ns = times[i].split(' ')[0]
93 | img_ns.append(int(cur_ns))
94 |
95 | # pose ground truth
96 | cam1 = np.load(save_path+"cam1/camera.npy")
97 | T_cam0_cam1 = np.identity(4)
98 | T_cam0_cam1[0, 3] = -cam1[4]
99 | T_imu_cam0 = np.load(save_path+"cam0/T_imu_cam0.npy")
100 | T_imu_cam1 = np.matmul(T_imu_cam0, T_cam0_cam1)
101 | gt_pose_cam1 = Pose(data_path+'gt_imu.csv', T_imu_cam1)
102 | imu_cam1 = Imu(data_path+'imu.txt', np.transpose(T_imu_cam1[:3, :3]))
103 |
104 | valid_ns, T_cam0_v1, pose_w_cam1, pose_cam1_v1, imu_cam1_v1 = [], [], [], [], []
105 | for i in tqdm(range(len(img_ns))):
106 | if not (gt_pose_cam1.isValidNs(img_ns[i]+ns_per_v*(img_h-1))
107 | and gt_pose_cam1.isValidNs(img_ns[i])
108 | and imu_cam1.isValidNs(img_ns[i]+ns_per_v*(img_h-1))
109 | and imu_cam1.isValidNs(img_ns[i])):
110 | continue
111 | valid_ns.append(img_ns[i])
112 |
113 | T_w_cam1 = gt_pose_cam1.getPoseAt(img_ns[i])
114 | t = T_w_cam1[0:3, 3]
115 | q = Rotation.from_matrix(T_w_cam1[0:3, 0:3]).as_quat()
116 | pose_w_cam1.append(
117 | np.array([i, t[0], t[1], t[2], q[0], q[1], q[2], q[3]]))
118 |
119 | T_cam1_w = LA.inv(T_w_cam1)
120 | T_cam0_w = np.matmul(T_cam0_cam1, T_cam1_w)
121 | # get pose for each scan line
122 | T_cam0_v1_i = []
123 | pose_cam1_v1_i = np.zeros((img_h, 6))
124 | imu_cam1_v1_i = np.zeros((img_h, 6))
125 | for v in range(img_h):
126 | # row-wise imu
127 | imu_cam1_v1_i[v] = imu_cam1.getImuAt(img_ns[i]+ns_per_v*v)
128 | # row-wise pose
129 | T_w_v1 = gt_pose_cam1.getPoseAt(img_ns[i]+ns_per_v*v)
130 | T_cam0_v1_i.append(np.matmul(T_cam0_w, T_w_v1))
131 |
132 | T_cam1_v1_i = np.matmul(T_cam1_w, T_w_v1)
133 | t = T_cam1_v1_i[0:3, 3]
134 | r = Rotation.from_matrix(T_cam1_v1_i[0:3, 0:3]).as_rotvec()
135 | pose_cam1_v1_i[v] = [t[0], t[1], t[2], r[0], r[1], r[2]]
136 | T_cam0_v1.append(T_cam0_v1_i)
137 | pose_cam1_v1.append(pose_cam1_v1_i)
138 | imu_cam1_v1.append(imu_cam1_v1_i)
139 |
140 | ns_path = os.path.join(save_path, "valid_ns.npy")
141 | np.save(ns_path, np.array(valid_ns))
142 |
143 | pose0_path = os.path.join(save_path, "T_cam0_v1.npy")
144 | np.save(pose0_path, np.array(T_cam0_v1))
145 |
146 | pose1w_path = os.path.join(save_path, "cam1/pose_w_cam1.txt")
147 | np.savetxt(pose1w_path, np.array(pose_w_cam1), delimiter=',')
148 |
149 | posev1_path = os.path.join(save_path, "cam1/pose_cam1_v1.npy")
150 | np.save(posev1_path, np.array(pose_cam1_v1))
151 |
152 | imu_cam1_path = os.path.join(save_path, "cam1/imu_cam1_v1.npy")
153 | np.save(imu_cam1_path, np.array(imu_cam1_v1))
154 |
--------------------------------------------------------------------------------
/dataset/pwcnet.py:
--------------------------------------------------------------------------------
1 | ################################## Third-party Code ##################################
2 | """
3 | PWC-Net model class written by Phil Ferriere
4 | https://github.com/philferriere/tfoptflow/blob/master/tfoptflow/model_pwcnet.py
5 |
6 | Licensed under the MIT License
7 | (see https://github.com/philferriere/tfoptflow/blob/master/LICENSE for details)
8 | """
9 | ######################################################################################
10 |
11 | from __future__ import absolute_import, division, print_function
12 | import numpy as np
13 | import tensorflow.compat.v1 as tf
14 | import pathlib
15 | import os
16 |
17 | from tensorflow.python.framework import constant_op
18 | from tensorflow.python.framework import dtypes
19 | from tensorflow.python.framework import ops
20 | from tensorflow.python.ops import array_ops
21 | from tensorflow.python.ops import math_ops
22 |
23 | _DEFAULT_PWCNET_TEST_OPTIONS = {
24 | 'ckpt_path': '/mnt/data2/jiawei/unrolling/sintel_gray_weights/pwcnet.sintel_gray.ckpt-54000',
25 | 'controller': '/device:CPU:0',
26 | 'batch_size': 1,
27 | 'pyr_lvls': 6,
28 | 'flow_pred_lvl': 2,
29 | 'search_range': 4
30 | }
31 |
32 | # from ref_model import PWCNet
33 |
34 |
35 | def cost_volume(c1, warp, search_range, name):
36 | """Build cost volume for associating a pixel from Image1 with its corresponding pixels in Image2.
37 | Args:
38 | c1: Level of the feature pyramid of Image1
39 | warp: Warped level of the feature pyramid of image22
40 | search_range: Search range (maximum displacement)
41 | """
42 | padded_lvl = tf.pad(warp, [[0, 0], [search_range, search_range], [
43 | search_range, search_range], [0, 0]])
44 | _, h, w, _ = tf.unstack(tf.shape(c1))
45 | max_offset = search_range * 2 + 1
46 |
47 | cost_vol = []
48 | for y in range(0, max_offset):
49 | for x in range(0, max_offset):
50 | slice = tf.slice(padded_lvl, [0, y, x, 0], [-1, h, w, -1])
51 | cost = tf.reduce_mean(c1 * slice, axis=3, keepdims=True)
52 | cost_vol.append(cost)
53 | cost_vol = tf.concat(cost_vol, axis=3)
54 | cost_vol = tf.nn.leaky_relu(cost_vol, alpha=0.1, name=name)
55 |
56 | return cost_vol
57 |
58 |
59 | def _interpolate_bilinear(grid,
60 | query_points,
61 | name='interpolate_bilinear',
62 | indexing='ij'):
63 | if indexing != 'ij' and indexing != 'xy':
64 | raise ValueError('Indexing mode must be \'ij\' or \'xy\'')
65 |
66 | with ops.name_scope(name):
67 | grid = ops.convert_to_tensor(grid)
68 | query_points = ops.convert_to_tensor(query_points)
69 | shape = array_ops.unstack(array_ops.shape(grid))
70 | if len(shape) != 4:
71 | msg = 'Grid must be 4 dimensional. Received: '
72 | raise ValueError(msg + str(shape))
73 |
74 | batch_size, height, width, channels = shape
75 | query_type = query_points.dtype
76 | query_shape = array_ops.unstack(array_ops.shape(query_points))
77 | grid_type = grid.dtype
78 |
79 | if len(query_shape) != 3:
80 | msg = ('Query points must be 3 dimensional. Received: ')
81 | raise ValueError(msg + str(query_shape))
82 |
83 | _, num_queries, _ = query_shape
84 |
85 | alphas = []
86 | floors = []
87 | ceils = []
88 |
89 | index_order = [0, 1] if indexing == 'ij' else [1, 0]
90 | unstacked_query_points = array_ops.unstack(query_points, axis=2)
91 |
92 | for dim in index_order:
93 | with ops.name_scope('dim-' + str(dim)):
94 | queries = unstacked_query_points[dim]
95 |
96 | size_in_indexing_dimension = shape[dim + 1]
97 |
98 | # max_floor is size_in_indexing_dimension - 2 so that max_floor + 1
99 | # is still a valid index into the grid.
100 | max_floor = math_ops.cast(
101 | size_in_indexing_dimension - 2, query_type)
102 | min_floor = constant_op.constant(0.0, dtype=query_type)
103 | floor = math_ops.minimum(
104 | math_ops.maximum(min_floor, math_ops.floor(queries)), max_floor)
105 | int_floor = math_ops.cast(floor, dtypes.int32)
106 | floors.append(int_floor)
107 | ceil = int_floor + 1
108 | ceils.append(ceil)
109 |
110 | # alpha has the same type as the grid, as we will directly use alpha
111 | # when taking linear combinations of pixel values from the image.
112 | alpha = math_ops.cast(queries - floor, grid_type)
113 | min_alpha = constant_op.constant(0.0, dtype=grid_type)
114 | max_alpha = constant_op.constant(1.0, dtype=grid_type)
115 | alpha = math_ops.minimum(
116 | math_ops.maximum(min_alpha, alpha), max_alpha)
117 |
118 | # Expand alpha to [b, n, 1] so we can use broadcasting
119 | # (since the alpha values don't depend on the channel).
120 | alpha = array_ops.expand_dims(alpha, 2)
121 | alphas.append(alpha)
122 |
123 | flattened_grid = array_ops.reshape(grid,
124 | [batch_size * height * width, channels])
125 | batch_offsets = array_ops.reshape(
126 | math_ops.range(batch_size) * height * width, [batch_size, 1])
127 |
128 | # This wraps array_ops.gather. We reshape the image data such that the
129 | # batch, y, and x coordinates are pulled into the first dimension.
130 | # Then we gather. Finally, we reshape the output back. It's possible this
131 | # code would be made simpler by using array_ops.gather_nd.
132 | def gather(y_coords, x_coords, name):
133 | with ops.name_scope('gather-' + name):
134 | linear_coordinates = batch_offsets + y_coords * width + x_coords
135 | gathered_values = array_ops.gather(
136 | flattened_grid, linear_coordinates)
137 | return array_ops.reshape(gathered_values,
138 | [batch_size, num_queries, channels])
139 |
140 | # grab the pixel values in the 4 corners around each query point
141 | top_left = gather(floors[0], floors[1], 'top_left')
142 | top_right = gather(floors[0], ceils[1], 'top_right')
143 | bottom_left = gather(ceils[0], floors[1], 'bottom_left')
144 | bottom_right = gather(ceils[0], ceils[1], 'bottom_right')
145 |
146 | # now, do the actual interpolation
147 | with ops.name_scope('interpolate'):
148 | interp_top = alphas[1] * (top_right - top_left) + top_left
149 | interp_bottom = alphas[1] * \
150 | (bottom_right - bottom_left) + bottom_left
151 | interp = alphas[0] * (interp_bottom - interp_top) + interp_top
152 |
153 | return interp
154 |
155 |
156 | def dense_image_warp(image, flow, name='dense_image_warp'):
157 | with ops.name_scope(name):
158 | batch_size, height, width, channels = array_ops.unstack(
159 | array_ops.shape(image))
160 | # The flow is defined on the image grid. Turn the flow into a list of query
161 | # points in the grid space.
162 | grid_x, grid_y = array_ops.meshgrid(
163 | math_ops.range(width), math_ops.range(height))
164 | stacked_grid = math_ops.cast(
165 | array_ops.stack([grid_y, grid_x], axis=2), flow.dtype)
166 | batched_grid = array_ops.expand_dims(stacked_grid, axis=0)
167 | query_points_on_grid = batched_grid - flow
168 | query_points_flattened = array_ops.reshape(query_points_on_grid,
169 | [batch_size, height * width, 2])
170 | # Compute values at the query points, then reshape the result back to the
171 | # image grid.
172 | interpolated = _interpolate_bilinear(image, query_points_flattened)
173 | interpolated = array_ops.reshape(interpolated,
174 | [batch_size, height, width, channels])
175 | return interpolated
176 |
177 |
178 | class ModelPWCNet:
179 | def __init__(self, name='pwcnet', session=None, options=_DEFAULT_PWCNET_TEST_OPTIONS):
180 | self.opts = options
181 | self.y_hat_train_tnsr = self.y_hat_val_tnsr = self.y_hat_test_tnsr = None
182 | self.name = name
183 |
184 | tf.reset_default_graph()
185 | self.graph = tf.Graph()
186 | with self.graph.as_default():
187 | # Configure a TF session, if one doesn't already exist
188 | if session is None:
189 | config = tf.ConfigProto()
190 | config.gpu_options.allow_growth = True
191 | config.allow_soft_placement = True
192 | self.sess = tf.Session(config=config)
193 | else:
194 | self.sess = session
195 |
196 | # Build the TF graph
197 | batch_size = self.opts['batch_size']
198 | self.x_tnsr = tf.placeholder(
199 | tf.float32, [batch_size] + [2, None, None, 3], 'x_tnsr')
200 | self.y_tnsr = tf.placeholder(
201 | tf.float32, [batch_size] + [None, None, 2], 'y_tnsr')
202 |
203 | # Build the backbone neural nets and collect the output tensors
204 | with tf.device(self.opts['controller']):
205 | self.flow_pred_tnsr, self.flow_pyr_tnsr = self.nn(self.x_tnsr)
206 |
207 | # Set output tensors
208 | self.y_hat_test_tnsr = [self.flow_pred_tnsr, self.flow_pyr_tnsr]
209 |
210 | # Init saver (override if you wish) and load checkpoint if it exists
211 | self.saver = tf.train.Saver()
212 |
213 | # Initialize the graph with the content of the checkpoint
214 | self.last_ckpt = os.path.join(os.getcwd(), self.opts['ckpt_path'])
215 | assert(self.last_ckpt is not None)
216 | self.saver.restore(self.sess, self.last_ckpt)
217 |
218 | ###
219 | # Sample mgmt
220 | ###
221 | def adapt_x(self, x):
222 | # Ensure we're dealing with RGB image pairs
223 | assert (isinstance(x, np.ndarray) or isinstance(x, list))
224 | if isinstance(x, np.ndarray):
225 | assert (len(x.shape) == 5)
226 | assert (x.shape[1] == 2 and x.shape[4] == 3)
227 | else:
228 | assert (len(x[0].shape) == 4)
229 | assert (x[0].shape[0] == 2 or x[0].shape[3] == 3)
230 |
231 | # Bring image range from 0..255 to 0..1 and use floats (also, list[(2,H,W,3)] -> (batch_size,2,H,W,3))
232 | x_adapt = np.array(x, dtype=np.float32) if isinstance(
233 | x, list) else x.astype(np.float32)
234 | x_adapt /= 255.
235 |
236 | # Make sure the image dimensions are multiples of 2**pyramid_levels, pad them if they're not
237 | _, pad_h = divmod(x_adapt.shape[2], 2**self.opts['pyr_lvls'])
238 | if pad_h != 0:
239 | pad_h = 2 ** self.opts['pyr_lvls'] - pad_h
240 | _, pad_w = divmod(x_adapt.shape[3], 2**self.opts['pyr_lvls'])
241 | if pad_w != 0:
242 | pad_w = 2 ** self.opts['pyr_lvls'] - pad_w
243 | x_adapt_info = None
244 | if pad_h != 0 or pad_w != 0:
245 | padding = [(0, 0), (0, 0), (0, pad_h), (0, pad_w), (0, 0)]
246 | x_adapt_info = x_adapt.shape # Save original shape
247 | x_adapt = np.pad(x_adapt, padding,
248 | mode='constant', constant_values=0.)
249 |
250 | return x_adapt, x_adapt_info
251 |
252 | def postproc_y_hat_test(self, y_hat, adapt_info=None):
253 | assert (isinstance(y_hat, list) and len(y_hat) == 2)
254 |
255 | # Have the samples been padded to fit the network's requirements? If so, crop flows back to original size.
256 | pred_flows = y_hat[0]
257 | if adapt_info is not None:
258 | pred_flows = pred_flows[:, 0:adapt_info[1], 0:adapt_info[2], :]
259 |
260 | # Individuate flows of the flow pyramid (at this point, they are still batched)
261 | pyramids = y_hat[1]
262 | pred_flows_pyramid = []
263 | for idx in range(len(pred_flows)):
264 | pyramid = []
265 | for lvl in range(self.opts['pyr_lvls'] - self.opts['flow_pred_lvl'] + 1):
266 | pyramid.append(pyramids[lvl][idx])
267 | pred_flows_pyramid.append(pyramid)
268 |
269 | return pred_flows, pred_flows_pyramid
270 |
271 | def predict_from_img_pairs(self, img_pairs, batch_size=1):
272 | with self.graph.as_default():
273 | # Chunk image pair list
274 | batch_size = self.opts['batch_size']
275 | test_size = len(img_pairs)
276 | rounds, rounds_left = divmod(test_size, batch_size)
277 | if rounds_left:
278 | rounds += 1
279 |
280 | # Loop through input samples and run inference on them
281 | preds, test_ptr = [], 0
282 | for _round in range(rounds):
283 | # In batch mode, make sure to wrap around if there aren't enough input samples to process
284 | if test_ptr + batch_size < test_size:
285 | new_ptr = test_ptr + batch_size
286 | indices = list(range(test_ptr, test_ptr + batch_size))
287 | else:
288 | new_ptr = (test_ptr + batch_size) % test_size
289 | indices = list(range(test_ptr, test_size)) + \
290 | list(range(0, new_ptr))
291 | test_ptr = new_ptr
292 |
293 | # Repackage input image pairs as np.ndarray
294 | x = np.array([img_pairs[idx] for idx in indices])
295 |
296 | # Make input samples conform to the network's requirements
297 | # x: [batch_size,2,H,W,3] uint8; x_adapt: [batch_size,2,H,W,3] float32
298 | x_adapt, x_adapt_info = self.adapt_x(x)
299 | if x_adapt_info is not None:
300 | y_adapt_info = (
301 | x_adapt_info[0], x_adapt_info[2], x_adapt_info[3], 2)
302 | else:
303 | y_adapt_info = None
304 |
305 | # Run the adapted samples through the network
306 | feed_dict = {self.x_tnsr: x_adapt}
307 | y_hat = self.sess.run(
308 | self.y_hat_test_tnsr, feed_dict=feed_dict)
309 | y_hats, _ = self.postproc_y_hat_test(y_hat, y_adapt_info)
310 |
311 | # Return flat list of predicted labels
312 | for y_hat in y_hats:
313 | preds.append(y_hat)
314 |
315 | return preds[0:test_size]
316 |
317 | ###
318 | # PWC-Net pyramid helpers
319 | ###
320 | def extract_features(self, x_tnsr, name='featpyr'):
321 | assert(1 <= self.opts['pyr_lvls'] <= 6)
322 | # Make the feature pyramids 1-based for better readability down the line
323 | num_chann = [None, 16, 32, 64, 96, 128, 196]
324 | c1, c2 = [None], [None]
325 | init = tf.keras.initializers.he_normal()
326 | with tf.variable_scope(name):
327 | for pyr, x, reuse, name in zip([c1, c2], [x_tnsr[:, 0], x_tnsr[:, 1]], [None, True], ['c1', 'c2']):
328 | for lvl in range(1, self.opts['pyr_lvls'] + 1):
329 | # tf.layers.conv2d(inputs, filters, kernel_size, strides=(1, 1), padding='valid', ... , name, reuse)
330 | # reuse is set to True because we want to learn a single set of weights for the pyramid
331 | # kernel_initializer = 'he_normal' or tf.keras.initializers.he_normal(seed=None)
332 | f = num_chann[lvl]
333 | x = tf.layers.conv2d(
334 | x, f, 3, 2, 'same', kernel_initializer=init, name='conv{}a'.format(lvl), reuse=reuse)
335 | x = tf.nn.leaky_relu(x, alpha=0.1)
336 | x = tf.layers.conv2d(
337 | x, f, 3, 1, 'same', kernel_initializer=init, name='conv{}aa'.format(lvl), reuse=reuse)
338 | x = tf.nn.leaky_relu(x, alpha=0.1)
339 | x = tf.layers.conv2d(
340 | x, f, 3, 1, 'same', kernel_initializer=init, name='conv{}b'.format(lvl), reuse=reuse)
341 | x = tf.nn.leaky_relu(x, alpha=0.1, name=str(name)+str(lvl))
342 | pyr.append(x)
343 | return c1, c2
344 |
345 | ###
346 | # PWC-Net warping helpers
347 | ###
348 | def warp(self, c2, sc_up_flow, lvl, name='warp'):
349 | op_name = str(name)+str(lvl)
350 | with tf.name_scope(name):
351 | return dense_image_warp(c2, sc_up_flow, name=op_name)
352 |
353 | def deconv(self, x, lvl, name='up_flow'):
354 | op_name = str(name)+str(lvl)
355 | with tf.variable_scope('upsample'):
356 | # tf.layers.conv2d_transpose(inputs, filters, kernel_size, strides=(1, 1), padding='valid', ... , name)
357 | return tf.layers.conv2d_transpose(x, 2, 4, 2, 'same', name=op_name)
358 |
359 | ###
360 | # Cost Volume helpers
361 | ###
362 | def corr(self, c1, warp, lvl, name='corr'):
363 | op_name = 'corr'+str(lvl)
364 | with tf.name_scope(name):
365 | return cost_volume(c1, warp, self.opts['search_range'], op_name)
366 |
367 | ###
368 | # Optical flow estimator helpers
369 | ###
370 | def predict_flow(self, corr, c1, up_flow, up_feat, lvl, name='predict_flow'):
371 | op_name = 'flow'+str(lvl)
372 | init = tf.keras.initializers.he_normal()
373 | with tf.variable_scope(name):
374 | if c1 is None and up_flow is None and up_feat is None:
375 | x = corr
376 | else:
377 | x = tf.concat([corr, c1, up_flow, up_feat], axis=3)
378 |
379 | conv = tf.layers.conv2d(
380 | x, 128, 3, 1, 'same', kernel_initializer=init, name='conv{}_0'.format(lvl))
381 | # default alpha is 0.2 for TF
382 | act = tf.nn.leaky_relu(conv, alpha=0.1)
383 | x = tf.concat([act, x], axis=3)
384 |
385 | conv = tf.layers.conv2d(
386 | x, 128, 3, 1, 'same', kernel_initializer=init, name='conv{}_1'.format(lvl))
387 | act = tf.nn.leaky_relu(conv, alpha=0.1)
388 | x = tf.concat([act, x], axis=3)
389 |
390 | conv = tf.layers.conv2d(
391 | x, 96, 3, 1, 'same', kernel_initializer=init, name='conv{}_2'.format(lvl))
392 | act = tf.nn.leaky_relu(conv, alpha=0.1)
393 | x = tf.concat([act, x], axis=3)
394 |
395 | conv = tf.layers.conv2d(
396 | x, 64, 3, 1, 'same', kernel_initializer=init, name='conv{}_3'.format(lvl))
397 | act = tf.nn.leaky_relu(conv, alpha=0.1)
398 | x = tf.concat([act, x], axis=3)
399 |
400 | conv = tf.layers.conv2d(
401 | x, 32, 3, 1, 'same', kernel_initializer=init, name='conv{}_4'.format(lvl))
402 | # will also be used as an input by the context network
403 | act = tf.nn.leaky_relu(conv, alpha=0.1)
404 | upfeat = tf.concat([act, x], axis=3, name='upfeat'+str(lvl))
405 |
406 | flow = tf.layers.conv2d(upfeat, 2, 3, 1, 'same', name=op_name)
407 |
408 | return upfeat, flow
409 |
410 | ###
411 | # PWC-Net context network helpers
412 | ###
413 | def refine_flow(self, feat, flow, lvl, name='ctxt'):
414 | op_name = 'refined_flow'+str(lvl)
415 | init = tf.keras.initializers.he_normal()
416 | with tf.variable_scope(name):
417 | x = tf.layers.conv2d(feat, 128, 3, 1, 'same', dilation_rate=1,
418 | kernel_initializer=init, name='dc_conv{}1'.format(lvl))
419 | x = tf.nn.leaky_relu(x, alpha=0.1) # default alpha is 0.2 for TF
420 | x = tf.layers.conv2d(x, 128, 3, 1, 'same', dilation_rate=2,
421 | kernel_initializer=init, name='dc_conv{}2'.format(lvl))
422 | x = tf.nn.leaky_relu(x, alpha=0.1)
423 | x = tf.layers.conv2d(x, 128, 3, 1, 'same', dilation_rate=4,
424 | kernel_initializer=init, name='dc_conv{}3'.format(lvl))
425 | x = tf.nn.leaky_relu(x, alpha=0.1)
426 | x = tf.layers.conv2d(x, 96, 3, 1, 'same', dilation_rate=8,
427 | kernel_initializer=init, name='dc_conv{}4'.format(lvl))
428 | x = tf.nn.leaky_relu(x, alpha=0.1)
429 | x = tf.layers.conv2d(x, 64, 3, 1, 'same', dilation_rate=16,
430 | kernel_initializer=init, name='dc_conv{}5'.format(lvl))
431 | x = tf.nn.leaky_relu(x, alpha=0.1)
432 | x = tf.layers.conv2d(x, 32, 3, 1, 'same', dilation_rate=1,
433 | kernel_initializer=init, name='dc_conv{}6'.format(lvl))
434 | x = tf.nn.leaky_relu(x, alpha=0.1)
435 | x = tf.layers.conv2d(x, 2, 3, 1, 'same', dilation_rate=1,
436 | kernel_initializer=init, name='dc_conv{}7'.format(lvl))
437 |
438 | return tf.add(flow, x, name=op_name)
439 |
440 | ###
441 | # PWC-Net nn builder
442 | ###
443 | def nn(self, x_tnsr, name='pwcnet'):
444 | with tf.variable_scope(name):
445 |
446 | # Extract pyramids of CNN features from both input images (1-based lists))
447 | c1, c2 = self.extract_features(x_tnsr)
448 |
449 | flow_pyr = []
450 |
451 | for lvl in range(self.opts['pyr_lvls'], self.opts['flow_pred_lvl'] - 1, -1):
452 |
453 | if lvl == self.opts['pyr_lvls']:
454 | # Compute the cost volume
455 | corr = self.corr(c1[lvl], c2[lvl], lvl)
456 |
457 | # Estimate the optical flow
458 | upfeat, flow = self.predict_flow(
459 | corr, None, None, None, lvl)
460 | else:
461 | # Warp level of Image1's using the upsampled flow
462 | scaler = 20. / 2**lvl # scaler values are 0.625, 1.25, 2.5, 5.0
463 | warp = self.warp(c2[lvl], up_flow * scaler, lvl)
464 |
465 | # Compute the cost volume
466 | corr = self.corr(c1[lvl], warp, lvl)
467 |
468 | # Estimate the optical flow
469 | upfeat, flow = self.predict_flow(
470 | corr, c1[lvl], up_flow, up_feat, lvl)
471 |
472 | _, lvl_height, lvl_width, _ = tf.unstack(tf.shape(c1[lvl]))
473 |
474 | if lvl != self.opts['flow_pred_lvl']:
475 | flow = self.refine_flow(upfeat, flow, lvl)
476 |
477 | # Upsample predicted flow and the features used to compute predicted flow
478 | flow_pyr.append(flow)
479 |
480 | up_flow = self.deconv(flow, lvl, 'up_flow')
481 | up_feat = self.deconv(upfeat, lvl, 'up_feat')
482 | else:
483 | # Refine the final predicted flow
484 | flow = self.refine_flow(upfeat, flow, lvl)
485 | flow_pyr.append(flow)
486 |
487 | # Upsample the predicted flow (final output) to match the size of the images
488 | scaler = 2**self.opts['flow_pred_lvl']
489 | size = (lvl_height * scaler, lvl_width * scaler)
490 | flow_pred = tf.image.resize_bilinear(
491 | flow, size, name="flow_pred") * scaler
492 | break
493 |
494 | return flow_pred, flow_pyr
495 |
--------------------------------------------------------------------------------
/dataset/stereoRectifier.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import absolute_import, division, print_function
18 | import numpy as np
19 | import cv2
20 | import os
21 | import yaml
22 | from numpy import linalg as LA
23 | from tqdm import tqdm
24 |
25 |
26 | def stereoRectify(data_path, save_path, resolution):
27 | img0_path = save_path+"cam0/images/"
28 | img1_path = save_path+"cam1/images/"
29 | if not os.path.exists(img0_path):
30 | os.makedirs(img0_path)
31 | if not os.path.exists(img1_path):
32 | os.makedirs(img1_path)
33 |
34 | # Read original calibration file
35 | with open(data_path+"camchain.yaml") as file:
36 | camchain = yaml.load(file, Loader=yaml.FullLoader)
37 |
38 | imageSize = tuple(camchain['cam0']['resolution'])
39 | cam0_intrinsics = camchain['cam0']['intrinsics']
40 | K0 = np.matrix([[cam0_intrinsics[0], 0, cam0_intrinsics[2]],
41 | [0, cam0_intrinsics[1], cam0_intrinsics[3]],
42 | [0, 0, 1]])
43 | D0 = np.array(camchain['cam0']['distortion_coeffs'])
44 |
45 | cam1_intrinsics = camchain['cam1']['intrinsics']
46 | K1 = np.matrix([[cam1_intrinsics[0], 0, cam1_intrinsics[2]],
47 | [0, cam1_intrinsics[1], cam1_intrinsics[3]],
48 | [0, 0, 1]])
49 | D1 = np.array(camchain['cam1']['distortion_coeffs'])
50 |
51 | T01 = np.matrix(camchain['cam1']['T_cn_cnm1'])
52 | R = T01[np.ix_([0, 1, 2], [0, 1, 2])]
53 | tvec = T01[np.ix_([0, 1, 2], [3])]
54 |
55 | # Fisheye stere0 rectify
56 | R0, R1, P0, P1, Q = cv2.fisheye.stereoRectify(
57 | K0, D0, K1, D1, imageSize, R, tvec, 0, newImageSize=resolution)
58 | map0 = cv2.fisheye.initUndistortRectifyMap(
59 | K0, D0, R0, P0, resolution, cv2.CV_32F)
60 | map1 = cv2.fisheye.initUndistortRectifyMap(
61 | K1, D1, R1, P1, resolution, cv2.CV_32F)
62 | np.save(save_path+"cam0/stereo_map.npy", np.array(map0))
63 | np.save(save_path+"cam1/stereo_map.npy", np.array(map1))
64 |
65 | # Loopup table for rolling shutter time query
66 | cols_idx, _ = np.indices((imageSize[1], imageSize[0]), dtype=np.float32)
67 | cols_idx = cols_idx / imageSize[1] * resolution[1]
68 | v1_lut = cv2.remap(cols_idx, map1[0], map1[1], cv2.INTER_NEAREST)
69 | v1_lut = np.array(v1_lut, dtype=int)
70 | np.save(save_path+"cam1/v1_lut.npy", v1_lut)
71 |
72 | fxfycxcytx0 = np.array(
73 | [P0[0, 0], P0[1, 1], P0[0, 2], P0[1, 2], P0[0, 3]/P0[0, 0]])
74 | fxfycxcytx1 = np.array(
75 | [P1[0, 0], P1[1, 1], P1[0, 2], P1[1, 2], P1[0, 3]/P1[0, 0]])
76 | np.save(save_path+"cam0/camera.npy", fxfycxcytx0)
77 | np.save(save_path+"cam1/camera.npy", fxfycxcytx1)
78 |
79 | T_cam0_imu = np.matrix(camchain['cam0']['T_cam_imu'])
80 | T2rectified = np.identity(4)
81 | T2rectified[0:3, 0:3] = R0
82 | T_imu_cam0 = LA.inv(T2rectified*T_cam0_imu)
83 | np.save(save_path+"cam0/T_imu_cam0.npy", T_imu_cam0)
84 |
85 |
86 | def stereoRemap(data_path, save_path):
87 | valid_ns = np.load(save_path+"valid_ns.npy")
88 | map0 = np.load(save_path+"cam0/stereo_map.npy")
89 | map1 = np.load(save_path+"cam1/stereo_map.npy")
90 | maps = [map0, map1]
91 | # Remap images
92 | for i in tqdm(range(valid_ns.shape[0])):
93 | for cam_i in [0, 1]:
94 | img = cv2.imread(
95 | '{}cam{}/images/{}.png'.format(data_path, cam_i, valid_ns[i]))
96 | img_rect = cv2.remap(
97 | img, maps[cam_i][0], maps[cam_i][1], cv2.INTER_LINEAR)
98 | save_file = '{}cam{}/images/{}.png'.format(save_path, cam_i, i)
99 | cv2.imwrite(save_file, img_rect)
100 |
--------------------------------------------------------------------------------
/dataset/tum_process.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import absolute_import, division, print_function
18 | import os
19 | import shutil
20 | import numpy as np
21 |
22 | from stereoRectifier import stereoRectify, stereoRemap
23 | from poseHandler import getPoses
24 | from depthEstimator import getDepth
25 | from gtFlowGenerator import getRS2GSFlows
26 | from gsImgRectifier import rectify_gs_imgs
27 |
28 | data_path = '/mnt/data2/jiawei/unrolling/tum_data/'
29 | save_path = os.getcwd()+'/../data/'
30 | seqs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
31 | output_resolution = (320, 256)
32 | ns_per_v = 29.4737*1023/(output_resolution[1]-1)*1000
33 |
34 | for seq in seqs:
35 | print('\n\n\nProcessing Sequence '+str(seq))
36 | seq_path = os.path.join(data_path, 'dataset-seq{}/dso/'.format(seq))
37 | seq_save_path = os.path.join(save_path, 'seq{}/'.format(seq))
38 |
39 | print(seq_save_path)
40 | if not os.path.exists(seq_save_path):
41 | os.makedirs(seq_save_path)
42 |
43 | stereoRectify(seq_path, seq_save_path, output_resolution)
44 |
45 | print('Getting Pose...')
46 | getPoses(seq_path, seq_save_path, output_resolution[1], ns_per_v)
47 |
48 | print('Stereo Rectifying...')
49 | stereoRemap(seq_path, seq_save_path)
50 |
51 | print('Getting Depth...')
52 | getDepth(seq_save_path)
53 |
54 | print('Getting Unrolling Flow...')
55 | getRS2GSFlows(seq_save_path, ns_per_v)
56 |
57 | print('Getting GS Image...')
58 | rectify_gs_imgs(seq_save_path, output_resolution)
59 |
60 | # clean up
61 | cam0_folder = os.path.join(seq_save_path, 'cam0/')
62 | shutil.rmtree(cam0_folder) if os.path.exists(cam0_folder) else None
63 | tmp_files = ['T_cam0_v1.npy', 'valid_ns.npy', 'cam1/stereo_map.npy']
64 | for file in tmp_files:
65 | file_path = os.path.join(seq_save_path, file)
66 | os.remove(file_path) if os.path.exists(file_path) else None
67 |
--------------------------------------------------------------------------------
/images/data_gen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IRVLab/unrolling/b670eacddc07c9c956c32354786a443ad18529e5/images/data_gen.png
--------------------------------------------------------------------------------
/images/dso.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IRVLab/unrolling/b670eacddc07c9c956c32354786a443ad18529e5/images/dso.jpg
--------------------------------------------------------------------------------
/images/networks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IRVLab/unrolling/b670eacddc07c9c956c32354786a443ad18529e5/images/networks.png
--------------------------------------------------------------------------------
/images/res_img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IRVLab/unrolling/b670eacddc07c9c956c32354786a443ad18529e5/images/res_img.png
--------------------------------------------------------------------------------
/images/rs_pose_net.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IRVLab/unrolling/b670eacddc07c9c956c32354786a443ad18529e5/images/rs_pose_net.png
--------------------------------------------------------------------------------
/network/DataLoader.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import division, absolute_import
18 | import os
19 | import numpy as np
20 | import keras
21 | import cv2
22 |
23 |
24 | class TumDataSet():
25 | def __init__(self, gyro=False, acc=False, test_seq=[2, 7], data_path='../data/'):
26 | num_seqs = 10
27 | test_seq = np.array(test_seq, dtype='int')
28 |
29 | # parameters
30 | lut = np.load(os.path.join(data_path, 'seq1/cam1/v1_lut.npy'))
31 | cam = np.load(os.path.join(data_path, 'seq1/cam1/camera.npy'))
32 | cam = np.array([[cam[0], 0, cam[2]],
33 | [0, cam[1], cam[3]],
34 | [0, 0, 1]], dtype='float32')
35 | self.params = {'lut': lut,
36 | 'cam': cam,
37 | 'img_shape': [256, 320]}
38 |
39 | # get entire dataset and split data for training/testing
40 | self.data = {}
41 | self.data['train'] = {'size': 0, 'image_paths': [], 'imus': [], 'poses': [],
42 | 'vels': [], 'depth_paths': [], 'flow_paths': []}
43 | self.data['val'] = {'size': 0, 'image_paths': [], 'imus': [], 'poses': [],
44 | 'vels': [], 'depth_paths': [], 'flow_paths': []}
45 | self.data['test'] = {}
46 | for seq in range(1, num_seqs+1):
47 | seq_path = os.path.join(data_path, 'seq'+str(seq)+'/cam1/')
48 | poses = np.load(seq_path+'pose_cam1_v1.npy')
49 | vels = poses[:, -1, :] # velocity = last row pose / 1.0
50 | imus_raw = np.load(seq_path+'imu_cam1_v1.npy')
51 | imus = np.empty((imus_raw.shape[0], imus_raw.shape[1], 0))
52 | if gyro:
53 | imus = np.append(imus, imus_raw[:, :, :3], axis=-1)
54 | if acc:
55 | imus = np.append(imus, imus_raw[:, :, 3:], axis=-1)
56 | count = len(os.listdir(seq_path + 'flows_rs2gs/'))
57 | image_paths, depth_paths, flow_paths = [], [], []
58 | for i in range(count):
59 | fi = str(i)
60 | image_paths.append(seq_path + 'images/' + fi + '.png')
61 | depth_paths.append(seq_path + 'depth/' + fi + '.npy')
62 | flow_paths.append(seq_path + 'flows_rs2gs/' + str(fi) + '.npy')
63 |
64 | # split data
65 | if seq in test_seq:
66 | self.data['test'][seq] = {'size': len(image_paths), 'image_paths': image_paths,
67 | 'imus': imus, 'poses': poses, 'vels': vels,
68 | 'depth_paths': depth_paths, 'flow_paths': flow_paths}
69 | else:
70 | # use the middle 10% as validation
71 | val_start = int(0.45*count)
72 | val_end = int(0.55*count)
73 | self.appendElementByIdx('train', image_paths, imus, depth_paths, flow_paths,
74 | poses, vels, [i for i in range(val_start)])
75 | self.appendElementByIdx('val', image_paths, imus, depth_paths, flow_paths,
76 | poses, vels, [i for i in range(val_start, val_end)])
77 | self.appendElementByIdx('train', image_paths, imus, depth_paths, flow_paths,
78 | poses, vels, [i for i in range(val_end, count)])
79 |
80 | self.data['train']['size'] = len(self.data['train']['image_paths'])
81 | self.data['val']['size'] = len(self.data['val']['image_paths'])
82 |
83 | def appendElementByIdx(self, split, image_paths, imus, depth_paths, flow_paths, poses, vels, indices):
84 | for i in indices:
85 | self.data[split]['image_paths'].append(image_paths[i])
86 | self.data[split]['imus'].append(imus[i])
87 | self.data[split]['poses'].append(poses[i])
88 | self.data[split]['vels'].append(vels[i])
89 | self.data[split]['depth_paths'].append(depth_paths[i])
90 | self.data[split]['flow_paths'].append(flow_paths[i])
91 |
92 |
93 | class DataGenerator(keras.utils.Sequence):
94 |
95 | def __init__(self, data, batch_size, dtype):
96 | self.data = data
97 | self.batch_size = batch_size
98 | self.dtype = dtype
99 | self.on_epoch_end()
100 |
101 | def __len__(self):
102 | return int(np.ceil(self.data['size'] / self.batch_size))
103 |
104 | def __getitem__(self, idx):
105 | indexes = self.indexes[idx*self.batch_size:(idx+1)*self.batch_size]
106 | batch_image = np.array(
107 | [cv2.imread(self.data['image_paths'][i]) for i in indexes]) / 255.0
108 | batch_depth = np.expand_dims(
109 | np.array([np.load(self.data['depth_paths'][i]) for i in indexes]), axis=-1)
110 | batch_flow = np.array(
111 | [np.load(self.data['flow_paths'][i]) for i in indexes])
112 | batch_depth_flow = np.concatenate((batch_depth, batch_flow), axis=-1)
113 |
114 | if self.dtype == 'depth':
115 | inputs = batch_image
116 | outputs = batch_depth
117 | elif self.dtype == 'vel':
118 | batch_vel = np.array([self.data['vels'][i] for i in indexes])
119 | inputs = batch_image
120 | outputs = {'vel': batch_vel, 'flow': batch_depth_flow}
121 | else:
122 | assert(self.dtype == 'pose')
123 | batch_imu = np.array([self.data['imus'][i] for i in indexes])
124 | batch_pose = np.array([self.data['poses'][i] for i in indexes])
125 | inputs = [batch_image, batch_imu]
126 | outputs = {'pose': batch_pose, 'flow': batch_depth_flow}
127 |
128 | return inputs, outputs
129 |
130 | def on_epoch_end(self):
131 | self.indexes = np.arange(self.data['size'])
132 | np.random.shuffle(self.indexes)
133 |
--------------------------------------------------------------------------------
/network/README.md:
--------------------------------------------------------------------------------
1 | # Network
2 | * Overview
3 |
4 |
5 | * **RsPoseNet**
6 |
7 |
8 |
9 | # Files
10 | * **DataLoader.py** loads the dataset, remember to modify the **data_path** in this file to the processed dataset.
11 | * **RsDepthNet.py** and **train_rsdepthnet.py** is the implementation of RsDepthNet.
12 | * **RsPoseNet.py** and **train_rsposenet.py** is the implementation of the proposed RsPoseNet.
13 | * **test.py** calculates the EPE and Improvement Ratio, as well as rectifies images.
14 |
15 | # Usage
16 | * Dependencies (version we use)
17 | * [numpy(1.17.4)](https://numpy.org/)
18 | * [cv2](https://pypi.org/project/opencv-python/) for reading images
19 | * [Tensorflow(2.3.0)](https://www.tensorflow.org/), [Keras(2.4.3)](https://keras.io/), [classification-models(*ResNet34*)](https://github.com/qubvel/classification_models) for network structure
20 | * [pandas(1.2.3)](https://pandas.pydata.org/) for image post-processing (interpolation)
21 |
22 | * Training
23 | ```
24 | python3 train_rsdepthnet.py
25 | python3 train_rsposenet.py
26 | ```
27 | or download the our trained [checkpoints](https://drive.google.com/file/d/1CMi2j5-aU4YCWay3ebMWkr3ClFqPsSSs/view?usp=sharing).
28 |
29 | * Testing
30 | ```
31 | python3 test.py
32 | ```
33 | the recitified images are saved to *./results/*.
--------------------------------------------------------------------------------
/network/RsDepthNet.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | # fmt: off
18 | from __future__ import absolute_import, division, print_function
19 | import os
20 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
21 | import tensorflow as tf
22 | from keras.models import Input, Model
23 | from keras.layers import Conv2D, Conv2DTranspose, Activation
24 | from keras.layers import BatchNormalization, UpSampling2D, Concatenate
25 |
26 | # fmt: on
27 |
28 |
29 | def iconv_pr(iconv_prv, pr_prv, conv_encoder, filters, lvl):
30 | upconv = Activation('relu')(BatchNormalization(name='upconv{}bn'.format(lvl))(
31 | Conv2DTranspose(filters, 4, 2, 'same', name='upconv'+str(lvl))(iconv_prv)))
32 | upsampled = UpSampling2D(interpolation='bilinear',
33 | name='upsampled'+str(lvl))(pr_prv)
34 | ctnt = Concatenate()([upconv, upsampled, conv_encoder])
35 | iconv = Conv2D(filters, 3, 1, 'same', activation='relu',
36 | name='iconv'+str(lvl))(ctnt)
37 | pr = Conv2D(1, 3, 1, 'same', activation='relu',
38 | name='pr'+str(lvl))(iconv)
39 | return [iconv, pr]
40 |
41 |
42 | class RsDepthNet():
43 | def __init__(self, params):
44 | rows, cols = params['img_shape']
45 | input_img = Input((rows, cols, 3))
46 | depth = self.depthNet(input_img)
47 | self.model = Model(inputs=input_img, outputs=depth)
48 |
49 | def depthNet(self, img):
50 | # encoder
51 | c1 = Conv2D(64, 7, 2, 'same', activation='relu', name='conv1')(img)
52 | c2 = Conv2D(128, 5, 2, 'same', activation='relu', name='conv2')(c1)
53 | c3a = Conv2D(256, 5, 2, 'same', activation='relu', name='conv3a')(c2)
54 | c3b = Conv2D(256, 3, 1, 'same', activation='relu', name='conv3b')(c3a)
55 | c4a = Conv2D(512, 3, 2, 'same', activation='relu', name='conv4a')(c3b)
56 | c4b = Conv2D(512, 3, 1, 'same', activation='relu', name='conv4b')(c4a)
57 | c5a = Conv2D(512, 3, 2, 'same', activation='relu', name='conv5a')(c4b)
58 | c5b = Conv2D(512, 3, 1, 'same', activation='relu', name='conv5b')(c5a)
59 | c6a = Conv2D(1024, 3, 2, 'same', activation='relu', name='conv6a')(c5b)
60 | c6b = Conv2D(1024, 3, 1, 'same', activation='relu', name='conv6b')(c6a)
61 |
62 | pr6 = Conv2D(1, 3, 1, 'same', activation='relu', name='pr6')(c6a)
63 |
64 | # decoder
65 | [ic5, pr5] = iconv_pr(c6b, pr6, c5b, 512, 5)
66 | [ic4, pr4] = iconv_pr(ic5, pr5, c4b, 256, 4)
67 | [ic3, pr3] = iconv_pr(ic4, pr4, c3b, 128, 3)
68 | [ic2, pr2] = iconv_pr(ic3, pr3, c2, 64, 2)
69 | [ic1, pr1] = iconv_pr(ic2, pr2, c1, 32, 1)
70 |
71 | d1 = UpSampling2D(interpolation='bilinear', name='depth')(pr1)
72 |
73 | return d1
74 |
75 | def depthLoss(self, y_true, y_pred):
76 | diff = tf.where(tf.math.is_nan(y_true),
77 | tf.zeros_like(y_true), y_true-y_pred)
78 | return tf.reduce_mean(tf.abs(diff))
79 |
--------------------------------------------------------------------------------
/network/RsPoseNet.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | # fmt: off
18 | from __future__ import absolute_import, division, print_function
19 | import os
20 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
21 | import tensorflow as tf
22 | from keras.models import Input, Model
23 | from keras.layers import Conv2D, Conv2DTranspose, Activation, LSTM
24 | from keras.layers import BatchNormalization, Concatenate, Reshape
25 | import numpy as np
26 |
27 | from helpers import baseNet, flowLossByPose
28 | # fmt: on
29 |
30 |
31 | def poseConv(x, filters, kernel_size, lvl):
32 | x = Conv2D(filters, kernel_size, (1, 2), 'same',
33 | activation='relu', name='conv'+str(lvl))(x)
34 | x = Conv2DTranspose(filters, kernel_size, (2, 1),
35 | 'same', name='upconv'+str(lvl))(x)
36 | x = Activation('relu')(BatchNormalization(name='bn'+str(lvl))(x))
37 | return x
38 |
39 |
40 | class RsPoseNet():
41 | def __init__(self, params, gyro=True, acc=True):
42 | rows, cols = params['img_shape']
43 | self.params = params
44 | self.pose_scale = 10
45 |
46 | # inputs
47 | input_img = Input((rows, cols, 3))
48 | input_imu = Input((rows, 3*gyro+3*acc))
49 | pose_scaled = self.poseNet(input_img, input_imu) # for poseLoss
50 | pose_mat = self.convertToPoseMat(pose_scaled) # for flowLoss
51 |
52 | self.model = Model(inputs=[input_img, input_imu], outputs={
53 | 'pose': pose_scaled, 'flow': pose_mat})
54 |
55 | def poseNet(self, input_img, input_imu):
56 | features = baseNet(input_img)
57 |
58 | x = poseConv(features, 512, 3, 5)
59 | x = poseConv(x, 256, 3, 4)
60 | x = poseConv(x, 128, 3, 3)
61 | x = poseConv(x, 64, 3, 2)
62 | x = poseConv(x, 32, 3, 1)
63 |
64 | img_pose = Conv2D(6, 1, 1, 'same', activation='tanh',
65 | name='pose_conv')(x)
66 |
67 | img_pose = Reshape(
68 | (self.params['img_shape'][0], 6), name='img_pose')(img_pose)
69 |
70 | # extend pose from image by IMU
71 | img_imu = Concatenate()([img_pose, input_imu])
72 | h = LSTM(6, return_sequences=True, name='imu_lstm1')(img_imu)
73 | pose = LSTM(6, return_sequences=True, name='pose')(h)
74 |
75 | return pose
76 |
77 | def convertToPoseMat(self, pose_scaled):
78 | # -1 x 256 x 6 -> -1 x 256 x 320 x 6
79 | pose_mat = tf.gather(pose_scaled / self.pose_scale,
80 | self.params['lut'], axis=1, name='flow')
81 | return pose_mat
82 |
83 | def poseLoss(self, y_true, y_pred):
84 | return tf.reduce_mean(tf.norm(self.pose_scale*y_true - y_pred, axis=-1))
85 |
86 | def flowLoss(self, y_true, y_pred):
87 | return flowLossByPose(y_true, y_pred, self.params)
88 |
--------------------------------------------------------------------------------
/network/helpers.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from __future__ import absolute_import, division, print_function
18 | import tensorflow as tf
19 | from classification_models.keras import Classifiers
20 | from keras.applications.vgg16 import VGG16
21 | import numpy as np
22 |
23 |
24 | def getFlow(depth, pose, params):
25 | rows, cols = params['img_shape']
26 |
27 | # split pose to translation and angel-axis representation rotation
28 | trans, rot = tf.split(pose, [3, 3], -1)
29 | angle = tf.expand_dims(tf.norm(rot, axis=-1), -1)
30 | cos_angle = tf.cos(angle)
31 | axis = rot / (angle + 1e-20)
32 |
33 | # recover 3D point in RS frame
34 | v_rs, u_rs = np.indices((rows, cols), dtype='float32')
35 | Kiu_rs = np.matmul(np.stack([u_rs, v_rs, np.ones_like(
36 | u_rs)], axis=-1), np.linalg.inv(params['cam']).T)
37 | depth = tf.stack([tf.squeeze(depth, axis=-1)]*3, axis=-1)
38 | xyz_rs = depth * Kiu_rs
39 |
40 | # project to GS frame
41 | xyz_gs = xyz_rs * cos_angle + tf.linalg.cross(axis, xyz_rs) * tf.sin(
42 | angle) + axis * tf.reduce_sum(axis * xyz_rs, -1, True) * (1-cos_angle) + trans
43 | uvd_gs = tf.matmul(xyz_gs, params['cam'].T)
44 | uv_gs, d_gs = tf.split(uvd_gs, [2, 1], -1)
45 | uv_gs = uv_gs / (d_gs + 1e-20)
46 |
47 | uv_rs = np.stack([u_rs, v_rs], axis=-1)
48 | flow = tf.identity(uv_gs - uv_rs, name='flow')
49 | return flow
50 |
51 |
52 | def flowLossByPose(df_true, p_pred, params):
53 | d_true, f_true = tf.split(df_true, [1, 2], -1)
54 | d_true = tf.where(tf.math.is_nan(d_true),
55 | tf.ones_like(d_true), d_true)
56 | f_pred = getFlow(d_true, p_pred, params)
57 | diff = tf.where(tf.math.is_nan(f_true),
58 | tf.zeros_like(f_true), f_true-f_pred)
59 | return tf.reduce_mean(tf.norm(diff, axis=-1))
60 |
61 |
62 | def baseNet(img_input, base='ResNet34'):
63 | _, rows, cols, _ = img_input.shape
64 | if base == 'ResNet34':
65 | ResNet34, _ = Classifiers.get('resnet34')
66 | features = ResNet34(input_shape=(rows, cols, 3),
67 | weights='imagenet', include_top=False)(img_input)
68 | elif base == 'ResNet50':
69 | ResNet50, _ = Classifiers.get('resnet50')
70 | features = ResNet50(input_shape=(rows, cols, 3),
71 | weights='imagenet', include_top=False)(img_input)
72 | elif base == 'VGG16':
73 | vgg = VGG16(input_shape=(rows, cols, 3),
74 | weights='imagenet', include_top=False)(img_input)
75 | features = vgg.get_layer('block5_pool')
76 | return features
77 |
--------------------------------------------------------------------------------
/network/test.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | # fmt: off
18 | from __future__ import print_function, division
19 | import os
20 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
21 | import time
22 | import shutil
23 | import numpy as np
24 | import pandas as pd
25 | import cv2
26 |
27 | from DataLoader import TumDataSet
28 | from RsDepthNet import RsDepthNet
29 | from helpers import getFlow
30 | from RsPoseNet import RsPoseNet
31 | # fmt: on
32 |
33 |
34 | def get_flows_pred(data, batch_size = 32):
35 | flows_pred = np.empty((0, rows, cols, 2))
36 | for i in range(0, data['size'], batch_size):
37 | rg = range(i, min(i+batch_size, data['size']))
38 | img = np.array([cv2.imread(data['image_paths'][j])
39 | for j in rg]) / 255.0
40 | imu = np.array([data['imus'][j] for j in rg])
41 | pose_mat = model_rspose.model.predict([img, imu])['flow']
42 | depth_pred = model_depth.model.predict(img)
43 | flow_pred = getFlow(depth_pred, pose_mat, dataset.params).numpy()
44 | flows_pred = np.append(flows_pred, flow_pred, axis=0)
45 |
46 | return flows_pred
47 |
48 |
49 | def rectify_imgs(data, flow, img_path):
50 | os.makedirs(img_path)
51 | for i in range(data['size']):
52 | flow_rs2gs = flow[i]
53 | size_1d = rows*cols
54 | ind_v, ind_u = np.indices((rows, cols), dtype='float32')
55 |
56 | # map: rs to gs
57 | uv_rs = np.stack((ind_u, ind_v), axis=-1)
58 | uv_gs = np.array(uv_rs + flow_rs2gs + 0.5, dtype='int')
59 | u_gs = np.clip(uv_gs[:, :, 0], 0, cols-1)
60 | v_gs = np.clip(uv_gs[:, :, 1], 0, rows-1)
61 | uv_gs_1d = v_gs * cols + u_gs
62 | uv_gs_1d = np.reshape(uv_gs_1d, (size_1d))
63 |
64 | # reverse the map: gs to rs
65 | flow_gs2rs_1d_u = np.full((size_1d), np.nan, dtype='float32')
66 | flow_gs2rs_1d_v = np.full((size_1d), np.nan, dtype='float32')
67 | flow_gs2rs_1d_u[uv_gs_1d] = np.reshape(-flow_rs2gs[:, :, 0], (size_1d))
68 | flow_gs2rs_1d_v[uv_gs_1d] = np.reshape(-flow_rs2gs[:, :, 1], (size_1d))
69 | flow_gs2rs = np.stack([np.reshape(flow_gs2rs_1d_u, (rows, cols)),
70 | np.reshape(flow_gs2rs_1d_v, (rows, cols))], axis=-1)
71 |
72 | # 2d interpolation
73 | flow_gs2rs[:, :, 0] = pd.DataFrame(flow_gs2rs[:, :, 0]).interpolate()
74 | flow_gs2rs[:, :, 1] = pd.DataFrame(flow_gs2rs[:, :, 1]).interpolate()
75 |
76 | # reconstruct gs image
77 | map_u = ind_u + flow_gs2rs[:, :, 0]
78 | map_v = ind_v + flow_gs2rs[:, :, 1]
79 | img_rs = cv2.imread(data['image_paths'][i])
80 | img_gs = cv2.remap(img_rs, map_u, map_v, cv2.INTER_LINEAR)
81 | cv2.imwrite('{}{}.png'.format(img_path, i), img_gs)
82 |
83 |
84 | if __name__ == "__main__":
85 | # load data
86 | dataset = TumDataSet(True, True)
87 | rows, cols = dataset.params['img_shape']
88 |
89 | # load depth model
90 | model_depth = RsDepthNet(dataset.params)
91 | model_depth.model.load_weights(os.path.join(
92 | os.getcwd(), 'checkpoints/model_depth.hdf5'))
93 |
94 | # load pose model
95 | model_rspose = RsPoseNet(dataset.params)
96 | model_rspose.model.load_weights(os.path.join(
97 | os.getcwd(), 'checkpoints/model_rspose_yy.hdf5'))
98 |
99 | save_path = 'results/'
100 | if os.path.exists(save_path):
101 | shutil.rmtree(save_path)
102 |
103 | seq_data = dataset.data['test']
104 | for seq, data in seq_data.items():
105 | print('\n\n\n******************** Sequence {} *********************'.format(seq))
106 | flows_gt = np.array([np.load(data['flow_paths'][j])
107 | for j in range(data['size'])])
108 | errs_input = np.nanmean(
109 | np.sqrt(np.sum(np.square(flows_gt), axis=-1)), axis=(1, 2))
110 | print('Input EPE: {:.3f}'.format(np.mean(errs_input)))
111 |
112 | # predict correction flow
113 | t0 = time.time()
114 | flows_pred = get_flows_pred(data)
115 | fps = data['size'] / (time.time() - t0)
116 | errs_pred = np.nanmean(
117 | np.sqrt(np.sum(np.square(flows_gt-flows_pred), axis=-1)), axis=(1, 2))
118 | print('Prediction: {:.3f} x {:.1f}% @ {:.1f}FPS'.format(np.mean(
119 | errs_pred), 100*(np.count_nonzero(errs_input-errs_pred > 0))/data['size'], fps))
120 |
121 | # rectify images
122 | t0 = time.time()
123 | rectify_imgs(data, flows_pred, '{}{}/'.format(save_path, seq))
124 | fps = data['size'] / (time.time() - t0)
125 | print('Rectify Images: {:.1f}FPS'.format(fps))
126 |
--------------------------------------------------------------------------------
/network/train_rsdepthnet.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | # fmt: off
18 | from __future__ import print_function, division
19 | import os
20 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
21 | import shutil
22 |
23 | from keras.optimizers import Adam
24 | from keras.callbacks import ModelCheckpoint, TensorBoard
25 |
26 | from DataLoader import TumDataSet, DataGenerator
27 | from RsDepthNet import RsDepthNet
28 | # fmt: on
29 |
30 | # dataset
31 | batch_size = 32
32 | tum = TumDataSet()
33 | train_dg = DataGenerator(tum.data['train'], batch_size, dtype='depth')
34 | val_dg = DataGenerator(tum.data['val'], batch_size, dtype='depth')
35 |
36 | # weight saving directory
37 | checkpoint_path = os.path.join(os.getcwd(), "checkpoints/")
38 | if not os.path.exists(checkpoint_path):
39 | os.makedirs(checkpoint_path)
40 | checkpoint_file = os.path.join(checkpoint_path, 'model_depth.hdf5')
41 |
42 | # tensorboard
43 | log_path = os.path.join(checkpoint_path, '.logs/depth')
44 | if os.path.exists(log_path):
45 | shutil.rmtree(log_path)
46 |
47 | # load model
48 | model = RsDepthNet(tum.params)
49 |
50 | # training
51 | model.model.compile(optimizer=Adam(learning_rate=1e-3), loss=model.depthLoss)
52 | model.model.fit(train_dg, validation_data=val_dg, epochs=100, callbacks=[
53 | ModelCheckpoint(checkpoint_file,
54 | save_weights_only=True, save_best_only=True),
55 | TensorBoard(log_dir=log_path)])
56 |
--------------------------------------------------------------------------------
/network/train_rsposenet.py:
--------------------------------------------------------------------------------
1 | # Learning Rolling Shutter Correction from Real Data without Camera Motion Assumption
2 | # Copyright (C) <2021>
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | # fmt: off
18 | from __future__ import print_function, division
19 | import sys
20 | import os
21 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
22 | import shutil
23 | import argparse
24 |
25 | from keras.optimizers import Adam
26 | from keras.callbacks import ModelCheckpoint, TensorBoard
27 |
28 | from DataLoader import TumDataSet, DataGenerator
29 | from RsPoseNet import RsPoseNet
30 | # fmt: on
31 |
32 | # whether to use IMU data
33 | parser = argparse.ArgumentParser()
34 | parser.add_argument('--ng', action='store_const', default=False,
35 | const=True, help='whether to disable gyroscope data')
36 | parser.add_argument('--na', action='store_const', default=False,
37 | const=True, help='whether to disable accelerator data')
38 | args = parser.parse_args()
39 | gyro = not args.ng
40 | acc = not args.na
41 | suffix = ('y' if gyro else 'n') + ('y' if acc else 'n')
42 | print('gyroscope: ' + ('y' if gyro else 'n') + '; ' +
43 | 'accelerator: ' + ('y' if acc else 'n'))
44 |
45 | # dataset
46 | batch_size = 32
47 | tum = TumDataSet(gyro, acc)
48 | train_dg = DataGenerator(tum.data['train'], batch_size, dtype='pose')
49 | val_dg = DataGenerator(tum.data['val'], batch_size, dtype='pose')
50 |
51 | # weight saving directory
52 | checkpoint_path = os.path.join(os.getcwd(), "checkpoints/")
53 | if not os.path.exists(checkpoint_path):
54 | os.makedirs(checkpoint_path)
55 |
56 | # tensorboard
57 | log_path = os.path.join(checkpoint_path, '.logs/rspose_'+suffix)
58 | if os.path.exists(log_path):
59 | shutil.rmtree(log_path)
60 |
61 | # checkpoint file
62 | checkpoint_file = os.path.join(
63 | checkpoint_path, 'model_rspose_{}.hdf5'.format(suffix))
64 |
65 | # load model
66 | model = RsPoseNet(tum.params, gyro, acc)
67 |
68 | # training
69 | print('Training with pose loss')
70 | model.model.compile(optimizer=Adam(learning_rate=1e-3),
71 | loss={'pose': model.poseLoss, 'flow': model.flowLoss},
72 | loss_weights={'pose': 1, 'flow': 0}) # flowLoss is included just for monitoring
73 | model.model.fit(train_dg, validation_data=val_dg, epochs=50, callbacks=[
74 | ModelCheckpoint(
75 | checkpoint_file, save_weights_only=True, save_best_only=True),
76 | TensorBoard(log_dir=log_path)])
77 |
78 | print('Training with flow loss')
79 | model.model.compile(optimizer=Adam(learning_rate=1e-4),
80 | loss={'pose': model.poseLoss, 'flow': model.flowLoss},
81 | loss_weights={'pose': 0, 'flow': 1})
82 | model.model.load_weights(checkpoint_file)
83 | model.model.fit(train_dg, validation_data=val_dg, epochs=50, callbacks=[
84 | ModelCheckpoint(
85 | checkpoint_file, save_weights_only=True, save_best_only=True),
86 | TensorBoard(log_dir=log_path)])
87 |
--------------------------------------------------------------------------------