├── .github
└── FUNDING.yml
├── LICENSE
├── README.md
├── football1.mp4
├── models
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── common.cpython-36.pyc
│ ├── experimental.cpython-36.pyc
│ └── yolo.cpython-36.pyc
├── common.py
├── experimental.py
└── yolo.py
├── pose-estimate.py
├── requirements.txt
└── utils
├── __init__.py
├── __pycache__
├── __init__.cpython-36.pyc
├── autoanchor.cpython-36.pyc
├── datasets.cpython-36.pyc
├── general.cpython-36.pyc
├── google_utils.cpython-36.pyc
├── loss.cpython-36.pyc
├── metrics.cpython-36.pyc
├── plots.cpython-36.pyc
└── torch_utils.cpython-36.pyc
├── activations.py
├── add_nms.py
├── autoanchor.py
├── datasets.py
├── general.py
├── google_utils.py
├── loss.py
├── metrics.py
├── plots.py
├── torch_utils.py
└── wandb_logging
├── __init__.py
├── log_dataset.py
└── wandb_utils.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: muhammadrizwanm
14 | thanks_dev: # Replace with a single thanks.dev username
15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # yolov7-pose-estimation
2 |
3 | ### Steps to Run Code
4 |
5 | - **Google Colab Users**: First, mount the drive:
6 | ```python
7 | from google.colab import drive
8 | drive.mount("/content/drive")
9 | ```
10 | - **Clone the repository**:
11 | ```bash
12 | git clone https://github.com/RizwanMunawar/yolov7-pose-estimation.git
13 | ```
14 | - **Go to the cloned folder**:
15 | ```bash
16 | cd yolov7-pose-estimation
17 | ```
18 | - **Create a virtual environment** (recommended):
19 | ```bash
20 | # Linux
21 | python3 -m venv psestenv
22 | source psestenv/bin/activate
23 |
24 | # Windows
25 | python3 -m venv psestenv
26 | cd psestenv/Scripts
27 | activate
28 | ```
29 | - **Upgrade pip**:
30 | ```bash
31 | pip install --upgrade pip
32 | ```
33 | - **Install requirements**:
34 | ```bash
35 | pip install -r requirements.txt
36 | ```
37 | - **Download YOLOv7 weights** and move to the working directory:
38 | [yolov7-w6-pose.pt](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-w6-pose.pt)
39 |
40 | - **Run the code**:
41 | ```bash
42 | python pose-estimate.py
43 |
44 | # Options:
45 | python pose-estimate.py --source "your-video.mp4" --device cpu # For CPU
46 | python pose-estimate.py --source 0 --view-img # For Webcam
47 | python pose-estimate.py --source "rtsp://your-ip" --device 0 --view-img # For LiveStream
48 | ```
49 |
50 | - Output: The processed video will be saved as **your-file-keypoint.mp4**
51 |
52 | ### RESULTS
53 |
54 |
55 |
56 | Football Match |
57 | Cricket Match |
58 | FPS & Time Comparison |
59 | Live Stream |
60 |
61 |
62 |  |
63 |  |
64 |  |
65 |  |
66 |
67 |
68 |
69 | ### References
70 | - YOLOv7 Repo: https://github.com/WongKinYiu/yolov7
71 | - Ultralytics: https://github.com/ultralytics/yolov5
72 |
73 | ### 📖 Articles
74 | - [YOLOv7 Training Guide](https://medium.com/augmented-startups/yolov7-training-on-custom-data-b86d23e6623)
75 | - [Computer Vision Roadmap](https://medium.com/augmented-startups/roadmap-for-computer-vision-engineer-45167b94518c)
76 |
--------------------------------------------------------------------------------
/football1.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/football1.mp4
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
1 | # init
--------------------------------------------------------------------------------
/models/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/models/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/models/__pycache__/common.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/models/__pycache__/common.cpython-36.pyc
--------------------------------------------------------------------------------
/models/__pycache__/experimental.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/models/__pycache__/experimental.cpython-36.pyc
--------------------------------------------------------------------------------
/models/__pycache__/yolo.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/models/__pycache__/yolo.cpython-36.pyc
--------------------------------------------------------------------------------
/models/experimental.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import random
3 | import torch
4 | import torch.nn as nn
5 |
6 | from models.common import Conv, DWConv
7 | from utils.google_utils import attempt_download
8 |
9 |
10 | class CrossConv(nn.Module):
11 | # Cross Convolution Downsample
12 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
13 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
14 | super(CrossConv, self).__init__()
15 | c_ = int(c2 * e) # hidden channels
16 | self.cv1 = Conv(c1, c_, (1, k), (1, s))
17 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
18 | self.add = shortcut and c1 == c2
19 |
20 | def forward(self, x):
21 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
22 |
23 |
24 | class Sum(nn.Module):
25 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
26 | def __init__(self, n, weight=False): # n: number of inputs
27 | super(Sum, self).__init__()
28 | self.weight = weight # apply weights boolean
29 | self.iter = range(n - 1) # iter object
30 | if weight:
31 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
32 |
33 | def forward(self, x):
34 | y = x[0] # no weight
35 | if self.weight:
36 | w = torch.sigmoid(self.w) * 2
37 | for i in self.iter:
38 | y = y + x[i + 1] * w[i]
39 | else:
40 | for i in self.iter:
41 | y = y + x[i + 1]
42 | return y
43 |
44 |
45 | class MixConv2d(nn.Module):
46 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
47 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
48 | super(MixConv2d, self).__init__()
49 | groups = len(k)
50 | if equal_ch: # equal c_ per group
51 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
52 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
53 | else: # equal weight.numel() per group
54 | b = [c2] + [0] * groups
55 | a = np.eye(groups + 1, groups, k=-1)
56 | a -= np.roll(a, 1, axis=1)
57 | a *= np.array(k) ** 2
58 | a[0] = 1
59 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
60 |
61 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
62 | self.bn = nn.BatchNorm2d(c2)
63 | self.act = nn.LeakyReLU(0.1, inplace=True)
64 |
65 | def forward(self, x):
66 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
67 |
68 |
69 | class Ensemble(nn.ModuleList):
70 | # Ensemble of models
71 | def __init__(self):
72 | super(Ensemble, self).__init__()
73 |
74 | def forward(self, x, augment=False):
75 | y = []
76 | for module in self:
77 | y.append(module(x, augment)[0])
78 | # y = torch.stack(y).max(0)[0] # max ensemble
79 | # y = torch.stack(y).mean(0) # mean ensemble
80 | y = torch.cat(y, 1) # nms ensemble
81 | return y, None # inference, train output
82 |
83 |
84 |
85 |
86 |
87 | class ORT_NMS(torch.autograd.Function):
88 | '''ONNX-Runtime NMS operation'''
89 | @staticmethod
90 | def forward(ctx,
91 | boxes,
92 | scores,
93 | max_output_boxes_per_class=torch.tensor([100]),
94 | iou_threshold=torch.tensor([0.45]),
95 | score_threshold=torch.tensor([0.25])):
96 | device = boxes.device
97 | batch = scores.shape[0]
98 | num_det = random.randint(0, 100)
99 | batches = torch.randint(0, batch, (num_det,)).sort()[0].to(device)
100 | idxs = torch.arange(100, 100 + num_det).to(device)
101 | zeros = torch.zeros((num_det,), dtype=torch.int64).to(device)
102 | selected_indices = torch.cat([batches[None], zeros[None], idxs[None]], 0).T.contiguous()
103 | selected_indices = selected_indices.to(torch.int64)
104 | return selected_indices
105 |
106 | @staticmethod
107 | def symbolic(g, boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold):
108 | return g.op("NonMaxSuppression", boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold)
109 |
110 |
111 | class TRT_NMS(torch.autograd.Function):
112 | '''TensorRT NMS operation'''
113 | @staticmethod
114 | def forward(
115 | ctx,
116 | boxes,
117 | scores,
118 | background_class=-1,
119 | box_coding=1,
120 | iou_threshold=0.45,
121 | max_output_boxes=100,
122 | plugin_version="1",
123 | score_activation=0,
124 | score_threshold=0.25,
125 | ):
126 | batch_size, num_boxes, num_classes = scores.shape
127 | num_det = torch.randint(0, max_output_boxes, (batch_size, 1), dtype=torch.int32)
128 | det_boxes = torch.randn(batch_size, max_output_boxes, 4)
129 | det_scores = torch.randn(batch_size, max_output_boxes)
130 | det_classes = torch.randint(0, num_classes, (batch_size, max_output_boxes), dtype=torch.int32)
131 | return num_det, det_boxes, det_scores, det_classes
132 |
133 | @staticmethod
134 | def symbolic(g,
135 | boxes,
136 | scores,
137 | background_class=-1,
138 | box_coding=1,
139 | iou_threshold=0.45,
140 | max_output_boxes=100,
141 | plugin_version="1",
142 | score_activation=0,
143 | score_threshold=0.25):
144 | out = g.op("TRT::EfficientNMS_TRT",
145 | boxes,
146 | scores,
147 | background_class_i=background_class,
148 | box_coding_i=box_coding,
149 | iou_threshold_f=iou_threshold,
150 | max_output_boxes_i=max_output_boxes,
151 | plugin_version_s=plugin_version,
152 | score_activation_i=score_activation,
153 | score_threshold_f=score_threshold,
154 | outputs=4)
155 | nums, boxes, scores, classes = out
156 | return nums, boxes, scores, classes
157 |
158 |
159 | class ONNX_ORT(nn.Module):
160 | '''onnx module with ONNX-Runtime NMS operation.'''
161 | def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=640, device=None):
162 | super().__init__()
163 | self.device = device if device else torch.device("cpu")
164 | self.max_obj = torch.tensor([max_obj]).to(device)
165 | self.iou_threshold = torch.tensor([iou_thres]).to(device)
166 | self.score_threshold = torch.tensor([score_thres]).to(device)
167 | self.max_wh = max_wh # if max_wh != 0 : non-agnostic else : agnostic
168 | self.convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
169 | dtype=torch.float32,
170 | device=self.device)
171 |
172 | def forward(self, x):
173 | boxes = x[:, :, :4]
174 | conf = x[:, :, 4:5]
175 | scores = x[:, :, 5:]
176 | scores *= conf
177 | boxes @= self.convert_matrix
178 | max_score, category_id = scores.max(2, keepdim=True)
179 | dis = category_id.float() * self.max_wh
180 | nmsbox = boxes + dis
181 | max_score_tp = max_score.transpose(1, 2).contiguous()
182 | selected_indices = ORT_NMS.apply(nmsbox, max_score_tp, self.max_obj, self.iou_threshold, self.score_threshold)
183 | X, Y = selected_indices[:, 0], selected_indices[:, 2]
184 | selected_boxes = boxes[X, Y, :]
185 | selected_categories = category_id[X, Y, :].float()
186 | selected_scores = max_score[X, Y, :]
187 | X = X.unsqueeze(1).float()
188 | return torch.cat([X, selected_boxes, selected_categories, selected_scores], 1)
189 |
190 | class ONNX_TRT(nn.Module):
191 | '''onnx module with TensorRT NMS operation.'''
192 | def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None ,device=None):
193 | super().__init__()
194 | assert max_wh is None
195 | self.device = device if device else torch.device('cpu')
196 | self.background_class = -1,
197 | self.box_coding = 1,
198 | self.iou_threshold = iou_thres
199 | self.max_obj = max_obj
200 | self.plugin_version = '1'
201 | self.score_activation = 0
202 | self.score_threshold = score_thres
203 |
204 | def forward(self, x):
205 | boxes = x[:, :, :4]
206 | conf = x[:, :, 4:5]
207 | scores = x[:, :, 5:]
208 | scores *= conf
209 | num_det, det_boxes, det_scores, det_classes = TRT_NMS.apply(boxes, scores, self.background_class, self.box_coding,
210 | self.iou_threshold, self.max_obj,
211 | self.plugin_version, self.score_activation,
212 | self.score_threshold)
213 | return num_det, det_boxes, det_scores, det_classes
214 |
215 |
216 | class End2End(nn.Module):
217 | '''export onnx or tensorrt model with NMS operation.'''
218 | def __init__(self, model, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None, device=None):
219 | super().__init__()
220 | device = device if device else torch.device('cpu')
221 | assert isinstance(max_wh,(int)) or max_wh is None
222 | self.model = model.to(device)
223 | self.model.model[-1].end2end = True
224 | self.patch_model = ONNX_TRT if max_wh is None else ONNX_ORT
225 | self.end2end = self.patch_model(max_obj, iou_thres, score_thres, max_wh, device)
226 | self.end2end.eval()
227 |
228 | def forward(self, x):
229 | x = self.model(x)
230 | x = self.end2end(x)
231 | return x
232 |
233 |
234 |
235 |
236 |
237 | def attempt_load(weights, map_location=None):
238 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
239 | model = Ensemble()
240 | for w in weights if isinstance(weights, list) else [weights]:
241 | attempt_download(w)
242 | ckpt = torch.load(w, map_location=map_location) # load
243 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
244 |
245 | # Compatibility updates
246 | for m in model.modules():
247 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
248 | m.inplace = True # pytorch 1.7.0 compatibility
249 | elif type(m) is nn.Upsample:
250 | m.recompute_scale_factor = None # torch 1.11.0 compatibility
251 | elif type(m) is Conv:
252 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
253 |
254 | if len(model) == 1:
255 | return model[-1] # return model
256 | else:
257 | print('Ensemble created with %s\n' % weights)
258 | for k in ['names', 'stride']:
259 | setattr(model, k, getattr(model[-1], k))
260 | return model # return ensemble
261 |
262 |
263 |
--------------------------------------------------------------------------------
/models/yolo.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import logging
3 | import sys
4 | from copy import deepcopy
5 |
6 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
7 | logger = logging.getLogger(__name__)
8 | import torch
9 | from models.common import *
10 | from models.experimental import *
11 | from utils.autoanchor import check_anchor_order
12 | from utils.general import make_divisible, check_file, set_logging
13 | from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
14 | select_device, copy_attr
15 | from utils.loss import SigmoidBin
16 |
17 | try:
18 | import thop # for FLOPS computation
19 | except ImportError:
20 | thop = None
21 |
22 |
23 | class Detect(nn.Module):
24 | stride = None # strides computed during build
25 | export = False # onnx export
26 | end2end = False
27 | include_nms = False
28 |
29 | def __init__(self, nc=80, anchors=(), ch=()): # detection layer
30 | super(Detect, self).__init__()
31 | self.nc = nc # number of classes
32 | self.no = nc + 5 # number of outputs per anchor
33 | self.nl = len(anchors) # number of detection layers
34 | self.na = len(anchors[0]) // 2 # number of anchors
35 | self.grid = [torch.zeros(1)] * self.nl # init grid
36 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
37 | self.register_buffer('anchors', a) # shape(nl,na,2)
38 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
39 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
40 |
41 | def forward(self, x):
42 | # x = x.copy() # for profiling
43 | z = [] # inference output
44 | self.training |= self.export
45 | for i in range(self.nl):
46 | x[i] = self.m[i](x[i]) # conv
47 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
48 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
49 |
50 | if not self.training: # inference
51 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
52 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
53 | y = x[i].sigmoid()
54 | if not torch.onnx.is_in_onnx_export():
55 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
56 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
57 | else:
58 | xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
59 | wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
60 | y = torch.cat((xy, wh, y[..., 4:]), -1)
61 | z.append(y.view(bs, -1, self.no))
62 |
63 | if self.training:
64 | out = x
65 | elif self.end2end:
66 | out = torch.cat(z, 1)
67 | elif self.include_nms:
68 | z = self.convert(z)
69 | out = (z, )
70 | else:
71 | out = (torch.cat(z, 1), x)
72 |
73 | return out
74 |
75 | @staticmethod
76 | def _make_grid(nx=20, ny=20):
77 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
78 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
79 |
80 | def convert(self, z):
81 | z = torch.cat(z, 1)
82 | box = z[:, :, :4]
83 | conf = z[:, :, 4:5]
84 | score = z[:, :, 5:]
85 | score *= conf
86 | convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
87 | dtype=torch.float32,
88 | device=z.device)
89 | box @= convert_matrix
90 | return (box, score)
91 |
92 |
93 | class IDetect(nn.Module):
94 | stride = None # strides computed during build
95 | export = False # onnx export
96 | end2end = False
97 | include_nms = False
98 |
99 | def __init__(self, nc=80, anchors=(), ch=()): # detection layer
100 | super(IDetect, self).__init__()
101 | self.nc = nc # number of classes
102 | self.no = nc + 5 # number of outputs per anchor
103 | self.nl = len(anchors) # number of detection layers
104 | self.na = len(anchors[0]) // 2 # number of anchors
105 | self.grid = [torch.zeros(1)] * self.nl # init grid
106 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
107 | self.register_buffer('anchors', a) # shape(nl,na,2)
108 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
109 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
110 |
111 | self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
112 | self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
113 |
114 | def forward(self, x):
115 | # x = x.copy() # for profiling
116 | z = [] # inference output
117 | self.training |= self.export
118 | for i in range(self.nl):
119 | x[i] = self.m[i](self.ia[i](x[i])) # conv
120 | x[i] = self.im[i](x[i])
121 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
122 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
123 |
124 | if not self.training: # inference
125 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
126 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
127 |
128 | y = x[i].sigmoid()
129 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
130 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
131 | z.append(y.view(bs, -1, self.no))
132 |
133 | return x if self.training else (torch.cat(z, 1), x)
134 |
135 | def fuseforward(self, x):
136 | # x = x.copy() # for profiling
137 | z = [] # inference output
138 | self.training |= self.export
139 | for i in range(self.nl):
140 | x[i] = self.m[i](x[i]) # conv
141 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
142 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
143 |
144 | if not self.training: # inference
145 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
146 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
147 |
148 | y = x[i].sigmoid()
149 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
150 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
151 | z.append(y.view(bs, -1, self.no))
152 |
153 | if self.training:
154 | out = x
155 | elif self.end2end:
156 | out = torch.cat(z, 1)
157 | elif self.include_nms:
158 | z = self.convert(z)
159 | out = (z, )
160 | else:
161 | out = (torch.cat(z, 1), x)
162 |
163 | return out
164 |
165 | def fuse(self):
166 | print("IDetect.fuse")
167 | # fuse ImplicitA and Convolution
168 | for i in range(len(self.m)):
169 | c1,c2,_,_ = self.m[i].weight.shape
170 | c1_,c2_, _,_ = self.ia[i].implicit.shape
171 | self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1)
172 |
173 | # fuse ImplicitM and Convolution
174 | for i in range(len(self.m)):
175 | c1,c2, _,_ = self.im[i].implicit.shape
176 | self.m[i].bias *= self.im[i].implicit.reshape(c2)
177 | self.m[i].weight *= self.im[i].implicit.transpose(0,1)
178 |
179 | @staticmethod
180 | def _make_grid(nx=20, ny=20):
181 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
182 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
183 |
184 | def convert(self, z):
185 | z = torch.cat(z, 1)
186 | box = z[:, :, :4]
187 | conf = z[:, :, 4:5]
188 | score = z[:, :, 5:]
189 | score *= conf
190 | convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
191 | dtype=torch.float32,
192 | device=z.device)
193 | box @= convert_matrix
194 | return (box, score)
195 |
196 |
197 | class IKeypoint(nn.Module):
198 | stride = None # strides computed during build
199 | export = False # onnx export
200 |
201 | def __init__(self, nc=80, anchors=(), nkpt=17, ch=(), inplace=True, dw_conv_kpt=False): # detection layer
202 | super(IKeypoint, self).__init__()
203 | self.nc = nc # number of classes
204 | self.nkpt = nkpt
205 | self.dw_conv_kpt = dw_conv_kpt
206 | self.no_det=(nc + 5) # number of outputs per anchor for box and class
207 | self.no_kpt = 3*self.nkpt ## number of outputs per anchor for keypoints
208 | self.no = self.no_det+self.no_kpt
209 | self.nl = len(anchors) # number of detection layers
210 | self.na = len(anchors[0]) // 2 # number of anchors
211 | self.grid = [torch.zeros(1)] * self.nl # init grid
212 | self.flip_test = False
213 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
214 | self.register_buffer('anchors', a) # shape(nl,na,2)
215 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
216 | self.m = nn.ModuleList(nn.Conv2d(x, self.no_det * self.na, 1) for x in ch) # output conv
217 |
218 | self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
219 | self.im = nn.ModuleList(ImplicitM(self.no_det * self.na) for _ in ch)
220 |
221 | if self.nkpt is not None:
222 | if self.dw_conv_kpt: #keypoint head is slightly more complex
223 | self.m_kpt = nn.ModuleList(
224 | nn.Sequential(DWConv(x, x, k=3), Conv(x,x),
225 | DWConv(x, x, k=3), Conv(x, x),
226 | DWConv(x, x, k=3), Conv(x,x),
227 | DWConv(x, x, k=3), Conv(x, x),
228 | DWConv(x, x, k=3), Conv(x, x),
229 | DWConv(x, x, k=3), nn.Conv2d(x, self.no_kpt * self.na, 1)) for x in ch)
230 | else: #keypoint head is a single convolution
231 | self.m_kpt = nn.ModuleList(nn.Conv2d(x, self.no_kpt * self.na, 1) for x in ch)
232 |
233 | self.inplace = inplace # use in-place ops (e.g. slice assignment)
234 |
235 | def forward(self, x):
236 | # x = x.copy() # for profiling
237 | z = [] # inference output
238 | self.training |= self.export
239 | for i in range(self.nl):
240 | if self.nkpt is None or self.nkpt==0:
241 | x[i] = self.im[i](self.m[i](self.ia[i](x[i]))) # conv
242 | else :
243 | x[i] = torch.cat((self.im[i](self.m[i](self.ia[i](x[i]))), self.m_kpt[i](x[i])), axis=1)
244 |
245 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
246 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
247 | x_det = x[i][..., :6]
248 | x_kpt = x[i][..., 6:]
249 |
250 | if not self.training: # inference
251 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
252 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
253 | kpt_grid_x = self.grid[i][..., 0:1]
254 | kpt_grid_y = self.grid[i][..., 1:2]
255 |
256 | if self.nkpt == 0:
257 | y = x[i].sigmoid()
258 | else:
259 | y = x_det.sigmoid()
260 |
261 | if self.inplace:
262 | xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
263 | wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
264 | if self.nkpt != 0:
265 | x_kpt[..., 0::3] = (x_kpt[..., ::3] * 2. - 0.5 + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy
266 | x_kpt[..., 1::3] = (x_kpt[..., 1::3] * 2. - 0.5 + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy
267 | #x_kpt[..., 0::3] = (x_kpt[..., ::3] + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy
268 | #x_kpt[..., 1::3] = (x_kpt[..., 1::3] + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy
269 | #print('=============')
270 | #print(self.anchor_grid[i].shape)
271 | #print(self.anchor_grid[i][...,0].unsqueeze(4).shape)
272 | #print(x_kpt[..., 0::3].shape)
273 | #x_kpt[..., 0::3] = ((x_kpt[..., 0::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy
274 | #x_kpt[..., 1::3] = ((x_kpt[..., 1::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy
275 | #x_kpt[..., 0::3] = (((x_kpt[..., 0::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy
276 | #x_kpt[..., 1::3] = (((x_kpt[..., 1::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy
277 | x_kpt[..., 2::3] = x_kpt[..., 2::3].sigmoid()
278 |
279 | y = torch.cat((xy, wh, y[..., 4:], x_kpt), dim = -1)
280 |
281 | else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
282 | xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
283 | wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
284 | if self.nkpt != 0:
285 | y[..., 6:] = (y[..., 6:] * 2. - 0.5 + self.grid[i].repeat((1,1,1,1,self.nkpt))) * self.stride[i] # xy
286 | y = torch.cat((xy, wh, y[..., 4:]), -1)
287 |
288 | z.append(y.view(bs, -1, self.no))
289 |
290 | return x if self.training else (torch.cat(z, 1), x)
291 |
292 | @staticmethod
293 | def _make_grid(nx=20, ny=20):
294 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
295 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
296 |
297 |
298 | class IAuxDetect(nn.Module):
299 | stride = None # strides computed during build
300 | export = False # onnx export
301 |
302 | def __init__(self, nc=80, anchors=(), ch=()): # detection layer
303 | super(IAuxDetect, self).__init__()
304 | self.nc = nc # number of classes
305 | self.no = nc + 5 # number of outputs per anchor
306 | self.nl = len(anchors) # number of detection layers
307 | self.na = len(anchors[0]) // 2 # number of anchors
308 | self.grid = [torch.zeros(1)] * self.nl # init grid
309 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
310 | self.register_buffer('anchors', a) # shape(nl,na,2)
311 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
312 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[:self.nl]) # output conv
313 | self.m2 = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[self.nl:]) # output conv
314 |
315 | self.ia = nn.ModuleList(ImplicitA(x) for x in ch[:self.nl])
316 | self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch[:self.nl])
317 |
318 | def forward(self, x):
319 | # x = x.copy() # for profiling
320 | z = [] # inference output
321 | self.training |= self.export
322 | for i in range(self.nl):
323 | x[i] = self.m[i](self.ia[i](x[i])) # conv
324 | x[i] = self.im[i](x[i])
325 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
326 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
327 |
328 | x[i+self.nl] = self.m2[i](x[i+self.nl])
329 | x[i+self.nl] = x[i+self.nl].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
330 |
331 | if not self.training: # inference
332 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
333 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
334 |
335 | y = x[i].sigmoid()
336 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
337 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
338 | z.append(y.view(bs, -1, self.no))
339 |
340 | return x if self.training else (torch.cat(z, 1), x[:self.nl])
341 |
342 | @staticmethod
343 | def _make_grid(nx=20, ny=20):
344 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
345 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
346 |
347 |
348 | class IBin(nn.Module):
349 | stride = None # strides computed during build
350 | export = False # onnx export
351 |
352 | def __init__(self, nc=80, anchors=(), ch=(), bin_count=21): # detection layer
353 | super(IBin, self).__init__()
354 | self.nc = nc # number of classes
355 | self.bin_count = bin_count
356 |
357 | self.w_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
358 | self.h_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
359 | # classes, x,y,obj
360 | self.no = nc + 3 + \
361 | self.w_bin_sigmoid.get_length() + self.h_bin_sigmoid.get_length() # w-bce, h-bce
362 | # + self.x_bin_sigmoid.get_length() + self.y_bin_sigmoid.get_length()
363 |
364 | self.nl = len(anchors) # number of detection layers
365 | self.na = len(anchors[0]) // 2 # number of anchors
366 | self.grid = [torch.zeros(1)] * self.nl # init grid
367 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
368 | self.register_buffer('anchors', a) # shape(nl,na,2)
369 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
370 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
371 |
372 | self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
373 | self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
374 |
375 | def forward(self, x):
376 |
377 | #self.x_bin_sigmoid.use_fw_regression = True
378 | #self.y_bin_sigmoid.use_fw_regression = True
379 | self.w_bin_sigmoid.use_fw_regression = True
380 | self.h_bin_sigmoid.use_fw_regression = True
381 |
382 | # x = x.copy() # for profiling
383 | z = [] # inference output
384 | self.training |= self.export
385 | for i in range(self.nl):
386 | x[i] = self.m[i](self.ia[i](x[i])) # conv
387 | x[i] = self.im[i](x[i])
388 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
389 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
390 |
391 | if not self.training: # inference
392 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
393 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
394 |
395 | y = x[i].sigmoid()
396 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
397 | #y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
398 |
399 |
400 | #px = (self.x_bin_sigmoid.forward(y[..., 0:12]) + self.grid[i][..., 0]) * self.stride[i]
401 | #py = (self.y_bin_sigmoid.forward(y[..., 12:24]) + self.grid[i][..., 1]) * self.stride[i]
402 |
403 | pw = self.w_bin_sigmoid.forward(y[..., 2:24]) * self.anchor_grid[i][..., 0]
404 | ph = self.h_bin_sigmoid.forward(y[..., 24:46]) * self.anchor_grid[i][..., 1]
405 |
406 | #y[..., 0] = px
407 | #y[..., 1] = py
408 | y[..., 2] = pw
409 | y[..., 3] = ph
410 |
411 | y = torch.cat((y[..., 0:4], y[..., 46:]), dim=-1)
412 |
413 | z.append(y.view(bs, -1, y.shape[-1]))
414 |
415 | return x if self.training else (torch.cat(z, 1), x)
416 |
417 | @staticmethod
418 | def _make_grid(nx=20, ny=20):
419 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
420 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
421 |
422 |
423 | class Model(nn.Module):
424 | def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
425 | super(Model, self).__init__()
426 | self.traced = False
427 | if isinstance(cfg, dict):
428 | self.yaml = cfg # model dict
429 | else: # is *.yaml
430 | import yaml # for torch hub
431 | self.yaml_file = Path(cfg).name
432 | with open(cfg) as f:
433 | self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict
434 |
435 | # Define model
436 | ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
437 | if nc and nc != self.yaml['nc']:
438 | logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
439 | self.yaml['nc'] = nc # override yaml value
440 | if anchors:
441 | logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
442 | self.yaml['anchors'] = round(anchors) # override yaml value
443 | self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
444 | self.names = [str(i) for i in range(self.yaml['nc'])] # default names
445 | # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
446 |
447 | # Build strides, anchors
448 | m = self.model[-1] # Detect()
449 | if isinstance(m, Detect):
450 | s = 256 # 2x min stride
451 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
452 | m.anchors /= m.stride.view(-1, 1, 1)
453 | check_anchor_order(m)
454 | self.stride = m.stride
455 | self._initialize_biases() # only run once
456 | # print('Strides: %s' % m.stride.tolist())
457 | if isinstance(m, IDetect):
458 | s = 256 # 2x min stride
459 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
460 | m.anchors /= m.stride.view(-1, 1, 1)
461 | check_anchor_order(m)
462 | self.stride = m.stride
463 | self._initialize_biases() # only run once
464 | # print('Strides: %s' % m.stride.tolist())
465 | if isinstance(m, IAuxDetect):
466 | s = 256 # 2x min stride
467 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]) # forward
468 | #print(m.stride)
469 | m.anchors /= m.stride.view(-1, 1, 1)
470 | check_anchor_order(m)
471 | self.stride = m.stride
472 | self._initialize_aux_biases() # only run once
473 | # print('Strides: %s' % m.stride.tolist())
474 | if isinstance(m, IBin):
475 | s = 256 # 2x min stride
476 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
477 | m.anchors /= m.stride.view(-1, 1, 1)
478 | check_anchor_order(m)
479 | self.stride = m.stride
480 | self._initialize_biases_bin() # only run once
481 | # print('Strides: %s' % m.stride.tolist())
482 | if isinstance(m, IKeypoint):
483 | s = 256 # 2x min stride
484 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
485 | m.anchors /= m.stride.view(-1, 1, 1)
486 | check_anchor_order(m)
487 | self.stride = m.stride
488 | self._initialize_biases_kpt() # only run once
489 | # print('Strides: %s' % m.stride.tolist())
490 |
491 | # Init weights, biases
492 | initialize_weights(self)
493 | self.info()
494 | logger.info('')
495 |
496 | def forward(self, x, augment=False, profile=False):
497 | if augment:
498 | img_size = x.shape[-2:] # height, width
499 | s = [1, 0.83, 0.67] # scales
500 | f = [None, 3, None] # flips (2-ud, 3-lr)
501 | y = [] # outputs
502 | for si, fi in zip(s, f):
503 | xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
504 | yi = self.forward_once(xi)[0] # forward
505 | # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
506 | yi[..., :4] /= si # de-scale
507 | if fi == 2:
508 | yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
509 | elif fi == 3:
510 | yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
511 | y.append(yi)
512 | return torch.cat(y, 1), None # augmented inference, train
513 | else:
514 | return self.forward_once(x, profile) # single-scale inference, train
515 |
516 | def forward_once(self, x, profile=False):
517 | y, dt = [], [] # outputs
518 | for m in self.model:
519 | if m.f != -1: # if not from previous layer
520 | x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
521 |
522 | if not hasattr(self, 'traced'):
523 | self.traced=False
524 |
525 | if self.traced:
526 | if isinstance(m, Detect) or isinstance(m, IDetect) or isinstance(m, IAuxDetect) or isinstance(m, IKeypoint):
527 | break
528 |
529 | if profile:
530 | c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin))
531 | o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS
532 | for _ in range(10):
533 | m(x.copy() if c else x)
534 | t = time_synchronized()
535 | for _ in range(10):
536 | m(x.copy() if c else x)
537 | dt.append((time_synchronized() - t) * 100)
538 | print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
539 |
540 | x = m(x) # run
541 |
542 | y.append(x if m.i in self.save else None) # save output
543 |
544 | if profile:
545 | print('%.1fms total' % sum(dt))
546 | return x
547 |
548 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
549 | # https://arxiv.org/abs/1708.02002 section 3.3
550 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
551 | m = self.model[-1] # Detect() module
552 | for mi, s in zip(m.m, m.stride): # from
553 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
554 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
555 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
556 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
557 |
558 | def _initialize_aux_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
559 | # https://arxiv.org/abs/1708.02002 section 3.3
560 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
561 | m = self.model[-1] # Detect() module
562 | for mi, mi2, s in zip(m.m, m.m2, m.stride): # from
563 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
564 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
565 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
566 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
567 | b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85)
568 | b2.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
569 | b2.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
570 | mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True)
571 |
572 | def _initialize_biases_bin(self, cf=None): # initialize biases into Detect(), cf is class frequency
573 | # https://arxiv.org/abs/1708.02002 section 3.3
574 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
575 | m = self.model[-1] # Bin() module
576 | bc = m.bin_count
577 | for mi, s in zip(m.m, m.stride): # from
578 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
579 | old = b[:, (0,1,2,bc+3)].data
580 | obj_idx = 2*bc+4
581 | b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99))
582 | b[:, obj_idx].data += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
583 | b[:, (obj_idx+1):].data += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
584 | b[:, (0,1,2,bc+3)].data = old
585 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
586 |
587 | def _initialize_biases_kpt(self, cf=None): # initialize biases into Detect(), cf is class frequency
588 | # https://arxiv.org/abs/1708.02002 section 3.3
589 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
590 | m = self.model[-1] # Detect() module
591 | for mi, s in zip(m.m, m.stride): # from
592 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
593 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
594 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
595 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
596 |
597 | def _print_biases(self):
598 | m = self.model[-1] # Detect() module
599 | for mi in m.m: # from
600 | b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
601 | print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
602 |
603 | # def _print_weights(self):
604 | # for m in self.model.modules():
605 | # if type(m) is Bottleneck:
606 | # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
607 |
608 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
609 | print('Fusing layers... ')
610 | for m in self.model.modules():
611 | if isinstance(m, RepConv):
612 | #print(f" fuse_repvgg_block")
613 | m.fuse_repvgg_block()
614 | elif isinstance(m, RepConv_OREPA):
615 | #print(f" switch_to_deploy")
616 | m.switch_to_deploy()
617 | elif type(m) is Conv and hasattr(m, 'bn'):
618 | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
619 | delattr(m, 'bn') # remove batchnorm
620 | m.forward = m.fuseforward # update forward
621 | elif isinstance(m, IDetect):
622 | m.fuse()
623 | m.forward = m.fuseforward
624 | self.info()
625 | return self
626 |
627 | def nms(self, mode=True): # add or remove NMS module
628 | present = type(self.model[-1]) is NMS # last layer is NMS
629 | if mode and not present:
630 | print('Adding NMS... ')
631 | m = NMS() # module
632 | m.f = -1 # from
633 | m.i = self.model[-1].i + 1 # index
634 | self.model.add_module(name='%s' % m.i, module=m) # add
635 | self.eval()
636 | elif not mode and present:
637 | print('Removing NMS... ')
638 | self.model = self.model[:-1] # remove
639 | return self
640 |
641 | def autoshape(self): # add autoShape module
642 | print('Adding autoShape... ')
643 | m = autoShape(self) # wrap model
644 | copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
645 | return m
646 |
647 | def info(self, verbose=False, img_size=640): # print model information
648 | model_info(self, verbose, img_size)
649 |
650 |
651 | def parse_model(d, ch): # model_dict, input_channels(3)
652 | logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
653 | anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
654 | na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
655 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
656 |
657 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
658 | for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
659 | m = eval(m) if isinstance(m, str) else m # eval strings
660 | for j, a in enumerate(args):
661 | try:
662 | args[j] = eval(a) if isinstance(a, str) else a # eval strings
663 | except:
664 | pass
665 |
666 | n = max(round(n * gd), 1) if n > 1 else n # depth gain
667 | if m in [nn.Conv2d, Conv, RobustConv, RobustConv2, DWConv, GhostConv, RepConv, RepConv_OREPA, DownC,
668 | SPP, SPPF, SPPCSPC, GhostSPPCSPC, MixConv2d, Focus, Stem, GhostStem, CrossConv,
669 | Bottleneck, BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
670 | RepBottleneck, RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
671 | Res, ResCSPA, ResCSPB, ResCSPC,
672 | RepRes, RepResCSPA, RepResCSPB, RepResCSPC,
673 | ResX, ResXCSPA, ResXCSPB, ResXCSPC,
674 | RepResX, RepResXCSPA, RepResXCSPB, RepResXCSPC,
675 | Ghost, GhostCSPA, GhostCSPB, GhostCSPC,
676 | SwinTransformerBlock, STCSPA, STCSPB, STCSPC,
677 | SwinTransformer2Block, ST2CSPA, ST2CSPB, ST2CSPC]:
678 | c1, c2 = ch[f], args[0]
679 | if c2 != no: # if not output
680 | c2 = make_divisible(c2 * gw, 8)
681 |
682 | args = [c1, c2, *args[1:]]
683 | if m in [DownC, SPPCSPC, GhostSPPCSPC,
684 | BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
685 | RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
686 | ResCSPA, ResCSPB, ResCSPC,
687 | RepResCSPA, RepResCSPB, RepResCSPC,
688 | ResXCSPA, ResXCSPB, ResXCSPC,
689 | RepResXCSPA, RepResXCSPB, RepResXCSPC,
690 | GhostCSPA, GhostCSPB, GhostCSPC,
691 | STCSPA, STCSPB, STCSPC,
692 | ST2CSPA, ST2CSPB, ST2CSPC]:
693 | args.insert(2, n) # number of repeats
694 | n = 1
695 | elif m is nn.BatchNorm2d:
696 | args = [ch[f]]
697 | elif m is Concat:
698 | c2 = sum([ch[x] for x in f])
699 | elif m is Chuncat:
700 | c2 = sum([ch[x] for x in f])
701 | elif m is Shortcut:
702 | c2 = ch[f[0]]
703 | elif m is Foldcut:
704 | c2 = ch[f] // 2
705 | elif m in [Detect, IDetect, IAuxDetect, IBin, IKeypoint]:
706 | args.append([ch[x] for x in f])
707 | if isinstance(args[1], int): # number of anchors
708 | args[1] = [list(range(args[1] * 2))] * len(f)
709 | elif m is ReOrg:
710 | c2 = ch[f] * 4
711 | elif m is Contract:
712 | c2 = ch[f] * args[0] ** 2
713 | elif m is Expand:
714 | c2 = ch[f] // args[0] ** 2
715 | else:
716 | c2 = ch[f]
717 |
718 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
719 | t = str(m)[8:-2].replace('__main__.', '') # module type
720 | np = sum([x.numel() for x in m_.parameters()]) # number params
721 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
722 | logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
723 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
724 | layers.append(m_)
725 | if i == 0:
726 | ch = []
727 | ch.append(c2)
728 | return nn.Sequential(*layers), sorted(save)
729 |
730 |
731 | if __name__ == '__main__':
732 | parser = argparse.ArgumentParser()
733 | parser.add_argument('--cfg', type=str, default='yolor-csp-c.yaml', help='model.yaml')
734 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
735 | parser.add_argument('--profile', action='store_true', help='profile model speed')
736 | opt = parser.parse_args()
737 | opt.cfg = check_file(opt.cfg) # check file
738 | set_logging()
739 | device = select_device(opt.device)
740 |
741 | # Create model
742 | model = Model(opt.cfg).to(device)
743 | model.train()
744 |
745 | if opt.profile:
746 | img = torch.rand(1, 3, 640, 640).to(device)
747 | y = model(img, profile=True)
748 |
749 | # Profile
750 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
751 | # y = model(img, profile=True)
752 |
753 | # Tensorboard
754 | # from torch.utils.tensorboard import SummaryWriter
755 | # tb_writer = SummaryWriter()
756 | # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
757 | # tb_writer.add_graph(model.model, img) # add model to tensorboard
758 | # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
759 |
--------------------------------------------------------------------------------
/pose-estimate.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import time
3 | import torch
4 | import argparse
5 | import numpy as np
6 | import matplotlib.pyplot as plt
7 | from torchvision import transforms
8 | from utils.datasets import letterbox
9 | from utils.torch_utils import select_device
10 | from models.experimental import attempt_load
11 | from utils.general import non_max_suppression_kpt,strip_optimizer,xyxy2xywh
12 | from utils.plots import output_to_keypoint, plot_skeleton_kpts,colors,plot_one_box_kpt
13 |
14 | @torch.no_grad()
15 | def run(poseweights="yolov7-w6-pose.pt",source="football1.mp4",device='cpu',view_img=False,
16 | save_conf=False,line_thickness = 3,hide_labels=False, hide_conf=True):
17 |
18 | frame_count = 0 #count no of frames
19 | total_fps = 0 #count total fps
20 | time_list = [] #list to store time
21 | fps_list = [] #list to store fps
22 |
23 | device = select_device(opt.device) #select device
24 | half = device.type != 'cpu'
25 |
26 | model = attempt_load(poseweights, map_location=device) #Load model
27 | _ = model.eval()
28 | names = model.module.names if hasattr(model, 'module') else model.names # get class names
29 |
30 | if source.isnumeric() :
31 | cap = cv2.VideoCapture(int(source)) #pass video to videocapture object
32 | else :
33 | cap = cv2.VideoCapture(source) #pass video to videocapture object
34 |
35 | if (cap.isOpened() == False): #check if videocapture not opened
36 | print('Error while trying to read video. Please check path again')
37 | raise SystemExit()
38 |
39 | else:
40 | frame_width = int(cap.get(3)) #get video frame width
41 | frame_height = int(cap.get(4)) #get video frame height
42 |
43 |
44 | vid_write_image = letterbox(cap.read()[1], (frame_width), stride=64, auto=True)[0] #init videowriter
45 | resize_height, resize_width = vid_write_image.shape[:2]
46 | out_video_name = f"{source.split('/')[-1].split('.')[0]}"
47 | out = cv2.VideoWriter(f"{source}_keypoint.mp4",
48 | cv2.VideoWriter_fourcc(*'mp4v'), 30,
49 | (resize_width, resize_height))
50 |
51 | while(cap.isOpened): #loop until cap opened or video not complete
52 |
53 | print("Frame {} Processing".format(frame_count+1))
54 |
55 | ret, frame = cap.read() #get frame and success from video capture
56 |
57 | if ret: #if success is true, means frame exist
58 | orig_image = frame #store frame
59 | image = cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB) #convert frame to RGB
60 | image = letterbox(image, (frame_width), stride=64, auto=True)[0]
61 | image_ = image.copy()
62 | image = transforms.ToTensor()(image)
63 | image = torch.tensor(np.array([image.numpy()]))
64 |
65 | image = image.to(device) #convert image data to device
66 | image = image.float() #convert image to float precision (cpu)
67 | start_time = time.time() #start time for fps calculation
68 |
69 | with torch.no_grad(): #get predictions
70 | output_data, _ = model(image)
71 |
72 | output_data = non_max_suppression_kpt(output_data, #Apply non max suppression
73 | 0.25, # Conf. Threshold.
74 | 0.65, # IoU Threshold.
75 | nc=model.yaml['nc'], # Number of classes.
76 | nkpt=model.yaml['nkpt'], # Number of keypoints.
77 | kpt_label=True)
78 |
79 | output = output_to_keypoint(output_data)
80 |
81 | im0 = image[0].permute(1, 2, 0) * 255 # Change format [b, c, h, w] to [h, w, c] for displaying the image.
82 | im0 = im0.cpu().numpy().astype(np.uint8)
83 |
84 | im0 = cv2.cvtColor(im0, cv2.COLOR_RGB2BGR) #reshape image format to (BGR)
85 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
86 |
87 | for i, pose in enumerate(output_data): # detections per image
88 |
89 | if len(output_data): #check if no pose
90 | for c in pose[:, 5].unique(): # Print results
91 | n = (pose[:, 5] == c).sum() # detections per class
92 | print("No of Objects in Current Frame : {}".format(n))
93 |
94 | for det_index, (*xyxy, conf, cls) in enumerate(reversed(pose[:,:6])): #loop over poses for drawing on frame
95 | c = int(cls) # integer class
96 | kpts = pose[det_index, 6:]
97 | label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
98 | plot_one_box_kpt(xyxy, im0, label=label, color=colors(c, True),
99 | line_thickness=opt.line_thickness,kpt_label=True, kpts=kpts, steps=3,
100 | orig_shape=im0.shape[:2])
101 |
102 |
103 | end_time = time.time() #Calculatio for FPS
104 | fps = 1 / (end_time - start_time)
105 | total_fps += fps
106 | frame_count += 1
107 |
108 | fps_list.append(total_fps) #append FPS in list
109 | time_list.append(end_time - start_time) #append time in list
110 |
111 | # Stream results
112 | if view_img:
113 | cv2.imshow("YOLOv7 Pose Estimation Demo", im0)
114 | cv2.waitKey(1) # 1 millisecond
115 |
116 | out.write(im0) #writing the video frame
117 |
118 | else:
119 | break
120 |
121 | cap.release()
122 | # cv2.destroyAllWindows()
123 | avg_fps = total_fps / frame_count
124 | print(f"Average FPS: {avg_fps:.3f}")
125 |
126 | #plot the comparision graph
127 | plot_fps_time_comparision(time_list=time_list,fps_list=fps_list)
128 |
129 |
130 | def parse_opt():
131 | parser = argparse.ArgumentParser()
132 | parser.add_argument('--poseweights', nargs='+', type=str, default='yolov7-w6-pose.pt', help='model path(s)')
133 | parser.add_argument('--source', type=str, default='football1.mp4', help='video/0 for webcam') #video source
134 | parser.add_argument('--device', type=str, default='cpu', help='cpu/0,1,2,3(gpu)') #device arugments
135 | parser.add_argument('--view-img', action='store_true', help='display results') #display results
136 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') #save confidence in txt writing
137 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') #box linethickness
138 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') #box hidelabel
139 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') #boxhideconf
140 | opt = parser.parse_args()
141 | return opt
142 |
143 | #function for plot fps and time comparision graph
144 | def plot_fps_time_comparision(time_list,fps_list):
145 | plt.figure()
146 | plt.xlabel('Time (s)')
147 | plt.ylabel('FPS')
148 | plt.title('FPS and Time Comparision Graph')
149 | plt.plot(time_list, fps_list,'b',label="FPS & Time")
150 | plt.savefig("FPS_and_Time_Comparision_pose_estimate.png")
151 |
152 |
153 | #main function
154 | def main(opt):
155 | run(**vars(opt))
156 |
157 | if __name__ == "__main__":
158 | opt = parse_opt()
159 | strip_optimizer(opt.device,opt.poseweights)
160 | main(opt)
161 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # Usage: pip install -r requirements.txt
2 |
3 | # Base ----------------------------------------
4 | matplotlib>=3.2.2
5 | numpy>=1.18.5
6 | opencv-python>=4.1.1
7 | Pillow>=7.1.2
8 | PyYAML>=5.3.1
9 | requests>=2.23.0
10 | scipy>=1.4.1
11 | torch>=1.7.0,!=1.12.0
12 | torchvision>=0.8.1,!=0.13.0
13 | tqdm>=4.41.0
14 | protobuf<4.21.3
15 |
16 | # Logging -------------------------------------
17 | tensorboard>=2.4.1
18 | # wandb
19 |
20 | # Plotting ------------------------------------
21 | pandas>=1.1.4
22 | seaborn>=0.11.0
23 |
24 |
25 | # Extras --------------------------------------
26 | ipython # interactive notebook
27 | psutil # system utilization
28 | thop # FLOPs computation
29 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 | # init
--------------------------------------------------------------------------------
/utils/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/autoanchor.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/autoanchor.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/datasets.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/datasets.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/general.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/general.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/google_utils.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/google_utils.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/loss.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/loss.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/metrics.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/metrics.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/plots.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/plots.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/torch_utils.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RizwanMunawar/yolov7-pose-estimation/6c81c3ade8d80e401cbad0bdb65f4682949b974f/utils/__pycache__/torch_utils.cpython-36.pyc
--------------------------------------------------------------------------------
/utils/activations.py:
--------------------------------------------------------------------------------
1 | # Activation functions
2 |
3 | import torch
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 |
7 |
8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU()
10 | @staticmethod
11 | def forward(x):
12 | return x * torch.sigmoid(x)
13 |
14 |
15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
16 | @staticmethod
17 | def forward(x):
18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML
19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
20 |
21 |
22 | class MemoryEfficientSwish(nn.Module):
23 | class F(torch.autograd.Function):
24 | @staticmethod
25 | def forward(ctx, x):
26 | ctx.save_for_backward(x)
27 | return x * torch.sigmoid(x)
28 |
29 | @staticmethod
30 | def backward(ctx, grad_output):
31 | x = ctx.saved_tensors[0]
32 | sx = torch.sigmoid(x)
33 | return grad_output * (sx * (1 + x * (1 - sx)))
34 |
35 | def forward(self, x):
36 | return self.F.apply(x)
37 |
38 |
39 | # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
40 | class Mish(nn.Module):
41 | @staticmethod
42 | def forward(x):
43 | return x * F.softplus(x).tanh()
44 |
45 |
46 | class MemoryEfficientMish(nn.Module):
47 | class F(torch.autograd.Function):
48 | @staticmethod
49 | def forward(ctx, x):
50 | ctx.save_for_backward(x)
51 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
52 |
53 | @staticmethod
54 | def backward(ctx, grad_output):
55 | x = ctx.saved_tensors[0]
56 | sx = torch.sigmoid(x)
57 | fx = F.softplus(x).tanh()
58 | return grad_output * (fx + x * sx * (1 - fx * fx))
59 |
60 | def forward(self, x):
61 | return self.F.apply(x)
62 |
63 |
64 | # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
65 | class FReLU(nn.Module):
66 | def __init__(self, c1, k=3): # ch_in, kernel
67 | super().__init__()
68 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
69 | self.bn = nn.BatchNorm2d(c1)
70 |
71 | def forward(self, x):
72 | return torch.max(x, self.bn(self.conv(x)))
73 |
--------------------------------------------------------------------------------
/utils/add_nms.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import onnx
3 | from onnx import shape_inference
4 | try:
5 | import onnx_graphsurgeon as gs
6 | except Exception as e:
7 | print('Import onnx_graphsurgeon failure: %s' % e)
8 |
9 | import logging
10 |
11 | LOGGER = logging.getLogger(__name__)
12 |
13 | class RegisterNMS(object):
14 | def __init__(
15 | self,
16 | onnx_model_path: str,
17 | precision: str = "fp32",
18 | ):
19 |
20 | self.graph = gs.import_onnx(onnx.load(onnx_model_path))
21 | assert self.graph
22 | LOGGER.info("ONNX graph created successfully")
23 | # Fold constants via ONNX-GS that PyTorch2ONNX may have missed
24 | self.graph.fold_constants()
25 | self.precision = precision
26 | self.batch_size = 1
27 | def infer(self):
28 | """
29 | Sanitize the graph by cleaning any unconnected nodes, do a topological resort,
30 | and fold constant inputs values. When possible, run shape inference on the
31 | ONNX graph to determine tensor shapes.
32 | """
33 | for _ in range(3):
34 | count_before = len(self.graph.nodes)
35 |
36 | self.graph.cleanup().toposort()
37 | try:
38 | for node in self.graph.nodes:
39 | for o in node.outputs:
40 | o.shape = None
41 | model = gs.export_onnx(self.graph)
42 | model = shape_inference.infer_shapes(model)
43 | self.graph = gs.import_onnx(model)
44 | except Exception as e:
45 | LOGGER.info(f"Shape inference could not be performed at this time:\n{e}")
46 | try:
47 | self.graph.fold_constants(fold_shapes=True)
48 | except TypeError as e:
49 | LOGGER.error(
50 | "This version of ONNX GraphSurgeon does not support folding shapes, "
51 | f"please upgrade your onnx_graphsurgeon module. Error:\n{e}"
52 | )
53 | raise
54 |
55 | count_after = len(self.graph.nodes)
56 | if count_before == count_after:
57 | # No new folding occurred in this iteration, so we can stop for now.
58 | break
59 |
60 | def save(self, output_path):
61 | """
62 | Save the ONNX model to the given location.
63 | Args:
64 | output_path: Path pointing to the location where to write
65 | out the updated ONNX model.
66 | """
67 | self.graph.cleanup().toposort()
68 | model = gs.export_onnx(self.graph)
69 | onnx.save(model, output_path)
70 | LOGGER.info(f"Saved ONNX model to {output_path}")
71 |
72 | def register_nms(
73 | self,
74 | *,
75 | score_thresh: float = 0.25,
76 | nms_thresh: float = 0.45,
77 | detections_per_img: int = 100,
78 | ):
79 | """
80 | Register the ``EfficientNMS_TRT`` plugin node.
81 | NMS expects these shapes for its input tensors:
82 | - box_net: [batch_size, number_boxes, 4]
83 | - class_net: [batch_size, number_boxes, number_labels]
84 | Args:
85 | score_thresh (float): The scalar threshold for score (low scoring boxes are removed).
86 | nms_thresh (float): The scalar threshold for IOU (new boxes that have high IOU
87 | overlap with previously selected boxes are removed).
88 | detections_per_img (int): Number of best detections to keep after NMS.
89 | """
90 |
91 | self.infer()
92 | # Find the concat node at the end of the network
93 | op_inputs = self.graph.outputs
94 | op = "EfficientNMS_TRT"
95 | attrs = {
96 | "plugin_version": "1",
97 | "background_class": -1, # no background class
98 | "max_output_boxes": detections_per_img,
99 | "score_threshold": score_thresh,
100 | "iou_threshold": nms_thresh,
101 | "score_activation": False,
102 | "box_coding": 0,
103 | }
104 |
105 | if self.precision == "fp32":
106 | dtype_output = np.float32
107 | elif self.precision == "fp16":
108 | dtype_output = np.float16
109 | else:
110 | raise NotImplementedError(f"Currently not supports precision: {self.precision}")
111 |
112 | # NMS Outputs
113 | output_num_detections = gs.Variable(
114 | name="num_detections",
115 | dtype=np.int32,
116 | shape=[self.batch_size, 1],
117 | ) # A scalar indicating the number of valid detections per batch image.
118 | output_boxes = gs.Variable(
119 | name="detection_boxes",
120 | dtype=dtype_output,
121 | shape=[self.batch_size, detections_per_img, 4],
122 | )
123 | output_scores = gs.Variable(
124 | name="detection_scores",
125 | dtype=dtype_output,
126 | shape=[self.batch_size, detections_per_img],
127 | )
128 | output_labels = gs.Variable(
129 | name="detection_classes",
130 | dtype=np.int32,
131 | shape=[self.batch_size, detections_per_img],
132 | )
133 |
134 | op_outputs = [output_num_detections, output_boxes, output_scores, output_labels]
135 |
136 | # Create the NMS Plugin node with the selected inputs. The outputs of the node will also
137 | # become the final outputs of the graph.
138 | self.graph.layer(op=op, name="batched_nms", inputs=op_inputs, outputs=op_outputs, attrs=attrs)
139 | LOGGER.info(f"Created NMS plugin '{op}' with attributes: {attrs}")
140 |
141 | self.graph.outputs = op_outputs
142 |
143 | self.infer()
144 |
145 | def save(self, output_path):
146 | """
147 | Save the ONNX model to the given location.
148 | Args:
149 | output_path: Path pointing to the location where to write
150 | out the updated ONNX model.
151 | """
152 | self.graph.cleanup().toposort()
153 | model = gs.export_onnx(self.graph)
154 | onnx.save(model, output_path)
155 | LOGGER.info(f"Saved ONNX model to {output_path}")
156 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # Auto-anchor utils
2 |
3 | import numpy as np
4 | import torch
5 | import yaml
6 | from scipy.cluster.vq import kmeans
7 | from tqdm import tqdm
8 |
9 | from utils.general import colorstr
10 |
11 |
12 | def check_anchor_order(m):
13 | # Check anchor order against stride order for YOLO Detect() module m, and correct if necessary
14 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
15 | da = a[-1] - a[0] # delta a
16 | ds = m.stride[-1] - m.stride[0] # delta s
17 | if da.sign() != ds.sign(): # same order
18 | print('Reversing anchor order')
19 | m.anchors[:] = m.anchors.flip(0)
20 | m.anchor_grid[:] = m.anchor_grid.flip(0)
21 |
22 |
23 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
24 | # Check anchor fit to data, recompute if necessary
25 | prefix = colorstr('autoanchor: ')
26 | print(f'\n{prefix}Analyzing anchors... ', end='')
27 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
28 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
29 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
30 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
31 |
32 | def metric(k): # compute metric
33 | r = wh[:, None] / k[None]
34 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
35 | best = x.max(1)[0] # best_x
36 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
37 | bpr = (best > 1. / thr).float().mean() # best possible recall
38 | return bpr, aat
39 |
40 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
41 | bpr, aat = metric(anchors)
42 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
43 | if bpr < 0.98: # threshold to recompute
44 | print('. Attempting to improve anchors, please wait...')
45 | na = m.anchor_grid.numel() // 2 # number of anchors
46 | try:
47 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
48 | except Exception as e:
49 | print(f'{prefix}ERROR: {e}')
50 | new_bpr = metric(anchors)[0]
51 | if new_bpr > bpr: # replace anchors
52 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
53 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
54 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
55 | check_anchor_order(m)
56 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
57 | else:
58 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
59 | print('') # newline
60 |
61 |
62 | def kmean_anchors(path='./data/coco.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
63 | """ Creates kmeans-evolved anchors from training dataset
64 |
65 | Arguments:
66 | path: path to dataset *.yaml, or a loaded dataset
67 | n: number of anchors
68 | img_size: image size used for training
69 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
70 | gen: generations to evolve anchors using genetic algorithm
71 | verbose: print all results
72 |
73 | Return:
74 | k: kmeans evolved anchors
75 |
76 | Usage:
77 | from utils.autoanchor import *; _ = kmean_anchors()
78 | """
79 | thr = 1. / thr
80 | prefix = colorstr('autoanchor: ')
81 |
82 | def metric(k, wh): # compute metrics
83 | r = wh[:, None] / k[None]
84 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
85 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
86 | return x, x.max(1)[0] # x, best_x
87 |
88 | def anchor_fitness(k): # mutation fitness
89 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
90 | return (best * (best > thr).float()).mean() # fitness
91 |
92 | def print_results(k):
93 | k = k[np.argsort(k.prod(1))] # sort small to large
94 | x, best = metric(k, wh0)
95 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
96 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
97 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
98 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
99 | for i, x in enumerate(k):
100 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
101 | return k
102 |
103 | if isinstance(path, str): # *.yaml file
104 | with open(path) as f:
105 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict
106 | from utils.datasets import LoadImagesAndLabels
107 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
108 | else:
109 | dataset = path # dataset
110 |
111 | # Get label wh
112 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
113 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
114 |
115 | # Filter
116 | i = (wh0 < 3.0).any(1).sum()
117 | if i:
118 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
119 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
120 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
121 |
122 | # Kmeans calculation
123 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
124 | s = wh.std(0) # sigmas for whitening
125 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
126 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
127 | k *= s
128 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
129 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
130 | k = print_results(k)
131 |
132 | # Plot
133 | # k, d = [None] * 20, [None] * 20
134 | # for i in tqdm(range(1, 21)):
135 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
136 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
137 | # ax = ax.ravel()
138 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
139 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
140 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
141 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
142 | # fig.savefig('wh.png', dpi=200)
143 |
144 | # Evolve
145 | npr = np.random
146 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
147 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
148 | for _ in pbar:
149 | v = np.ones(sh)
150 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
151 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
152 | kg = (k.copy() * v).clip(min=2.0)
153 | fg = anchor_fitness(kg)
154 | if fg > f:
155 | f, k = fg, kg.copy()
156 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
157 | if verbose:
158 | print_results(k)
159 |
160 | return print_results(k)
161 |
--------------------------------------------------------------------------------
/utils/google_utils.py:
--------------------------------------------------------------------------------
1 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2 |
3 | import os
4 | import platform
5 | import subprocess
6 | import time
7 | from pathlib import Path
8 |
9 | import requests
10 | import torch
11 |
12 |
13 | def gsutil_getsize(url=''):
14 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
16 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes
17 |
18 |
19 | def attempt_download(file, repo='WongKinYiu/yolov7'):
20 | # Attempt file download if does not exist
21 | file = Path(str(file).strip().replace("'", '').lower())
22 |
23 | if not file.exists():
24 | try:
25 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
26 | assets = [x['name'] for x in response['assets']] # release assets
27 | tag = response['tag_name'] # i.e. 'v1.0'
28 | except: # fallback plan
29 | assets = ['yolov7.pt']
30 | tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]
31 |
32 | name = file.name
33 | if name in assets:
34 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
35 | redundant = False # second download option
36 | try: # GitHub
37 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
38 | print(f'Downloading {url} to {file}...')
39 | torch.hub.download_url_to_file(url, file)
40 | assert file.exists() and file.stat().st_size > 1E6 # check
41 | except Exception as e: # GCP
42 | print(f'Download error: {e}')
43 | assert redundant, 'No secondary mirror'
44 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
45 | print(f'Downloading {url} to {file}...')
46 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
47 | finally:
48 | if not file.exists() or file.stat().st_size < 1E6: # check
49 | file.unlink(missing_ok=True) # remove partial downloads
50 | print(f'ERROR: Download failure: {msg}')
51 | print('')
52 | return
53 |
54 |
55 | def gdrive_download(id='', file='tmp.zip'):
56 | # Downloads a file from Google Drive. from yolov7.utils.google_utils import *; gdrive_download()
57 | t = time.time()
58 | file = Path(file)
59 | cookie = Path('cookie') # gdrive cookie
60 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
61 | file.unlink(missing_ok=True) # remove existing file
62 | cookie.unlink(missing_ok=True) # remove existing cookie
63 |
64 | # Attempt file download
65 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
66 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
67 | if os.path.exists('cookie'): # large file
68 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
69 | else: # small file
70 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
71 | r = os.system(s) # execute, capture return
72 | cookie.unlink(missing_ok=True) # remove existing cookie
73 |
74 | # Error check
75 | if r != 0:
76 | file.unlink(missing_ok=True) # remove partial
77 | print('Download error ') # raise Exception('Download error')
78 | return r
79 |
80 | # Unzip if archive
81 | if file.suffix == '.zip':
82 | print('unzipping... ', end='')
83 | os.system(f'unzip -q {file}') # unzip
84 | file.unlink() # remove zip to free space
85 |
86 | print(f'Done ({time.time() - t:.1f}s)')
87 | return r
88 |
89 |
90 | def get_token(cookie="./cookie"):
91 | with open(cookie) as f:
92 | for line in f:
93 | if "download" in line:
94 | return line.split()[-1]
95 | return ""
96 |
97 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
98 | # # Uploads a file to a bucket
99 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
100 | #
101 | # storage_client = storage.Client()
102 | # bucket = storage_client.get_bucket(bucket_name)
103 | # blob = bucket.blob(destination_blob_name)
104 | #
105 | # blob.upload_from_filename(source_file_name)
106 | #
107 | # print('File {} uploaded to {}.'.format(
108 | # source_file_name,
109 | # destination_blob_name))
110 | #
111 | #
112 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
113 | # # Uploads a blob from a bucket
114 | # storage_client = storage.Client()
115 | # bucket = storage_client.get_bucket(bucket_name)
116 | # blob = bucket.blob(source_blob_name)
117 | #
118 | # blob.download_to_filename(destination_file_name)
119 | #
120 | # print('Blob {} downloaded to {}.'.format(
121 | # source_blob_name,
122 | # destination_file_name))
123 |
--------------------------------------------------------------------------------
/utils/metrics.py:
--------------------------------------------------------------------------------
1 | # Model validation metrics
2 |
3 | from pathlib import Path
4 |
5 | import matplotlib.pyplot as plt
6 | import numpy as np
7 | import torch
8 |
9 | from . import general
10 |
11 |
12 | def fitness(x):
13 | # Model fitness as a weighted combination of metrics
14 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
15 | return (x[:, :4] * w).sum(1)
16 |
17 |
18 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
19 | """ Compute the average precision, given the recall and precision curves.
20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21 | # Arguments
22 | tp: True positives (nparray, nx1 or nx10).
23 | conf: Objectness value from 0-1 (nparray).
24 | pred_cls: Predicted object classes (nparray).
25 | target_cls: True object classes (nparray).
26 | plot: Plot precision-recall curve at mAP@0.5
27 | save_dir: Plot save directory
28 | # Returns
29 | The average precision as computed in py-faster-rcnn.
30 | """
31 |
32 | # Sort by objectness
33 | i = np.argsort(-conf)
34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35 |
36 | # Find unique classes
37 | unique_classes = np.unique(target_cls)
38 | nc = unique_classes.shape[0] # number of classes, number of detections
39 |
40 | # Create Precision-Recall curve and compute AP for each class
41 | px, py = np.linspace(0, 1, 1000), [] # for plotting
42 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43 | for ci, c in enumerate(unique_classes):
44 | i = pred_cls == c
45 | n_l = (target_cls == c).sum() # number of labels
46 | n_p = i.sum() # number of predictions
47 |
48 | if n_p == 0 or n_l == 0:
49 | continue
50 | else:
51 | # Accumulate FPs and TPs
52 | fpc = (1 - tp[i]).cumsum(0)
53 | tpc = tp[i].cumsum(0)
54 |
55 | # Recall
56 | recall = tpc / (n_l + 1e-16) # recall curve
57 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58 |
59 | # Precision
60 | precision = tpc / (tpc + fpc) # precision curve
61 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62 |
63 | # AP from recall-precision curve
64 | for j in range(tp.shape[1]):
65 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
66 | if plot and j == 0:
67 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
68 |
69 | # Compute F1 (harmonic mean of precision and recall)
70 | f1 = 2 * p * r / (p + r + 1e-16)
71 | if plot:
72 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76 |
77 | i = f1.mean(0).argmax() # max F1 index
78 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
79 |
80 |
81 | def compute_ap(recall, precision):
82 | """ Compute the average precision, given the recall and precision curves
83 | # Arguments
84 | recall: The recall curve (list)
85 | precision: The precision curve (list)
86 | # Returns
87 | Average precision, precision curve, recall curve
88 | """
89 |
90 | # Append sentinel values to beginning and end
91 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
92 | mpre = np.concatenate(([1.], precision, [0.]))
93 |
94 | # Compute the precision envelope
95 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
96 |
97 | # Integrate area under curve
98 | method = 'interp' # methods: 'continuous', 'interp'
99 | if method == 'interp':
100 | x = np.linspace(0, 1, 101) # 101-point interp (COCO)
101 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
102 | else: # 'continuous'
103 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
104 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
105 |
106 | return ap, mpre, mrec
107 |
108 |
109 | class ConfusionMatrix:
110 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
111 | def __init__(self, nc, conf=0.25, iou_thres=0.45):
112 | self.matrix = np.zeros((nc + 1, nc + 1))
113 | self.nc = nc # number of classes
114 | self.conf = conf
115 | self.iou_thres = iou_thres
116 |
117 | def process_batch(self, detections, labels):
118 | """
119 | Return intersection-over-union (Jaccard index) of boxes.
120 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
121 | Arguments:
122 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class
123 | labels (Array[M, 5]), class, x1, y1, x2, y2
124 | Returns:
125 | None, updates confusion matrix accordingly
126 | """
127 | detections = detections[detections[:, 4] > self.conf]
128 | gt_classes = labels[:, 0].int()
129 | detection_classes = detections[:, 5].int()
130 | iou = general.box_iou(labels[:, 1:], detections[:, :4])
131 |
132 | x = torch.where(iou > self.iou_thres)
133 | if x[0].shape[0]:
134 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
135 | if x[0].shape[0] > 1:
136 | matches = matches[matches[:, 2].argsort()[::-1]]
137 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
138 | matches = matches[matches[:, 2].argsort()[::-1]]
139 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
140 | else:
141 | matches = np.zeros((0, 3))
142 |
143 | n = matches.shape[0] > 0
144 | m0, m1, _ = matches.transpose().astype(np.int16)
145 | for i, gc in enumerate(gt_classes):
146 | j = m0 == i
147 | if n and sum(j) == 1:
148 | self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
149 | else:
150 | self.matrix[self.nc, gc] += 1 # background FP
151 |
152 | if n:
153 | for i, dc in enumerate(detection_classes):
154 | if not any(m1 == i):
155 | self.matrix[dc, self.nc] += 1 # background FN
156 |
157 | def matrix(self):
158 | return self.matrix
159 |
160 | def plot(self, save_dir='', names=()):
161 | try:
162 | import seaborn as sn
163 |
164 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
165 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
166 |
167 | fig = plt.figure(figsize=(12, 9), tight_layout=True)
168 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
169 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
170 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
171 | xticklabels=names + ['background FP'] if labels else "auto",
172 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
173 | fig.axes[0].set_xlabel('True')
174 | fig.axes[0].set_ylabel('Predicted')
175 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
176 | except Exception as e:
177 | pass
178 |
179 | def print(self):
180 | for i in range(self.nc + 1):
181 | print(' '.join(map(str, self.matrix[i])))
182 |
183 |
184 | # Plots ----------------------------------------------------------------------------------------------------------------
185 |
186 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
187 | # Precision-recall curve
188 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
189 | py = np.stack(py, axis=1)
190 |
191 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
192 | for i, y in enumerate(py.T):
193 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
194 | else:
195 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
196 |
197 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
198 | ax.set_xlabel('Recall')
199 | ax.set_ylabel('Precision')
200 | ax.set_xlim(0, 1)
201 | ax.set_ylim(0, 1)
202 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
203 | fig.savefig(Path(save_dir), dpi=250)
204 |
205 |
206 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
207 | # Metric-confidence curve
208 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
209 |
210 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
211 | for i, y in enumerate(py):
212 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
213 | else:
214 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
215 |
216 | y = py.mean(0)
217 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
218 | ax.set_xlabel(xlabel)
219 | ax.set_ylabel(ylabel)
220 | ax.set_xlim(0, 1)
221 | ax.set_ylim(0, 1)
222 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
223 | fig.savefig(Path(save_dir), dpi=250)
224 |
--------------------------------------------------------------------------------
/utils/plots.py:
--------------------------------------------------------------------------------
1 | # Plotting utils
2 |
3 | import glob
4 | import math
5 | import os
6 | import random
7 | from copy import copy
8 | from pathlib import Path
9 |
10 | import cv2
11 | import matplotlib
12 | import matplotlib.pyplot as plt
13 | import numpy as np
14 | import pandas as pd
15 | import seaborn as sns
16 | import torch
17 | import yaml
18 | from PIL import Image, ImageDraw, ImageFont
19 | from scipy.signal import butter, filtfilt
20 |
21 | from utils.general import xywh2xyxy, xyxy2xywh
22 | from utils.metrics import fitness
23 |
24 | # Settings
25 | matplotlib.rc('font', **{'size': 11})
26 | matplotlib.use('Agg') # for writing to files only
27 |
28 | class Colors:
29 | # Ultralytics color palette https://ultralytics.com/
30 | def __init__(self):
31 | self.palette = [self.hex2rgb(c) for c in matplotlib.colors.TABLEAU_COLORS.values()]
32 | self.n = len(self.palette)
33 |
34 | def __call__(self, i, bgr=False):
35 | c = self.palette[int(i) % self.n]
36 | return (c[2], c[1], c[0]) if bgr else c
37 |
38 | @staticmethod
39 | def hex2rgb(h): # rgb order (PIL)
40 | return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
41 |
42 |
43 | def plot_one_box_kpt(x, im, color=None, label=None, line_thickness=3, kpt_label=False, kpts=None, steps=2, orig_shape=None):
44 | # Plots one bounding box on image 'im' using OpenCV
45 | assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
46 | tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
47 | color = color or [random.randint(0, 255) for _ in range(3)]
48 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
49 | cv2.rectangle(im, c1, c2, (255,0,0), thickness=tl*1//3, lineType=cv2.LINE_AA)
50 | if label:
51 | if len(label.split(' ')) > 1:
52 | label = label.split(' ')[-1]
53 | tf = max(tl - 1, 1) # font thickness
54 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 6, thickness=tf)[0]
55 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
56 | cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
57 | cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 6, [225, 255, 255], thickness=tf//2, lineType=cv2.LINE_AA)
58 | if kpt_label:
59 | plot_skeleton_kpts(im, kpts, steps, orig_shape=orig_shape)
60 |
61 | colors = Colors()
62 |
63 | def color_list():
64 | def hex2rgb(h):
65 | return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
66 |
67 | return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949)
68 |
69 |
70 | def hist2d(x, y, n=100):
71 | # 2d histogram used in labels.png and evolve.png
72 | xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
73 | hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
74 | xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
75 | yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
76 | return np.log(hist[xidx, yidx])
77 |
78 |
79 | def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
80 | # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
81 | def butter_lowpass(cutoff, fs, order):
82 | nyq = 0.5 * fs
83 | normal_cutoff = cutoff / nyq
84 | return butter(order, normal_cutoff, btype='low', analog=False)
85 |
86 | b, a = butter_lowpass(cutoff, fs, order=order)
87 | return filtfilt(b, a, data) # forward-backward filter
88 |
89 |
90 | def plot_one_box(x, img, color=None, label=None, line_thickness=1):
91 | # Plots one bounding box on image img
92 | tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 2 # line/font thickness
93 | color = color or [random.randint(0, 255) for _ in range(3)]
94 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
95 | cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
96 | if label:
97 | tf = max(tl - 1, 1) # font thickness
98 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
99 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
100 | cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
101 | cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
102 |
103 |
104 | def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None):
105 | img = Image.fromarray(img)
106 | draw = ImageDraw.Draw(img)
107 | line_thickness = line_thickness or max(int(min(img.size) / 200), 2)
108 | draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
109 | if label:
110 | fontsize = max(round(max(img.size) / 40), 12)
111 | font = ImageFont.truetype("Arial.ttf", fontsize)
112 | txt_width, txt_height = font.getsize(label)
113 | draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
114 | draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
115 | return np.asarray(img)
116 |
117 |
118 | def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
119 | # Compares the two methods for width-height anchor multiplication
120 | # https://github.com/ultralytics/yolov3/issues/168
121 | x = np.arange(-4.0, 4.0, .1)
122 | ya = np.exp(x)
123 | yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
124 |
125 | fig = plt.figure(figsize=(6, 3), tight_layout=True)
126 | plt.plot(x, ya, '.-', label='YOLOv3')
127 | plt.plot(x, yb ** 2, '.-', label='YOLOR ^2')
128 | plt.plot(x, yb ** 1.6, '.-', label='YOLOR ^1.6')
129 | plt.xlim(left=-4, right=4)
130 | plt.ylim(bottom=0, top=6)
131 | plt.xlabel('input')
132 | plt.ylabel('output')
133 | plt.grid()
134 | plt.legend()
135 | fig.savefig('comparison.png', dpi=200)
136 |
137 |
138 | def output_to_target(output):
139 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
140 | targets = []
141 | for i, o in enumerate(output):
142 | for *box, conf, cls in o.cpu().numpy():
143 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
144 | return np.array(targets)
145 |
146 |
147 | def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
148 | # Plot image grid with labels
149 |
150 | if isinstance(images, torch.Tensor):
151 | images = images.cpu().float().numpy()
152 | if isinstance(targets, torch.Tensor):
153 | targets = targets.cpu().numpy()
154 |
155 | # un-normalise
156 | if np.max(images[0]) <= 1:
157 | images *= 255
158 |
159 | tl = 3 # line thickness
160 | tf = max(tl - 1, 1) # font thickness
161 | bs, _, h, w = images.shape # batch size, _, height, width
162 | bs = min(bs, max_subplots) # limit plot images
163 | ns = np.ceil(bs ** 0.5) # number of subplots (square)
164 |
165 | # Check if we should resize
166 | scale_factor = max_size / max(h, w)
167 | if scale_factor < 1:
168 | h = math.ceil(scale_factor * h)
169 | w = math.ceil(scale_factor * w)
170 |
171 | colors = color_list() # list of colors
172 | mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
173 | for i, img in enumerate(images):
174 | if i == max_subplots: # if last batch has fewer images than we expect
175 | break
176 |
177 | block_x = int(w * (i // ns))
178 | block_y = int(h * (i % ns))
179 |
180 | img = img.transpose(1, 2, 0)
181 | if scale_factor < 1:
182 | img = cv2.resize(img, (w, h))
183 |
184 | mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
185 | if len(targets) > 0:
186 | image_targets = targets[targets[:, 0] == i]
187 | boxes = xywh2xyxy(image_targets[:, 2:6]).T
188 | classes = image_targets[:, 1].astype('int')
189 | labels = image_targets.shape[1] == 6 # labels if no conf column
190 | conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
191 |
192 | if boxes.shape[1]:
193 | if boxes.max() <= 1.01: # if normalized with tolerance 0.01
194 | boxes[[0, 2]] *= w # scale to pixels
195 | boxes[[1, 3]] *= h
196 | elif scale_factor < 1: # absolute coords need scale if image scales
197 | boxes *= scale_factor
198 | boxes[[0, 2]] += block_x
199 | boxes[[1, 3]] += block_y
200 | for j, box in enumerate(boxes.T):
201 | cls = int(classes[j])
202 | color = colors[cls % len(colors)]
203 | cls = names[cls] if names else cls
204 | if labels or conf[j] > 0.25: # 0.25 conf thresh
205 | label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
206 | plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
207 |
208 | # Draw image filename labels
209 | if paths:
210 | label = Path(paths[i]).name[:40] # trim to 40 char
211 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
212 | cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
213 | lineType=cv2.LINE_AA)
214 |
215 | # Image border
216 | cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
217 |
218 | if fname:
219 | r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
220 | mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
221 | # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
222 | Image.fromarray(mosaic).save(fname) # PIL save
223 | return mosaic
224 |
225 |
226 | def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
227 | # Plot LR simulating training for full epochs
228 | optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
229 | y = []
230 | for _ in range(epochs):
231 | scheduler.step()
232 | y.append(optimizer.param_groups[0]['lr'])
233 | plt.plot(y, '.-', label='LR')
234 | plt.xlabel('epoch')
235 | plt.ylabel('LR')
236 | plt.grid()
237 | plt.xlim(0, epochs)
238 | plt.ylim(0)
239 | plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
240 | plt.close()
241 |
242 |
243 | def plot_test_txt(): # from utils.plots import *; plot_test()
244 | # Plot test.txt histograms
245 | x = np.loadtxt('test.txt', dtype=np.float32)
246 | box = xyxy2xywh(x[:, :4])
247 | cx, cy = box[:, 0], box[:, 1]
248 |
249 | fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
250 | ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
251 | ax.set_aspect('equal')
252 | plt.savefig('hist2d.png', dpi=300)
253 |
254 | fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
255 | ax[0].hist(cx, bins=600)
256 | ax[1].hist(cy, bins=600)
257 | plt.savefig('hist1d.png', dpi=200)
258 |
259 |
260 | def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
261 | # Plot targets.txt histograms
262 | x = np.loadtxt('targets.txt', dtype=np.float32).T
263 | s = ['x targets', 'y targets', 'width targets', 'height targets']
264 | fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
265 | ax = ax.ravel()
266 | for i in range(4):
267 | ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
268 | ax[i].legend()
269 | ax[i].set_title(s[i])
270 | plt.savefig('targets.jpg', dpi=200)
271 |
272 |
273 | def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
274 | # Plot study.txt generated by test.py
275 | fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
276 | # ax = ax.ravel()
277 |
278 | fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
279 | # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolor-p6', 'yolor-w6', 'yolor-e6', 'yolor-d6']]:
280 | for f in sorted(Path(path).glob('study*.txt')):
281 | y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
282 | x = np.arange(y.shape[1]) if x is None else np.array(x)
283 | s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
284 | # for i in range(7):
285 | # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
286 | # ax[i].set_title(s[i])
287 |
288 | j = y[3].argmax() + 1
289 | ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
290 | label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
291 |
292 | ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
293 | 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
294 |
295 | ax2.grid(alpha=0.2)
296 | ax2.set_yticks(np.arange(20, 60, 5))
297 | ax2.set_xlim(0, 57)
298 | ax2.set_ylim(30, 55)
299 | ax2.set_xlabel('GPU Speed (ms/img)')
300 | ax2.set_ylabel('COCO AP val')
301 | ax2.legend(loc='lower right')
302 | plt.savefig(str(Path(path).name) + '.png', dpi=300)
303 |
304 |
305 | def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
306 | # plot dataset labels
307 | print('Plotting labels... ')
308 | c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
309 | nc = int(c.max() + 1) # number of classes
310 | colors = color_list()
311 | x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
312 |
313 | # seaborn correlogram
314 | sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
315 | plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
316 | plt.close()
317 |
318 | # matplotlib labels
319 | matplotlib.use('svg') # faster
320 | ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
321 | ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
322 | ax[0].set_ylabel('instances')
323 | if 0 < len(names) < 30:
324 | ax[0].set_xticks(range(len(names)))
325 | ax[0].set_xticklabels(names, rotation=90, fontsize=10)
326 | else:
327 | ax[0].set_xlabel('classes')
328 | sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
329 | sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
330 |
331 | # rectangles
332 | labels[:, 1:3] = 0.5 # center
333 | labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
334 | img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
335 | for cls, *box in labels[:1000]:
336 | ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
337 | ax[1].imshow(img)
338 | ax[1].axis('off')
339 |
340 | for a in [0, 1, 2, 3]:
341 | for s in ['top', 'right', 'left', 'bottom']:
342 | ax[a].spines[s].set_visible(False)
343 |
344 | plt.savefig(save_dir / 'labels.jpg', dpi=200)
345 | matplotlib.use('Agg')
346 | plt.close()
347 |
348 | # loggers
349 | for k, v in loggers.items() or {}:
350 | if k == 'wandb' and v:
351 | v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
352 |
353 |
354 | def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
355 | # Plot hyperparameter evolution results in evolve.txt
356 | with open(yaml_file) as f:
357 | hyp = yaml.load(f, Loader=yaml.SafeLoader)
358 | x = np.loadtxt('evolve.txt', ndmin=2)
359 | f = fitness(x)
360 | # weights = (f - f.min()) ** 2 # for weighted results
361 | plt.figure(figsize=(10, 12), tight_layout=True)
362 | matplotlib.rc('font', **{'size': 8})
363 | for i, (k, v) in enumerate(hyp.items()):
364 | y = x[:, i + 7]
365 | # mu = (y * weights).sum() / weights.sum() # best weighted result
366 | mu = y[f.argmax()] # best single result
367 | plt.subplot(6, 5, i + 1)
368 | plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
369 | plt.plot(mu, f.max(), 'k+', markersize=15)
370 | plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
371 | if i % 5 != 0:
372 | plt.yticks([])
373 | print('%15s: %.3g' % (k, mu))
374 | plt.savefig('evolve.png', dpi=200)
375 | print('\nPlot saved as evolve.png')
376 |
377 |
378 | def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
379 | # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
380 | ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
381 | s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
382 | files = list(Path(save_dir).glob('frames*.txt'))
383 | for fi, f in enumerate(files):
384 | try:
385 | results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
386 | n = results.shape[1] # number of rows
387 | x = np.arange(start, min(stop, n) if stop else n)
388 | results = results[:, x]
389 | t = (results[0] - results[0].min()) # set t0=0s
390 | results[0] = x
391 | for i, a in enumerate(ax):
392 | if i < len(results):
393 | label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
394 | a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
395 | a.set_title(s[i])
396 | a.set_xlabel('time (s)')
397 | # if fi == len(files) - 1:
398 | # a.set_ylim(bottom=0)
399 | for side in ['top', 'right']:
400 | a.spines[side].set_visible(False)
401 | else:
402 | a.remove()
403 | except Exception as e:
404 | print('Warning: Plotting error for %s; %s' % (f, e))
405 |
406 | ax[1].legend()
407 | plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
408 |
409 |
410 | def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
411 | # Plot training 'results*.txt', overlaying train and val losses
412 | s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
413 | t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
414 | for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
415 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
416 | n = results.shape[1] # number of rows
417 | x = range(start, min(stop, n) if stop else n)
418 | fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
419 | ax = ax.ravel()
420 | for i in range(5):
421 | for j in [i, i + 5]:
422 | y = results[j, x]
423 | ax[i].plot(x, y, marker='.', label=s[j])
424 | # y_smooth = butter_lowpass_filtfilt(y)
425 | # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
426 |
427 | ax[i].set_title(t[i])
428 | ax[i].legend()
429 | ax[i].set_ylabel(f) if i == 0 else None # add filename
430 | fig.savefig(f.replace('.txt', '.png'), dpi=200)
431 |
432 |
433 | def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
434 | # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
435 | fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
436 | ax = ax.ravel()
437 | s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
438 | 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
439 | if bucket:
440 | # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
441 | files = ['results%g.txt' % x for x in id]
442 | c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
443 | os.system(c)
444 | else:
445 | files = list(Path(save_dir).glob('results*.txt'))
446 | assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
447 | for fi, f in enumerate(files):
448 | try:
449 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
450 | n = results.shape[1] # number of rows
451 | x = range(start, min(stop, n) if stop else n)
452 | for i in range(10):
453 | y = results[i, x]
454 | if i in [0, 1, 2, 5, 6, 7]:
455 | y[y == 0] = np.nan # don't show zero loss values
456 | # y /= y[0] # normalize
457 | label = labels[fi] if len(labels) else f.stem
458 | ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
459 | ax[i].set_title(s[i])
460 | # if i in [5, 6, 7]: # share train and val loss y axes
461 | # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
462 | except Exception as e:
463 | print('Warning: Plotting error for %s; %s' % (f, e))
464 |
465 | ax[1].legend()
466 | fig.savefig(Path(save_dir) / 'results.png', dpi=200)
467 |
468 |
469 | def output_to_keypoint(output):
470 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
471 | targets = []
472 | for i, o in enumerate(output):
473 | kpts = o[:,6:]
474 | o = o[:,:6]
475 | for index, (*box, conf, cls) in enumerate(o.cpu().numpy()):
476 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf, *list(kpts.cpu().numpy()[index])])
477 | return np.array(targets)
478 |
479 |
480 | def plot_skeleton_kpts(im, kpts, steps, orig_shape=None):
481 | #Plot the skeleton and keypointsfor coco datatset
482 | palette = np.array([[255, 128, 0], [255, 153, 51], [255, 178, 102],
483 | [230, 230, 0], [255, 153, 255], [153, 204, 255],
484 | [255, 102, 255], [255, 51, 255], [102, 178, 255],
485 | [51, 153, 255], [255, 153, 153], [255, 102, 102],
486 | [255, 51, 51], [153, 255, 153], [102, 255, 102],
487 | [51, 255, 51], [0, 255, 0], [0, 0, 255], [255, 0, 0],
488 | [255, 255, 255]])
489 |
490 | skeleton = [[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12],
491 | [7, 13], [6, 7], [6, 8], [7, 9], [8, 10], [9, 11], [2, 3],
492 | [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]]
493 |
494 | pose_limb_color = palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]]
495 | pose_kpt_color = palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]]
496 | radius = 5
497 | num_kpts = len(kpts) // steps
498 |
499 | for kid in range(num_kpts):
500 | r, g, b = pose_kpt_color[kid]
501 | x_coord, y_coord = kpts[steps * kid], kpts[steps * kid + 1]
502 | if not (x_coord % 640 == 0 or y_coord % 640 == 0):
503 | if steps == 3:
504 | conf = kpts[steps * kid + 2]
505 | if conf < 0.5:
506 | continue
507 | cv2.circle(im, (int(x_coord), int(y_coord)), radius, (int(r), int(g), int(b)), -1)
508 |
509 | for sk_id, sk in enumerate(skeleton):
510 | r, g, b = pose_limb_color[sk_id]
511 | pos1 = (int(kpts[(sk[0]-1)*steps]), int(kpts[(sk[0]-1)*steps+1]))
512 | pos2 = (int(kpts[(sk[1]-1)*steps]), int(kpts[(sk[1]-1)*steps+1]))
513 | if steps == 3:
514 | conf1 = kpts[(sk[0]-1)*steps+2]
515 | conf2 = kpts[(sk[1]-1)*steps+2]
516 | if conf1<0.5 or conf2<0.5:
517 | continue
518 | if pos1[0]%640 == 0 or pos1[1]%640==0 or pos1[0]<0 or pos1[1]<0:
519 | continue
520 | if pos2[0] % 640 == 0 or pos2[1] % 640 == 0 or pos2[0]<0 or pos2[1]<0:
521 | continue
522 | cv2.line(im, pos1, pos2, (int(r), int(g), int(b)), thickness=2)
523 |
--------------------------------------------------------------------------------
/utils/torch_utils.py:
--------------------------------------------------------------------------------
1 | # YOLOR PyTorch utils
2 |
3 | import datetime
4 | import logging
5 | import math
6 | import os
7 | import platform
8 | import subprocess
9 | import time
10 | from contextlib import contextmanager
11 | from copy import deepcopy
12 | from pathlib import Path
13 |
14 | import torch
15 | import torch.backends.cudnn as cudnn
16 | import torch.nn as nn
17 | import torch.nn.functional as F
18 | import torchvision
19 |
20 | try:
21 | import thop # for FLOPS computation
22 | except ImportError:
23 | thop = None
24 | logger = logging.getLogger(__name__)
25 |
26 |
27 | @contextmanager
28 | def torch_distributed_zero_first(local_rank: int):
29 | """
30 | Decorator to make all processes in distributed training wait for each local_master to do something.
31 | """
32 | if local_rank not in [-1, 0]:
33 | torch.distributed.barrier()
34 | yield
35 | if local_rank == 0:
36 | torch.distributed.barrier()
37 |
38 |
39 | def init_torch_seeds(seed=0):
40 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
41 | torch.manual_seed(seed)
42 | if seed == 0: # slower, more reproducible
43 | cudnn.benchmark, cudnn.deterministic = False, True
44 | else: # faster, less reproducible
45 | cudnn.benchmark, cudnn.deterministic = True, False
46 |
47 |
48 | def date_modified(path=__file__):
49 | # return human-readable file modification date, i.e. '2021-3-26'
50 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
51 | return f'{t.year}-{t.month}-{t.day}'
52 |
53 |
54 | def git_describe(path=Path(__file__).parent): # path must be a directory
55 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
56 | s = f'git -C {path} describe --tags --long --always'
57 | try:
58 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
59 | except subprocess.CalledProcessError as e:
60 | return '' # not a git repository
61 |
62 |
63 | def select_device(device='', batch_size=None):
64 | # device = 'cpu' or '0' or '0,1,2,3'
65 | s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
66 | cpu = device.lower() == 'cpu'
67 | if cpu:
68 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
69 | elif device: # non-cpu device requested
70 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
71 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
72 |
73 | cuda = not cpu and torch.cuda.is_available()
74 | if cuda:
75 | n = torch.cuda.device_count()
76 | if n > 1 and batch_size: # check that batch_size is compatible with device_count
77 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
78 | space = ' ' * len(s)
79 | for i, d in enumerate(device.split(',') if device else range(n)):
80 | p = torch.cuda.get_device_properties(i)
81 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
82 | else:
83 | s += 'CPU\n'
84 |
85 | logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
86 | return torch.device('cuda:0' if cuda else 'cpu')
87 |
88 |
89 | def time_synchronized():
90 | # pytorch-accurate time
91 | if torch.cuda.is_available():
92 | torch.cuda.synchronize()
93 | return time.time()
94 |
95 |
96 | def profile(x, ops, n=100, device=None):
97 | # profile a pytorch module or list of modules. Example usage:
98 | # x = torch.randn(16, 3, 640, 640) # input
99 | # m1 = lambda x: x * torch.sigmoid(x)
100 | # m2 = nn.SiLU()
101 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
102 |
103 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104 | x = x.to(device)
105 | x.requires_grad = True
106 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
107 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
108 | for m in ops if isinstance(ops, list) else [ops]:
109 | m = m.to(device) if hasattr(m, 'to') else m # device
110 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
111 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
112 | try:
113 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
114 | except:
115 | flops = 0
116 |
117 | for _ in range(n):
118 | t[0] = time_synchronized()
119 | y = m(x)
120 | t[1] = time_synchronized()
121 | try:
122 | _ = y.sum().backward()
123 | t[2] = time_synchronized()
124 | except: # no backward method
125 | t[2] = float('nan')
126 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
127 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
128 |
129 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
130 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
131 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
132 | print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
133 |
134 |
135 | def is_parallel(model):
136 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
137 |
138 |
139 | def intersect_dicts(da, db, exclude=()):
140 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
141 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
142 |
143 |
144 | def initialize_weights(model):
145 | for m in model.modules():
146 | t = type(m)
147 | if t is nn.Conv2d:
148 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
149 | elif t is nn.BatchNorm2d:
150 | m.eps = 1e-3
151 | m.momentum = 0.03
152 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
153 | m.inplace = True
154 |
155 |
156 | def find_modules(model, mclass=nn.Conv2d):
157 | # Finds layer indices matching module class 'mclass'
158 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
159 |
160 |
161 | def sparsity(model):
162 | # Return global model sparsity
163 | a, b = 0., 0.
164 | for p in model.parameters():
165 | a += p.numel()
166 | b += (p == 0).sum()
167 | return b / a
168 |
169 |
170 | def prune(model, amount=0.3):
171 | # Prune model to requested global sparsity
172 | import torch.nn.utils.prune as prune
173 | print('Pruning model... ', end='')
174 | for name, m in model.named_modules():
175 | if isinstance(m, nn.Conv2d):
176 | prune.l1_unstructured(m, name='weight', amount=amount) # prune
177 | prune.remove(m, 'weight') # make permanent
178 | print(' %.3g global sparsity' % sparsity(model))
179 |
180 |
181 | def fuse_conv_and_bn(conv, bn):
182 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
183 | fusedconv = nn.Conv2d(conv.in_channels,
184 | conv.out_channels,
185 | kernel_size=conv.kernel_size,
186 | stride=conv.stride,
187 | padding=conv.padding,
188 | groups=conv.groups,
189 | bias=True).requires_grad_(False).to(conv.weight.device)
190 |
191 | # prepare filters
192 | w_conv = conv.weight.clone().view(conv.out_channels, -1)
193 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
194 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
195 |
196 | # prepare spatial bias
197 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
198 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
199 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
200 |
201 | return fusedconv
202 |
203 |
204 | def model_info(model, verbose=False, img_size=640):
205 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
206 | n_p = sum(x.numel() for x in model.parameters()) # number parameters
207 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
208 | if verbose:
209 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
210 | for i, (name, p) in enumerate(model.named_parameters()):
211 | name = name.replace('module_list.', '')
212 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
213 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
214 |
215 | try: # FLOPS
216 | from thop import profile
217 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
218 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
219 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
220 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
221 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
222 | except (ImportError, Exception):
223 | fs = ''
224 |
225 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
226 |
227 |
228 | def load_classifier(name='resnet101', n=2):
229 | # Loads a pretrained model reshaped to n-class output
230 | model = torchvision.models.__dict__[name](pretrained=True)
231 |
232 | # ResNet model properties
233 | # input_size = [3, 224, 224]
234 | # input_space = 'RGB'
235 | # input_range = [0, 1]
236 | # mean = [0.485, 0.456, 0.406]
237 | # std = [0.229, 0.224, 0.225]
238 |
239 | # Reshape output to n classes
240 | filters = model.fc.weight.shape[1]
241 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
242 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
243 | model.fc.out_features = n
244 | return model
245 |
246 |
247 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
248 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple
249 | if ratio == 1.0:
250 | return img
251 | else:
252 | h, w = img.shape[2:]
253 | s = (int(h * ratio), int(w * ratio)) # new size
254 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
255 | if not same_shape: # pad/crop img
256 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
257 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
258 |
259 |
260 | def copy_attr(a, b, include=(), exclude=()):
261 | # Copy attributes from b to a, options to only include [...] and to exclude [...]
262 | for k, v in b.__dict__.items():
263 | if (len(include) and k not in include) or k.startswith('_') or k in exclude:
264 | continue
265 | else:
266 | setattr(a, k, v)
267 |
268 |
269 | class ModelEMA:
270 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
271 | Keep a moving average of everything in the model state_dict (parameters and buffers).
272 | This is intended to allow functionality like
273 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
274 | A smoothed version of the weights is necessary for some training schemes to perform well.
275 | This class is sensitive where it is initialized in the sequence of model init,
276 | GPU assignment and distributed training wrappers.
277 | """
278 |
279 | def __init__(self, model, decay=0.9999, updates=0):
280 | # Create EMA
281 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
282 | # if next(model.parameters()).device.type != 'cpu':
283 | # self.ema.half() # FP16 EMA
284 | self.updates = updates # number of EMA updates
285 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
286 | for p in self.ema.parameters():
287 | p.requires_grad_(False)
288 |
289 | def update(self, model):
290 | # Update EMA parameters
291 | with torch.no_grad():
292 | self.updates += 1
293 | d = self.decay(self.updates)
294 |
295 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
296 | for k, v in self.ema.state_dict().items():
297 | if v.dtype.is_floating_point:
298 | v *= d
299 | v += (1. - d) * msd[k].detach()
300 |
301 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
302 | # Update EMA attributes
303 | copy_attr(self.ema, model, include, exclude)
304 |
305 |
306 | class BatchNormXd(torch.nn.modules.batchnorm._BatchNorm):
307 | def _check_input_dim(self, input):
308 | # The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
309 | # is this method that is overwritten by the sub-class
310 | # This original goal of this method was for tensor sanity checks
311 | # If you're ok bypassing those sanity checks (eg. if you trust your inference
312 | # to provide the right dimensional inputs), then you can just use this method
313 | # for easy conversion from SyncBatchNorm
314 | # (unfortunately, SyncBatchNorm does not store the original class - if it did
315 | # we could return the one that was originally created)
316 | return
317 |
318 | def revert_sync_batchnorm(module):
319 | # this is very similar to the function that it is trying to revert:
320 | # https://github.com/pytorch/pytorch/blob/c8b3686a3e4ba63dc59e5dcfe5db3430df256833/torch/nn/modules/batchnorm.py#L679
321 | module_output = module
322 | if isinstance(module, torch.nn.modules.batchnorm.SyncBatchNorm):
323 | new_cls = BatchNormXd
324 | module_output = BatchNormXd(module.num_features,
325 | module.eps, module.momentum,
326 | module.affine,
327 | module.track_running_stats)
328 | if module.affine:
329 | with torch.no_grad():
330 | module_output.weight = module.weight
331 | module_output.bias = module.bias
332 | module_output.running_mean = module.running_mean
333 | module_output.running_var = module.running_var
334 | module_output.num_batches_tracked = module.num_batches_tracked
335 | if hasattr(module, "qconfig"):
336 | module_output.qconfig = module.qconfig
337 | for name, child in module.named_children():
338 | module_output.add_module(name, revert_sync_batchnorm(child))
339 | del module
340 | return module_output
341 |
342 |
343 | class TracedModel(nn.Module):
344 |
345 | def __init__(self, model=None, device=None, img_size=(640,640)):
346 | super(TracedModel, self).__init__()
347 |
348 | print(" Convert model to Traced-model... ")
349 | self.stride = model.stride
350 | self.names = model.names
351 | self.model = model
352 |
353 | self.model = revert_sync_batchnorm(self.model)
354 | self.model.to('cpu')
355 | self.model.eval()
356 |
357 | self.detect_layer = self.model.model[-1]
358 | self.model.traced = True
359 |
360 | rand_example = torch.rand(1, 3, img_size, img_size)
361 |
362 | traced_script_module = torch.jit.trace(self.model, rand_example, strict=False)
363 | #traced_script_module = torch.jit.script(self.model)
364 | traced_script_module.save("traced_model.pt")
365 | print(" traced_script_module saved! ")
366 | self.model = traced_script_module
367 | self.model.to(device)
368 | self.detect_layer.to(device)
369 | print(" model is traced! \n")
370 |
371 | def forward(self, x, augment=False, profile=False):
372 | out = self.model(x)
373 | out = self.detect_layer(out)
374 | return out
--------------------------------------------------------------------------------
/utils/wandb_logging/__init__.py:
--------------------------------------------------------------------------------
1 | # init
--------------------------------------------------------------------------------
/utils/wandb_logging/log_dataset.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | import yaml
4 |
5 | from wandb_utils import WandbLogger
6 |
7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
8 |
9 |
10 | def create_dataset_artifact(opt):
11 | with open(opt.data) as f:
12 | data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
13 | logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')
14 |
15 |
16 | if __name__ == '__main__':
17 | parser = argparse.ArgumentParser()
18 | parser.add_argument('--data', type=str, default='data/coco.yaml', help='data.yaml path')
19 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
20 | parser.add_argument('--project', type=str, default='YOLOR', help='name of W&B Project')
21 | opt = parser.parse_args()
22 | opt.resume = False # Explicitly disallow resume check for dataset upload job
23 |
24 | create_dataset_artifact(opt)
25 |
--------------------------------------------------------------------------------
/utils/wandb_logging/wandb_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import sys
3 | from pathlib import Path
4 |
5 | import torch
6 | import yaml
7 | from tqdm import tqdm
8 |
9 | sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
10 | from utils.datasets import LoadImagesAndLabels
11 | from utils.datasets import img2label_paths
12 | from utils.general import colorstr, xywh2xyxy, check_dataset
13 |
14 | try:
15 | import wandb
16 | from wandb import init, finish
17 | except ImportError:
18 | wandb = None
19 |
20 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
21 |
22 |
23 | def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
24 | return from_string[len(prefix):]
25 |
26 |
27 | def check_wandb_config_file(data_config_file):
28 | wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
29 | if Path(wandb_config).is_file():
30 | return wandb_config
31 | return data_config_file
32 |
33 |
34 | def get_run_info(run_path):
35 | run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
36 | run_id = run_path.stem
37 | project = run_path.parent.stem
38 | model_artifact_name = 'run_' + run_id + '_model'
39 | return run_id, project, model_artifact_name
40 |
41 |
42 | def check_wandb_resume(opt):
43 | process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None
44 | if isinstance(opt.resume, str):
45 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
46 | if opt.global_rank not in [-1, 0]: # For resuming DDP runs
47 | run_id, project, model_artifact_name = get_run_info(opt.resume)
48 | api = wandb.Api()
49 | artifact = api.artifact(project + '/' + model_artifact_name + ':latest')
50 | modeldir = artifact.download()
51 | opt.weights = str(Path(modeldir) / "last.pt")
52 | return True
53 | return None
54 |
55 |
56 | def process_wandb_config_ddp_mode(opt):
57 | with open(opt.data) as f:
58 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict
59 | train_dir, val_dir = None, None
60 | if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
61 | api = wandb.Api()
62 | train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
63 | train_dir = train_artifact.download()
64 | train_path = Path(train_dir) / 'data/images/'
65 | data_dict['train'] = str(train_path)
66 |
67 | if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
68 | api = wandb.Api()
69 | val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
70 | val_dir = val_artifact.download()
71 | val_path = Path(val_dir) / 'data/images/'
72 | data_dict['val'] = str(val_path)
73 | if train_dir or val_dir:
74 | ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
75 | with open(ddp_data_path, 'w') as f:
76 | yaml.dump(data_dict, f)
77 | opt.data = ddp_data_path
78 |
79 |
80 | class WandbLogger():
81 | def __init__(self, opt, name, run_id, data_dict, job_type='Training'):
82 | # Pre-training routine --
83 | self.job_type = job_type
84 | self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict
85 | # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call
86 | if isinstance(opt.resume, str): # checks resume from artifact
87 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
88 | run_id, project, model_artifact_name = get_run_info(opt.resume)
89 | model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
90 | assert wandb, 'install wandb to resume wandb runs'
91 | # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
92 | self.wandb_run = wandb.init(id=run_id, project=project, resume='allow')
93 | opt.resume = model_artifact_name
94 | elif self.wandb:
95 | self.wandb_run = wandb.init(config=opt,
96 | resume="allow",
97 | project='YOLOR' if opt.project == 'runs/train' else Path(opt.project).stem,
98 | name=name,
99 | job_type=job_type,
100 | id=run_id) if not wandb.run else wandb.run
101 | if self.wandb_run:
102 | if self.job_type == 'Training':
103 | if not opt.resume:
104 | wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict
105 | # Info useful for resuming from artifacts
106 | self.wandb_run.config.opt = vars(opt)
107 | self.wandb_run.config.data_dict = wandb_data_dict
108 | self.data_dict = self.setup_training(opt, data_dict)
109 | if self.job_type == 'Dataset Creation':
110 | self.data_dict = self.check_and_upload_dataset(opt)
111 | else:
112 | prefix = colorstr('wandb: ')
113 | print(f"{prefix}Install Weights & Biases for YOLOR logging with 'pip install wandb' (recommended)")
114 |
115 | def check_and_upload_dataset(self, opt):
116 | assert wandb, 'Install wandb to upload dataset'
117 | check_dataset(self.data_dict)
118 | config_path = self.log_dataset_artifact(opt.data,
119 | opt.single_cls,
120 | 'YOLOR' if opt.project == 'runs/train' else Path(opt.project).stem)
121 | print("Created dataset config file ", config_path)
122 | with open(config_path) as f:
123 | wandb_data_dict = yaml.load(f, Loader=yaml.SafeLoader)
124 | return wandb_data_dict
125 |
126 | def setup_training(self, opt, data_dict):
127 | self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants
128 | self.bbox_interval = opt.bbox_interval
129 | if isinstance(opt.resume, str):
130 | modeldir, _ = self.download_model_artifact(opt)
131 | if modeldir:
132 | self.weights = Path(modeldir) / "last.pt"
133 | config = self.wandb_run.config
134 | opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
135 | self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \
136 | config.opt['hyp']
137 | data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume
138 | if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download
139 | self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
140 | opt.artifact_alias)
141 | self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
142 | opt.artifact_alias)
143 | self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None
144 | if self.train_artifact_path is not None:
145 | train_path = Path(self.train_artifact_path) / 'data/images/'
146 | data_dict['train'] = str(train_path)
147 | if self.val_artifact_path is not None:
148 | val_path = Path(self.val_artifact_path) / 'data/images/'
149 | data_dict['val'] = str(val_path)
150 | self.val_table = self.val_artifact.get("val")
151 | self.map_val_table_path()
152 | if self.val_artifact is not None:
153 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
154 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
155 | if opt.bbox_interval == -1:
156 | self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
157 | return data_dict
158 |
159 | def download_dataset_artifact(self, path, alias):
160 | if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
161 | dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
162 | assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
163 | datadir = dataset_artifact.download()
164 | return datadir, dataset_artifact
165 | return None, None
166 |
167 | def download_model_artifact(self, opt):
168 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
169 | model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
170 | assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
171 | modeldir = model_artifact.download()
172 | epochs_trained = model_artifact.metadata.get('epochs_trained')
173 | total_epochs = model_artifact.metadata.get('total_epochs')
174 | assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % (
175 | total_epochs)
176 | return modeldir, model_artifact
177 | return None, None
178 |
179 | def log_model(self, path, opt, epoch, fitness_score, best_model=False):
180 | model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
181 | 'original_url': str(path),
182 | 'epochs_trained': epoch + 1,
183 | 'save period': opt.save_period,
184 | 'project': opt.project,
185 | 'total_epochs': opt.epochs,
186 | 'fitness_score': fitness_score
187 | })
188 | model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
189 | wandb.log_artifact(model_artifact,
190 | aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
191 | print("Saving model artifact on epoch ", epoch + 1)
192 |
193 | def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
194 | with open(data_file) as f:
195 | data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
196 | nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
197 | names = {k: v for k, v in enumerate(names)} # to index dictionary
198 | self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
199 | data['train']), names, name='train') if data.get('train') else None
200 | self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
201 | data['val']), names, name='val') if data.get('val') else None
202 | if data.get('train'):
203 | data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
204 | if data.get('val'):
205 | data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
206 | path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path
207 | data.pop('download', None)
208 | with open(path, 'w') as f:
209 | yaml.dump(data, f)
210 |
211 | if self.job_type == 'Training': # builds correct artifact pipeline graph
212 | self.wandb_run.use_artifact(self.val_artifact)
213 | self.wandb_run.use_artifact(self.train_artifact)
214 | self.val_artifact.wait()
215 | self.val_table = self.val_artifact.get('val')
216 | self.map_val_table_path()
217 | else:
218 | self.wandb_run.log_artifact(self.train_artifact)
219 | self.wandb_run.log_artifact(self.val_artifact)
220 | return path
221 |
222 | def map_val_table_path(self):
223 | self.val_table_map = {}
224 | print("Mapping dataset")
225 | for i, data in enumerate(tqdm(self.val_table.data)):
226 | self.val_table_map[data[3]] = data[0]
227 |
228 | def create_dataset_table(self, dataset, class_to_id, name='dataset'):
229 | # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
230 | artifact = wandb.Artifact(name=name, type="dataset")
231 | img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
232 | img_files = tqdm(dataset.img_files) if not img_files else img_files
233 | for img_file in img_files:
234 | if Path(img_file).is_dir():
235 | artifact.add_dir(img_file, name='data/images')
236 | labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
237 | artifact.add_dir(labels_path, name='data/labels')
238 | else:
239 | artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
240 | label_file = Path(img2label_paths([img_file])[0])
241 | artifact.add_file(str(label_file),
242 | name='data/labels/' + label_file.name) if label_file.exists() else None
243 | table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
244 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
245 | for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
246 | height, width = shapes[0]
247 | labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) * torch.Tensor([width, height, width, height])
248 | box_data, img_classes = [], {}
249 | for cls, *xyxy in labels[:, 1:].tolist():
250 | cls = int(cls)
251 | box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
252 | "class_id": cls,
253 | "box_caption": "%s" % (class_to_id[cls]),
254 | "scores": {"acc": 1},
255 | "domain": "pixel"})
256 | img_classes[cls] = class_to_id[cls]
257 | boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
258 | table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes),
259 | Path(paths).name)
260 | artifact.add(table, name)
261 | return artifact
262 |
263 | def log_training_progress(self, predn, path, names):
264 | if self.val_table and self.result_table:
265 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
266 | box_data = []
267 | total_conf = 0
268 | for *xyxy, conf, cls in predn.tolist():
269 | if conf >= 0.25:
270 | box_data.append(
271 | {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
272 | "class_id": int(cls),
273 | "box_caption": "%s %.3f" % (names[cls], conf),
274 | "scores": {"class_score": conf},
275 | "domain": "pixel"})
276 | total_conf = total_conf + conf
277 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
278 | id = self.val_table_map[Path(path).name]
279 | self.result_table.add_data(self.current_epoch,
280 | id,
281 | wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
282 | total_conf / max(1, len(box_data))
283 | )
284 |
285 | def log(self, log_dict):
286 | if self.wandb_run:
287 | for key, value in log_dict.items():
288 | self.log_dict[key] = value
289 |
290 | def end_epoch(self, best_result=False):
291 | if self.wandb_run:
292 | wandb.log(self.log_dict)
293 | self.log_dict = {}
294 | if self.result_artifact:
295 | train_results = wandb.JoinedTable(self.val_table, self.result_table, "id")
296 | self.result_artifact.add(train_results, 'result')
297 | wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch),
298 | ('best' if best_result else '')])
299 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
300 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
301 |
302 | def finish_run(self):
303 | if self.wandb_run:
304 | if self.log_dict:
305 | wandb.log(self.log_dict)
306 | wandb.run.finish()
307 |
--------------------------------------------------------------------------------