├── .gitignore
├── LICENSE
├── README.md
├── constants.py
├── demo
├── data.tar.gz
├── image_demo.py
├── sample_1.gif
└── sample_2.gif
├── download_weights_large.sh
├── download_weights_small.sh
├── env.yml
├── re3_utils
├── __init__.py
├── python_util.py
├── pytorch_util
│ ├── CaffeLSTMCell.py
│ ├── __init__.py
│ ├── dataloader.py
│ ├── pytorch_util_functions.py
│ └── tensorboard_logger.py
└── util
│ ├── IOU.py
│ ├── __init__.py
│ ├── bb_util.py
│ ├── drawing.py
│ └── im_util.py
├── tracker
├── __init__.py
├── network.py
└── re3_tracker.py
└── training
├── README.md
├── datasets
├── README.md
├── imagenet_video
│ └── make_label_files.py
└── otb_100
│ └── make_labels.py
├── get_datasets.py
├── pt_dataset.py
├── test_net.py
└── unrolled_solver.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.caffemodel
2 | *.jpg
3 | *~
4 | *.swp
5 | *.pyc
6 | logs/
7 | demo/data/
8 | labels/
9 | *.mp4
10 | *.json
11 | *.pt
12 | *.pkl
13 | .idea
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Re3 in PyTorch
2 | [Re3: Real-Time Recurrent Regression Networks for Visual Tracking of Generic Objects](https://danielgordon10.github.io/pdfs/re3.pdf)
3 |
4 |
5 |
6 | This is the Official Repository for Re3 in PyTorch. However, it has some significant differences between it and the [TensorFlow repository](https://github.com/danielgordon10/re3-tensorflow).
7 | 1. Due to PyTorch's dynamic graph construction, the network can now be trained one unroll at a time. This means less time preprocessing the images, but also it doesn't parallelize as well.
8 | 1. The simulation code is removed as it does not work with this one unroll setup.
9 | 1. The code is Python 3 compatible and encouraged.
10 |
11 | ## First Time Setup:
12 | I have switched from virtualenv to Anaconda because it allows for easier CUDA integration. The setup is much the same as in the TensorFlow version.
13 | ```bash
14 | conda create -n re3-pytorch-env python=3.6.8
15 | conda env update -n re3-pytorch-env -f env.yml
16 | ```
17 |
18 | ## Model:
19 | The model weights we used in our paper were ported from Caffe to Tensorflow and then to PyTorch. There may be slight differences in performance from the original paper.
20 | Weights can be downloaded by running `sh download_weights_large.sh`
21 |
22 | A smaller network trained in PyTorch is also available. Its performance is worse, but it is significantly faster.
23 | These weights can be downloaded by running `sh download_weights_small.sh`.
24 | Additionally, set `USE_SMALL_NET = True` in [constants.py](constants.py).
25 |
26 | ## Run the Demo:
27 | 1. [Download the pretrained weights](#model)
28 | 1. Run `python demo/image_demo.py`
29 |
30 |
31 | ## Folders and Files:
32 | ### Most important for using Re3 in a new project:
33 | 1. [tracker/re3_tracker.py](tracker/re3_tracker.py) - The tracker file for actually tracking objects.
34 | 1. [tracker/network.py](tracker/network.py) - The network file specifying the layout of Re3.
35 | 1. [constants.py](constants.py) - A place to put constants that are used in multiple files such as image size and log location.
36 |
37 | ### Most important for (re)training Re3 on new data:
38 | 1. [Training Readme](training/README.md)
39 | 1. [Dataset Readme](training/datasets/README.md)
40 | 1. [training/unrolled_solver.py](training/unrolled_solver.py)
41 |
42 | Re3 is released under the GPL V3.
43 |
44 | Please cite Re3 in your publications if it helps your research:
45 | ```
46 | @article{gordon2018re3,
47 | title={Re3: Real-Time Recurrent Regression Networks for Visual Tracking of Generic Objects},
48 | author={Gordon, Daniel and Farhadi, Ali and Fox, Dieter},
49 | journal={IEEE Robotics and Automation Letters},
50 | volume={3},
51 | number={2},
52 | pages={788--795},
53 | year={2018},
54 | publisher={IEEE}
55 | }
56 | ```
57 |
--------------------------------------------------------------------------------
/constants.py:
--------------------------------------------------------------------------------
1 | # Network Constants
2 |
3 | USE_SMALL_NET = False
4 |
5 | CROP_SIZE = 227
6 | CROP_PAD = 2
7 | MAX_TRACK_LENGTH = 32
8 |
9 | import os.path
10 |
11 | LOG_DIR = os.path.join(os.path.dirname(__file__), "logs/")
12 | DATA_DIR = os.path.join(
13 | os.path.dirname(__file__), os.path.pardir, os.path.pardir, os.path.pardir, os.path.pardir, "Datasets"
14 | )
15 |
16 | GPU_ID = "0"
17 |
18 | # Drawing constants
19 | OUTPUT_WIDTH = 640
20 | OUTPUT_HEIGHT = 480
21 | PADDING = 2
22 |
--------------------------------------------------------------------------------
/demo/data.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/demo/data.tar.gz
--------------------------------------------------------------------------------
/demo/image_demo.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import os.path
3 | import sys
4 |
5 | import cv2
6 |
7 | basedir = os.path.dirname(__file__)
8 | sys.path.append(os.path.abspath(os.path.join(basedir, os.path.pardir)))
9 | from tracker import re3_tracker
10 |
11 | if not os.path.exists(os.path.join(basedir, "data")):
12 | import tarfile
13 |
14 | tar = tarfile.open(os.path.join(basedir, "data.tar.gz"))
15 | tar.extractall(path=basedir)
16 |
17 | cv2.namedWindow("Image", cv2.WINDOW_NORMAL)
18 | cv2.resizeWindow("Image", 640, 480)
19 | tracker = re3_tracker.Re3Tracker()
20 | image_paths = sorted(glob.glob(os.path.join(os.path.dirname(__file__), "data", "*.jpg")))
21 | initial_bbox = [175, 154, 251, 229]
22 | tracker.track("ball", image_paths[0], initial_bbox)
23 | for image_path in image_paths:
24 | image = cv2.imread(image_path)
25 | # Tracker expects RGB, but opencv loads BGR.
26 | imageRGB = image[:, :, ::-1]
27 | bbox = tracker.track("ball", imageRGB)
28 | cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), [0, 0, 255], 2)
29 | cv2.imshow("Image", image)
30 | cv2.waitKey(1)
31 |
--------------------------------------------------------------------------------
/demo/sample_1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/demo/sample_1.gif
--------------------------------------------------------------------------------
/demo/sample_2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/demo/sample_2.gif
--------------------------------------------------------------------------------
/download_weights_large.sh:
--------------------------------------------------------------------------------
1 | mkdir -p logs
2 | cd logs
3 | echo "File size is 712 MB"
4 | gdown https://drive.google.com/uc?id=1J5LAnoxG_BCGanC9vObY5ETSrRH47B3_
5 | tar -zxvf checkpoints.tar.gz
6 | rm -rf checkpoints.tar.gz
7 |
--------------------------------------------------------------------------------
/download_weights_small.sh:
--------------------------------------------------------------------------------
1 | mkdir -p logs
2 | cd logs
3 | echo "File size is 440 MB"
4 | gdown https://drive.google.com/uc?id=1IEZKqee75EeX1K1aUvfZnE0KOZ44YHQf
5 | tar -zxvf checkpoints_small.tar.gz
6 | rm -rf checkpoints_small.tar.gz
7 |
--------------------------------------------------------------------------------
/env.yml:
--------------------------------------------------------------------------------
1 | name: re3-test
2 | channels:
3 | - pytorch
4 | - anaconda
5 | - conda-forge
6 | - defaults
7 | dependencies:
8 | - attrs=19.3.0
9 | - cudatoolkit=10.1.243
10 | - ffmpeg=4.2
11 | - freetype=2.9.1
12 | - imageio-ffmpeg=0.3.0
13 | - numpy=1.18.1
14 | - numpy-base=1.18.1
15 | - pip
16 | - py=1.8.1
17 | - python=3.6.8
18 | - pytorch=1.4.0
19 | - scikit-learn=0.21.2
20 | - scipy=1.3.2
21 | - torchvision=0.5.0
22 | - yaml=0.1.7
23 | - intel-openmp=2019.4
24 | - pip:
25 | - black==19.3b0
26 | - imageio==2.6.1
27 | - matplotlib==3.1.2
28 | - opencv-python==4.1.0.25
29 | - scikit-image==0.16.2
30 | - tqdm==4.32.2
31 | - gdown==3.11.0
32 | - tensorflow==1.5.0
33 |
--------------------------------------------------------------------------------
/re3_utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/re3_utils/__init__.py
--------------------------------------------------------------------------------
/re3_utils/python_util.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | from typing import List, Optional
4 |
5 | import imageio
6 | import numpy as np
7 | import tqdm
8 |
9 |
10 | def get_time_str():
11 | tt = time.localtime()
12 | time_str = "%04d_%02d_%02d_%02d_%02d_%02d" % (tt.tm_year, tt.tm_mon, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec)
13 | return time_str
14 |
15 |
16 | def images_to_video(
17 | images: List[np.ndarray], output_dir: str, video_name: str, fps: int = 10, quality: Optional[float] = 5, **kwargs
18 | ):
19 | """Calls imageio to run FFMPEG on a list of images. For more info on
20 | parameters, see
21 | https://imageio.readthedocs.io/en/stable/format_ffmpeg.html
22 | Args:
23 | images: The list of images. Images should be HxWx3 in RGB order.
24 | output_dir: The folder to put the video in.
25 | video_name: The navme for the video.
26 | fps: Frames per second for the video. Not all values work with FFMPEG,
27 | use at your own risk.
28 | quality: Default is 5. Uses variable bit rate. Highest quality is 10,
29 | lowest is 0. Set to None to prevent variable bitrate flags to
30 | FFMPEG so you can manually specify them using output_params instead.
31 | Specifying a fixed bitrate using ‘bitrate’ disables this parameter.
32 | """
33 | assert 0 <= quality <= 10
34 | if not os.path.exists(output_dir):
35 | os.makedirs(output_dir)
36 | video_name = os.path.join(output_dir, video_name.replace(" ", "_").replace("\n", "_") + ".mp4")
37 | print("Writing video to", video_name)
38 | writer = imageio.get_writer(video_name, fps=fps, quality=quality, **kwargs)
39 | for im in tqdm.tqdm(images):
40 | writer.append_data(im)
41 | writer.close()
42 |
--------------------------------------------------------------------------------
/re3_utils/pytorch_util/CaffeLSTMCell.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 |
5 |
6 | class CaffeLSTMCell(nn.Module):
7 | def __init__(self, input_size, output_size):
8 | super(CaffeLSTMCell, self).__init__()
9 |
10 | self.input_size = input_size
11 | self.output_size = output_size
12 |
13 | self.block_input = nn.Linear(input_size + output_size, output_size)
14 | self.input_gate = nn.Linear(input_size + output_size * 2, output_size)
15 | self.forget_gate = nn.Linear(input_size + output_size * 2, output_size)
16 | self.output_gate = nn.Linear(input_size + output_size * 2, output_size)
17 |
18 | def forward(self, inputs, hx=None):
19 | if hx is None or (hx[0] is None and hx[1] is None):
20 | zeros = torch.zeros(inputs.size(0), self.output_size, dtype=inputs.dtype, device=inputs.device)
21 | hx = (zeros, zeros)
22 |
23 | cell_outputs_prev, cell_state_prev = hx
24 |
25 | lstm_concat = torch.cat([inputs, cell_outputs_prev], 1)
26 | peephole_concat = torch.cat([lstm_concat, cell_state_prev], 1)
27 |
28 | block_input = torch.tanh(self.block_input(lstm_concat))
29 |
30 | input_gate = torch.sigmoid(self.input_gate(peephole_concat))
31 | input_mult = input_gate * block_input
32 |
33 | forget_gate = torch.sigmoid(self.forget_gate(peephole_concat))
34 | forget_mult = forget_gate * cell_state_prev
35 |
36 | cell_state_new = input_mult + forget_mult
37 | cell_state_activated = torch.tanh(cell_state_new)
38 |
39 | output_concat = torch.cat([lstm_concat, cell_state_new], 1)
40 | output_gate = torch.sigmoid(self.output_gate(output_concat))
41 | cell_outputs_new = output_gate * cell_state_activated
42 |
43 | return cell_outputs_new, cell_state_new
44 |
--------------------------------------------------------------------------------
/re3_utils/pytorch_util/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/re3_utils/pytorch_util/__init__.py
--------------------------------------------------------------------------------
/re3_utils/pytorch_util/dataloader.py:
--------------------------------------------------------------------------------
1 | # Copied from pytorch source. Please use their copyright.
2 |
3 | import torch
4 | import torch.multiprocessing as multiprocessing
5 | from torch.utils.data.sampler import SequentialSampler, RandomSampler, BatchSampler
6 | import collections
7 | import re
8 | import sys
9 | import traceback
10 | import threading
11 | from torch._six import string_classes
12 |
13 |
14 | if sys.version_info[0] == 2:
15 | import Queue as queue
16 | else:
17 | import queue
18 |
19 |
20 | _use_shared_memory = False
21 | """Whether to use shared memory in default_collate"""
22 |
23 |
24 | class ExceptionWrapper(object):
25 | "Wraps an exception plus traceback to communicate across threads"
26 |
27 | def __init__(self, exc_info):
28 | self.exc_type = exc_info[0]
29 | self.exc_msg = "".join(traceback.format_exception(*exc_info))
30 |
31 |
32 | def _worker_loop(dataset, index_queue, data_queue, collate_fn, init_fn, init_fn_args, worker_id):
33 | global _use_shared_memory
34 | _use_shared_memory = True
35 |
36 | if init_fn is not None:
37 | print("calling init fn")
38 | if init_fn_args is not None:
39 | init_fn(init_fn_args, worker_id)
40 | else:
41 | init_fn(worker_id)
42 |
43 | torch.set_num_threads(1)
44 | while True:
45 | r = index_queue.get()
46 | if r is None:
47 | data_queue.put(None)
48 | break
49 | idx, batch_indices = r
50 | try:
51 | samples = collate_fn([dataset[i] for i in batch_indices])
52 | except Exception:
53 | data_queue.put((idx, ExceptionWrapper(sys.exc_info())))
54 | else:
55 | data_queue.put((idx, samples))
56 |
57 |
58 | def _pin_memory_loop(in_queue, out_queue, done_event):
59 | while True:
60 | try:
61 | r = in_queue.get()
62 | except Exception:
63 | if done_event.is_set():
64 | return
65 | raise
66 | if r is None:
67 | break
68 | if isinstance(r[1], ExceptionWrapper):
69 | out_queue.put(r)
70 | continue
71 | idx, batch = r
72 | try:
73 | batch = pin_memory_batch(batch)
74 | except Exception:
75 | out_queue.put((idx, ExceptionWrapper(sys.exc_info())))
76 | else:
77 | out_queue.put((idx, batch))
78 |
79 |
80 | numpy_type_map = {
81 | "float64": torch.DoubleTensor,
82 | "float32": torch.FloatTensor,
83 | "float16": torch.HalfTensor,
84 | "int64": torch.LongTensor,
85 | "int32": torch.IntTensor,
86 | "int16": torch.ShortTensor,
87 | "int8": torch.CharTensor,
88 | "uint8": torch.ByteTensor,
89 | }
90 |
91 |
92 | def default_collate(batch):
93 | "Puts each data field into a tensor with outer dimension batch size"
94 |
95 | error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
96 | elem_type = type(batch[0])
97 | if torch.is_tensor(batch[0]):
98 | out = None
99 | if _use_shared_memory:
100 | # If we're in a background process, concatenate directly into a
101 | # shared memory tensor to avoid an extra copy
102 | numel = sum([x.numel() for x in batch])
103 | storage = batch[0].storage()._new_shared(numel)
104 | out = batch[0].new(storage)
105 | return torch.stack(batch, 0, out=out)
106 | elif elem_type.__module__ == "numpy" and elem_type.__name__ != "str_" and elem_type.__name__ != "string_":
107 | elem = batch[0]
108 | if elem_type.__name__ == "ndarray":
109 | # array of string classes and object
110 | if re.search("[SaUO]", elem.dtype.str) is not None:
111 | raise TypeError(error_msg.format(elem.dtype))
112 |
113 | return torch.stack([torch.from_numpy(b) for b in batch], 0)
114 | if elem.shape == (): # scalars
115 | py_type = float if elem.dtype.name.startswith("float") else int
116 | return numpy_type_map[elem.dtype.name](list(map(py_type, batch)))
117 | elif isinstance(batch[0], int):
118 | return torch.LongTensor(batch)
119 | elif isinstance(batch[0], float):
120 | return torch.DoubleTensor(batch)
121 | elif isinstance(batch[0], string_classes):
122 | return batch
123 | elif isinstance(batch[0], collections.Mapping):
124 | return {key: default_collate([d[key] for d in batch]) for key in batch[0]}
125 | elif isinstance(batch[0], collections.Sequence):
126 | transposed = zip(*batch)
127 | return [default_collate(samples) for samples in transposed]
128 |
129 | raise TypeError((error_msg.format(type(batch[0]))))
130 |
131 |
132 | def pin_memory_batch(batch):
133 | if torch.is_tensor(batch):
134 | return batch.pin_memory()
135 | elif isinstance(batch, string_classes):
136 | return batch
137 | elif isinstance(batch, collections.Mapping):
138 | return {k: pin_memory_batch(sample) for k, sample in batch.items()}
139 | elif isinstance(batch, collections.Sequence):
140 | return [pin_memory_batch(sample) for sample in batch]
141 | else:
142 | return batch
143 |
144 |
145 | class DataLoaderIter(object):
146 | "Iterates once over the DataLoader's dataset, as specified by the sampler"
147 |
148 | def __init__(self, loader):
149 | self.dataset = loader.dataset
150 | self.collate_fn = loader.collate_fn
151 | self.batch_sampler = loader.batch_sampler
152 | self.num_workers = loader.num_workers
153 | self.pin_memory = loader.pin_memory
154 | self.done_event = threading.Event()
155 |
156 | self.sample_iter = iter(self.batch_sampler)
157 |
158 | if self.num_workers > 0:
159 | self.worker_init_fn = loader.worker_init_fn
160 | self.worker_init_fn_args = loader.worker_init_fn_args
161 | self.index_queue = multiprocessing.SimpleQueue()
162 | self.data_queue = multiprocessing.SimpleQueue()
163 | self.batches_outstanding = 0
164 | self.shutdown = False
165 | self.send_idx = 0
166 | self.rcvd_idx = 0
167 | self.reorder_dict = {}
168 |
169 | self.workers = [
170 | multiprocessing.Process(
171 | target=_worker_loop,
172 | args=(
173 | self.dataset,
174 | self.index_queue,
175 | self.data_queue,
176 | self.collate_fn,
177 | self.worker_init_fn,
178 | self.worker_init_fn_args,
179 | i,
180 | ),
181 | )
182 | for i in range(self.num_workers)
183 | ]
184 |
185 | for w in self.workers:
186 | w.daemon = True # ensure that the worker exits on process exit
187 | w.start()
188 |
189 | if self.pin_memory:
190 | in_data = self.data_queue
191 | self.data_queue = queue.Queue()
192 | self.pin_thread = threading.Thread(
193 | target=_pin_memory_loop, args=(in_data, self.data_queue, self.done_event)
194 | )
195 | self.pin_thread.daemon = True
196 | self.pin_thread.start()
197 |
198 | # prime the prefetch loop
199 | for _ in range(2 * self.num_workers):
200 | self._put_indices()
201 |
202 | def __len__(self):
203 | return len(self.batch_sampler)
204 |
205 | def __next__(self):
206 | if self.num_workers == 0: # same-process loading
207 | indices = next(self.sample_iter) # may raise StopIteration
208 | batch = self.collate_fn([self.dataset[i] for i in indices])
209 | if self.pin_memory:
210 | batch = pin_memory_batch(batch)
211 | return batch
212 |
213 | # check if the next sample has already been generated
214 | if self.rcvd_idx in self.reorder_dict:
215 | batch = self.reorder_dict.pop(self.rcvd_idx)
216 | return self._process_next_batch(batch)
217 |
218 | if self.batches_outstanding == 0:
219 | self._shutdown_workers()
220 | raise StopIteration
221 |
222 | while True:
223 | assert not self.shutdown and self.batches_outstanding > 0
224 | idx, batch = self.data_queue.get()
225 | self.batches_outstanding -= 1
226 | if idx != self.rcvd_idx:
227 | # store out-of-order samples
228 | self.reorder_dict[idx] = batch
229 | continue
230 | return self._process_next_batch(batch)
231 |
232 | next = __next__ # Python 2 compatibility
233 |
234 | def __iter__(self):
235 | return self
236 |
237 | def _put_indices(self):
238 | assert self.batches_outstanding < 2 * self.num_workers
239 | indices = next(self.sample_iter, None)
240 | if indices is None:
241 | return
242 | self.index_queue.put((self.send_idx, indices))
243 | self.batches_outstanding += 1
244 | self.send_idx += 1
245 |
246 | def _process_next_batch(self, batch):
247 | self.rcvd_idx += 1
248 | self._put_indices()
249 | if isinstance(batch, ExceptionWrapper):
250 | raise batch.exc_type(batch.exc_msg)
251 | return batch
252 |
253 | def __getstate__(self):
254 | # TODO: add limited pickling support for sharing an iterator
255 | # across multiple threads for HOGWILD.
256 | # Probably the best way to do this is by moving the sample pushing
257 | # to a separate thread and then just sharing the data queue
258 | # but signalling the end is tricky without a non-blocking API
259 | raise NotImplementedError("DataLoaderIterator cannot be pickled")
260 |
261 | def _shutdown_workers(self):
262 | if not self.shutdown:
263 | self.shutdown = True
264 | self.done_event.set()
265 | for _ in self.workers:
266 | self.index_queue.put(None)
267 |
268 | def __del__(self):
269 | if self.num_workers > 0:
270 | self._shutdown_workers()
271 |
272 |
273 | class DataLoader(object):
274 | """
275 | Data loader. Combines a dataset and a sampler, and provides
276 | single- or multi-process iterators over the dataset.
277 |
278 | Arguments:
279 | dataset (Re3Dataset): dataset from which to load the data.
280 | batch_size (int, optional): how many samples per batch to load
281 | (default: 1).
282 | shuffle (bool, optional): set to ``True`` to have the data reshuffled
283 | at every epoch (default: False).
284 | sampler (Sampler, optional): defines the strategy to draw samples from
285 | the dataset. If specified, ``shuffle`` must be False.
286 | batch_sampler (Sampler, optional): like sampler, but returns a batch of
287 | indices at a time. Mutually exclusive with batch_size, shuffle,
288 | sampler, and drop_last.
289 | num_workers (int, optional): how many subprocesses to use for data
290 | loading. 0 means that the data will be loaded in the main process
291 | (default: 0)
292 | collate_fn (callable, optional): merges a list of samples to form a mini-batch.
293 | pin_memory (bool, optional): If ``True``, the data loader will copy tensors
294 | into CUDA pinned memory before returning them.
295 | drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
296 | if the dataset size is not divisible by the batch size. If ``False`` and
297 | the size of dataset is not divisible by the batch size, then the last batch
298 | will be smaller. (default: False)
299 | """
300 |
301 | def __init__(
302 | self,
303 | dataset,
304 | batch_size=1,
305 | shuffle=False,
306 | sampler=None,
307 | batch_sampler=None,
308 | num_workers=0,
309 | collate_fn=default_collate,
310 | pin_memory=False,
311 | drop_last=False,
312 | worker_init_fn=None,
313 | worker_init_fn_args=None,
314 | ):
315 | self.dataset = dataset
316 | self.batch_size = batch_size
317 | self.num_workers = num_workers
318 | self.collate_fn = collate_fn
319 | self.pin_memory = pin_memory
320 | self.drop_last = drop_last
321 | self.worker_init_fn = worker_init_fn
322 | self.worker_init_fn_args = worker_init_fn_args
323 |
324 | if batch_sampler is not None:
325 | if batch_size > 1 or shuffle or sampler is not None or drop_last:
326 | raise ValueError(
327 | "batch_sampler is mutually exclusive with " "batch_size, shuffle, sampler, and drop_last"
328 | )
329 |
330 | if sampler is not None and shuffle:
331 | raise ValueError("sampler is mutually exclusive with shuffle")
332 |
333 | if batch_sampler is None:
334 | if sampler is None:
335 | if shuffle:
336 | sampler = RandomSampler(dataset)
337 | else:
338 | sampler = SequentialSampler(dataset)
339 | batch_sampler = BatchSampler(sampler, batch_size, drop_last)
340 |
341 | self.sampler = sampler
342 | self.batch_sampler = batch_sampler
343 |
344 | def __iter__(self):
345 | return DataLoaderIter(self)
346 |
347 | def __len__(self):
348 | return len(self.batch_sampler)
349 |
--------------------------------------------------------------------------------
/re3_utils/pytorch_util/pytorch_util_functions.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import numbers
3 | import os
4 | import re
5 | from collections import defaultdict, OrderedDict
6 |
7 | import numpy as np
8 | import torch
9 | import torch.nn.functional as F
10 | from torch import nn
11 |
12 |
13 | def restore(net, save_file, saved_variable_prefix="", new_variable_prefix="", skip_filter=None):
14 | print("restoring from", save_file)
15 | try:
16 | with torch.no_grad():
17 | net_state_dict = net.state_dict()
18 | if torch.cuda.is_available():
19 | device = next(net.parameters()).device
20 | restore_state_dict = torch.load(save_file, device)
21 | else:
22 | restore_state_dict = torch.load(save_file, map_location="cpu")
23 |
24 | restored_var_names = set()
25 | new_var_names = set()
26 |
27 | print("Restoring:")
28 | for restore_var_name in restore_state_dict.keys():
29 | new_var_name = new_variable_prefix + restore_var_name[len(saved_variable_prefix) :]
30 | if skip_filter is not None and not skip_filter(new_var_name):
31 | print("Skipping", new_var_name, "due to skip_filter")
32 | continue
33 | if new_var_name in net_state_dict:
34 | var_size = net_state_dict[new_var_name].size()
35 | restore_size = restore_state_dict[restore_var_name].size()
36 | if var_size != restore_size:
37 | print("Shape mismatch for var", restore_var_name, "expected", var_size, "got", restore_size)
38 | else:
39 | if isinstance(net_state_dict[new_var_name], torch.nn.Parameter):
40 | # backwards compatibility for serialized parameters
41 | net_state_dict[new_var_name] = restore_state_dict[restore_var_name].data
42 | try:
43 | net_state_dict[new_var_name].copy_(restore_state_dict[restore_var_name])
44 | if len(saved_variable_prefix) > 0 or len(new_variable_prefix) > 0:
45 | print(
46 | str(restore_var_name)
47 | + " -> "
48 | + str(new_var_name)
49 | + " -> \t"
50 | + str(var_size)
51 | + " = "
52 | + str(int(np.prod(var_size) * 4 / 10 ** 6))
53 | + "MB"
54 | )
55 | else:
56 | print(
57 | str(restore_var_name)
58 | + " -> \t"
59 | + str(var_size)
60 | + " = "
61 | + str(int(np.prod(var_size) * 4 / 10 ** 6))
62 | + "MB"
63 | )
64 | restored_var_names.add(restore_var_name)
65 | new_var_names.add(new_var_name)
66 | except Exception as ex:
67 | print(
68 | "Exception while copying the parameter named {}, whose dimensions in the model are"
69 | " {} and whose dimensions in the checkpoint are {}, ...".format(
70 | restore_var_name, var_size, restore_size
71 | )
72 | )
73 | raise ex
74 |
75 | ignored_var_names = sorted(list(set(restore_state_dict.keys()) - restored_var_names))
76 | unset_var_names = sorted(list(set(net_state_dict.keys()) - new_var_names))
77 | print("")
78 | if len(ignored_var_names) == 0:
79 | print("Restored all variables")
80 | else:
81 | print("Did not restore:\n\t" + "\n\t".join(ignored_var_names))
82 | if len(unset_var_names) == 0:
83 | print("No new variables")
84 | else:
85 | print("Initialized but did not modify:\n\t" + "\n\t".join(unset_var_names))
86 |
87 | print("Restored %s" % save_file)
88 | except:
89 | print("Got exception while trying to restore")
90 | import traceback
91 |
92 | traceback.print_exc()
93 |
94 |
95 | def restore_from_folder(net, folder, saved_variable_prefix="", new_variable_prefix="", skip_filter=None):
96 | print("restoring from", folder)
97 | checkpoints = sorted(glob.glob(folder + "/*.pt"), key=os.path.getmtime)
98 | start_it = 0
99 | try:
100 | if len(checkpoints) > 0:
101 | restore(net, checkpoints[-1], saved_variable_prefix, new_variable_prefix, skip_filter)
102 | nums = re.findall(r"\d+", checkpoints[-1])
103 | start_it = int(nums[-1])
104 | else:
105 | print("No checkpoints found")
106 | except Exception as ex:
107 | print("could not parse epoch, assuming 0")
108 | return start_it
109 |
110 |
111 | def save(net, file_name, num_to_keep=1, iteration=None):
112 | if iteration is not None:
113 | file_name = os.path.join(file_name, "%09d.pt" % iteration)
114 | if not os.path.exists(os.path.dirname(file_name)):
115 | os.makedirs(os.path.dirname(file_name))
116 | torch.save(net.state_dict(), file_name)
117 | folder = os.path.dirname(file_name)
118 | checkpoints = sorted(glob.glob(folder + "/*.pt"), key=os.path.getmtime)
119 | print("Saved %s" % file_name)
120 | if num_to_keep > 0:
121 | for ff in checkpoints[:-num_to_keep]:
122 | os.remove(ff)
123 |
124 |
125 | def rename_network_variables(change_dict, filepath, new_basedir):
126 | state_dict = torch.load(filepath, map_location="cpu")
127 | new_state_dict = OrderedDict()
128 | for key, val in state_dict.items():
129 | found_match = False
130 | for bad_key in change_dict.keys():
131 | if key[: len(bad_key)] == bad_key:
132 | new_key = change_dict[bad_key] + key[len(bad_key) :]
133 | print(key + "\t->\t" + new_key)
134 | new_state_dict[new_key] = val
135 | found_match = True
136 | break
137 | if not found_match:
138 | new_state_dict[key] = val
139 |
140 | new_path = os.path.join(new_basedir, filepath)
141 | if not os.path.exists(os.path.dirname(new_path)):
142 | os.makedirs(os.path.dirname(new_path))
143 | torch.save(new_state_dict, new_path)
144 |
145 |
146 | def rename_many_networks_variables(change_dict, basedir, new_basedir="converted"):
147 | assert basedir != new_basedir, "This may cause problems with os.walk"
148 | for root, dirs, files in os.walk("logs"):
149 | for file in files:
150 | filename = os.path.join(root, file)
151 | if os.path.splitext(file)[1] == ".pt":
152 | rename_network_variables(change_dict, filename, new_basedir)
153 |
154 |
155 | def remove_dim_get_shape(curr_shape, dim):
156 | assert dim > 0, "Axis must be greater than 0"
157 | curr_shape = list(curr_shape)
158 | axis_shape = curr_shape.pop(dim)
159 | curr_shape[dim - 1] *= axis_shape
160 | return curr_shape
161 |
162 |
163 | def remove_dim(input_tensor, dim):
164 | curr_shape = list(input_tensor.shape)
165 | if type(dim) == int:
166 | new_shape = remove_dim_get_shape(curr_shape, dim)
167 | else:
168 | for ax in sorted(dim, reverse=True):
169 | curr_shape = remove_dim_get_shape(curr_shape, ax)
170 | new_shape = curr_shape
171 | return input_tensor.view(new_shape)
172 |
173 |
174 | class RemoveDim(nn.Module):
175 | def __init__(self, dim):
176 | super(RemoveDim, self).__init__()
177 | self.dim = dim
178 |
179 | def forward(self, input_tensor):
180 | return remove_dim(input_tensor, self.dim)
181 |
182 |
183 | def split_axis_get_shape(curr_shape, axis, d1, d2):
184 | assert axis < len(curr_shape), "Axis must be less than the current rank"
185 | curr_shape.insert(axis, d1)
186 | curr_shape[axis + 1] = d2
187 | return curr_shape
188 |
189 |
190 | def split_axis(input_tensor, axis, d1, d2):
191 | curr_shape = list(input_tensor.shape)
192 | new_shape = split_axis_get_shape(curr_shape, axis, d1, d2)
193 | return input_tensor.view(new_shape)
194 |
195 |
196 | def detatch_recursive(h):
197 | """Wraps hidden states in new Tensors, to detach them from their history."""
198 | if isinstance(h, torch.Tensor):
199 | return h.detach()
200 | else:
201 | return tuple(detatch_recursive(v) for v in h)
202 |
203 |
204 | def to_numpy_array(array):
205 | if isinstance(array, torch.Tensor):
206 | return array.detach().cpu().numpy()
207 | elif isinstance(array, dict):
208 | return {key: to_numpy_array(val) for key, val in array.items()}
209 | else:
210 | return np.asarray(array)
211 |
212 |
213 | numpy_dtype_to_pytorch_dtype_warn = False
214 |
215 |
216 | def numpy_dtype_to_pytorch_dtype(numpy_dtype):
217 | global numpy_dtype_to_pytorch_dtype_warn
218 | # Extremely gross conversion but the only one I've found
219 | numpy_dtype = np.dtype(numpy_dtype)
220 | if numpy_dtype == np.uint32:
221 | if not numpy_dtype_to_pytorch_dtype_warn:
222 | print("numpy -> torch dtype uint32 not supported, using int32")
223 | numpy_dtype_to_pytorch_dtype_warn = True
224 | numpy_dtype = np.int32
225 | return torch.from_numpy(np.zeros(0, dtype=numpy_dtype)).detach().dtype
226 |
227 |
228 | from_numpy_warn = defaultdict(lambda: False)
229 |
230 |
231 | def from_numpy(np_array):
232 | global from_numpy_warn
233 | np_array = np.asarray(np_array)
234 | if np_array.dtype == np.uint32:
235 | if not from_numpy_warn[np.uint32]:
236 | print("numpy -> torch dtype uint32 not supported, using int32")
237 | from_numpy_warn[np.uint32] = True
238 | np_array = np_array.astype(np.int32)
239 | elif np_array.dtype == np.dtype("O"):
240 | if not from_numpy_warn[np.dtype("O")]:
241 | print("numpy -> torch dtype Object not supported, returning numpy array")
242 | from_numpy_warn[np.dtype("O")] = True
243 | return np_array
244 | elif np_array.dtype.type == np.str_:
245 | if not from_numpy_warn[np.str_]:
246 | print("numpy -> torch dtype numpy.str_ not supported, returning numpy array")
247 | from_numpy_warn[np.str_] = True
248 | return np_array
249 | return torch.from_numpy(np_array)
250 |
251 |
252 | def weighted_loss(loss_function_output, weights, reduction="mean"):
253 | if isinstance(weights, numbers.Number):
254 | if reduction == "mean":
255 | return weights * torch.mean(loss_function_output)
256 | elif reduction == "sum":
257 | return weights * torch.sum(loss_function_output)
258 | else:
259 | return weights * loss_function_output
260 |
261 | elif weights.dtype == torch.uint8 and reduction != "none":
262 | if reduction == "mean":
263 | return torch.mean(torch.masked_select(loss_function_output, weights))
264 | else:
265 | return torch.sum(torch.masked_select(loss_function_output, weights))
266 | else:
267 | if reduction == "mean":
268 | return torch.mean(loss_function_output * weights)
269 | elif reduction == "sum":
270 | return torch.sum(loss_function_output * weights)
271 | else:
272 | return loss_function_output * weights
273 |
274 |
275 | def get_one_hot(data, num_inds, dtype=torch.float32):
276 | assert (data.max() < num_inds).item()
277 | placeholder = torch.zeros(data.shape + (num_inds,), device=data.device, dtype=dtype)
278 | placeholder_shape = placeholder.shape
279 | placeholder = placeholder.view(-1, num_inds)
280 | placeholder[torch.arange(data.numel()), data.view(-1)] = 1
281 | placeholder = placeholder.view(placeholder_shape)
282 | return placeholder
283 |
284 |
285 | def get_one_hot_numpy(data, num_inds, dtype=np.float32):
286 | data = np.asarray(data)
287 | assert data.max() < num_inds
288 | placeholder = np.zeros(data.shape + (num_inds,), dtype=dtype)
289 | placeholder_shape = placeholder.shape
290 | placeholder = placeholder.reshape(-1, num_inds)
291 | placeholder[np.arange(data.size), data.reshape(-1)] = 1
292 | placeholder = placeholder.reshape(placeholder_shape)
293 | return placeholder
294 |
295 |
296 | surfnorm_kernel = None
297 |
298 |
299 | def depth_to_surface_normals(depth, surfnorm_scalar=256):
300 | global surfnorm_kernel
301 | if surfnorm_kernel is None:
302 | surfnorm_kernel = torch.from_numpy(
303 | np.array(
304 | [
305 | [[1, 2, 1], [0, 0, 0], [-1, -2, -1]],
306 | [[1, 0, -1], [2, 0, -2], [1, 0, -1]],
307 | [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
308 | ]
309 | )
310 | )[:, np.newaxis, ...].to(dtype=torch.float32, device=depth.device)
311 | with torch.no_grad():
312 | surface_normals = F.conv2d(depth, surfnorm_scalar * surfnorm_kernel, padding=1)
313 | surface_normals[:, 2, ...] = 1
314 | surface_normals = surface_normals / surface_normals.norm(dim=1, keepdim=True)
315 | return surface_normals
316 |
317 |
318 | def multi_class_cross_entropy_loss(predictions, labels, reduction="mean", dim=-1):
319 | # Predictions should be logits, labels should be probabilities.
320 | loss = labels * F.log_softmax(predictions, dim=dim)
321 | if reduction == "none":
322 | return -1 * loss
323 | elif reduction == "mean":
324 | return -1 * torch.mean(loss) * predictions.shape[dim] # mean across all dimensions except softmax one.
325 | elif reduction == "sum":
326 | return -1 * torch.sum(loss)
327 | else:
328 | raise NotImplementedError("Not known reduction type")
329 |
330 |
331 | class Flatten(nn.Module):
332 | def forward(self, x):
333 | return x.view(x.size(0), -1)
334 |
335 |
336 | class DummyScope(nn.Module):
337 | """Used for keeping scope the same between pretrain and interactive training."""
338 |
339 | def __init__(self, module, scope_list):
340 | super(DummyScope, self).__init__()
341 | assert isinstance(scope_list, list) and len(scope_list) > 0
342 | self.scope_list = scope_list
343 | if len(scope_list) > 1:
344 | setattr(self, scope_list[0], DummyScope(module, scope_list[1:]))
345 | elif len(scope_list) == 1:
346 | setattr(self, scope_list[0], module)
347 |
348 | def forward(self, *input, **kwargs):
349 | return getattr(self, self.scope_list[0])(*input, **kwargs)
350 |
351 |
352 | def get_data_parallel(module, device_ids):
353 | if device_ids is None or len(device_ids) == 1:
354 | return DummyScope(module, ["module"])
355 | else:
356 | print("Torch using", len(device_ids), "GPUs", device_ids)
357 | return torch.nn.DataParallel(module, device_ids=device_ids)
358 |
359 |
360 | def reset_module(module):
361 | module_list = [sub_mod for sub_mod in module.modules()]
362 | ss = 0
363 | while ss < len(module_list):
364 | sub_mod = module_list[ss]
365 | if hasattr(sub_mod, "reset_parameters"):
366 | sub_mod.reset_parameters()
367 | ss += len([_ for _ in sub_mod.modules()])
368 | else:
369 | ss += 1
370 |
371 |
372 | def normalize(input_tensor, mean, std=None):
373 | mean = from_numpy(mean).to(input_tensor.device, input_tensor.dtype)
374 | if std is not None:
375 | std = from_numpy(std).to(input_tensor.device, input_tensor.dtype)
376 | input_tensor = input_tensor - mean
377 | if std is not None:
378 | input_tensor = input_tensor / std
379 | return input_tensor
380 |
381 |
382 | def setup_devices(devices):
383 | if not torch.cuda.is_available():
384 | raise Exception("Cuda not found")
385 | torch_devices = [int(gpu_id.strip()) for gpu_id in str(devices).split(",")]
386 | devices = ["cuda:" + str(device) for device in torch_devices]
387 | return devices
388 |
--------------------------------------------------------------------------------
/re3_utils/pytorch_util/tensorboard_logger.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import numpy as np
4 | import scipy.misc
5 | import tensorflow as tf
6 |
7 | try:
8 | from StringIO import StringIO # Python 2.7
9 | except ImportError:
10 | from io import BytesIO as StringIO # Python 3.x
11 |
12 |
13 | def kernel_to_image(data, padsize=1):
14 | """Turns a convolutional kernel into an image of nicely tiled filters.
15 | :param data: numpy array in format N x C x H x W.
16 | :param padsize: optional int to indicate visual padding between the filters.
17 | :return: image of the filters in a tiled/mosaic layout
18 | """
19 | if len(data.shape) > 4:
20 | data = np.squeeze(data)
21 | data = np.transpose(data, (0, 2, 3, 1))
22 | data_shape = tuple(data.shape)
23 | min_val = np.min(np.reshape(data, (data_shape[0], -1)), axis=1)
24 | data = np.transpose((np.transpose(data, (1, 2, 3, 0)) - min_val), (3, 0, 1, 2))
25 | max_val = np.max(np.reshape(data, (data_shape[0], -1)), axis=1)
26 | data = np.transpose((np.transpose(data, (1, 2, 3, 0)) / max_val), (3, 0, 1, 2))
27 |
28 | n = int(np.ceil(np.sqrt(data_shape[0])))
29 | ndim = len(data.shape)
30 | padding = ((0, n ** 2 - data_shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (ndim - 3)
31 | data = np.pad(data, padding, mode="constant", constant_values=0)
32 | # tile the filters into an image
33 | data_shape = data.shape
34 | data = np.transpose(np.reshape(data, ((n, n) + data_shape[1:])), ((0, 2, 1, 3) + tuple(range(4, ndim + 1))))
35 | data_shape = data.shape
36 | data = np.reshape(data, ((n * data_shape[1], n * data_shape[3]) + data_shape[4:]))
37 | return (data * 255).astype(np.uint8)
38 |
39 |
40 | class SummaryWriter(tf.summary.FileWriter):
41 | def __init__(self, path):
42 | if not os.path.exists(path):
43 | os.makedirs(path)
44 | super(SummaryWriter, self).__init__(path)
45 | import threading
46 |
47 | self.lock = threading.Lock()
48 | self.count = 0
49 |
50 | def add_summary(self, summary, global_step=None, increment_step_counter=True):
51 | self.lock.acquire()
52 | if global_step is None:
53 | global_step = 0
54 | if self.count < global_step:
55 | self.count = global_step
56 | elif increment_step_counter:
57 | self.count += 1
58 | super(SummaryWriter, self).add_summary(summary, self.count)
59 | self.flush()
60 | self.lock.release()
61 |
62 | def increment(self):
63 | self.lock.acquire()
64 | self.count += 1
65 | self.lock.release()
66 |
67 |
68 | # Code referenced from https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514
69 | class Logger(object):
70 | def __init__(self, log_dir):
71 | """Create a summary writer logging to log_dir."""
72 | self.writer = SummaryWriter(log_dir)
73 |
74 | @property
75 | def count(self):
76 | return self.writer.count
77 |
78 | @count.setter
79 | def count(self, new_count):
80 | if self.writer.count < new_count:
81 | self.writer.count = new_count
82 |
83 | def multi_scalar_log(self, tags, values, step):
84 | for tag, value in zip(tags, values):
85 | summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])
86 | self.writer.add_summary(summary, step, False)
87 | self.writer.increment()
88 |
89 | def dict_log(self, items_to_log, step):
90 | tags, values = zip(*items_to_log.items())
91 | self.multi_scalar_log(tags, values, step)
92 |
93 | def scalar_summary(self, tag, value, step, increment_counter):
94 | """Log a scalar variable."""
95 | summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])
96 | self.writer.add_summary(summary, step, increment_counter)
97 |
98 | def network_conv_summary(self, network, step):
99 | for ii, (name, val) in enumerate(network.state_dict().items()):
100 | val = val.detach().cpu().numpy()
101 | name = "layer_%03d/" % ii + name
102 | if len(val.squeeze().shape) == 4:
103 | self.conv_variable_summaries(val, step, name, False)
104 | else:
105 | self.variable_summaries(val, step, name, False)
106 | self.writer.increment()
107 |
108 | def network_variable_summary(self, network, step):
109 | for ii, (name, val) in enumerate(network.state_dict().items()):
110 | name = "layer_%03d/" % ii + name
111 | val = val.detach().cpu().numpy()
112 | self.variable_summaries(val, step, name, False)
113 | self.writer.increment()
114 |
115 | def variable_summaries(self, var, step, scope="", increment_counter=True):
116 | # Some useful stats for variables.
117 | if len(scope) > 0:
118 | scope = "/" + scope
119 | scope = "summaries" + scope
120 | mean = np.mean(np.abs(var))
121 | self.scalar_summary(scope + "/mean_abs", mean, step, increment_counter)
122 |
123 | def conv_variable_summaries(self, var, step, scope="", increment_counter=True):
124 | # Useful stats for variables and the kernel images.
125 | self.variable_summaries(var, step, scope, increment_counter)
126 | if len(scope) > 0:
127 | scope = "/" + scope
128 | scope = "conv_summaries" + scope + "/filters"
129 | var_shape = var.shape
130 | if not (var_shape[0] == 1 and var_shape[1] == 1):
131 | if var_shape[2] < 3:
132 | var = np.tile(var, [1, 1, 3, 1])
133 | var_shape = var.shape
134 | summary_image = kernel_to_image(var[:, :3, :, :])[np.newaxis, ...]
135 | self.image_summary(scope, summary_image, step, increment_counter)
136 |
137 | def image_summary(self, tag, images, step, increment_counter):
138 | """Log a list of images."""
139 |
140 | img_summaries = []
141 | for i, img in enumerate(images):
142 | # Write the image to a string
143 | s = StringIO()
144 | scipy.misc.toimage(img).save(s, format="png")
145 |
146 | # Create an Image object
147 | img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1])
148 | # Create a Summary value
149 | img_summaries.append(tf.Summary.Value(tag="%s/%d" % (tag, i), image=img_sum))
150 |
151 | # Create and write Summary
152 | summary = tf.Summary(value=img_summaries)
153 | self.writer.add_summary(summary, step, increment_counter)
154 |
155 | def histo_summary(self, tag, values, step, bins=1000, increment_counter=True):
156 | """Log a histogram of the tensor of values."""
157 |
158 | # Create a histogram using numpy
159 | counts, bin_edges = np.histogram(values, bins=bins)
160 |
161 | # Fill the fields of the histogram proto
162 | hist = tf.HistogramProto()
163 | hist.min = float(np.min(values))
164 | hist.max = float(np.max(values))
165 | hist.num = int(np.prod(values.shape))
166 | hist.sum = float(np.sum(values))
167 | hist.sum_squares = float(np.sum(values ** 2))
168 |
169 | # Drop the start of the first bin
170 | bin_edges = bin_edges[1:]
171 |
172 | # Add bin edges and counts
173 | for edge in bin_edges:
174 | hist.bucket_limit.append(edge)
175 | for c in counts:
176 | hist.bucket.append(c)
177 |
178 | # Create and write Summary
179 | summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)])
180 | self.writer.add_summary(summary, step, increment_counter)
181 | self.writer.flush()
182 |
--------------------------------------------------------------------------------
/re3_utils/util/IOU.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | """
4 | @rects1 numpy dx4 matrix of bounding boxes
5 | @rect2 single numpy 1x4 matrix of bounding box
6 | @return dx1 IOUs
7 | Rectangles are [x1, y1, x2, y2]
8 | """
9 |
10 |
11 | def IOU_numpy(rects1, rect2):
12 | # intersection = np.fmin(np.zeros((rects1.shape[0],1))
13 | (d, n) = rects1.shape
14 | x1s = np.fmax(rects1[:, 0], rect2[0])
15 | x2s = np.fmin(rects1[:, 2], rect2[2])
16 | y1s = np.fmax(rects1[:, 1], rect2[1])
17 | y2s = np.fmin(rects1[:, 3], rect2[3])
18 | ws = np.fmax(x2s - x1s, 0)
19 | hs = np.fmax(y2s - y1s, 0)
20 | intersection = ws * hs
21 | rects1Area = (rects1[:, 2] - rects1[:, 0]) * (rects1[:, 3] - rects1[:, 1])
22 | rect2Area = (rect2[2] - rect2[0]) * (rect2[3] - rect2[1])
23 | union = np.fmax(rects1Area + rect2Area - intersection, 0.00001)
24 | return intersection * 1.0 / union
25 |
26 |
27 | def IOU_lists(rects1, rects2):
28 | (d, n) = rects1.shape
29 | x1s = np.fmax(rects1[:, 0], rects2[:, 0])
30 | x2s = np.fmin(rects1[:, 2], rects2[:, 2])
31 | y1s = np.fmax(rects1[:, 1], rects2[:, 1])
32 | y2s = np.fmin(rects1[:, 3], rects2[:, 3])
33 | ws = np.fmax(x2s - x1s, 0)
34 | hs = np.fmax(y2s - y1s, 0)
35 | intersection = ws * hs
36 | rects1Area = (rects1[:, 2] - rects1[:, 0]) * (rects1[:, 3] - rects1[:, 1])
37 | rects2Area = (rects2[:, 2] - rects2[:, 0]) * (rects2[:, 3] - rects2[:, 1])
38 | union = np.fmax(rects1Area + rects2Area - intersection, 0.00001)
39 | return intersection * 1.0 / union
40 |
41 |
42 | # Rectangles are [x1, y1, x2, y2]
43 | def IOU(rect1, rect2):
44 | if not isinstance(rect1, np.ndarray):
45 | rect1 = np.array(rect1)
46 | if not isinstance(rect2, np.ndarray):
47 | rect2 = np.array(rect2)
48 | rect1 = [min(rect1[[0, 2]]), min(rect1[[1, 3]]), max(rect1[[0, 2]]), max(rect1[[1, 3]])]
49 | rect2 = [min(rect2[[0, 2]]), min(rect2[[1, 3]]), max(rect2[[0, 2]]), max(rect2[[1, 3]])]
50 | intersection = max(0, min(rect1[2], rect2[2]) - max(rect1[0], rect2[0])) * max(
51 | 0, min(rect1[3], rect2[3]) - max(rect1[1], rect2[1])
52 | )
53 |
54 | union = (rect1[2] - rect1[0]) * (rect1[3] - rect1[1]) + (rect2[2] - rect2[0]) * (rect2[3] - rect2[1]) - intersection
55 |
56 | return intersection * 1.0 / max(union, 0.00001)
57 |
58 |
59 | def intersection(rect1, rect2):
60 | return max(0, min(rect1[2], rect2[2]) - max(rect1[0], rect2[0])) * max(
61 | 0, min(rect1[3], rect2[3]) - max(rect1[1], rect2[1])
62 | )
63 |
64 |
65 | """
66 | @rects1 numpy dx5 matrix of bounding boxes
67 | @rect2 single numpy 1x4 matrix of bounding box
68 | @return nx5 rects where n is number of rects over overlapThresh
69 | Rectangles are [x1, y1, x2, y2, 0]
70 | """
71 |
72 |
73 | def get_overlapping_boxes(rects1, rect2, overlapThresh=0.001):
74 | x1s = np.fmax(rects1[:, 0], rect2[0])
75 | x2s = np.fmin(rects1[:, 2], rect2[2])
76 | y1s = np.fmax(rects1[:, 1], rect2[1])
77 | y2s = np.fmin(rects1[:, 3], rect2[3])
78 | ws = np.fmax(x2s - x1s, 0)
79 | hs = np.fmax(y2s - y1s, 0)
80 | intersection = ws * hs
81 | rects1Area = (rects1[:, 2] - rects1[:, 0]) * (rects1[:, 3] - rects1[:, 1])
82 | rect2Area = (rect2[2] - rect2[0]) * (rect2[3] - rect2[1])
83 | union = np.fmax(rects1Area + rect2Area - intersection, 0.00001)
84 | ious = intersection * 1.0 / union
85 | rects1[:, 4] = ious
86 | rects1 = rects1[ious > overlapThresh, :]
87 | return rects1
88 |
89 |
90 | """
91 | @rects1 numpy dx4 matrix of bounding boxes
92 | @rect2 single numpy 1x4 matrix of bounding box
93 | @return number of rects over overlapThresh
94 | Rectangles are [x1, y1, x2, y2]
95 | """
96 |
97 |
98 | def count_overlapping_boxes(rects1, rect2, overlapThresh=0.001):
99 | if rects1.shape[1] == 0:
100 | return 0
101 | x1s = np.fmax(rects1[:, 0], rect2[0])
102 | x2s = np.fmin(rects1[:, 2], rect2[2])
103 | y1s = np.fmax(rects1[:, 1], rect2[1])
104 | y2s = np.fmin(rects1[:, 3], rect2[3])
105 | ws = np.fmax(x2s - x1s, 0)
106 | hs = np.fmax(y2s - y1s, 0)
107 | intersection = ws * hs
108 | rects1Area = (rects1[:, 2] - rects1[:, 0]) * (rects1[:, 3] - rects1[:, 1])
109 | rect2Area = (rect2[2] - rect2[0]) * (rect2[3] - rect2[1])
110 | union = np.fmax(rects1Area + rect2Area - intersection, 0.00001)
111 | ious = intersection * 1.0 / union
112 | return np.sum(ious > overlapThresh)
113 |
--------------------------------------------------------------------------------
/re3_utils/util/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/re3_utils/util/__init__.py
--------------------------------------------------------------------------------
/re3_utils/util/bb_util.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import numbers
3 |
4 | LIMIT = 99999999
5 |
6 | # BBoxes are [x1, y1, x2, y2]
7 | def clip_bbox(bboxes, minClip, maxXClip, maxYClip):
8 | bboxesOut = bboxes
9 | addedAxis = False
10 | if len(bboxesOut.shape) == 1:
11 | addedAxis = True
12 | bboxesOut = bboxesOut[:, np.newaxis]
13 | bboxesOut[[0, 2], ...] = np.clip(bboxesOut[[0, 2], ...], minClip, maxXClip)
14 | bboxesOut[[1, 3], ...] = np.clip(bboxesOut[[1, 3], ...], minClip, maxYClip)
15 | if addedAxis:
16 | bboxesOut = bboxesOut[:, 0]
17 | return bboxesOut
18 |
19 |
20 | # [x1 y1, x2, y2] to [xMid, yMid, width, height]
21 | def xyxy_to_xywh(bboxes, clipMin=-LIMIT, clipWidth=LIMIT, clipHeight=LIMIT, round=False):
22 | addedAxis = False
23 | if isinstance(bboxes, list):
24 | bboxes = np.array(bboxes).astype(np.float32)
25 | if len(bboxes.shape) == 1:
26 | addedAxis = True
27 | bboxes = bboxes[:, np.newaxis]
28 | bboxesOut = np.zeros(bboxes.shape)
29 | x1 = bboxes[0, ...]
30 | y1 = bboxes[1, ...]
31 | x2 = bboxes[2, ...]
32 | y2 = bboxes[3, ...]
33 | bboxesOut[0, ...] = (x1 + x2) / 2.0
34 | bboxesOut[1, ...] = (y1 + y2) / 2.0
35 | bboxesOut[2, ...] = x2 - x1
36 | bboxesOut[3, ...] = y2 - y1
37 | if clipMin != -LIMIT or clipWidth != LIMIT or clipHeight != LIMIT:
38 | bboxesOut = clip_bbox(bboxesOut, clipMin, clipWidth, clipHeight)
39 | if bboxesOut.shape[0] > 4:
40 | bboxesOut[4:, ...] = bboxes[4:, ...]
41 | if addedAxis:
42 | bboxesOut = bboxesOut[:, 0]
43 | if round:
44 | bboxesOut = np.round(bboxesOut).astype(int)
45 | return bboxesOut
46 |
47 |
48 | # [xMid, yMid, width, height] to [x1 y1, x2, y2]
49 | def xywh_to_xyxy(bboxes, clipMin=-LIMIT, clipWidth=LIMIT, clipHeight=LIMIT, round=False):
50 | addedAxis = False
51 | if isinstance(bboxes, list):
52 | bboxes = np.array(bboxes).astype(np.float32)
53 | if len(bboxes.shape) == 1:
54 | addedAxis = True
55 | bboxes = bboxes[:, np.newaxis]
56 | bboxesOut = np.zeros(bboxes.shape)
57 | xMid = bboxes[0, ...]
58 | yMid = bboxes[1, ...]
59 | width = bboxes[2, ...]
60 | height = bboxes[3, ...]
61 | bboxesOut[0, ...] = xMid - width / 2.0
62 | bboxesOut[1, ...] = yMid - height / 2.0
63 | bboxesOut[2, ...] = xMid + width / 2.0
64 | bboxesOut[3, ...] = yMid + height / 2.0
65 | if clipMin != -LIMIT or clipWidth != LIMIT or clipHeight != LIMIT:
66 | bboxesOut = clip_bbox(bboxesOut, clipMin, clipWidth, clipHeight)
67 | if bboxesOut.shape[0] > 4:
68 | bboxesOut[4:, ...] = bboxes[4:, ...]
69 | if addedAxis:
70 | bboxesOut = bboxesOut[:, 0]
71 | if round:
72 | bboxesOut = np.round(bboxesOut).astype(int)
73 | return bboxesOut
74 |
75 |
76 | # @bboxes {np.array} 4xn array of boxes to be scaled
77 | # @scalars{number or arraylike} scalars for width and height of boxes
78 | # @in_place{bool} If false, creates new bboxes.
79 | def scale_bbox(bboxes, scalars, clipMin=-LIMIT, clipWidth=LIMIT, clipHeight=LIMIT, round=False, in_place=False):
80 | addedAxis = False
81 | if isinstance(bboxes, list):
82 | bboxes = np.array(bboxes, dtype=np.float32)
83 | if len(bboxes.shape) == 1:
84 | addedAxis = True
85 | bboxes = bboxes[:, np.newaxis]
86 | if isinstance(scalars, numbers.Number):
87 | scalars = np.full((2, bboxes.shape[1]), scalars, dtype=np.float32)
88 | if not isinstance(scalars, np.ndarray):
89 | scalars = np.array(scalars, dtype=np.float32)
90 | if len(scalars.shape) == 1:
91 | scalars = np.tile(scalars[:, np.newaxis], (1, bboxes.shape[1])).astype(np.float32)
92 |
93 | bboxes = bboxes.astype(np.float32)
94 |
95 | width = bboxes[2, ...] - bboxes[0, ...]
96 | height = bboxes[3, ...] - bboxes[1, ...]
97 | xMid = (bboxes[0, ...] + bboxes[2, ...]) / 2.0
98 | yMid = (bboxes[1, ...] + bboxes[3, ...]) / 2.0
99 | if not in_place:
100 | bboxesOut = bboxes.copy()
101 | else:
102 | bboxesOut = bboxes
103 |
104 | bboxesOut[0, ...] = xMid - width * scalars[0, ...] / 2.0
105 | bboxesOut[1, ...] = yMid - height * scalars[1, ...] / 2.0
106 | bboxesOut[2, ...] = xMid + width * scalars[0, ...] / 2.0
107 | bboxesOut[3, ...] = yMid + height * scalars[1, ...] / 2.0
108 |
109 | if clipMin != -LIMIT or clipWidth != LIMIT or clipHeight != LIMIT:
110 | bboxesOut = clip_bbox(bboxesOut, clipMin, clipWidth, clipHeight)
111 | if addedAxis:
112 | bboxesOut = bboxesOut[:, 0]
113 | if round:
114 | bboxesOut = np.round(bboxesOut).astype(np.int32)
115 | return bboxesOut
116 |
117 |
118 | def make_square(bboxes, in_place=False):
119 | if isinstance(bboxes, list):
120 | bboxes = np.array(bboxes).astype(np.float32)
121 | if len(bboxes.shape) == 1:
122 | numBoxes = 1
123 | width = bboxes[2] - bboxes[0]
124 | height = bboxes[3] - bboxes[1]
125 | else:
126 | numBoxes = bboxes.shape[1]
127 | width = bboxes[2, ...] - bboxes[0, ...]
128 | height = bboxes[3, ...] - bboxes[1, ...]
129 | maxSize = np.maximum(width, height)
130 | scalars = np.zeros((2, numBoxes))
131 | scalars[0, ...] = maxSize * 1.0 / width
132 | scalars[1, ...] = maxSize * 1.0 / height
133 | return scale_bbox(bboxes, scalars, in_place=in_place)
134 |
135 |
136 | # Converts from the full image coordinate system to range 0:crop_padding. Useful for getting the coordinates
137 | # of a bounding box from image coordinates to the location within the cropped image.
138 | # @bbox_to_change xyxy bbox whose coordinates will be converted to the new reference frame
139 | # @crop_location xyxy box of the new origin and max points (without padding)
140 | # @crop_padding the amount to pad the crop_location box (1 would be keep it the same, 2 would be doubled)
141 | # @crop_size the maximum size of the coordinate frame of bbox_to_change.
142 | def to_crop_coordinate_system(bbox_to_change, crop_location, crop_padding, crop_size):
143 | if isinstance(bbox_to_change, list):
144 | bbox_to_change = np.array(bbox_to_change)
145 | if isinstance(crop_location, list):
146 | crop_location = np.array(crop_location)
147 | bbox_to_change = bbox_to_change.astype(np.float32)
148 | crop_location = crop_location.astype(np.float32)
149 |
150 | crop_location = scale_bbox(crop_location, crop_padding)
151 | crop_location_xywh = xyxy_to_xywh(crop_location)
152 | bbox_to_change -= crop_location[[0, 1, 0, 1]]
153 | bbox_to_change *= crop_size / crop_location_xywh[[2, 3, 2, 3]]
154 | return bbox_to_change
155 |
156 |
157 | # Inverts the transformation from to_crop_coordinate_system
158 | # @crop_size the maximum size of the coordinate frame of bbox_to_change.
159 | def from_crop_coordinate_system(bbox_to_change, crop_location, crop_padding, crop_size):
160 | if isinstance(bbox_to_change, list):
161 | bbox_to_change = np.array(bbox_to_change)
162 | if isinstance(crop_location, list):
163 | crop_location = np.array(crop_location)
164 | bbox_to_change = bbox_to_change.astype(np.float32)
165 | crop_location = crop_location.astype(np.float32)
166 |
167 | crop_location = scale_bbox(crop_location, crop_padding)
168 | crop_location_xywh = xyxy_to_xywh(crop_location)
169 | bbox_to_change *= crop_location_xywh[[2, 3, 2, 3]] / crop_size
170 | bbox_to_change += crop_location[[0, 1, 0, 1]]
171 | return bbox_to_change
172 |
--------------------------------------------------------------------------------
/re3_utils/util/drawing.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 |
4 | BORDER = 0
5 | CV_FONT = cv2.FONT_HERSHEY_DUPLEX
6 |
7 | # plots: array of numpy array images to plot. Can be of different sizes and dimensions as long as they are 2 or 3 dimensional.
8 | # rows: int number of rows in subplot. If there are fewer images than rows, it will add empty space for the blanks.
9 | # if there are fewer rows than images, it will not draw the remaining images.
10 | # cols: int number of columns in subplot. Similar to rows.
11 | # outputWidth: int width in pixels of a single subplot output image.
12 | # outputHeight: int height in pixels of a single subplot output image.
13 | # border: int amount of border padding pixels between each image.
14 | # titles: titles for each subplot to be rendered on top of images.
15 | # fancy_text: if true, uses a fancier font than CV_FONT, but takes longer to render.
16 | def subplot(plots, rows, cols, outputWidth, outputHeight, border=BORDER, titles=None, fancy_text=False):
17 | returnedImage = np.full(
18 | ((outputHeight + 2 * border) * rows, (outputWidth + 2 * border) * cols, 3), 191, dtype=np.uint8
19 | )
20 | if fancy_text:
21 | from PIL import Image, ImageDraw, ImageFont
22 |
23 | FANCY_FONT = ImageFont.truetype("/usr/share/fonts/truetype/roboto/hinted/Roboto-Bold.ttf", 20)
24 | for row in range(rows):
25 | for col in range(cols):
26 | if col + cols * row >= len(plots):
27 | return returnedImage
28 | im = plots[col + cols * row]
29 | if im is None:
30 | continue
31 | if im.dtype != np.uint8 or len(im.shape) < 3:
32 | im = im.astype(np.float32)
33 | im -= np.min(im)
34 | im *= 255 / max(np.max(im), 0.0001)
35 | im = 255 - im.astype(np.uint8)
36 | if len(im.shape) < 3:
37 | im = cv2.applyColorMap(im, cv2.COLORMAP_JET)
38 | if im.shape != (outputHeight, outputWidth, 3):
39 | imWidth = im.shape[1] * outputHeight / im.shape[0]
40 | if imWidth > outputWidth:
41 | imWidth = outputWidth
42 | imHeight = im.shape[0] * outputWidth / im.shape[1]
43 | else:
44 | imWidth = im.shape[1] * outputHeight / im.shape[0]
45 | imHeight = outputHeight
46 | imWidth = int(imWidth)
47 | imHeight = int(imHeight)
48 | im = cv2.resize(im, (imWidth, imHeight), interpolation=cv2.INTER_NEAREST)
49 | if imWidth != outputWidth:
50 | pad0 = int(np.floor((outputWidth - imWidth) * 1.0 / 2))
51 | pad1 = int(np.ceil((outputWidth - imWidth) * 1.0 / 2))
52 | im = np.lib.pad(im, ((0, 0), (pad0, pad1), (0, 0)), "constant", constant_values=0)
53 | elif imHeight != outputHeight:
54 | pad0 = int(np.floor((outputHeight - imHeight) * 1.0 / 2))
55 | pad1 = int(np.ceil((outputHeight - imHeight) * 1.0 / 2))
56 | im = np.lib.pad(im, ((pad0, pad1), (0, 0), (0, 0)), "constant", constant_values=0)
57 | if (
58 | titles is not None
59 | and len(titles) > 1
60 | and len(titles) > col + cols * row
61 | and len(titles[col + cols * row]) > 0
62 | ):
63 | if fancy_text:
64 | if im.dtype != np.uint8:
65 | im = im.astype(np.uint8)
66 | im = Image.fromarray(im)
67 | draw = ImageDraw.Draw(im)
68 | for x in range(9, 12):
69 | for y in range(9, 12):
70 | draw.text((x, y), titles[col + cols * row], (0, 0, 0), font=FANCY_FONT)
71 | draw.text((10, 10), titles[col + cols * row], (255, 255, 255), font=FANCY_FONT)
72 | im = np.array(im)
73 | else:
74 | cv2.putText(im, titles[col + cols * row], (10, 30), CV_FONT, 0.5, [0, 0, 0], 4)
75 | cv2.putText(im, titles[col + cols * row], (10, 30), CV_FONT, 0.5, [255, 255, 255], 1)
76 | returnedImage[
77 | border + (outputHeight + border) * row : (outputHeight + border) * (row + 1),
78 | border + (outputWidth + border) * col : (outputWidth + border) * (col + 1),
79 | :,
80 | ] = im
81 | im = returnedImage
82 | # for one long title
83 | if titles is not None and len(titles) == 1:
84 | if fancy_text:
85 | if im.dtype != np.uint8:
86 | im = im.astype(np.uint8)
87 | im = Image.fromarray(im)
88 | draw = ImageDraw.Draw(im)
89 | for x in range(9, 12):
90 | for y in range(9, 12):
91 | draw.text((x, y), titles[0], (0, 0, 0), font=FANCY_FONT)
92 | draw.text((10, 10), titles[0], (255, 255, 255), font=FANCY_FONT)
93 | im = np.array(im)
94 | else:
95 | cv2.putText(im, titles[0], (10, 30), CV_FONT, 0.5, [0, 0, 0], 4)
96 | cv2.putText(im, titles[0], (10, 30), CV_FONT, 0.5, [255, 255, 255], 1)
97 |
98 | return im
99 |
100 |
101 | # BBoxes are [x1 y1 x2 y2]
102 | def drawRect(image, bbox, padding, color):
103 | from my_utils.util import bb_util
104 |
105 | imageHeight = image.shape[0]
106 | imageWidth = image.shape[1]
107 | bbox = np.round(np.array(bbox)) # mostly just for copying
108 | bbox = bb_util.clip_bbox(bbox, padding, imageWidth - padding, imageHeight - padding).astype(int).squeeze()
109 | padding = int(padding)
110 | image[bbox[1] - padding : bbox[3] + padding + 1, bbox[0] - padding : bbox[0] + padding + 1] = color
111 | image[bbox[1] - padding : bbox[3] + padding + 1, bbox[2] - padding : bbox[2] + padding + 1] = color
112 | image[bbox[1] - padding : bbox[1] + padding + 1, bbox[0] - padding : bbox[2] + padding + 1] = color
113 | image[bbox[3] - padding : bbox[3] + padding + 1, bbox[0] - padding : bbox[2] + padding + 1] = color
114 | return image
115 |
116 |
117 | def drawPoint(image, point, size, padding, color):
118 | if not isinstance(point, np.ndarray):
119 | point = np.array(point)
120 | point = tuple(point.astype(int).tolist())
121 | cv2.circle(image, point, int(size), color, int(padding))
122 | """
123 | bbox = xywh_to_xyxy([point[0], point[1], size, size])
124 | drawRect(image, bbox, padding, color)
125 | """
126 | return image
127 |
128 |
129 | def images_to_sprite(data, padsize=1, padval=0):
130 | # Expects NxHxWx3.
131 | data = data.astype(np.float64)
132 | min = np.min(data.reshape((data.shape[0], -1)), axis=1)
133 | data = (data.transpose(1, 2, 3, 0) - min).transpose(3, 0, 1, 2)
134 | max = np.max(data.reshape((data.shape[0], -1)), axis=1)
135 | data = (data.transpose(1, 2, 3, 0) / max).transpose(3, 0, 1, 2)
136 |
137 | n = int(np.ceil(np.sqrt(data.shape[0])))
138 | padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
139 | data = np.pad(data, padding, mode="constant", constant_values=(padval, padval))
140 | # tile the filters into an image
141 | data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
142 | data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
143 | data = (data * 255).astype(np.uint8)
144 | return data
145 |
--------------------------------------------------------------------------------
/re3_utils/util/im_util.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 |
4 | # @inputImage{ndarray HxWx3} Full input image.
5 | # @bbox{ndarray or list 4x1} bbox to be cropped in x1,y1,x2,y2 format.
6 | # @padScale{number} scalar representing amount of padding around image.
7 | # padScale=1 will be exactly the bbox, padScale=2 will be 2x the input image.
8 | # @outputSize{number} Size in pixels of output crop. Crop will be square and
9 | # warped.
10 | # @return{tuple(patch, outputBox)} the output patch and bounding box
11 | # representing its coordinates.
12 | def get_cropped_input(inputImage, bbox, padScale, outputSize):
13 | bbox = np.array(bbox)
14 | width = float(bbox[2] - bbox[0])
15 | height = float(bbox[3] - bbox[1])
16 | imShape = np.array(inputImage.shape)
17 | if len(imShape) < 3:
18 | inputImage = inputImage[:, :, np.newaxis]
19 | xC = float(bbox[0] + bbox[2]) / 2
20 | yC = float(bbox[1] + bbox[3]) / 2
21 | boxOn = np.zeros(4)
22 | boxOn[0] = float(xC - padScale * width / 2)
23 | boxOn[1] = float(yC - padScale * height / 2)
24 | boxOn[2] = float(xC + padScale * width / 2)
25 | boxOn[3] = float(yC + padScale * height / 2)
26 | outputBox = boxOn.copy()
27 | boxOn = np.round(boxOn).astype(int)
28 | boxOnWH = np.array([boxOn[2] - boxOn[0], boxOn[3] - boxOn[1]])
29 | imagePatch = inputImage[
30 | max(boxOn[1], 0) : min(boxOn[3], imShape[0]), max(boxOn[0], 0) : min(boxOn[2], imShape[1]), :
31 | ]
32 | boundedBox = np.clip(boxOn, 0, imShape[[1, 0, 1, 0]])
33 | boundedBoxWH = np.array([boundedBox[2] - boundedBox[0], boundedBox[3] - boundedBox[1]])
34 |
35 | if imagePatch.shape[0] == 0 or imagePatch.shape[1] == 0:
36 | patch = np.zeros((int(outputSize), int(outputSize), 3))
37 | else:
38 | patch = cv2.resize(
39 | imagePatch,
40 | (
41 | max(1, int(np.round(outputSize * boundedBoxWH[0] / boxOnWH[0]))),
42 | max(1, int(np.round(outputSize * boundedBoxWH[1] / boxOnWH[1]))),
43 | ),
44 | )
45 | if len(patch.shape) < 3:
46 | patch = patch[:, :, np.newaxis]
47 | patchShape = np.array(patch.shape)
48 |
49 | pad = np.zeros(4, dtype=int)
50 | pad[:2] = np.maximum(0, -boxOn[:2] * outputSize / boxOnWH)
51 | pad[2:] = outputSize - (pad[:2] + patchShape[[1, 0]])
52 |
53 | if np.any(pad != 0):
54 | if len(pad[pad < 0]) > 0:
55 | patch = np.zeros((int(outputSize), int(outputSize), 3))
56 | else:
57 | patch = np.lib.pad(patch, ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), "constant", constant_values=0)
58 | return patch, outputBox
59 |
60 |
61 | def get_image_size(fname):
62 | import struct, imghdr, re
63 |
64 | """Determine the image type of fhandle and return its size.
65 | from draco"""
66 | # Only a loop so we can break. Should never run more than once.
67 | while True:
68 | with open(fname, "rb") as fhandle:
69 | head = fhandle.read(32)
70 | if len(head) != 32:
71 | break
72 | if imghdr.what(fname) == "png":
73 | check = struct.unpack(">i", head[4:8])[0]
74 | if check != 0x0D0A1A0A:
75 | break
76 | width, height = struct.unpack(">ii", head[16:24])
77 | elif imghdr.what(fname) == "gif":
78 | width, height = struct.unpack("H", fhandle.read(2))[0] - 2
91 | # We are at a SOFn block
92 | fhandle.seek(1, 1) # Skip `precision' byte.
93 | height, width = struct.unpack(">HH", fhandle.read(4))
94 | except Exception: # IGNORE:W0703
95 | break
96 | elif imghdr.what(fname) == "pgm":
97 | header, width, height, maxval = re.search(
98 | b"(^P5\s(?:\s*#.*[\r\n])*"
99 | b"(\d+)\s(?:\s*#.*[\r\n])*"
100 | b"(\d+)\s(?:\s*#.*[\r\n])*"
101 | b"(\d+)\s(?:\s*#.*[\r\n]\s)*)",
102 | head,
103 | ).groups()
104 | width = int(width)
105 | height = int(height)
106 | elif imghdr.what(fname) == "bmp":
107 | _, width, height, depth = re.search(b"((\d+)\sx\s" b"(\d+)\sx\s" b"(\d+))", str).groups()
108 | width = int(width)
109 | height = int(height)
110 | else:
111 | break
112 | return width, height
113 | imShape = cv2.imread(fname).shape
114 | return imShape[1], imShape[0]
115 |
--------------------------------------------------------------------------------
/tracker/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielgordon10/re3-pytorch/04e10d2a17a81db7cd40de3f73135b0cfe0da10e/tracker/__init__.py
--------------------------------------------------------------------------------
/tracker/network.py:
--------------------------------------------------------------------------------
1 | import os.path
2 | import sys
3 |
4 | import numpy as np
5 | import torch
6 | import torch.nn as nn
7 | import torch.nn.functional as F
8 | import torch.optim as optim
9 | from torchvision import transforms
10 |
11 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
12 |
13 | from re3_utils.pytorch_util import pytorch_util_functions as pt_util
14 | from re3_utils.pytorch_util.CaffeLSTMCell import CaffeLSTMCell
15 |
16 |
17 | class ConvBlock(nn.Module):
18 | """
19 | Helper module that consists of a Conv -> Norm -> ReLU
20 | """
21 |
22 | def __init__(self, in_channels, out_channels, padding=1, kernel_size=3, stride=1, with_nonlinearity=True):
23 | super(ConvBlock, self).__init__()
24 | self.conv = nn.Conv2d(in_channels, out_channels, padding=padding, kernel_size=kernel_size, stride=stride)
25 | self.bn = nn.GroupNorm(32, out_channels)
26 | self.nonlinearity = nn.ELU(inplace=True)
27 | self.with_nonlinearity = with_nonlinearity
28 |
29 | def forward(self, x):
30 | x = self.conv(x)
31 | x = self.bn(x)
32 | if self.with_nonlinearity:
33 | x = self.nonlinearity(x)
34 | return x
35 |
36 |
37 | class Re3NetBase(nn.Module):
38 | def __init__(self, device, args=None):
39 | super(Re3NetBase, self).__init__()
40 | self.device = device
41 | self.args = args
42 | self.learning_rate = None
43 | self.optimizer = None
44 | self.outputs = None
45 |
46 | def loss(self, outputs, labels):
47 | l1_loss = F.l1_loss(outputs, labels)
48 | return l1_loss
49 |
50 | def setup_optimizer(self, learning_rate):
51 | self.learning_rate = learning_rate
52 | self.optimizer = optim.Adam(self.parameters(), lr=self.learning_rate, weight_decay=0.0005)
53 |
54 | def update_learning_rate(self, lr_new):
55 | if self.learning_rate != lr_new:
56 | for param_group in self.optimizer.param_groups:
57 | param_group["lr"] = lr_new
58 | self.learning_rate = lr_new
59 |
60 | def step(self, inputs, labels):
61 | self.optimizer.zero_grad()
62 | self.outputs = self(inputs)
63 | loss = self.loss(self.outputs, labels)
64 | loss.backward()
65 | self.optimizer.step()
66 | return loss.data.cpu().numpy()[0]
67 |
68 |
69 | class Re3Net(Re3NetBase):
70 | def __init__(self, device, lstm_size=1024, args=None):
71 | super(Re3Net, self).__init__(device, args)
72 | self.device = device
73 | self.lstm_size = lstm_size
74 | self.conv = nn.ModuleList(
75 | [
76 | nn.Conv2d(3, 96, 11, stride=4, padding=0),
77 | nn.Conv2d(96, 256, 5, padding=2, groups=2),
78 | nn.Conv2d(256, 384, 3, padding=1),
79 | nn.Conv2d(384, 384, 3, padding=1, groups=2),
80 | nn.Conv2d(384, 256, 3, padding=1, groups=2),
81 | ]
82 | )
83 | self.lrn = nn.ModuleList(
84 | [
85 | nn.LocalResponseNorm(size=5, alpha=0.0001, beta=0.75),
86 | nn.LocalResponseNorm(size=5, alpha=0.0001, beta=0.75),
87 | ]
88 | )
89 |
90 | self.conv_skip = nn.ModuleList([nn.Conv2d(96, 16, 1), nn.Conv2d(256, 32, 1), nn.Conv2d(256, 64, 1), ])
91 | self.prelu_skip = nn.ModuleList([torch.nn.PReLU(16), torch.nn.PReLU(32), torch.nn.PReLU(64)])
92 |
93 | self.fc6 = nn.Linear(74208, 2048)
94 |
95 | self.lstm1 = CaffeLSTMCell(2048, self.lstm_size)
96 | self.lstm2 = CaffeLSTMCell(2048 + self.lstm_size, self.lstm_size)
97 |
98 | self.lstm_state = None
99 |
100 | self.fc_output_out = nn.Linear(self.lstm_size, 4)
101 |
102 | self.transform = transforms.Compose(
103 | [
104 | transforms.Lambda(lambda x: x if len(x.shape) == 4 else pt_util.remove_dim(x, 1)),
105 | transforms.Lambda(lambda x: x.to(torch.float32)),
106 | transforms.Lambda(
107 | lambda x: pt_util.normalize(
108 | x,
109 | mean=np.array([123.151630838, 115.902882574, 103.062623801], dtype=np.float32)[
110 | np.newaxis, np.newaxis, np.newaxis, :
111 | ],
112 | )
113 | ),
114 | transforms.Lambda(lambda x: x.permute(0, 3, 1, 2)),
115 | ]
116 | )
117 |
118 | def forward(self, input, lstm_state=None):
119 | batch_size = input.shape[0]
120 | input = self.transform(input).to(device=self.device)
121 | conv1 = self.conv[0](input)
122 | pool1 = F.relu(F.max_pool2d(conv1, (3, 3), stride=2))
123 | lrn1 = self.lrn[0](pool1)
124 |
125 | conv1_skip = self.prelu_skip[0](self.conv_skip[0](lrn1))
126 | conv1_skip_flat = pt_util.remove_dim(conv1_skip, [2, 3])
127 |
128 | conv2 = self.conv[1](lrn1)
129 | pool2 = F.relu(F.max_pool2d(conv2, (3, 3), stride=2))
130 | lrn2 = self.lrn[1](pool2)
131 |
132 | conv2_skip = self.prelu_skip[1](self.conv_skip[1](lrn2))
133 | conv2_skip_flat = pt_util.remove_dim(conv2_skip, [2, 3])
134 |
135 | conv3 = F.relu(self.conv[2](lrn2))
136 | conv4 = F.relu(self.conv[3](conv3))
137 | conv5 = F.relu(self.conv[4](conv4))
138 | pool5 = F.relu(F.max_pool2d(conv5, (3, 3), stride=2))
139 | pool5_flat = pt_util.remove_dim(pool5, [2, 3])
140 |
141 | conv5_skip = self.prelu_skip[2](self.conv_skip[2](conv5))
142 | conv5_skip_flat = pt_util.remove_dim(conv5_skip, [2, 3])
143 |
144 | skip_concat = torch.cat([conv1_skip_flat, conv2_skip_flat, conv5_skip_flat, pool5_flat], 1)
145 | skip_concat = pt_util.split_axis(skip_concat, 0, -1, 2)
146 | reshaped = pt_util.remove_dim(skip_concat, 2)
147 |
148 | fc6 = F.relu(self.fc6(reshaped))
149 |
150 | if lstm_state is None:
151 | outputs1, state1 = self.lstm1(fc6)
152 | outputs2, state2 = self.lstm2(torch.cat((fc6, outputs1), 1))
153 | else:
154 | outputs1, state1, outputs2, state2 = lstm_state
155 | outputs1, state1 = self.lstm1(fc6, (outputs1, state1))
156 | outputs2, state2 = self.lstm2(torch.cat((fc6, outputs1), 1), (outputs2, state2))
157 |
158 | self.lstm_state = (outputs1, state1, outputs2, state2)
159 |
160 | fc_output_out = self.fc_output_out(outputs2)
161 | return fc_output_out
162 |
163 |
164 | class Re3SmallNet(Re3NetBase):
165 | def __init__(self, device, lstm_size=512, args=None):
166 | super(Re3SmallNet, self).__init__(device, args)
167 | self.lstm_size = lstm_size
168 |
169 | self.feature_extractor = nn.Sequential(
170 | ConvBlock(in_channels=3, out_channels=32, padding=3, kernel_size=7, stride=4),
171 | ConvBlock(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1),
172 | nn.MaxPool2d(kernel_size=2, stride=2),
173 | ConvBlock(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),
174 | nn.MaxPool2d(kernel_size=2, stride=2),
175 | ConvBlock(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1),
176 | nn.MaxPool2d(kernel_size=2, stride=2),
177 | ConvBlock(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1),
178 | )
179 |
180 | self.transform = transforms.Compose(
181 | [
182 | transforms.Lambda(lambda x: x if len(x.shape) == 4 else pt_util.remove_dim(x, 1)),
183 | transforms.Lambda(lambda x: x.to(torch.float32)),
184 | transforms.Lambda(
185 | lambda x: pt_util.normalize(
186 | x,
187 | mean=np.array([123.675, 116.28, 103.53])[np.newaxis, np.newaxis, np.newaxis, :],
188 | std=np.array([58.395, 57.12, 57.375])[np.newaxis, np.newaxis, np.newaxis, :],
189 | )
190 | ),
191 | transforms.Lambda(lambda x: x.permute(0, 3, 1, 2)),
192 | ]
193 | )
194 |
195 | self.fc6 = nn.Linear(50176, 2048)
196 | self.lstm1 = nn.LSTMCell(2048, self.lstm_size)
197 | self.lstm2 = nn.LSTMCell(2048 + self.lstm_size, self.lstm_size)
198 | self.fc_output = nn.Sequential(
199 | nn.Linear(self.lstm_size, self.lstm_size), nn.ELU(inplace=True), nn.Linear(self.lstm_size, 4)
200 | )
201 | self.learning_rate = None
202 | self.optimizer = None
203 | self.outputs = None
204 | self.lstm_state = None
205 |
206 | def forward(self, input, lstm_state=None):
207 | x = input.to(self.device, dtype=torch.float32)
208 | x = self.transform(x)
209 | x = self.feature_extractor(x)
210 | x = pt_util.split_axis(x, 0, -1, 2)
211 | x = pt_util.remove_dim(x, (2, 3, 4))
212 |
213 | fc6 = F.elu(self.fc6(x))
214 |
215 | if lstm_state is None:
216 | outputs1, state1 = self.lstm1(fc6)
217 | outputs2, state2 = self.lstm2(torch.cat((fc6, outputs1), 1))
218 | else:
219 | outputs1, state1, outputs2, state2 = lstm_state
220 | outputs1, state1 = self.lstm1(fc6, (outputs1, state1))
221 | outputs2, state2 = self.lstm2(torch.cat((fc6, outputs1), 1), (outputs2, state2))
222 |
223 | self.lstm_state = (outputs1, state1, outputs2, state2)
224 |
225 | output = self.fc_output(outputs2)
226 | return output
227 |
--------------------------------------------------------------------------------
/tracker/re3_tracker.py:
--------------------------------------------------------------------------------
1 | import os.path
2 | import sys
3 | import time
4 |
5 | import cv2
6 | import numpy as np
7 |
8 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
9 |
10 | from re3_utils.util import bb_util
11 | from re3_utils.util import im_util
12 | from re3_utils.pytorch_util import pytorch_util_functions as pt_util
13 |
14 | from tracker.network import Re3Net, Re3SmallNet
15 |
16 | # Network Constants
17 | from constants import CROP_SIZE
18 | from constants import CROP_PAD
19 | from constants import LOG_DIR
20 | from constants import MAX_TRACK_LENGTH
21 | from constants import USE_SMALL_NET
22 |
23 | SPEED_OUTPUT = True
24 |
25 |
26 | class Re3Tracker(object):
27 | def __init__(self, gpu_id=0):
28 | gpu_id = pt_util.setup_devices(gpu_id)[0]
29 |
30 | if USE_SMALL_NET:
31 | self.network = Re3SmallNet(gpu_id)
32 | pt_util.restore_from_folder(self.network, os.path.join(LOG_DIR, "checkpoints_small"))
33 | else:
34 | self.network = Re3Net(gpu_id)
35 | pt_util.restore_from_folder(self.network, os.path.join(LOG_DIR, "checkpoints"))
36 | self.network.to(gpu_id)
37 | self.network.eval()
38 |
39 |
40 | self.tracked_data = {}
41 |
42 | self.t_time = 0
43 | self.total_forward_count = -1
44 |
45 | # unique_id{str}: A unique id for the object being tracked.
46 | # image{str or numpy array}: The current image or the path to the current image.
47 | # starting_box{None or 4x1 numpy array or list}: 4x1 bounding box in X1, Y1, X2, Y2 format.
48 | def track(self, unique_id, image, starting_box=None):
49 | start_time = time.time()
50 |
51 | if type(image) == str:
52 | image = cv2.imread(image)[:, :, ::-1]
53 | else:
54 | image = image.copy()
55 |
56 | image_read_time = time.time() - start_time
57 |
58 | if starting_box is not None:
59 | lstm_state = None
60 | past_bbox = np.array(starting_box) # turns list into numpy array if not and copies for safety.
61 | prev_image = image
62 | original_features = None
63 | forward_count = 0
64 | elif unique_id in self.tracked_data:
65 | lstm_state, past_bbox, prev_image, original_features, forward_count = self.tracked_data[unique_id]
66 | else:
67 | raise Exception("Unique_id %s with no initial bounding box" % unique_id)
68 |
69 | cropped_input0, past_b_box_padded = im_util.get_cropped_input(prev_image, past_bbox, CROP_PAD, CROP_SIZE)
70 | cropped_input1, _ = im_util.get_cropped_input(image, past_bbox, CROP_PAD, CROP_SIZE)
71 | # import pdb
72 | # pdb.set_trace()
73 |
74 | image_input = pt_util.from_numpy((np.stack([cropped_input0, cropped_input1])))
75 | raw_output = self.network(image_input, lstm_state)
76 | raw_output = pt_util.to_numpy_array(raw_output)
77 | lstm_state = self.network.lstm_state
78 | if forward_count == 0:
79 | original_features = [var.clone().detach() for var in self.network.lstm_state]
80 |
81 | prev_image = image
82 |
83 | # Shift output box to full image coordinate system.
84 | output_box = bb_util.from_crop_coordinate_system(raw_output.squeeze() / 10.0, past_b_box_padded, 1, 1)
85 | # import pdb
86 | # pdb.set_trace()
87 | if forward_count > 0 and forward_count % MAX_TRACK_LENGTH == 0:
88 | cropped_input, _ = im_util.get_cropped_input(image, output_box, CROP_PAD, CROP_SIZE)
89 | image_input = pt_util.from_numpy(np.tile(cropped_input[np.newaxis, ...], (2, 1, 1, 1)))
90 | self.network(image_input, original_features)
91 | lstm_state = self.network.lstm_state
92 |
93 | forward_count += 1
94 | self.total_forward_count += 1
95 |
96 | if starting_box is not None:
97 | # Use label if it's given
98 | output_box = np.array(starting_box)
99 |
100 | self.tracked_data[unique_id] = (lstm_state, output_box, image, original_features, forward_count)
101 | end_time = time.time()
102 | if self.total_forward_count > 0:
103 | self.t_time += end_time - start_time - image_read_time
104 | if SPEED_OUTPUT and self.total_forward_count % 100 == 0:
105 | print("Current tracking speed: %.3f FPS" % (1 / (end_time - start_time - image_read_time)))
106 | print("Current image read speed: %.3f FPS" % (1 / (image_read_time)))
107 | print("Mean tracking speed: %.3f FPS\n" % (self.total_forward_count / max(0.00001, self.t_time)))
108 | return output_box
109 |
--------------------------------------------------------------------------------
/training/README.md:
--------------------------------------------------------------------------------
1 | # Training
2 | This training setup is simpler than the TensorFlow version due to the dynamic graph structure of PyTorch.
3 |
4 | ## Commands
5 | Typically you can train the network with commands such as:
6 | ```
7 | python unrolled_solver.py -rtc -n 2 -b 64
8 | ```
9 | Which says to run the solver with length 2 unrolls, a batch size of 64, to restore from a checkpoint if it exists, to show timing information, and to delete old checkpoints after new ones are saved (this does not use Tensorflow's method and will delete ALL older checkpoints in the checkpoint folder).
10 | To view all the options for both, simply run with the `-h` flag.
11 | For debugging, it is often useful to see the network's output on the input images. For this use the `-o` flag.
12 | To change GPU, use `-v GPU_ID`.
13 | When training with 16/32 unrolls, it is probably a good idea to run the val process as well. This runs the current tracker against a validation set using the test_net.py script. To do this, add the `--run_val` flag. A common command towards the end of training would be
14 | ```
15 | python unrolled_solver.py -rtc -n 32 -b 8 -v 0 --run_val --val_device 1
16 | ```
17 |
18 | ## Unrolls
19 | The training regime from the Re3 paper is to start with 2 unrolls and a batch size of 64. When the loss plateaus, unroll 2x and decrease the batch size by 2x (or don't if you have enough memory). The loss will be written to the logs which can be read via running [tensorboard](https://www.tensorflow.org/get_started/summaries_and_tensorboard). I find this quite helpful. Every time you increase the number of unrolls, the loss will jump up. This is expected. I have also set up tensorboard to show images of the first 3 channels of each convolutional filter. This can be useful for debugging as well to make sure the initialization is correct, and that values are changing between iterations.
20 |
21 | ## Testing
22 | To test the network, run the test.py script. This has many helpful flags which can tweak the testing, such as choosing to display or not display the images, to record a video, to skip some number of initial frames, to only test every n videos, and more. To view all the options, use the `-h` flag.
23 |
24 |
25 |
--------------------------------------------------------------------------------
/training/datasets/README.md:
--------------------------------------------------------------------------------
1 | # Datasets
2 | Datasets can be added fairly easily by creating a compliant numpy label file and adding just a few lines of code. See the imagenet_video folder for an example. Given a path to the data, [imagenet_video/make_label_files.py](imagenet_video/make_label_files.py) creates the label files for the train and test set. To add new datasets, a similar file will be necessary. The other files that need to be modified are [get_datasets.py](../get_datasets.py) follow the example in the file, [batch_cache.py](../batch_cache.py) add a line like 168
3 | ```python
4 | self.add_dataset('your_dataset_name_here')
5 | ```
6 | and [unrolled_solver.py](../unrolled_solver.py) add a line like 158
7 | ```python
8 | add_dataset('your_dataset_name_here')
9 | ```
10 | These datasets should be listed in the same order in both files.
11 |
12 | Rather than putting your data in the repository, I recommend using simlinks (ln -s) or putting a base data path in the [constants.py](../../constants.py) file.
13 |
14 |
15 | ## Label file.
16 | For each dataset, for each mode that you have (train/val/test) there should be a labels.npy file as well as a file listing all the image paths called image_names.txt. All labels.npy files should be of the format:
17 |
18 | |0 |1 |2 |3 |4 |5 |6 |... |
19 | |:------:|:------:|:------:|:------:|:------:|:------:|:------:|:------:|
20 | |xmin |ymin |xmax |ymax |video_id|track_id|im_id |extra |
21 |
22 | The rows should be ordered such that tracks are sequential (rather than having all tracks in a single image sequentially ordered). If desired, the rows can be easily reordered using np.lexsort (see [imagenet_video/make_label_files.py](imagenet_video/make_label_files.py) for an example.
23 |
--------------------------------------------------------------------------------
/training/datasets/imagenet_video/make_label_files.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | import glob
4 | import xml.etree.ElementTree as ET
5 | import time
6 | import random
7 | import os
8 | import sys
9 |
10 | basedir = os.path.dirname(__file__)
11 | sys.path.append(os.path.abspath(os.path.join(basedir, os.path.pardir, os.path.pardir, os.path.pardir)))
12 |
13 | from re3_utils.util import drawing
14 | from re3_utils.util.im_util import get_image_size
15 |
16 | DEBUG = False
17 |
18 |
19 | def main(label_type):
20 | wildcard = "/*/*/" if label_type == "train" else "/*/"
21 | dataset_path = "data/ILSVRC2015/"
22 | annotationPath = dataset_path + "Annotations/"
23 | imagePath = dataset_path + "Data/"
24 |
25 | if not DEBUG:
26 | if not os.path.exists(os.path.join("labels", label_type)):
27 | os.makedirs(os.path.join("labels", label_type))
28 | imageNameFile = open("labels/" + label_type + "/image_names.txt", "w")
29 |
30 | videos = sorted(glob.glob(annotationPath + "VID/" + label_type + wildcard))
31 |
32 | bboxes = []
33 | imNum = 0
34 | totalImages = len(glob.glob(annotationPath + "VID/" + label_type + wildcard + "*.xml"))
35 | print "totalImages", totalImages
36 | classes = {
37 | "n01674464": 1,
38 | "n01662784": 2,
39 | "n02342885": 3,
40 | "n04468005": 4,
41 | "n02509815": 5,
42 | "n02084071": 6,
43 | "n01503061": 7,
44 | "n02324045": 8,
45 | "n02402425": 9,
46 | "n02834778": 10,
47 | "n02419796": 11,
48 | "n02374451": 12,
49 | "n04530566": 13,
50 | "n02118333": 14,
51 | "n02958343": 15,
52 | "n02510455": 16,
53 | "n03790512": 17,
54 | "n02391049": 18,
55 | "n02121808": 19,
56 | "n01726692": 20,
57 | "n02062744": 21,
58 | "n02503517": 22,
59 | "n02691156": 23,
60 | "n02129165": 24,
61 | "n02129604": 25,
62 | "n02355227": 26,
63 | "n02484322": 27,
64 | "n02411705": 28,
65 | "n02924116": 29,
66 | "n02131653": 30,
67 | }
68 |
69 | for vv, video in enumerate(videos):
70 | labels = sorted(glob.glob(video + "*.xml"))
71 | images = [label.replace("Annotations", "Data").replace("xml", "JPEG") for label in labels]
72 | trackColor = dict()
73 | for ii, imageName in enumerate(images):
74 | if imNum % 100 == 0:
75 | print "imNum %d of %d = %.2f%%" % (imNum, totalImages, imNum * 100.0 / totalImages)
76 | if not DEBUG:
77 | # Leave off initial bit of path so we can just add parent dir to path later.
78 | imageNameFile.write(imageName + "\n")
79 | label = labels[ii]
80 | labelTree = ET.parse(label)
81 | imgSize = get_image_size(images[ii])
82 | area = imgSize[0] * imgSize[1]
83 | if DEBUG:
84 | print "\n%s" % images[ii]
85 | image = cv2.imread(images[ii])
86 | print "video", vv, "image", ii
87 | for obj in labelTree.findall("object"):
88 | cls = obj.find("name").text
89 | assert cls in classes
90 | classInd = classes[cls]
91 |
92 | occl = int(obj.find("occluded").text)
93 | trackId = int(obj.find("trackid").text)
94 | bbox = obj.find("bndbox")
95 | bbox = [
96 | int(bbox.find("xmin").text),
97 | int(bbox.find("ymin").text),
98 | int(bbox.find("xmax").text),
99 | int(bbox.find("ymax").text),
100 | vv,
101 | trackId,
102 | imNum,
103 | classInd,
104 | occl,
105 | ]
106 |
107 | if DEBUG:
108 | print "name", obj.find("name").text, "\n"
109 | print bbox
110 | if trackId not in trackColor:
111 | trackColor[trackId] = [random.random() * 255 for _ in xrange(3)]
112 | drawing.drawRect(image, bbox[:4], 3, trackColor[trackId])
113 | bboxes.append(bbox)
114 | if DEBUG:
115 | cv2.imshow("image", image)
116 | cv2.waitKey(1)
117 |
118 | imNum += 1
119 |
120 | bboxes = np.array(bboxes)
121 | # Reorder by video_id, then track_id, then video image number so all labels for a single track are next to each other.
122 | # This only matters if a single image could have multiple tracks.
123 | order = np.lexsort((bboxes[:, 6], bboxes[:, 5], bboxes[:, 4]))
124 | bboxes = bboxes[order, :]
125 | if not DEBUG:
126 | np.save("labels/" + label_type + "/labels.npy", bboxes)
127 |
128 |
129 | if __name__ == "__main__":
130 | main("train")
131 | main("val")
132 |
--------------------------------------------------------------------------------
/training/datasets/otb_100/make_labels.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import re
3 |
4 | import numpy as np
5 |
6 | all_lines = []
7 | im_id = 0
8 | video_id = 0
9 | image_names = []
10 | for folder in sorted(glob.glob("data/*/*")):
11 | im_id_start = im_id
12 | label_files = sorted(glob.glob(folder + "/groundtruth_rect*.txt"))
13 | image_files = sorted(glob.glob(folder + "/img/*.jpg"))
14 | image_names.extend(image_files)
15 | for track_id, label_file in enumerate(label_files):
16 | lines = [map(float, re.split("[,\s]", line.strip())) for line in open(label_file)]
17 | if len(lines) != len(image_files):
18 | print("not equal", len(lines), len(image_files), folder)
19 | for line in lines:
20 | line.extend([video_id, track_id, im_id])
21 | im_id += 1
22 | all_lines.extend(lines)
23 | im_id = im_id_start
24 | video_id += 1
25 | im_id += len(image_files)
26 |
27 | all_lines = np.array(all_lines)
28 | all_lines[:, 2] += all_lines[:, 0]
29 | all_lines[:, 3] += all_lines[:, 1]
30 | np.save("labels/val/labels.npy", all_lines)
31 | ff = open("labels/val/image_names.txt", "w")
32 | ff.write("\n".join(image_names))
33 | ff.close()
34 | print("done")
35 | print("num labels", all_lines.shape[0])
36 | print("num images", len(image_names))
37 |
--------------------------------------------------------------------------------
/training/get_datasets.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import glob
3 | import os
4 |
5 | import sys
6 |
7 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
8 | from constants import DATA_DIR
9 |
10 |
11 | def get_data_for_dataset(dataset_name, mode):
12 | # Implement this for each dataset.
13 | dataset = None
14 | if dataset_name == "imagenet_video":
15 | image_datadir = os.path.join(DATA_DIR, "Imagenet_Video", "provided_small")
16 | datadir = os.path.join(os.path.dirname(__file__), "datasets", "imagenet_video")
17 | gt = np.load(datadir + "/labels/" + mode + "/labels_small_boxes.npy")
18 | image_paths = [
19 | image_datadir + "/" + line[5:].strip() for line in open(datadir + "/labels/" + mode + "/image_names.txt")
20 | ]
21 |
22 | """
23 | image_datadir = os.path.join(
24 | DATA_DIR,
25 | 'Imagenet_Video',
26 | 'provided')
27 | datadir = os.path.join(
28 | os.path.dirname(__file__),
29 | 'datasets',
30 | 'imagenet_video')
31 | gt = np.load(datadir + '/labels/' + mode + '/labels.npy')
32 | image_paths = [image_datadir + '/' + line[5:].strip()
33 | for line in open(datadir + '/labels/' + mode + '/image_names.txt')]
34 | """
35 |
36 | elif dataset_name == "alov":
37 | image_datadir = os.path.join(DATA_DIR, "ALOV")
38 | datadir = os.path.join(os.path.dirname(__file__), "datasets", "alov")
39 | gt = np.load(datadir + "/labels/" + mode + "/labels.npy")
40 | image_paths = [
41 | image_datadir + "/" + line.strip() for line in open(datadir + "/labels/" + mode + "/image_names.txt")
42 | ]
43 | elif dataset_name == "caltech_pedestrian":
44 | image_datadir = os.path.join(DATA_DIR, "Caltech_Pedestrian", "dataset",)
45 | datadir = os.path.join(os.path.dirname(__file__), "datasets", "caltech_pedestrian")
46 | gt = np.load(datadir + "/labels/" + mode + "/labels.npy")
47 | image_paths = [
48 | image_datadir + "/" + line.strip() for line in open(datadir + "/labels/" + mode + "/image_names.txt")
49 | ]
50 | elif dataset_name == "kitti":
51 | image_datadir = os.path.join(DATA_DIR, "KITTI", "dataset",)
52 | datadir = os.path.join(os.path.dirname(__file__), "datasets", "kitti")
53 | gt = np.load(datadir + "/labels/" + mode + "/labels.npy")
54 | image_paths = [
55 | image_datadir + "/" + line.strip() for line in open(datadir + "/labels/" + mode + "/image_names.txt")
56 | ]
57 | elif dataset_name == "vot":
58 | image_datadir = os.path.join(DATA_DIR, "VOT2014", "dataset",)
59 | datadir = os.path.join(os.path.dirname(__file__), "datasets", "vot")
60 | gt = np.load(datadir + "/labels/" + mode + "/labels.npy")
61 | image_paths = [
62 | image_datadir + "/" + line.strip() for line in open(datadir + "/labels/" + mode + "/image_names.txt")
63 | ]
64 | return {"gt": gt, "image_paths": image_paths, "dataset": dataset}
65 |
--------------------------------------------------------------------------------
/training/pt_dataset.py:
--------------------------------------------------------------------------------
1 | import os
2 | import random
3 | import sys
4 |
5 | import cv2
6 | import numpy as np
7 | import torch
8 | from torch.utils.data import DataLoader
9 |
10 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
11 |
12 | from training import get_datasets
13 |
14 | from constants import CROP_PAD
15 | from constants import CROP_SIZE
16 |
17 | from re3_utils.util import bb_util
18 | from re3_utils.util import im_util
19 | from re3_utils.util import IOU
20 |
21 | np.set_printoptions(suppress=True)
22 | np.set_printoptions(precision=4)
23 |
24 |
25 | AREA_CUTOFF = 0.25
26 |
27 |
28 | class VideoDataset(torch.utils.data.Dataset):
29 | def __init__(self, num_unrolls):
30 | self.num_unrolls = num_unrolls
31 | self.all_keys = set()
32 | self.image_paths = []
33 | self.datasets = []
34 | self.key_lookup = {}
35 |
36 | self.create_keys()
37 |
38 | def add_dataset(self, dataset_name):
39 | dataset_ind = len(self.image_paths)
40 | data = get_datasets.get_data_for_dataset(dataset_name, "train")
41 | gt = data["gt"]
42 | num_keys = 0
43 | for xx in range(gt.shape[0] - self.num_unrolls):
44 | start_line = gt[xx, :].astype(int)
45 | end_line = gt[xx + self.num_unrolls, :].astype(int)
46 | # Check that still in the same sequence.
47 | # Video_id should match, track_id should match, and image number should be exactly num_unrolls frames later.
48 | if (
49 | start_line[4] == end_line[4]
50 | and start_line[5] == end_line[5]
51 | and start_line[6] + self.num_unrolls == end_line[6]
52 | ):
53 | # Add the key.
54 | self.all_keys.add((dataset_ind, start_line[4], start_line[5], start_line[6]))
55 | num_keys += 1
56 | print("#%s keys: %d" % (dataset_name, num_keys))
57 |
58 | image_paths = data["image_paths"]
59 | # Add the array to image_paths. Note that image paths is indexed by the dataset number THEN by the image line.
60 | self.image_paths.append(image_paths)
61 |
62 | dataset_ind = len(self.datasets)
63 | dataset_gt = gt
64 | for xx in range(dataset_gt.shape[0]):
65 | line = dataset_gt[xx, :].astype(int)
66 | self.key_lookup[(dataset_ind, line[4], line[5], line[6])] = xx
67 | self.datasets.append(dataset_gt)
68 |
69 | def create_keys(self):
70 | self.add_dataset("imagenet_video")
71 |
72 | def lookup_func(self, key):
73 | images = None
74 | labels = None
75 | try:
76 | images = []
77 | labels = []
78 | ind = key[-1]
79 | for dd in range(self.num_unrolls):
80 | path = self.image_paths[key[0]][ind + dd]
81 | image = cv2.imread(path)[:, :, ::-1]
82 | images.append(image)
83 | new_key = list(key)
84 | new_key[3] += dd
85 | new_key = tuple(new_key)
86 | image_index = self.key_lookup[new_key]
87 | bbox_on = self.datasets[new_key[0]][image_index, :4].copy()
88 | labels.append(bbox_on)
89 | except Exception as ex:
90 | import traceback
91 |
92 | trace = traceback.format_exc()
93 | print(trace)
94 | error_file = open("error.txt", "a+")
95 | error_file.write("exception in lookup_func %s\n" % str(ex))
96 | error_file.write(str(trace))
97 | finally:
98 | return images, labels
99 |
100 | def get_sample(self):
101 | key = random.sample(self.all_keys, 1)[0]
102 | images, labels = self.lookup_func(key)
103 | return {"images": images, "labels": labels}
104 |
105 | def __len__(self):
106 | return 2 ** 62
107 |
108 | def __getitem__(self, idx):
109 | return self.get_sample()
110 |
111 |
112 | def collate_fn(batch):
113 | return batch
114 |
115 |
116 | def get_data_loader(num_unrolls, batch_size, num_threads):
117 | dataset = VideoDataset(num_unrolls)
118 | data_loader = DataLoader(
119 | dataset, batch_size=batch_size, num_workers=num_threads, shuffle=False, pin_memory=True, collate_fn=collate_fn
120 | )
121 | return data_loader
122 |
123 |
124 | # Make sure there is a minimum intersection with the ground truth box and the visible crop.
125 | def fix_bbox_intersection(bbox, gtBox):
126 | if type(bbox) == list:
127 | bbox = np.array(bbox)
128 | if type(gtBox) == list:
129 | gtBox = np.array(gtBox)
130 |
131 | bbox = bbox.copy()
132 |
133 | gtBoxArea = float((gtBox[3] - gtBox[1]) * (gtBox[2] - gtBox[0]))
134 | bboxLarge = bb_util.scale_bbox(bbox, CROP_PAD)
135 | while IOU.intersection(bboxLarge, gtBox) / gtBoxArea < AREA_CUTOFF:
136 | bbox = bbox * 0.9 + gtBox * 0.1
137 | bboxLarge = bb_util.scale_bbox(bbox, CROP_PAD)
138 | return bbox
139 |
140 |
141 | # Randomly jitter the box for a bit of noise.
142 | def add_noise(bbox, prev_bbox, image_width, image_height):
143 | num_tries = 0
144 | bbox_xywh_init = bb_util.xyxy_to_xywh(bbox)
145 | while num_tries < 10:
146 | bbox_xywh = bbox_xywh_init.copy()
147 | center_noise = np.random.laplace(0, 1.0 / 5, 2) * bbox_xywh[[2, 3]]
148 | size_noise = np.clip(np.random.laplace(1, 1.0 / 15, 2), 0.6, 1.4)
149 | bbox_xywh[[2, 3]] *= size_noise
150 | bbox_xywh[[0, 1]] = bbox_xywh[[0, 1]] + center_noise
151 | if not (
152 | bbox_xywh[0] < prev_bbox[0]
153 | or bbox_xywh[1] < prev_bbox[1]
154 | or bbox_xywh[0] > prev_bbox[2]
155 | or bbox_xywh[1] > prev_bbox[3]
156 | or bbox_xywh[0] < 0
157 | or bbox_xywh[1] < 0
158 | or bbox_xywh[0] > image_width
159 | or bbox_xywh[1] > image_height
160 | ):
161 | num_tries = 10
162 | else:
163 | num_tries += 1
164 | return fix_bbox_intersection(bb_util.xywh_to_xyxy(bbox_xywh), prev_bbox)
165 |
166 |
167 | def get_next_image_crops(images, labels, dd, noisy_box, mirrored, real_motion, network_outs):
168 | if network_outs is not None:
169 | xyxy_pred = network_outs.squeeze() / 10
170 | output_box = bb_util.from_crop_coordinate_system(xyxy_pred, noisy_box, CROP_PAD, 1)
171 | bbox_prev = noisy_box
172 | elif dd == 0:
173 | bbox_prev = labels[dd]
174 | else:
175 | bbox_prev = labels[dd - 1]
176 |
177 | bbox_on = labels[dd]
178 | if dd == 0:
179 | noisy_box = bbox_on.copy()
180 | elif not real_motion and network_outs is None:
181 | noisy_box = add_noise(bbox_on, bbox_on, images[0].shape[1], images[0].shape[0])
182 | else:
183 | noisy_box = fix_bbox_intersection(bbox_prev, bbox_on)
184 |
185 | image0 = im_util.get_cropped_input(images[max(dd - 1, 0)], bbox_prev, CROP_PAD, CROP_SIZE)[0]
186 |
187 | image1 = im_util.get_cropped_input(images[dd], noisy_box, CROP_PAD, CROP_SIZE)[0]
188 |
189 | shifted_bbox = bb_util.to_crop_coordinate_system(bbox_on, noisy_box, CROP_PAD, 1)
190 | shifted_bbox_xywh = bb_util.xyxy_to_xywh(shifted_bbox)
191 | xywh_labels = shifted_bbox_xywh
192 | xyxy_labels = bb_util.xywh_to_xyxy(xywh_labels) * 10
193 | return image0, image1, xyxy_labels, noisy_box
194 |
195 |
196 | def get_next_image_crops_mp(images, label, dd, noisy_box, mirrored, real_motion, network_outs):
197 | if network_outs is not None:
198 | xyxy_pred = network_outs.squeeze() / 10
199 | output_box = bb_util.from_crop_coordinate_system(xyxy_pred, noisy_box, CROP_PAD, 1)
200 | bbox_prev = noisy_box
201 | elif dd == 0:
202 | bbox_prev = label[1] # labels[dd]
203 | else:
204 | bbox_prev = label[0] # labels[dd - 1]
205 |
206 | bbox_on = label[1] # labels[dd]
207 | if dd == 0:
208 | noisy_box = bbox_on.copy()
209 | elif not real_motion and network_outs is None:
210 | noisy_box = add_noise(bbox_on, bbox_on, images[0].shape[1], images[0].shape[0])
211 | else:
212 | noisy_box = fix_bbox_intersection(bbox_prev, bbox_on)
213 |
214 | image0 = im_util.get_cropped_input(
215 | # images[max(dd-1, 0)], bbox_prev, CROP_PAD, CROP_SIZE)[0]
216 | images[0],
217 | bbox_prev,
218 | CROP_PAD,
219 | CROP_SIZE,
220 | )[0]
221 |
222 | image1 = im_util.get_cropped_input(
223 | # images[dd], noisy_box, CROP_PAD, CROP_SIZE)[0]
224 | images[1],
225 | noisy_box,
226 | CROP_PAD,
227 | CROP_SIZE,
228 | )[0]
229 |
230 | shifted_bbox = bb_util.to_crop_coordinate_system(bbox_on, noisy_box, CROP_PAD, 1)
231 | shifted_bbox_xywh = bb_util.xyxy_to_xywh(shifted_bbox)
232 | xywh_labels = shifted_bbox_xywh
233 | xyxy_labels = bb_util.xywh_to_xyxy(xywh_labels) * 10
234 | return image0, image1, xyxy_labels, noisy_box
235 |
--------------------------------------------------------------------------------
/training/test_net.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import json
3 | import os
4 | import sys
5 | import time
6 |
7 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
8 |
9 | from re3_utils.util.drawing import *
10 | from re3_utils.util.IOU import *
11 |
12 | from training import get_datasets
13 | from tracker import re3_tracker
14 |
15 | # Display constants
16 | from constants import OUTPUT_WIDTH
17 | from constants import OUTPUT_HEIGHT
18 | from constants import PADDING
19 | from constants import GPU_ID
20 |
21 | NUM_COLS = 1
22 | NUM_ROWS = 1
23 | BORDER = 0
24 | FPS = 30
25 | DISPLAY = True
26 |
27 | np.set_printoptions(precision=6)
28 | np.set_printoptions(suppress=True)
29 |
30 |
31 | def run_frame(im_on, gt_on):
32 | # Necessary for linking up global variables.
33 | global tracker
34 | global totalIou, numFrames
35 | global initialize
36 | global imageNames
37 | global ignoreFrames, initializeFrames, lostTarget
38 |
39 | titles = []
40 |
41 | if gt_on == 0 or not (
42 | gt[gt_on, 4] == gt[gt_on - 1, 4] and gt[gt_on, 5] == gt[gt_on - 1, 5] and gt[gt_on, 6] - 1 == gt[gt_on - 1, 6]
43 | ):
44 | print("beginning sequence", gt[gt_on, [5, 6]])
45 | # Clear the state if a new sequence has started.
46 | initialize = True
47 | ignoreFrames = 0
48 | initializeFrames = 0
49 |
50 | iou = 1
51 | robustness = 1
52 |
53 | gtBox = gt[gt_on, :4].copy()
54 |
55 | if DISPLAY:
56 | inputImageBGR = cv2.imread(imageNames[im_on])
57 | inputImage = inputImageBGR[:, :, ::-1]
58 | imageToDraw = inputImageBGR.copy()
59 | drawRect(imageToDraw, gtBox, PADDING * 2, [0, 255, 0])
60 | else:
61 | inputImage = imageNames[im_on]
62 |
63 | if ignoreFrames > 0:
64 | ignoreFrames -= 1
65 | else:
66 | if initialize:
67 | outputBox = tracker.track("test_track", inputImage, gtBox)
68 | initialize = False
69 | else:
70 | outputBox = tracker.track("test_track", inputImage)
71 |
72 | if DISPLAY:
73 | drawRect(imageToDraw, outputBox, PADDING, [0, 0, 255])
74 |
75 | if initializeFrames == 0:
76 | iou = IOU(outputBox, gtBox)
77 | totalIou += iou
78 | if iou == 0:
79 | ignoreFrames = 5
80 | initializeFrames = 10
81 | lostTarget += 1
82 | initialize = True
83 | numFrames += 1
84 | robustness = np.exp(-30.0 * lostTarget / numFrames)
85 | else:
86 | initializeFrames -= 1
87 |
88 | meanIou = totalIou * 1.0 / max(numFrames, 1)
89 |
90 | if DISPLAY:
91 | imageToDraw[0, 0] = 255
92 | imageToDraw[0, 1] = 0
93 | titles.append(
94 | "Frame %d, IOU %.2f, Mean IOU %.2f, Robustness %.2f, Dropped %d"
95 | % (gt_on, iou, meanIou, robustness, lostTarget)
96 | )
97 | imPlots = [imageToDraw]
98 |
99 | results = {
100 | "gt_on": gt_on,
101 | "meanIou": meanIou,
102 | "robustness": robustness,
103 | "lostTarget": lostTarget,
104 | }
105 |
106 | if DISPLAY:
107 | return imPlots, titles, results
108 | else:
109 | return results
110 |
111 |
112 | # Main function
113 | if __name__ == "__main__":
114 | parser = argparse.ArgumentParser(description="Show the Network Results.")
115 | parser.add_argument("-d", "--debug", action="store_true", default=False)
116 | parser.add_argument("-r", "--record", action="store_true", default=False)
117 | parser.add_argument(
118 | "-f",
119 | "--fancy_text",
120 | action="store_true",
121 | default=False,
122 | help="Use a fancier font than OpenCVs, but takes longer to render an image."
123 | "This should be used for making higher-quality videos.",
124 | )
125 | parser.add_argument("-n", "--max_images", action="store", default=-1, dest="maxCount", type=int)
126 | parser.add_argument("-s", "--num_images_to_skip", action="store", default=0, dest="skipCount", type=int)
127 | parser.add_argument("-m", "--mode", action="store", default="val", type=str, help="train or val")
128 | parser.add_argument("--dataset", default="imagenet_video", type=str, help="name of the dataset")
129 | parser.add_argument(
130 | "--video-sample-rate",
131 | default=1,
132 | type=int,
133 | help="One of every n videos will be run. Useful for testing portions of larger datasets.",
134 | )
135 | parser.add_argument("-v", "--cuda_visible_devices", type=str, default=str(GPU_ID), help="Device number or string")
136 | feature_parser = parser.add_mutually_exclusive_group(required=False)
137 | feature_parser.add_argument("--display", dest="display", action="store_true")
138 | feature_parser.add_argument("--no-display", dest="display", action="store_false")
139 | parser.set_defaults(display=True)
140 | FLAGS = parser.parse_args()
141 |
142 | DISPLAY = FLAGS.display
143 |
144 | data = get_datasets.get_data_for_dataset(FLAGS.dataset, FLAGS.mode)
145 | gt = data["gt"]
146 | imageNames = data["image_paths"]
147 | sample_inds = np.where(gt[:, 4] % FLAGS.video_sample_rate == 0)[0]
148 | gt = gt[sample_inds, :]
149 | numImages = gt.shape[0]
150 | imageNums = gt[:, 6].astype(int)
151 |
152 | if FLAGS.maxCount == -1:
153 | FLAGS.maxCount = numImages - FLAGS.skipCount
154 |
155 | tracker = re3_tracker.Re3Tracker(FLAGS.cuda_visible_devices)
156 |
157 | print("Testing", numImages, "frames")
158 |
159 | # Set up global data holders
160 | imOn = FLAGS.skipCount
161 | numFrames = 0
162 | ignoreFrames = 0
163 | initializeFrames = 0
164 | lostTarget = 0
165 | currentTrackLength = 0
166 | initialize = True
167 |
168 | totalIou = 0
169 |
170 | if FLAGS.record:
171 | tt = time.localtime()
172 | import imageio
173 |
174 | writer = imageio.get_writer(
175 | "./video_%02d_%02d_%02d_%02d_%02d.mp4" % (tt.tm_mon, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec), fps=FPS
176 | )
177 |
178 | if DISPLAY:
179 | cv2.namedWindow("Output")
180 |
181 | maxIter = min(FLAGS.maxCount + FLAGS.skipCount, numImages)
182 | for imOn in range(FLAGS.skipCount, maxIter):
183 | if DISPLAY:
184 | plots, titles, results = run_frame(imageNums[int(imOn)], int(imOn))
185 | im = subplot(
186 | plots,
187 | NUM_ROWS,
188 | NUM_COLS,
189 | titles=titles,
190 | outputWidth=OUTPUT_WIDTH,
191 | outputHeight=OUTPUT_HEIGHT,
192 | border=BORDER,
193 | fancy_text=FLAGS.fancy_text,
194 | )
195 | cv2.imshow("Output", im)
196 | waitKey = cv2.waitKey(1)
197 | if FLAGS.record:
198 | if imOn % 100 == 0:
199 | print(imOn)
200 | writer.append_data(im[:, :, ::-1])
201 | else:
202 | results = run_frame(imageNums[int(imOn)], int(imOn))
203 | if imOn % 100 == 0 or (imOn + 1) == maxIter:
204 | print("Results: " + str([key + " : " + str(results[key]) for key in sorted(results.keys())]))
205 |
206 | if FLAGS.record:
207 | writer.close()
208 |
209 | with open("results.json", "w") as f:
210 | json.dump(results, f, indent=2)
211 |
--------------------------------------------------------------------------------
/training/unrolled_solver.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import os
3 | import os.path
4 | import sys
5 | import threading
6 | import time
7 |
8 | import cv2
9 | import numpy as np
10 | import torch
11 |
12 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
13 |
14 | from training import pt_dataset
15 | from tracker.network import Re3SmallNet
16 | from re3_utils.pytorch_util import pytorch_util_functions as pt_util
17 | from re3_utils.util import bb_util
18 | from re3_utils.util import drawing
19 | from re3_utils import python_util
20 |
21 | from constants import CROP_PAD
22 | from constants import CROP_SIZE
23 | from constants import GPU_ID
24 | from constants import LOG_DIR
25 | from constants import OUTPUT_WIDTH
26 | from constants import OUTPUT_HEIGHT
27 | from re3_utils.pytorch_util import tensorboard_logger
28 |
29 |
30 | NUM_ITERATIONS = int(1e6)
31 | REAL_MOTION_PROB = 1.0 / 8
32 | USE_NETWORK_PROB = 0.5
33 |
34 |
35 | def get_next_image_crops(args):
36 | return pt_dataset.get_next_image_crops_mp(*args)
37 |
38 |
39 | def main(args):
40 | num_unrolls = args.num_unrolls
41 | batch_size = args.batch_size
42 | timing = args.timing
43 | debug = args.debug or args.output
44 |
45 | device = pt_util.setup_devices(args.device)[0]
46 | np.set_printoptions(suppress=True)
47 | np.set_printoptions(precision=4)
48 |
49 | # pool = mp.Pool(min(batch_size, mp.cpu_count()))
50 |
51 | time_str = python_util.get_time_str()
52 | checkpoint_path = os.path.join(LOG_DIR, "checkpoints")
53 | if not os.path.exists(checkpoint_path):
54 | os.makedirs(checkpoint_path)
55 |
56 | train_logger = None
57 | if not debug:
58 | tensorboard_dir = os.path.join(LOG_DIR, "tensorboard", time_str + "_train")
59 | if not os.path.exists(tensorboard_dir):
60 | os.makedirs(tensorboard_dir)
61 | train_logger = tensorboard_logger.Logger(tensorboard_dir)
62 |
63 | data_loader = pt_dataset.get_data_loader(num_unrolls, batch_size, args.num_threads)
64 | batch_iter = iter(data_loader)
65 |
66 | network = Re3SmallNet(device, args)
67 | network.setup_optimizer(1e-5)
68 | network.to(device)
69 | network.train()
70 |
71 | start_iter = 0
72 | if args.restore:
73 | print("Restoring")
74 | start_iter = pt_util.restore_from_folder(network, checkpoint_path,)
75 | print("Restored", start_iter)
76 |
77 | if debug:
78 | cv2.namedWindow("debug", cv2.WINDOW_NORMAL)
79 | cv2.resizeWindow("debug", OUTPUT_WIDTH, OUTPUT_HEIGHT)
80 |
81 | try:
82 | time_total = 0.000001
83 | num_iters = 0
84 | iteration = start_iter
85 | # Run training iterations in the main thread.
86 |
87 | while iteration < args.max_steps:
88 | if train_logger is not None and iteration % 1000 == 0:
89 | train_logger.network_conv_summary(network, iteration)
90 | if iteration == 10000:
91 | network.update_learning_rate(1e-6)
92 | if (iteration - 1) % 10 == 0:
93 | current_time_start = time.time()
94 |
95 | start_solver = time.time()
96 | # Timers: initial data read time | data time | forward time | backward time | total time
97 | timers = np.zeros(5)
98 |
99 | try:
100 | image_sequences = next(batch_iter)
101 | except StopIteration:
102 | batch_iter = iter(data_loader)
103 | image_sequences = next(batch_iter)
104 | timers[0] = time.time() - start_solver
105 |
106 | outputs = []
107 | labels = []
108 | images = []
109 | noisy_boxes = [None for _ in range(len(image_sequences))]
110 | mirrored = np.random.random(batch_size) < 0.5
111 | real_motion = np.random.random(batch_size) < REAL_MOTION_PROB
112 | use_network_outs = np.random.random(batch_size) < USE_NETWORK_PROB
113 | lstm_state = None
114 | network_outs = [None for _ in range(len(image_sequences))]
115 | for dd in range(num_unrolls):
116 | batch_images = []
117 | batch_labels = []
118 | process_t_start = time.time()
119 |
120 | for ii, vals in enumerate(image_sequences):
121 | image_sequence = vals["images"]
122 | label_sequence = vals["labels"]
123 | image0, image1, xyxy_labels, noisy_box = pt_dataset.get_next_image_crops(
124 | image_sequence,
125 | label_sequence,
126 | dd,
127 | noisy_boxes[ii],
128 | mirrored[ii],
129 | real_motion[ii],
130 | network_outs[ii],
131 | )
132 | batch_images.append((image0, image1))
133 | batch_labels.append(xyxy_labels)
134 | noisy_boxes[ii] = noisy_box
135 |
136 | images.append(batch_images)
137 | labels.append(batch_labels)
138 | image_tensor = pt_util.from_numpy(batch_images)
139 | timers[1] += time.time() - process_t_start
140 | forward_t_start = time.time()
141 | output = network(image_tensor, lstm_state)
142 | outputs.append(output)
143 | output = pt_util.to_numpy_array(output)
144 | for ii in range(batch_size):
145 | if use_network_outs[ii]:
146 | network_outs[ii] = output[ii]
147 | lstm_state = network.lstm_state
148 | timers[2] += time.time() - forward_t_start
149 |
150 | backward_t_start = time.time()
151 | labels = pt_util.from_numpy(labels)
152 | network.optimizer.zero_grad()
153 | outputs = torch.stack(outputs)
154 | loss_value = network.loss(outputs, labels.to(dtype=outputs.dtype, device=network.device))
155 | loss_value.backward()
156 | network.optimizer.step()
157 | loss_value = loss_value.item()
158 | timers[3] = time.time() - backward_t_start
159 |
160 | end_solver = time.time()
161 | timers[4] = time.time() - start_solver
162 | time_total += end_solver - start_solver
163 | per_image_timers = timers / (num_unrolls * batch_size)
164 |
165 | if train_logger is not None and iteration % 10 == 0:
166 | train_logger.dict_log(
167 | {
168 | "losses/loss": loss_value,
169 | "stats/data_read_time": timers[0],
170 | "stats/data_time": timers[1],
171 | "stats/forward_time": timers[2],
172 | "stats/backward_time": timers[3],
173 | "stats/total_time": timers[4],
174 | "per_image_stats/data_read_time": per_image_timers[0],
175 | "per_image_stats/data_time": per_image_timers[1],
176 | "per_image_stats/forward_time": per_image_timers[2],
177 | "per_image_stats/backward_time": per_image_timers[3],
178 | "per_image_stats/total_time": per_image_timers[4],
179 | },
180 | iteration,
181 | )
182 |
183 | num_iters += 1
184 | iteration += 1
185 | if timing and (iteration - 1) % 10 == 0:
186 | print("Iteration: %d" % (iteration - 1))
187 | print("Loss: %.3f" % loss_value)
188 | print("Average Time: %.3f" % (time_total / num_iters))
189 | print("Current Time: %.3f" % (end_solver - start_solver))
190 | if num_iters > 20:
191 | print("Current Average: %.3f" % ((time.time() - current_time_start) / 10))
192 | print("")
193 |
194 | # Save a checkpoint and remove old ones.
195 | if iteration % 500 == 0 or iteration == args.max_steps:
196 | pt_util.save(network, LOG_DIR + "/checkpoints/iteration_%07d.pt" % iteration, num_to_keep=1)
197 |
198 | # Every once in a while save a checkpoint that isn't ever removed except by hand.
199 | if iteration % 10000 == 0 or iteration == args.max_steps:
200 | pt_util.save(network, LOG_DIR + "/checkpoints/long_checkpoints/iteration_%07d.pt" % iteration)
201 | if not debug:
202 | if args.run_val and (num_iters == 1 or iteration % 1000 == 0):
203 | # Run a validation set eval in a separate process.
204 | def test_func():
205 | test_iter_on = iteration
206 | print("Staring test iter", test_iter_on)
207 | import subprocess
208 | import json
209 |
210 | command = [
211 | "python",
212 | "test_net.py",
213 | "--video-sample-rate",
214 | str(10),
215 | "--no-display",
216 | "-v",
217 | str(args.val_device),
218 | ]
219 | subprocess.call(command)
220 | result = json.load(open("results.json", "r"))
221 | train_logger.dict_log(
222 | {
223 | "eval/robustness": result["robustness"],
224 | "eval/lost_targets": result["lostTarget"],
225 | "eval/mean_iou": result["meanIou"],
226 | "eval/avg_measure": (result["meanIou"] + result["robustness"]) / 2,
227 | },
228 | test_iter_on,
229 | )
230 | os.remove("results.json")
231 | print("Ending test iter", test_iter_on)
232 |
233 | test_thread = threading.Thread(target=test_func)
234 | test_thread.daemon = True
235 | test_thread.start()
236 | if args.output:
237 | # Look at some of the outputs.
238 | print("new batch")
239 | images = (
240 | np.array(images)
241 | .transpose((1, 0, 2, 3, 4, 5))
242 | .reshape((batch_size, num_unrolls, 2, CROP_SIZE, CROP_SIZE, 3))
243 | )
244 | labels = pt_util.to_numpy_array(labels).transpose(1, 0, 2)
245 | outputs = pt_util.to_numpy_array(outputs).transpose(1, 0, 2)
246 | for bb in range(batch_size):
247 | for dd in range(num_unrolls):
248 | image0 = images[bb, dd, 0, ...]
249 | image1 = images[bb, dd, 1, ...]
250 |
251 | label = labels[bb, dd, :]
252 | xyxy_label = label / 10
253 | label_box = xyxy_label * CROP_PAD
254 |
255 | output = outputs[bb, dd, ...]
256 | xyxy_pred = output / 10
257 | output_box = xyxy_pred * CROP_PAD
258 |
259 | drawing.drawRect(image0, bb_util.xywh_to_xyxy(np.full((4, 1), 0.5) * CROP_SIZE), 2, [0, 255, 0])
260 | drawing.drawRect(image1, xyxy_label * CROP_SIZE, 2, [0, 255, 0])
261 | drawing.drawRect(image1, xyxy_pred * CROP_SIZE, 2, [255, 0, 0])
262 |
263 | plots = [image0, image1]
264 | subplot = drawing.subplot(
265 | plots, 1, 2, outputWidth=OUTPUT_WIDTH, outputHeight=OUTPUT_HEIGHT, border=5
266 | )
267 | cv2.imshow("debug", subplot[:, :, ::-1])
268 | cv2.waitKey(0)
269 | except Exception as e:
270 | import traceback
271 |
272 | traceback.print_exc()
273 | finally:
274 | # Save if error or killed by ctrl-c.
275 | if not debug:
276 | print("Saving...")
277 | pt_util.save(network, LOG_DIR + "/checkpoints/iteration_%07d.pt" % iteration, num_to_keep=-1)
278 |
279 |
280 | if __name__ == "__main__":
281 | parser = argparse.ArgumentParser(description="Training for Re3.")
282 | parser.add_argument("-n", "--num-unrolls", action="store", default=2, type=int)
283 | parser.add_argument("-b", "--batch-size", action="store", default=64, type=int)
284 | parser.add_argument("-v", "--device", type=str, default=str(GPU_ID), help="Device number or string")
285 | parser.add_argument("-r", "--restore", action="store_true", default=False)
286 | parser.add_argument("-d", "--debug", action="store_true", default=False)
287 | parser.add_argument("-t", "--timing", action="store_true", default=False)
288 | parser.add_argument("-o", "--output", action="store_true", default=False)
289 | parser.add_argument("-c", "--clear-snapshots", action="store_true", default=False, dest="clearSnapshots")
290 | parser.add_argument("--num-threads", action="store", default=2, type=int)
291 | parser.add_argument("--run-val", action="store_true", default=False)
292 | parser.add_argument("--val-device", type=str, default="0", help="Device number or string for val process to use.")
293 | parser.add_argument("-m", "--max-steps", type=int, default=NUM_ITERATIONS, help="Number of steps to run trainer.")
294 | args = parser.parse_args()
295 | main(args)
296 |
--------------------------------------------------------------------------------