김우재

feat: add RTMP-based service code

Showing 91 changed files with 9172 additions and 1 deletions
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
2 2
3 ![Demo](./assets/demo.gif) 3 ![Demo](./assets/demo.gif)
4 4
5 -## Architecture 5 +## Architectures
6 6
7 ![Architecture 1](./assets/architecture1.png) 7 ![Architecture 1](./assets/architecture1.png)
8 8
......
1 +
2 +# insert at 1, 0 is the script path (or '' in REPL)
3 +#sys.path.insert(1, '/yolov5-5.0.5')
4 +
5 +
6 +# import subprocess
7 +import os
8 +
9 +# # YOLO Setting
10 +# model_path = "./best.pt" # it automatically downloads yolov5s model to given path
11 +# device = "cpu" # or "cpu"
12 +# yolov5 = YOLOv5(model_path, device)
13 +
14 +# # ts file to mp4 file
15 +# ts_file = 'sample.ts'
16 +# mp4_file = 'sample.mp4'
17 +# subprocess.run(['ffmpeg', '-i', ts_file, mp4_file])
18 +
19 +#!/usr/local/bin/python3
20 +# -*- coding: utf-8 -*-
21 +import re
22 +import sys
23 +from yolo_module.yolov5.detect import main
24 +if __name__ == '__main__':
25 + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
26 + sys.exit(main())
...\ No newline at end of file ...\ No newline at end of file
1 +GNU GENERAL PUBLIC LICENSE
2 + Version 3, 29 June 2007
3 +
4 + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5 + Everyone is permitted to copy and distribute verbatim copies
6 + of this license document, but changing it is not allowed.
7 +
8 + Preamble
9 +
10 + The GNU General Public License is a free, copyleft license for
11 +software and other kinds of works.
12 +
13 + The licenses for most software and other practical works are designed
14 +to take away your freedom to share and change the works. By contrast,
15 +the GNU General Public License is intended to guarantee your freedom to
16 +share and change all versions of a program--to make sure it remains free
17 +software for all its users. We, the Free Software Foundation, use the
18 +GNU General Public License for most of our software; it applies also to
19 +any other work released this way by its authors. You can apply it to
20 +your programs, too.
21 +
22 + When we speak of free software, we are referring to freedom, not
23 +price. Our General Public Licenses are designed to make sure that you
24 +have the freedom to distribute copies of free software (and charge for
25 +them if you wish), that you receive source code or can get it if you
26 +want it, that you can change the software or use pieces of it in new
27 +free programs, and that you know you can do these things.
28 +
29 + To protect your rights, we need to prevent others from denying you
30 +these rights or asking you to surrender the rights. Therefore, you have
31 +certain responsibilities if you distribute copies of the software, or if
32 +you modify it: responsibilities to respect the freedom of others.
33 +
34 + For example, if you distribute copies of such a program, whether
35 +gratis or for a fee, you must pass on to the recipients the same
36 +freedoms that you received. You must make sure that they, too, receive
37 +or can get the source code. And you must show them these terms so they
38 +know their rights.
39 +
40 + Developers that use the GNU GPL protect your rights with two steps:
41 +(1) assert copyright on the software, and (2) offer you this License
42 +giving you legal permission to copy, distribute and/or modify it.
43 +
44 + For the developers' and authors' protection, the GPL clearly explains
45 +that there is no warranty for this free software. For both users' and
46 +authors' sake, the GPL requires that modified versions be marked as
47 +changed, so that their problems will not be attributed erroneously to
48 +authors of previous versions.
49 +
50 + Some devices are designed to deny users access to install or run
51 +modified versions of the software inside them, although the manufacturer
52 +can do so. This is fundamentally incompatible with the aim of
53 +protecting users' freedom to change the software. The systematic
54 +pattern of such abuse occurs in the area of products for individuals to
55 +use, which is precisely where it is most unacceptable. Therefore, we
56 +have designed this version of the GPL to prohibit the practice for those
57 +products. If such problems arise substantially in other domains, we
58 +stand ready to extend this provision to those domains in future versions
59 +of the GPL, as needed to protect the freedom of users.
60 +
61 + Finally, every program is threatened constantly by software patents.
62 +States should not allow patents to restrict development and use of
63 +software on general-purpose computers, but in those that do, we wish to
64 +avoid the special danger that patents applied to a free program could
65 +make it effectively proprietary. To prevent this, the GPL assures that
66 +patents cannot be used to render the program non-free.
67 +
68 + The precise terms and conditions for copying, distribution and
69 +modification follow.
70 +
71 + TERMS AND CONDITIONS
72 +
73 + 0. Definitions.
74 +
75 + "This License" refers to version 3 of the GNU General Public License.
76 +
77 + "Copyright" also means copyright-like laws that apply to other kinds of
78 +works, such as semiconductor masks.
79 +
80 + "The Program" refers to any copyrightable work licensed under this
81 +License. Each licensee is addressed as "you". "Licensees" and
82 +"recipients" may be individuals or organizations.
83 +
84 + To "modify" a work means to copy from or adapt all or part of the work
85 +in a fashion requiring copyright permission, other than the making of an
86 +exact copy. The resulting work is called a "modified version" of the
87 +earlier work or a work "based on" the earlier work.
88 +
89 + A "covered work" means either the unmodified Program or a work based
90 +on the Program.
91 +
92 + To "propagate" a work means to do anything with it that, without
93 +permission, would make you directly or secondarily liable for
94 +infringement under applicable copyright law, except executing it on a
95 +computer or modifying a private copy. Propagation includes copying,
96 +distribution (with or without modification), making available to the
97 +public, and in some countries other activities as well.
98 +
99 + To "convey" a work means any kind of propagation that enables other
100 +parties to make or receive copies. Mere interaction with a user through
101 +a computer network, with no transfer of a copy, is not conveying.
102 +
103 + An interactive user interface displays "Appropriate Legal Notices"
104 +to the extent that it includes a convenient and prominently visible
105 +feature that (1) displays an appropriate copyright notice, and (2)
106 +tells the user that there is no warranty for the work (except to the
107 +extent that warranties are provided), that licensees may convey the
108 +work under this License, and how to view a copy of this License. If
109 +the interface presents a list of user commands or options, such as a
110 +menu, a prominent item in the list meets this criterion.
111 +
112 + 1. Source Code.
113 +
114 + The "source code" for a work means the preferred form of the work
115 +for making modifications to it. "Object code" means any non-source
116 +form of a work.
117 +
118 + A "Standard Interface" means an interface that either is an official
119 +standard defined by a recognized standards body, or, in the case of
120 +interfaces specified for a particular programming language, one that
121 +is widely used among developers working in that language.
122 +
123 + The "System Libraries" of an executable work include anything, other
124 +than the work as a whole, that (a) is included in the normal form of
125 +packaging a Major Component, but which is not part of that Major
126 +Component, and (b) serves only to enable use of the work with that
127 +Major Component, or to implement a Standard Interface for which an
128 +implementation is available to the public in source code form. A
129 +"Major Component", in this context, means a major essential component
130 +(kernel, window system, and so on) of the specific operating system
131 +(if any) on which the executable work runs, or a compiler used to
132 +produce the work, or an object code interpreter used to run it.
133 +
134 + The "Corresponding Source" for a work in object code form means all
135 +the source code needed to generate, install, and (for an executable
136 +work) run the object code and to modify the work, including scripts to
137 +control those activities. However, it does not include the work's
138 +System Libraries, or general-purpose tools or generally available free
139 +programs which are used unmodified in performing those activities but
140 +which are not part of the work. For example, Corresponding Source
141 +includes interface definition files associated with source files for
142 +the work, and the source code for shared libraries and dynamically
143 +linked subprograms that the work is specifically designed to require,
144 +such as by intimate data communication or control flow between those
145 +subprograms and other parts of the work.
146 +
147 + The Corresponding Source need not include anything that users
148 +can regenerate automatically from other parts of the Corresponding
149 +Source.
150 +
151 + The Corresponding Source for a work in source code form is that
152 +same work.
153 +
154 + 2. Basic Permissions.
155 +
156 + All rights granted under this License are granted for the term of
157 +copyright on the Program, and are irrevocable provided the stated
158 +conditions are met. This License explicitly affirms your unlimited
159 +permission to run the unmodified Program. The output from running a
160 +covered work is covered by this License only if the output, given its
161 +content, constitutes a covered work. This License acknowledges your
162 +rights of fair use or other equivalent, as provided by copyright law.
163 +
164 + You may make, run and propagate covered works that you do not
165 +convey, without conditions so long as your license otherwise remains
166 +in force. You may convey covered works to others for the sole purpose
167 +of having them make modifications exclusively for you, or provide you
168 +with facilities for running those works, provided that you comply with
169 +the terms of this License in conveying all material for which you do
170 +not control copyright. Those thus making or running the covered works
171 +for you must do so exclusively on your behalf, under your direction
172 +and control, on terms that prohibit them from making any copies of
173 +your copyrighted material outside their relationship with you.
174 +
175 + Conveying under any other circumstances is permitted solely under
176 +the conditions stated below. Sublicensing is not allowed; section 10
177 +makes it unnecessary.
178 +
179 + 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 +
181 + No covered work shall be deemed part of an effective technological
182 +measure under any applicable law fulfilling obligations under article
183 +11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 +similar laws prohibiting or restricting circumvention of such
185 +measures.
186 +
187 + When you convey a covered work, you waive any legal power to forbid
188 +circumvention of technological measures to the extent such circumvention
189 +is effected by exercising rights under this License with respect to
190 +the covered work, and you disclaim any intention to limit operation or
191 +modification of the work as a means of enforcing, against the work's
192 +users, your or third parties' legal rights to forbid circumvention of
193 +technological measures.
194 +
195 + 4. Conveying Verbatim Copies.
196 +
197 + You may convey verbatim copies of the Program's source code as you
198 +receive it, in any medium, provided that you conspicuously and
199 +appropriately publish on each copy an appropriate copyright notice;
200 +keep intact all notices stating that this License and any
201 +non-permissive terms added in accord with section 7 apply to the code;
202 +keep intact all notices of the absence of any warranty; and give all
203 +recipients a copy of this License along with the Program.
204 +
205 + You may charge any price or no price for each copy that you convey,
206 +and you may offer support or warranty protection for a fee.
207 +
208 + 5. Conveying Modified Source Versions.
209 +
210 + You may convey a work based on the Program, or the modifications to
211 +produce it from the Program, in the form of source code under the
212 +terms of section 4, provided that you also meet all of these conditions:
213 +
214 + a) The work must carry prominent notices stating that you modified
215 + it, and giving a relevant date.
216 +
217 + b) The work must carry prominent notices stating that it is
218 + released under this License and any conditions added under section
219 + 7. This requirement modifies the requirement in section 4 to
220 + "keep intact all notices".
221 +
222 + c) You must license the entire work, as a whole, under this
223 + License to anyone who comes into possession of a copy. This
224 + License will therefore apply, along with any applicable section 7
225 + additional terms, to the whole of the work, and all its parts,
226 + regardless of how they are packaged. This License gives no
227 + permission to license the work in any other way, but it does not
228 + invalidate such permission if you have separately received it.
229 +
230 + d) If the work has interactive user interfaces, each must display
231 + Appropriate Legal Notices; however, if the Program has interactive
232 + interfaces that do not display Appropriate Legal Notices, your
233 + work need not make them do so.
234 +
235 + A compilation of a covered work with other separate and independent
236 +works, which are not by their nature extensions of the covered work,
237 +and which are not combined with it such as to form a larger program,
238 +in or on a volume of a storage or distribution medium, is called an
239 +"aggregate" if the compilation and its resulting copyright are not
240 +used to limit the access or legal rights of the compilation's users
241 +beyond what the individual works permit. Inclusion of a covered work
242 +in an aggregate does not cause this License to apply to the other
243 +parts of the aggregate.
244 +
245 + 6. Conveying Non-Source Forms.
246 +
247 + You may convey a covered work in object code form under the terms
248 +of sections 4 and 5, provided that you also convey the
249 +machine-readable Corresponding Source under the terms of this License,
250 +in one of these ways:
251 +
252 + a) Convey the object code in, or embodied in, a physical product
253 + (including a physical distribution medium), accompanied by the
254 + Corresponding Source fixed on a durable physical medium
255 + customarily used for software interchange.
256 +
257 + b) Convey the object code in, or embodied in, a physical product
258 + (including a physical distribution medium), accompanied by a
259 + written offer, valid for at least three years and valid for as
260 + long as you offer spare parts or customer support for that product
261 + model, to give anyone who possesses the object code either (1) a
262 + copy of the Corresponding Source for all the software in the
263 + product that is covered by this License, on a durable physical
264 + medium customarily used for software interchange, for a price no
265 + more than your reasonable cost of physically performing this
266 + conveying of source, or (2) access to copy the
267 + Corresponding Source from a network server at no charge.
268 +
269 + c) Convey individual copies of the object code with a copy of the
270 + written offer to provide the Corresponding Source. This
271 + alternative is allowed only occasionally and noncommercially, and
272 + only if you received the object code with such an offer, in accord
273 + with subsection 6b.
274 +
275 + d) Convey the object code by offering access from a designated
276 + place (gratis or for a charge), and offer equivalent access to the
277 + Corresponding Source in the same way through the same place at no
278 + further charge. You need not require recipients to copy the
279 + Corresponding Source along with the object code. If the place to
280 + copy the object code is a network server, the Corresponding Source
281 + may be on a different server (operated by you or a third party)
282 + that supports equivalent copying facilities, provided you maintain
283 + clear directions next to the object code saying where to find the
284 + Corresponding Source. Regardless of what server hosts the
285 + Corresponding Source, you remain obligated to ensure that it is
286 + available for as long as needed to satisfy these requirements.
287 +
288 + e) Convey the object code using peer-to-peer transmission, provided
289 + you inform other peers where the object code and Corresponding
290 + Source of the work are being offered to the general public at no
291 + charge under subsection 6d.
292 +
293 + A separable portion of the object code, whose source code is excluded
294 +from the Corresponding Source as a System Library, need not be
295 +included in conveying the object code work.
296 +
297 + A "User Product" is either (1) a "consumer product", which means any
298 +tangible personal property which is normally used for personal, family,
299 +or household purposes, or (2) anything designed or sold for incorporation
300 +into a dwelling. In determining whether a product is a consumer product,
301 +doubtful cases shall be resolved in favor of coverage. For a particular
302 +product received by a particular user, "normally used" refers to a
303 +typical or common use of that class of product, regardless of the status
304 +of the particular user or of the way in which the particular user
305 +actually uses, or expects or is expected to use, the product. A product
306 +is a consumer product regardless of whether the product has substantial
307 +commercial, industrial or non-consumer uses, unless such uses represent
308 +the only significant mode of use of the product.
309 +
310 + "Installation Information" for a User Product means any methods,
311 +procedures, authorization keys, or other information required to install
312 +and execute modified versions of a covered work in that User Product from
313 +a modified version of its Corresponding Source. The information must
314 +suffice to ensure that the continued functioning of the modified object
315 +code is in no case prevented or interfered with solely because
316 +modification has been made.
317 +
318 + If you convey an object code work under this section in, or with, or
319 +specifically for use in, a User Product, and the conveying occurs as
320 +part of a transaction in which the right of possession and use of the
321 +User Product is transferred to the recipient in perpetuity or for a
322 +fixed term (regardless of how the transaction is characterized), the
323 +Corresponding Source conveyed under this section must be accompanied
324 +by the Installation Information. But this requirement does not apply
325 +if neither you nor any third party retains the ability to install
326 +modified object code on the User Product (for example, the work has
327 +been installed in ROM).
328 +
329 + The requirement to provide Installation Information does not include a
330 +requirement to continue to provide support service, warranty, or updates
331 +for a work that has been modified or installed by the recipient, or for
332 +the User Product in which it has been modified or installed. Access to a
333 +network may be denied when the modification itself materially and
334 +adversely affects the operation of the network or violates the rules and
335 +protocols for communication across the network.
336 +
337 + Corresponding Source conveyed, and Installation Information provided,
338 +in accord with this section must be in a format that is publicly
339 +documented (and with an implementation available to the public in
340 +source code form), and must require no special password or key for
341 +unpacking, reading or copying.
342 +
343 + 7. Additional Terms.
344 +
345 + "Additional permissions" are terms that supplement the terms of this
346 +License by making exceptions from one or more of its conditions.
347 +Additional permissions that are applicable to the entire Program shall
348 +be treated as though they were included in this License, to the extent
349 +that they are valid under applicable law. If additional permissions
350 +apply only to part of the Program, that part may be used separately
351 +under those permissions, but the entire Program remains governed by
352 +this License without regard to the additional permissions.
353 +
354 + When you convey a copy of a covered work, you may at your option
355 +remove any additional permissions from that copy, or from any part of
356 +it. (Additional permissions may be written to require their own
357 +removal in certain cases when you modify the work.) You may place
358 +additional permissions on material, added by you to a covered work,
359 +for which you have or can give appropriate copyright permission.
360 +
361 + Notwithstanding any other provision of this License, for material you
362 +add to a covered work, you may (if authorized by the copyright holders of
363 +that material) supplement the terms of this License with terms:
364 +
365 + a) Disclaiming warranty or limiting liability differently from the
366 + terms of sections 15 and 16 of this License; or
367 +
368 + b) Requiring preservation of specified reasonable legal notices or
369 + author attributions in that material or in the Appropriate Legal
370 + Notices displayed by works containing it; or
371 +
372 + c) Prohibiting misrepresentation of the origin of that material, or
373 + requiring that modified versions of such material be marked in
374 + reasonable ways as different from the original version; or
375 +
376 + d) Limiting the use for publicity purposes of names of licensors or
377 + authors of the material; or
378 +
379 + e) Declining to grant rights under trademark law for use of some
380 + trade names, trademarks, or service marks; or
381 +
382 + f) Requiring indemnification of licensors and authors of that
383 + material by anyone who conveys the material (or modified versions of
384 + it) with contractual assumptions of liability to the recipient, for
385 + any liability that these contractual assumptions directly impose on
386 + those licensors and authors.
387 +
388 + All other non-permissive additional terms are considered "further
389 +restrictions" within the meaning of section 10. If the Program as you
390 +received it, or any part of it, contains a notice stating that it is
391 +governed by this License along with a term that is a further
392 +restriction, you may remove that term. If a license document contains
393 +a further restriction but permits relicensing or conveying under this
394 +License, you may add to a covered work material governed by the terms
395 +of that license document, provided that the further restriction does
396 +not survive such relicensing or conveying.
397 +
398 + If you add terms to a covered work in accord with this section, you
399 +must place, in the relevant source files, a statement of the
400 +additional terms that apply to those files, or a notice indicating
401 +where to find the applicable terms.
402 +
403 + Additional terms, permissive or non-permissive, may be stated in the
404 +form of a separately written license, or stated as exceptions;
405 +the above requirements apply either way.
406 +
407 + 8. Termination.
408 +
409 + You may not propagate or modify a covered work except as expressly
410 +provided under this License. Any attempt otherwise to propagate or
411 +modify it is void, and will automatically terminate your rights under
412 +this License (including any patent licenses granted under the third
413 +paragraph of section 11).
414 +
415 + However, if you cease all violation of this License, then your
416 +license from a particular copyright holder is reinstated (a)
417 +provisionally, unless and until the copyright holder explicitly and
418 +finally terminates your license, and (b) permanently, if the copyright
419 +holder fails to notify you of the violation by some reasonable means
420 +prior to 60 days after the cessation.
421 +
422 + Moreover, your license from a particular copyright holder is
423 +reinstated permanently if the copyright holder notifies you of the
424 +violation by some reasonable means, this is the first time you have
425 +received notice of violation of this License (for any work) from that
426 +copyright holder, and you cure the violation prior to 30 days after
427 +your receipt of the notice.
428 +
429 + Termination of your rights under this section does not terminate the
430 +licenses of parties who have received copies or rights from you under
431 +this License. If your rights have been terminated and not permanently
432 +reinstated, you do not qualify to receive new licenses for the same
433 +material under section 10.
434 +
435 + 9. Acceptance Not Required for Having Copies.
436 +
437 + You are not required to accept this License in order to receive or
438 +run a copy of the Program. Ancillary propagation of a covered work
439 +occurring solely as a consequence of using peer-to-peer transmission
440 +to receive a copy likewise does not require acceptance. However,
441 +nothing other than this License grants you permission to propagate or
442 +modify any covered work. These actions infringe copyright if you do
443 +not accept this License. Therefore, by modifying or propagating a
444 +covered work, you indicate your acceptance of this License to do so.
445 +
446 + 10. Automatic Licensing of Downstream Recipients.
447 +
448 + Each time you convey a covered work, the recipient automatically
449 +receives a license from the original licensors, to run, modify and
450 +propagate that work, subject to this License. You are not responsible
451 +for enforcing compliance by third parties with this License.
452 +
453 + An "entity transaction" is a transaction transferring control of an
454 +organization, or substantially all assets of one, or subdividing an
455 +organization, or merging organizations. If propagation of a covered
456 +work results from an entity transaction, each party to that
457 +transaction who receives a copy of the work also receives whatever
458 +licenses to the work the party's predecessor in interest had or could
459 +give under the previous paragraph, plus a right to possession of the
460 +Corresponding Source of the work from the predecessor in interest, if
461 +the predecessor has it or can get it with reasonable efforts.
462 +
463 + You may not impose any further restrictions on the exercise of the
464 +rights granted or affirmed under this License. For example, you may
465 +not impose a license fee, royalty, or other charge for exercise of
466 +rights granted under this License, and you may not initiate litigation
467 +(including a cross-claim or counterclaim in a lawsuit) alleging that
468 +any patent claim is infringed by making, using, selling, offering for
469 +sale, or importing the Program or any portion of it.
470 +
471 + 11. Patents.
472 +
473 + A "contributor" is a copyright holder who authorizes use under this
474 +License of the Program or a work on which the Program is based. The
475 +work thus licensed is called the contributor's "contributor version".
476 +
477 + A contributor's "essential patent claims" are all patent claims
478 +owned or controlled by the contributor, whether already acquired or
479 +hereafter acquired, that would be infringed by some manner, permitted
480 +by this License, of making, using, or selling its contributor version,
481 +but do not include claims that would be infringed only as a
482 +consequence of further modification of the contributor version. For
483 +purposes of this definition, "control" includes the right to grant
484 +patent sublicenses in a manner consistent with the requirements of
485 +this License.
486 +
487 + Each contributor grants you a non-exclusive, worldwide, royalty-free
488 +patent license under the contributor's essential patent claims, to
489 +make, use, sell, offer for sale, import and otherwise run, modify and
490 +propagate the contents of its contributor version.
491 +
492 + In the following three paragraphs, a "patent license" is any express
493 +agreement or commitment, however denominated, not to enforce a patent
494 +(such as an express permission to practice a patent or covenant not to
495 +sue for patent infringement). To "grant" such a patent license to a
496 +party means to make such an agreement or commitment not to enforce a
497 +patent against the party.
498 +
499 + If you convey a covered work, knowingly relying on a patent license,
500 +and the Corresponding Source of the work is not available for anyone
501 +to copy, free of charge and under the terms of this License, through a
502 +publicly available network server or other readily accessible means,
503 +then you must either (1) cause the Corresponding Source to be so
504 +available, or (2) arrange to deprive yourself of the benefit of the
505 +patent license for this particular work, or (3) arrange, in a manner
506 +consistent with the requirements of this License, to extend the patent
507 +license to downstream recipients. "Knowingly relying" means you have
508 +actual knowledge that, but for the patent license, your conveying the
509 +covered work in a country, or your recipient's use of the covered work
510 +in a country, would infringe one or more identifiable patents in that
511 +country that you have reason to believe are valid.
512 +
513 + If, pursuant to or in connection with a single transaction or
514 +arrangement, you convey, or propagate by procuring conveyance of, a
515 +covered work, and grant a patent license to some of the parties
516 +receiving the covered work authorizing them to use, propagate, modify
517 +or convey a specific copy of the covered work, then the patent license
518 +you grant is automatically extended to all recipients of the covered
519 +work and works based on it.
520 +
521 + A patent license is "discriminatory" if it does not include within
522 +the scope of its coverage, prohibits the exercise of, or is
523 +conditioned on the non-exercise of one or more of the rights that are
524 +specifically granted under this License. You may not convey a covered
525 +work if you are a party to an arrangement with a third party that is
526 +in the business of distributing software, under which you make payment
527 +to the third party based on the extent of your activity of conveying
528 +the work, and under which the third party grants, to any of the
529 +parties who would receive the covered work from you, a discriminatory
530 +patent license (a) in connection with copies of the covered work
531 +conveyed by you (or copies made from those copies), or (b) primarily
532 +for and in connection with specific products or compilations that
533 +contain the covered work, unless you entered into that arrangement,
534 +or that patent license was granted, prior to 28 March 2007.
535 +
536 + Nothing in this License shall be construed as excluding or limiting
537 +any implied license or other defenses to infringement that may
538 +otherwise be available to you under applicable patent law.
539 +
540 + 12. No Surrender of Others' Freedom.
541 +
542 + If conditions are imposed on you (whether by court order, agreement or
543 +otherwise) that contradict the conditions of this License, they do not
544 +excuse you from the conditions of this License. If you cannot convey a
545 +covered work so as to satisfy simultaneously your obligations under this
546 +License and any other pertinent obligations, then as a consequence you may
547 +not convey it at all. For example, if you agree to terms that obligate you
548 +to collect a royalty for further conveying from those to whom you convey
549 +the Program, the only way you could satisfy both those terms and this
550 +License would be to refrain entirely from conveying the Program.
551 +
552 + 13. Use with the GNU Affero General Public License.
553 +
554 + Notwithstanding any other provision of this License, you have
555 +permission to link or combine any covered work with a work licensed
556 +under version 3 of the GNU Affero General Public License into a single
557 +combined work, and to convey the resulting work. The terms of this
558 +License will continue to apply to the part which is the covered work,
559 +but the special requirements of the GNU Affero General Public License,
560 +section 13, concerning interaction through a network will apply to the
561 +combination as such.
562 +
563 + 14. Revised Versions of this License.
564 +
565 + The Free Software Foundation may publish revised and/or new versions of
566 +the GNU General Public License from time to time. Such new versions will
567 +be similar in spirit to the present version, but may differ in detail to
568 +address new problems or concerns.
569 +
570 + Each version is given a distinguishing version number. If the
571 +Program specifies that a certain numbered version of the GNU General
572 +Public License "or any later version" applies to it, you have the
573 +option of following the terms and conditions either of that numbered
574 +version or of any later version published by the Free Software
575 +Foundation. If the Program does not specify a version number of the
576 +GNU General Public License, you may choose any version ever published
577 +by the Free Software Foundation.
578 +
579 + If the Program specifies that a proxy can decide which future
580 +versions of the GNU General Public License can be used, that proxy's
581 +public statement of acceptance of a version permanently authorizes you
582 +to choose that version for the Program.
583 +
584 + Later license versions may give you additional or different
585 +permissions. However, no additional obligations are imposed on any
586 +author or copyright holder as a result of your choosing to follow a
587 +later version.
588 +
589 + 15. Disclaimer of Warranty.
590 +
591 + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 +
600 + 16. Limitation of Liability.
601 +
602 + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 +SUCH DAMAGES.
611 +
612 + 17. Interpretation of Sections 15 and 16.
613 +
614 + If the disclaimer of warranty and limitation of liability provided
615 +above cannot be given local legal effect according to their terms,
616 +reviewing courts shall apply local law that most closely approximates
617 +an absolute waiver of all civil liability in connection with the
618 +Program, unless a warranty or assumption of liability accompanies a
619 +copy of the Program in return for a fee.
620 +
621 + END OF TERMS AND CONDITIONS
622 +
623 + How to Apply These Terms to Your New Programs
624 +
625 + If you develop a new program, and you want it to be of the greatest
626 +possible use to the public, the best way to achieve this is to make it
627 +free software which everyone can redistribute and change under these terms.
628 +
629 + To do so, attach the following notices to the program. It is safest
630 +to attach them to the start of each source file to most effectively
631 +state the exclusion of warranty; and each file should have at least
632 +the "copyright" line and a pointer to where the full notice is found.
633 +
634 + <one line to give the program's name and a brief idea of what it does.>
635 + Copyright (C) <year> <name of author>
636 +
637 + This program is free software: you can redistribute it and/or modify
638 + it under the terms of the GNU General Public License as published by
639 + the Free Software Foundation, either version 3 of the License, or
640 + (at your option) any later version.
641 +
642 + This program is distributed in the hope that it will be useful,
643 + but WITHOUT ANY WARRANTY; without even the implied warranty of
644 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 + GNU General Public License for more details.
646 +
647 + You should have received a copy of the GNU General Public License
648 + along with this program. If not, see <http://www.gnu.org/licenses/>.
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 + <program> Copyright (C) <year> <name of author>
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 +<http://www.gnu.org/licenses/>.
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 +<http://www.gnu.org/philosophy/why-not-lgpl.html>.
...\ No newline at end of file ...\ No newline at end of file
1 +# Include the README
2 +include *.md
3 +
4 +# Include the license file
5 +include LICENSE
6 +
7 +# Include setup.py
8 +include setup.py
9 +
10 +# Include the data files
11 +recursive-include yolov5/data *
12 +
13 +# Include the yml files in models folder
14 +recursive-include yolov5/models *
1 +Metadata-Version: 2.1
2 +Name: yolov5
3 +Version: 5.0.5
4 +Summary: Packaged version of the Yolov5 object detector
5 +Home-page: https://github.com/fcakyon/yolov5-pip
6 +Author:
7 +License: GPL
8 +Description: <h1 align="center">
9 + packaged ultralytics/yolov5
10 + </h1>
11 +
12 + <h4 align="center">
13 + pip install yolov5
14 + </h4>
15 +
16 + <div align="center">
17 + <a href="https://badge.fury.io/py/yolov5"><img src="https://badge.fury.io/py/yolov5.svg" alt="pypi version"></a>
18 + <a href="https://pepy.tech/project/yolov5"><img src="https://pepy.tech/badge/yolov5/month" alt="downloads"></a>
19 + <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml"><img src="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml/badge.svg" alt="ci testing"></a>
20 + <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml"><img src="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml/badge.svg" alt="package testing"></a>
21 + </div>
22 +
23 + ## Overview
24 +
25 + You can finally install [YOLOv5 object detector](https://github.com/ultralytics/yolov5) using [pip](https://pypi.org/project/yolov5/) and integrate into your project easily.
26 +
27 + <img src="https://user-images.githubusercontent.com/26833433/114313216-f0a5e100-9af5-11eb-8445-c682b60da2e3.png" width="1000">
28 +
29 + ## Installation
30 +
31 + - Install yolov5 using pip `(for Python >=3.7)`:
32 +
33 + ```console
34 + pip install yolov5
35 + ```
36 +
37 + - Install yolov5 using pip `(for Python 3.6)`:
38 +
39 + ```console
40 + pip install "numpy>=1.18.5,<1.20" "matplotlib>=3.2.2,<4"
41 + pip install yolov5
42 + ```
43 +
44 + ## Basic Usage
45 +
46 + ```python
47 + import yolov5
48 +
49 + # model
50 + model = yolov5.load('yolov5s')
51 +
52 + # image
53 + img = 'https://github.com/ultralytics/yolov5/raw/master/data/images/zidane.jpg'
54 +
55 + # inference
56 + results = model(img)
57 +
58 + # inference with larger input size
59 + results = model(img, size=1280)
60 +
61 + # inference with test time augmentation
62 + results = model(img, augment=True)
63 +
64 + # show results
65 + results.show()
66 +
67 + # save results
68 + results.save(save_dir='results/')
69 +
70 + ```
71 +
72 + ## Alternative Usage
73 +
74 + ```python
75 + from yolo_module.yolov5 import YOLOv5
76 +
77 + # set model params
78 + model_path = "yolov5/weights/yolov5s.pt" # it automatically downloads yolov5s model to given path
79 + device = "cuda" # or "cpu"
80 +
81 + # init yolov5 model
82 + yolov5 = YOLOv5(model_path, device)
83 +
84 + # load images
85 + image1 = 'https://github.com/ultralytics/yolov5/raw/master/data/images/zidane.jpg'
86 + image2 = 'https://github.com/ultralytics/yolov5/blob/master/data/images/bus.jpg'
87 +
88 + # perform inference
89 + results = yolov5.predict(image1)
90 +
91 + # perform inference with larger input size
92 + results = yolov5.predict(image1, size=1280)
93 +
94 + # perform inference with test time augmentation
95 + results = yolov5.predict(image1, augment=True)
96 +
97 + # perform inference on multiple images
98 + results = yolov5.predict([image1, image2], size=1280, augment=True)
99 +
100 + # show detection bounding boxes on image
101 + results.show()
102 +
103 + # save results into "results/" folder
104 + results.save(save_dir='results/')
105 + ```
106 +
107 + ## Scripts
108 +
109 + You can call yolo_train, yolo_detect and yolo_test commands after installing the package via `pip`:
110 +
111 + ### Training
112 +
113 + Run commands below to reproduce results on [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) dataset (dataset auto-downloads on first use). Training times for YOLOv5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). Use the largest `--batch-size` your GPU allows (batch sizes shown for 16 GB devices).
114 +
115 + ```bash
116 + $ yolo_train --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64
117 + yolov5m 40
118 + yolov5l 24
119 + yolov5x 16
120 + ```
121 +
122 + ### Inference
123 +
124 + yolo_detect command runs inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
125 +
126 + ```bash
127 + $ yolo_detect --source 0 # webcam
128 + file.jpg # image
129 + file.mp4 # video
130 + path/ # directory
131 + path/*.jpg # glob
132 + rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream
133 + rtmp://192.168.1.105/live/test # rtmp stream
134 + http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream
135 + ```
136 +
137 + To run inference on example images in `yolov5/data/images`:
138 +
139 + ```bash
140 + $ yolo_detect --source yolov5/data/images --weights yolov5s.pt --conf 0.25
141 + ```
142 +
143 + ## Status
144 +
145 + Builds for the latest commit for `Windows/Linux/MacOS` with `Python3.6/3.7/3.8`: <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml"><img src="https://github.com/fcakyon/yolov5-python/workflows/CI%20CPU%20Testing/badge.svg" alt="CI CPU testing"></a>
146 +
147 + Status for the train/detect/test scripts: <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml"><img src="https://github.com/fcakyon/yolov5-python/workflows/Package%20CPU%20Testing/badge.svg" alt="Package CPU testing"></a>
148 +
149 +Keywords: machine-learning,deep-learning,ml,pytorch,YOLO,object-detection,vision,YOLOv3,YOLOv4,YOLOv5
150 +Platform: UNKNOWN
151 +Classifier: Development Status :: 5 - Production/Stable
152 +Classifier: License :: OSI Approved :: GNU General Public License (GPL)
153 +Classifier: Operating System :: OS Independent
154 +Classifier: Intended Audience :: Developers
155 +Classifier: Intended Audience :: Science/Research
156 +Classifier: Programming Language :: Python :: 3
157 +Classifier: Programming Language :: Python :: 3.6
158 +Classifier: Programming Language :: Python :: 3.7
159 +Classifier: Programming Language :: Python :: 3.8
160 +Classifier: Topic :: Software Development :: Libraries
161 +Classifier: Topic :: Software Development :: Libraries :: Python Modules
162 +Classifier: Topic :: Education
163 +Classifier: Topic :: Scientific/Engineering
164 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
165 +Classifier: Topic :: Scientific/Engineering :: Image Recognition
166 +Requires-Python: >=3.6
167 +Description-Content-Type: text/markdown
168 +Provides-Extra: tests
1 +<h1 align="center">
2 + packaged ultralytics/yolov5
3 +</h1>
4 +
5 +<h4 align="center">
6 + pip install yolov5
7 +</h4>
8 +
9 +<div align="center">
10 + <a href="https://badge.fury.io/py/yolov5"><img src="https://badge.fury.io/py/yolov5.svg" alt="pypi version"></a>
11 + <a href="https://pepy.tech/project/yolov5"><img src="https://pepy.tech/badge/yolov5/month" alt="downloads"></a>
12 + <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml"><img src="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml/badge.svg" alt="ci testing"></a>
13 + <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml"><img src="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml/badge.svg" alt="package testing"></a>
14 +</div>
15 +
16 +## Overview
17 +
18 +You can finally install [YOLOv5 object detector](https://github.com/ultralytics/yolov5) using [pip](https://pypi.org/project/yolov5/) and integrate into your project easily.
19 +
20 +<img src="https://user-images.githubusercontent.com/26833433/114313216-f0a5e100-9af5-11eb-8445-c682b60da2e3.png" width="1000">
21 +
22 +## Installation
23 +
24 +- Install yolov5 using pip `(for Python >=3.7)`:
25 +
26 +```console
27 +pip install yolov5
28 +```
29 +
30 +- Install yolov5 using pip `(for Python 3.6)`:
31 +
32 +```console
33 +pip install "numpy>=1.18.5,<1.20" "matplotlib>=3.2.2,<4"
34 +pip install yolov5
35 +```
36 +
37 +## Basic Usage
38 +
39 +```python
40 +import yolov5
41 +
42 +# model
43 +model = yolov5.load('yolov5s')
44 +
45 +# image
46 +img = 'https://github.com/ultralytics/yolov5/raw/master/data/images/zidane.jpg'
47 +
48 +# inference
49 +results = model(img)
50 +
51 +# inference with larger input size
52 +results = model(img, size=1280)
53 +
54 +# inference with test time augmentation
55 +results = model(img, augment=True)
56 +
57 +# show results
58 +results.show()
59 +
60 +# save results
61 +results.save(save_dir='results/')
62 +
63 +```
64 +
65 +## Alternative Usage
66 +
67 +```python
68 +from yolo_module.yolov5 import YOLOv5
69 +
70 +# set model params
71 +model_path = "yolov5/weights/yolov5s.pt" # it automatically downloads yolov5s model to given path
72 +device = "cuda" # or "cpu"
73 +
74 +# init yolov5 model
75 +yolov5 = YOLOv5(model_path, device)
76 +
77 +# load images
78 +image1 = 'https://github.com/ultralytics/yolov5/raw/master/data/images/zidane.jpg'
79 +image2 = 'https://github.com/ultralytics/yolov5/blob/master/data/images/bus.jpg'
80 +
81 +# perform inference
82 +results = yolov5.predict(image1)
83 +
84 +# perform inference with larger input size
85 +results = yolov5.predict(image1, size=1280)
86 +
87 +# perform inference with test time augmentation
88 +results = yolov5.predict(image1, augment=True)
89 +
90 +# perform inference on multiple images
91 +results = yolov5.predict([image1, image2], size=1280, augment=True)
92 +
93 +# show detection bounding boxes on image
94 +results.show()
95 +
96 +# save results into "results/" folder
97 +results.save(save_dir='results/')
98 +```
99 +
100 +## Scripts
101 +
102 +You can call yolo_train, yolo_detect and yolo_test commands after installing the package via `pip`:
103 +
104 +### Training
105 +
106 +Run commands below to reproduce results on [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) dataset (dataset auto-downloads on first use). Training times for YOLOv5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). Use the largest `--batch-size` your GPU allows (batch sizes shown for 16 GB devices).
107 +
108 +```bash
109 +$ yolo_train --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64
110 + yolov5m 40
111 + yolov5l 24
112 + yolov5x 16
113 +```
114 +
115 +### Inference
116 +
117 +yolo_detect command runs inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
118 +
119 +```bash
120 +$ yolo_detect --source 0 # webcam
121 + file.jpg # image
122 + file.mp4 # video
123 + path/ # directory
124 + path/*.jpg # glob
125 + rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream
126 + rtmp://192.168.1.105/live/test # rtmp stream
127 + http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream
128 +```
129 +
130 +To run inference on example images in `yolov5/data/images`:
131 +
132 +```bash
133 +$ yolo_detect --source yolov5/data/images --weights yolov5s.pt --conf 0.25
134 +```
135 +
136 +## Status
137 +
138 +Builds for the latest commit for `Windows/Linux/MacOS` with `Python3.6/3.7/3.8`: <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml"><img src="https://github.com/fcakyon/yolov5-python/workflows/CI%20CPU%20Testing/badge.svg" alt="CI CPU testing"></a>
139 +
140 +Status for the train/detect/test scripts: <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml"><img src="https://github.com/fcakyon/yolov5-python/workflows/Package%20CPU%20Testing/badge.svg" alt="Package CPU testing"></a>
1 +[egg_info]
2 +tag_build =
3 +tag_date = 0
4 +
1 +import io
2 +import os
3 +import re
4 +
5 +import setuptools
6 +
7 +
8 +def get_long_description():
9 + base_dir = os.path.abspath(os.path.dirname(__file__))
10 + with io.open(os.path.join(base_dir, "README.md"), encoding="utf-8") as f:
11 + return f.read()
12 +
13 +
14 +def get_requirements():
15 + with open("requirements.txt") as f:
16 + return f.read().splitlines()
17 +
18 +
19 +def get_version():
20 + current_dir = os.path.abspath(os.path.dirname(__file__))
21 + version_file = os.path.join(current_dir, "yolov5", "__init__.py")
22 + with io.open(version_file, encoding="utf-8") as f:
23 + return re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read(), re.M).group(1)
24 +
25 +
26 +setuptools.setup(
27 + name="yolov5",
28 + version=get_version(),
29 + author="",
30 + license="GPL",
31 + description="Packaged version of the Yolov5 object detector",
32 + long_description=get_long_description(),
33 + long_description_content_type="text/markdown",
34 + url="https://github.com/fcakyon/yolov5-pip",
35 + packages=setuptools.find_packages(exclude=["tests"]),
36 + python_requires=">=3.6",
37 + install_requires=get_requirements(),
38 + extras_require={"tests": ["pytest"]},
39 + include_package_data=True,
40 + options={'bdist_wheel':{'python_tag':'py36.py37.py38'}},
41 + classifiers=[
42 + "Development Status :: 5 - Production/Stable",
43 + "License :: OSI Approved :: GNU General Public License (GPL)",
44 + "Operating System :: OS Independent",
45 + "Intended Audience :: Developers",
46 + "Intended Audience :: Science/Research",
47 + "Programming Language :: Python :: 3",
48 + "Programming Language :: Python :: 3.6",
49 + "Programming Language :: Python :: 3.7",
50 + "Programming Language :: Python :: 3.8",
51 + "Topic :: Software Development :: Libraries",
52 + "Topic :: Software Development :: Libraries :: Python Modules",
53 + "Topic :: Education",
54 + "Topic :: Scientific/Engineering",
55 + "Topic :: Scientific/Engineering :: Artificial Intelligence",
56 + "Topic :: Scientific/Engineering :: Image Recognition",
57 + ],
58 + keywords="machine-learning, deep-learning, ml, pytorch, YOLO, object-detection, vision, YOLOv3, YOLOv4, YOLOv5",
59 + entry_points={'console_scripts': [
60 + 'yolo_train=yolov5.train:main',
61 + 'yolo_test=yolov5.test:main',
62 + 'yolo_detect=yolov5.detect:main',
63 + 'yolo_export=yolov5.models.export:main'
64 + ],
65 + }
66 +)
1 +Metadata-Version: 2.1
2 +Name: yolov5
3 +Version: 5.0.5
4 +Summary: Packaged version of the Yolov5 object detector
5 +Home-page: https://github.com/fcakyon/yolov5-pip
6 +Author:
7 +License: GPL
8 +Description: <h1 align="center">
9 + packaged ultralytics/yolov5
10 + </h1>
11 +
12 + <h4 align="center">
13 + pip install yolov5
14 + </h4>
15 +
16 + <div align="center">
17 + <a href="https://badge.fury.io/py/yolov5"><img src="https://badge.fury.io/py/yolov5.svg" alt="pypi version"></a>
18 + <a href="https://pepy.tech/project/yolov5"><img src="https://pepy.tech/badge/yolov5/month" alt="downloads"></a>
19 + <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml"><img src="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml/badge.svg" alt="ci testing"></a>
20 + <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml"><img src="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml/badge.svg" alt="package testing"></a>
21 + </div>
22 +
23 + ## Overview
24 +
25 + You can finally install [YOLOv5 object detector](https://github.com/ultralytics/yolov5) using [pip](https://pypi.org/project/yolov5/) and integrate into your project easily.
26 +
27 + <img src="https://user-images.githubusercontent.com/26833433/114313216-f0a5e100-9af5-11eb-8445-c682b60da2e3.png" width="1000">
28 +
29 + ## Installation
30 +
31 + - Install yolov5 using pip `(for Python >=3.7)`:
32 +
33 + ```console
34 + pip install yolov5
35 + ```
36 +
37 + - Install yolov5 using pip `(for Python 3.6)`:
38 +
39 + ```console
40 + pip install "numpy>=1.18.5,<1.20" "matplotlib>=3.2.2,<4"
41 + pip install yolov5
42 + ```
43 +
44 + ## Basic Usage
45 +
46 + ```python
47 + import yolov5
48 +
49 + # model
50 + model = yolov5.load('yolov5s')
51 +
52 + # image
53 + img = 'https://github.com/ultralytics/yolov5/raw/master/data/images/zidane.jpg'
54 +
55 + # inference
56 + results = model(img)
57 +
58 + # inference with larger input size
59 + results = model(img, size=1280)
60 +
61 + # inference with test time augmentation
62 + results = model(img, augment=True)
63 +
64 + # show results
65 + results.show()
66 +
67 + # save results
68 + results.save(save_dir='results/')
69 +
70 + ```
71 +
72 + ## Alternative Usage
73 +
74 + ```python
75 + from yolo_module.yolov5 import YOLOv5
76 +
77 + # set model params
78 + model_path = "yolov5/weights/yolov5s.pt" # it automatically downloads yolov5s model to given path
79 + device = "cuda" # or "cpu"
80 +
81 + # init yolov5 model
82 + yolov5 = YOLOv5(model_path, device)
83 +
84 + # load images
85 + image1 = 'https://github.com/ultralytics/yolov5/raw/master/data/images/zidane.jpg'
86 + image2 = 'https://github.com/ultralytics/yolov5/blob/master/data/images/bus.jpg'
87 +
88 + # perform inference
89 + results = yolov5.predict(image1)
90 +
91 + # perform inference with larger input size
92 + results = yolov5.predict(image1, size=1280)
93 +
94 + # perform inference with test time augmentation
95 + results = yolov5.predict(image1, augment=True)
96 +
97 + # perform inference on multiple images
98 + results = yolov5.predict([image1, image2], size=1280, augment=True)
99 +
100 + # show detection bounding boxes on image
101 + results.show()
102 +
103 + # save results into "results/" folder
104 + results.save(save_dir='results/')
105 + ```
106 +
107 + ## Scripts
108 +
109 + You can call yolo_train, yolo_detect and yolo_test commands after installing the package via `pip`:
110 +
111 + ### Training
112 +
113 + Run commands below to reproduce results on [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) dataset (dataset auto-downloads on first use). Training times for YOLOv5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). Use the largest `--batch-size` your GPU allows (batch sizes shown for 16 GB devices).
114 +
115 + ```bash
116 + $ yolo_train --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64
117 + yolov5m 40
118 + yolov5l 24
119 + yolov5x 16
120 + ```
121 +
122 + ### Inference
123 +
124 + yolo_detect command runs inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
125 +
126 + ```bash
127 + $ yolo_detect --source 0 # webcam
128 + file.jpg # image
129 + file.mp4 # video
130 + path/ # directory
131 + path/*.jpg # glob
132 + rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream
133 + rtmp://192.168.1.105/live/test # rtmp stream
134 + http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream
135 + ```
136 +
137 + To run inference on example images in `yolov5/data/images`:
138 +
139 + ```bash
140 + $ yolo_detect --source yolov5/data/images --weights yolov5s.pt --conf 0.25
141 + ```
142 +
143 + ## Status
144 +
145 + Builds for the latest commit for `Windows/Linux/MacOS` with `Python3.6/3.7/3.8`: <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/ci.yml"><img src="https://github.com/fcakyon/yolov5-python/workflows/CI%20CPU%20Testing/badge.svg" alt="CI CPU testing"></a>
146 +
147 + Status for the train/detect/test scripts: <a href="https://github.com/fcakyon/yolov5-pip/actions/workflows/package_testing.yml"><img src="https://github.com/fcakyon/yolov5-python/workflows/Package%20CPU%20Testing/badge.svg" alt="Package CPU testing"></a>
148 +
149 +Keywords: machine-learning,deep-learning,ml,pytorch,YOLO,object-detection,vision,YOLOv3,YOLOv4,YOLOv5
150 +Platform: UNKNOWN
151 +Classifier: Development Status :: 5 - Production/Stable
152 +Classifier: License :: OSI Approved :: GNU General Public License (GPL)
153 +Classifier: Operating System :: OS Independent
154 +Classifier: Intended Audience :: Developers
155 +Classifier: Intended Audience :: Science/Research
156 +Classifier: Programming Language :: Python :: 3
157 +Classifier: Programming Language :: Python :: 3.6
158 +Classifier: Programming Language :: Python :: 3.7
159 +Classifier: Programming Language :: Python :: 3.8
160 +Classifier: Topic :: Software Development :: Libraries
161 +Classifier: Topic :: Software Development :: Libraries :: Python Modules
162 +Classifier: Topic :: Education
163 +Classifier: Topic :: Scientific/Engineering
164 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
165 +Classifier: Topic :: Scientific/Engineering :: Image Recognition
166 +Requires-Python: >=3.6
167 +Description-Content-Type: text/markdown
168 +Provides-Extra: tests
1 +LICENSE
2 +MANIFEST.in
3 +README.md
4 +setup.py
5 +yolov5/__init__.py
6 +yolov5/detect.py
7 +yolov5/helpers.py
8 +yolov5/hubconf.py
9 +yolov5/test.py
10 +yolov5/train.py
11 +yolov5.egg-info/PKG-INFO
12 +yolov5.egg-info/SOURCES.txt
13 +yolov5.egg-info/dependency_links.txt
14 +yolov5.egg-info/entry_points.txt
15 +yolov5.egg-info/requires.txt
16 +yolov5.egg-info/top_level.txt
17 +yolov5/data/GlobalWheat2020.yaml
18 +yolov5/data/VisDrone.yaml
19 +yolov5/data/argoverse_hd.yaml
20 +yolov5/data/coco.yaml
21 +yolov5/data/coco128.yaml
22 +yolov5/data/hyp.finetune.yaml
23 +yolov5/data/hyp.finetune_objects365.yaml
24 +yolov5/data/hyp.scratch.yaml
25 +yolov5/data/objects365.yaml
26 +yolov5/data/visdrone.yaml
27 +yolov5/data/voc.yaml
28 +yolov5/data/images/bus.jpg
29 +yolov5/data/images/zidane.jpg
30 +yolov5/data/scripts/get_argoverse_hd.sh
31 +yolov5/data/scripts/get_coco.sh
32 +yolov5/data/scripts/get_coco128.sh
33 +yolov5/data/scripts/get_voc.sh
34 +yolov5/models/__init__.py
35 +yolov5/models/common.py
36 +yolov5/models/experimental.py
37 +yolov5/models/export.py
38 +yolov5/models/yolo.py
39 +yolov5/models/yolov5l.yaml
40 +yolov5/models/yolov5m.yaml
41 +yolov5/models/yolov5s.yaml
42 +yolov5/models/yolov5x.yaml
43 +yolov5/models/hub/anchors.yaml
44 +yolov5/models/hub/yolov3-spp.yaml
45 +yolov5/models/hub/yolov3-tiny.yaml
46 +yolov5/models/hub/yolov3.yaml
47 +yolov5/models/hub/yolov5-fpn.yaml
48 +yolov5/models/hub/yolov5-p2.yaml
49 +yolov5/models/hub/yolov5-p6.yaml
50 +yolov5/models/hub/yolov5-p7.yaml
51 +yolov5/models/hub/yolov5-panet.yaml
52 +yolov5/models/hub/yolov5l6.yaml
53 +yolov5/models/hub/yolov5m6.yaml
54 +yolov5/models/hub/yolov5s-transformer.yaml
55 +yolov5/models/hub/yolov5s6.yaml
56 +yolov5/models/hub/yolov5x6.yaml
57 +yolov5/utils/__init__.py
58 +yolov5/utils/activations.py
59 +yolov5/utils/autoanchor.py
60 +yolov5/utils/datasets.py
61 +yolov5/utils/general.py
62 +yolov5/utils/google_utils.py
63 +yolov5/utils/loss.py
64 +yolov5/utils/metrics.py
65 +yolov5/utils/plots.py
66 +yolov5/utils/torch_utils.py
67 +yolov5/utils/aws/__init__.py
68 +yolov5/utils/aws/resume.py
69 +yolov5/utils/neptuneai_logging/__init__.py
70 +yolov5/utils/neptuneai_logging/neptuneai_utils.py
71 +yolov5/utils/wandb_logging/__init__.py
72 +yolov5/utils/wandb_logging/log_dataset.py
73 +yolov5/utils/wandb_logging/wandb_utils.py
...\ No newline at end of file ...\ No newline at end of file
1 +[console_scripts]
2 +yolo_detect = yolov5.detect:main
3 +yolo_export = yolov5.models.export:main
4 +yolo_test = yolov5.test:main
5 +yolo_train = yolov5.train:main
6 +
1 +matplotlib>=3.2.2
2 +numpy>=1.18.5
3 +opencv-python>=4.1.2
4 +Pillow
5 +PyYAML>=5.3.1
6 +scipy>=1.4.1
7 +torch>=1.7.0
8 +torchvision>=0.8.1
9 +tqdm>=4.41.0
10 +tensorboard>=2.4.1
11 +seaborn>=0.11.0
12 +pandas
13 +thop
14 +pycocotools>=2.0
15 +
16 +[tests]
17 +pytest
1 +from yolo_module.yolov5.helpers import YOLOv5
2 +from yolo_module.yolov5.helpers import load_model as load
3 +
4 +__version__ = "5.0.5"
1 +# Global Wheat 2020 dataset http://www.global-wheat.com/
2 +# Train command: python train.py --data GlobalWheat2020.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /datasets/GlobalWheat2020
6 +# /yolov5
7 +
8 +
9 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 +train: # 3422 images
11 + - ../datasets/GlobalWheat2020/images/arvalis_1
12 + - ../datasets/GlobalWheat2020/images/arvalis_2
13 + - ../datasets/GlobalWheat2020/images/arvalis_3
14 + - ../datasets/GlobalWheat2020/images/ethz_1
15 + - ../datasets/GlobalWheat2020/images/rres_1
16 + - ../datasets/GlobalWheat2020/images/inrae_1
17 + - ../datasets/GlobalWheat2020/images/usask_1
18 +
19 +val: # 748 images (WARNING: train set contains ethz_1)
20 + - ../datasets/GlobalWheat2020/images/ethz_1
21 +
22 +test: # 1276 images
23 + - ../datasets/GlobalWheat2020/images/utokyo_1
24 + - ../datasets/GlobalWheat2020/images/utokyo_2
25 + - ../datasets/GlobalWheat2020/images/nau_1
26 + - ../datasets/GlobalWheat2020/images/uq_1
27 +
28 +# number of classes
29 +nc: 1
30 +
31 +# class names
32 +names: [ 'wheat_head' ]
33 +
34 +
35 +# download command/URL (optional) --------------------------------------------------------------------------------------
36 +download: |
37 + from utils.general import download, Path
38 +
39 + # Download
40 + dir = Path('../datasets/GlobalWheat2020') # dataset directory
41 + urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
42 + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
43 + download(urls, dir=dir)
44 +
45 + # Make Directories
46 + for p in 'annotations', 'images', 'labels':
47 + (dir / p).mkdir(parents=True, exist_ok=True)
48 +
49 + # Move
50 + for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
51 + 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
52 + (dir / p).rename(dir / 'images' / p) # move to /images
53 + f = (dir / p).with_suffix('.json') # json file
54 + if f.exists():
55 + f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
1 +# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
2 +# Train command: python train.py --data argoverse_hd.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /argoverse
6 +# /yolov5
7 +
8 +
9 +# download command/URL (optional)
10 +download: bash data/scripts/get_argoverse_hd.sh
11 +
12 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 +train: ../argoverse/Argoverse-1.1/images/train/ # 39384 images
14 +val: ../argoverse/Argoverse-1.1/images/val/ # 15062 iamges
15 +test: ../argoverse/Argoverse-1.1/images/test/ # Submit to: https://eval.ai/web/challenges/challenge-page/800/overview
16 +
17 +# number of classes
18 +nc: 8
19 +
20 +# class names
21 +names: [ 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign' ]
1 +# COCO 2017 dataset http://cocodataset.org
2 +# Train command: python train.py --data coco.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /coco
6 +# /yolov5
7 +
8 +
9 +# download command/URL (optional)
10 +download: bash data/scripts/get_coco.sh
11 +
12 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 +train: ../coco/train2017.txt # 118287 images
14 +val: ../coco/val2017.txt # 5000 images
15 +test: ../coco/test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
16 +
17 +# number of classes
18 +nc: 80
19 +
20 +# class names
21 +names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
22 + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
23 + 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
24 + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
25 + 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
26 + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
27 + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
28 + 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
29 + 'hair drier', 'toothbrush' ]
30 +
31 +# Print classes
32 +# with open('data/coco.yaml') as f:
33 +# d = yaml.safe_load(f) # dict
34 +# for i, x in enumerate(d['names']):
35 +# print(i, x)
1 +# COCO 2017 dataset http://cocodataset.org - first 128 training images
2 +# Train command: python train.py --data coco128.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /coco128
6 +# /yolov5
7 +
8 +
9 +# download command/URL (optional)
10 +download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
11 +
12 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 +train: ../coco128/images/train2017/ # 128 images
14 +val: ../coco128/images/train2017/ # 128 images
15 +
16 +# number of classes
17 +nc: 80
18 +
19 +# class names
20 +names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
21 + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
22 + 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
23 + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
24 + 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
25 + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
26 + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
27 + 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
28 + 'hair drier', 'toothbrush' ]
1 +# Hyperparameters for VOC finetuning
2 +# python train.py --batch 64 --weights yolov5m.pt --data voc.yaml --img 512 --epochs 50
3 +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 +
5 +
6 +# Hyperparameter Evolution Results
7 +# Generations: 306
8 +# P R mAP.5 mAP.5:.95 box obj cls
9 +# Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146
10 +
11 +lr0: 0.0032
12 +lrf: 0.12
13 +momentum: 0.843
14 +weight_decay: 0.00036
15 +warmup_epochs: 2.0
16 +warmup_momentum: 0.5
17 +warmup_bias_lr: 0.05
18 +box: 0.0296
19 +cls: 0.243
20 +cls_pw: 0.631
21 +obj: 0.301
22 +obj_pw: 0.911
23 +iou_t: 0.2
24 +anchor_t: 2.91
25 +# anchors: 3.63
26 +fl_gamma: 0.0
27 +hsv_h: 0.0138
28 +hsv_s: 0.664
29 +hsv_v: 0.464
30 +degrees: 0.373
31 +translate: 0.245
32 +scale: 0.898
33 +shear: 0.602
34 +perspective: 0.0
35 +flipud: 0.00856
36 +fliplr: 0.5
37 +mosaic: 1.0
38 +mixup: 0.243
1 +lr0: 0.00258
2 +lrf: 0.17
3 +momentum: 0.779
4 +weight_decay: 0.00058
5 +warmup_epochs: 1.33
6 +warmup_momentum: 0.86
7 +warmup_bias_lr: 0.0711
8 +box: 0.0539
9 +cls: 0.299
10 +cls_pw: 0.825
11 +obj: 0.632
12 +obj_pw: 1.0
13 +iou_t: 0.2
14 +anchor_t: 3.44
15 +anchors: 3.2
16 +fl_gamma: 0.0
17 +hsv_h: 0.0188
18 +hsv_s: 0.704
19 +hsv_v: 0.36
20 +degrees: 0.0
21 +translate: 0.0902
22 +scale: 0.491
23 +shear: 0.0
24 +perspective: 0.0
25 +flipud: 0.0
26 +fliplr: 0.5
27 +mosaic: 1.0
28 +mixup: 0.0
1 +# Hyperparameters for COCO training from scratch
2 +# python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
3 +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 +
5 +
6 +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 +lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8 +momentum: 0.937 # SGD momentum/Adam beta1
9 +weight_decay: 0.0005 # optimizer weight decay 5e-4
10 +warmup_epochs: 3.0 # warmup epochs (fractions ok)
11 +warmup_momentum: 0.8 # warmup initial momentum
12 +warmup_bias_lr: 0.1 # warmup initial bias lr
13 +box: 0.05 # box loss gain
14 +cls: 0.5 # cls loss gain
15 +cls_pw: 1.0 # cls BCELoss positive_weight
16 +obj: 1.0 # obj loss gain (scale with pixels)
17 +obj_pw: 1.0 # obj BCELoss positive_weight
18 +iou_t: 0.20 # IoU training threshold
19 +anchor_t: 4.0 # anchor-multiple threshold
20 +# anchors: 3 # anchors per output layer (0 to ignore)
21 +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22 +hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23 +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24 +hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25 +degrees: 0.0 # image rotation (+/- deg)
26 +translate: 0.1 # image translation (+/- fraction)
27 +scale: 0.5 # image scale (+/- gain)
28 +shear: 0.0 # image shear (+/- deg)
29 +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30 +flipud: 0.0 # image flip up-down (probability)
31 +fliplr: 0.5 # image flip left-right (probability)
32 +mosaic: 1.0 # image mosaic (probability)
33 +mixup: 0.0 # image mixup (probability)
1 +# Objects365 dataset https://www.objects365.org/
2 +# Train command: python train.py --data objects365.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /datasets/objects365
6 +# /yolov5
7 +
8 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
9 +train: ../datasets/objects365/images/train # 1742289 images
10 +val: ../datasets/objects365/images/val # 5570 images
11 +
12 +# number of classes
13 +nc: 365
14 +
15 +# class names
16 +names: [ 'Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup',
17 + 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book',
18 + 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag',
19 + 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV',
20 + 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle',
21 + 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird',
22 + 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck',
23 + 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning',
24 + 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife',
25 + 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock',
26 + 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish',
27 + 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan',
28 + 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard',
29 + 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign',
30 + 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat',
31 + 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard',
32 + 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry',
33 + 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks',
34 + 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors',
35 + 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape',
36 + 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck',
37 + 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette',
38 + 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket',
39 + 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine',
40 + 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine',
41 + 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon',
42 + 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse',
43 + 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball',
44 + 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin',
45 + 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts',
46 + 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit',
47 + 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD',
48 + 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder',
49 + 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips',
50 + 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab',
51 + 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal',
52 + 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart',
53 + 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French',
54 + 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell',
55 + 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil',
56 + 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis' ]
57 +
58 +
59 +# download command/URL (optional) --------------------------------------------------------------------------------------
60 +download: |
61 + from pycocotools.coco import COCO
62 + from tqdm import tqdm
63 +
64 + from utils.general import download, Path
65 +
66 + # Make Directories
67 + dir = Path('../datasets/objects365') # dataset directory
68 + for p in 'images', 'labels':
69 + (dir / p).mkdir(parents=True, exist_ok=True)
70 + for q in 'train', 'val':
71 + (dir / p / q).mkdir(parents=True, exist_ok=True)
72 +
73 + # Download
74 + url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/"
75 + download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json
76 + download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train',
77 + curl=True, delete=False, threads=8)
78 +
79 + # Move
80 + train = dir / 'images' / 'train'
81 + for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'):
82 + f.rename(train / f.name) # move to /images/train
83 +
84 + # Labels
85 + coco = COCO(dir / 'zhiyuan_objv2_train.json')
86 + names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
87 + for cid, cat in enumerate(names):
88 + catIds = coco.getCatIds(catNms=[cat])
89 + imgIds = coco.getImgIds(catIds=catIds)
90 + for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
91 + width, height = im["width"], im["height"]
92 + path = Path(im["file_name"]) # image filename
93 + try:
94 + with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file:
95 + annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
96 + for a in coco.loadAnns(annIds):
97 + x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
98 + x, y = x + w / 2, y + h / 2 # xy to center
99 + file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n")
100 +
101 + except Exception as e:
102 + print(e)
1 +#!/bin/bash
2 +# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
3 +# Download command: bash data/scripts/get_argoverse_hd.sh
4 +# Train command: python train.py --data argoverse_hd.yaml
5 +# Default dataset location is next to YOLOv5:
6 +# /parent_folder
7 +# /argoverse
8 +# /yolov5
9 +
10 +# Download/unzip images
11 +d='../argoverse/' # unzip directory
12 +mkdir $d
13 +url=https://argoverse-hd.s3.us-east-2.amazonaws.com/
14 +f=Argoverse-HD-Full.zip
15 +curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &# download, unzip, remove in background
16 +wait # finish background tasks
17 +
18 +cd ../argoverse/Argoverse-1.1/
19 +ln -s tracking images
20 +
21 +cd ../Argoverse-HD/annotations/
22 +
23 +python3 - "$@" <<END
24 +import json
25 +from pathlib import Path
26 +
27 +annotation_files = ["train.json", "val.json"]
28 +print("Converting annotations to YOLOv5 format...")
29 +
30 +for val in annotation_files:
31 + a = json.load(open(val, "rb"))
32 +
33 + label_dict = {}
34 + for annot in a['annotations']:
35 + img_id = annot['image_id']
36 + img_name = a['images'][img_id]['name']
37 + img_label_name = img_name[:-3] + "txt"
38 +
39 + cls = annot['category_id'] # instance class id
40 + x_center, y_center, width, height = annot['bbox']
41 + x_center = (x_center + width / 2) / 1920. # offset and scale
42 + y_center = (y_center + height / 2) / 1200. # offset and scale
43 + width /= 1920. # scale
44 + height /= 1200. # scale
45 +
46 + img_dir = "./labels/" + a['seq_dirs'][a['images'][annot['image_id']]['sid']]
47 +
48 + Path(img_dir).mkdir(parents=True, exist_ok=True)
49 + if img_dir + "/" + img_label_name not in label_dict:
50 + label_dict[img_dir + "/" + img_label_name] = []
51 +
52 + label_dict[img_dir + "/" + img_label_name].append(f"{cls} {x_center} {y_center} {width} {height}\n")
53 +
54 + for filename in label_dict:
55 + with open(filename, "w") as file:
56 + for string in label_dict[filename]:
57 + file.write(string)
58 +
59 +END
60 +
61 +mv ./labels ../../Argoverse-1.1/
1 +#!/bin/bash
2 +# COCO 2017 dataset http://cocodataset.org
3 +# Download command: bash data/scripts/get_coco.sh
4 +# Train command: python train.py --data coco.yaml
5 +# Default dataset location is next to YOLOv5:
6 +# /parent_folder
7 +# /coco
8 +# /yolov5
9 +
10 +# Download/unzip labels
11 +d='../' # unzip directory
12 +url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
13 +f='coco2017labels.zip' # or 'coco2017labels-segments.zip', 68 MB
14 +echo 'Downloading' $url$f ' ...'
15 +curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
16 +
17 +# Download/unzip images
18 +d='../coco/images' # unzip directory
19 +url=http://images.cocodataset.org/zips/
20 +f1='train2017.zip' # 19G, 118k images
21 +f2='val2017.zip' # 1G, 5k images
22 +f3='test2017.zip' # 7G, 41k images (optional)
23 +for f in $f1 $f2; do
24 + echo 'Downloading' $url$f '...'
25 + curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
26 +done
27 +wait # finish background tasks
1 +#!/bin/bash
2 +# COCO128 dataset https://www.kaggle.com/ultralytics/coco128
3 +# Download command: bash data/scripts/get_coco128.sh
4 +# Train command: python train.py --data coco128.yaml
5 +# Default dataset location is next to /yolov5:
6 +# /parent_folder
7 +# /coco128
8 +# /yolov5
9 +
10 +# Download/unzip images and labels
11 +d='../' # unzip directory
12 +url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
13 +f='coco128.zip' # or 'coco2017labels-segments.zip', 68 MB
14 +echo 'Downloading' $url$f ' ...'
15 +curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
16 +
17 +wait # finish background tasks
1 +#!/bin/bash
2 +# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/
3 +# Download command: bash data/scripts/get_voc.sh
4 +# Train command: python train.py --data voc.yaml
5 +# Default dataset location is next to YOLOv5:
6 +# /parent_folder
7 +# /VOC
8 +# /yolov5
9 +
10 +start=$(date +%s)
11 +mkdir -p ../tmp
12 +cd ../tmp/
13 +
14 +# Download/unzip images and labels
15 +d='.' # unzip directory
16 +url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
17 +f1=VOCtrainval_06-Nov-2007.zip # 446MB, 5012 images
18 +f2=VOCtest_06-Nov-2007.zip # 438MB, 4953 images
19 +f3=VOCtrainval_11-May-2012.zip # 1.95GB, 17126 images
20 +for f in $f3 $f2 $f1; do
21 + echo 'Downloading' $url$f '...'
22 + curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
23 +done
24 +wait # finish background tasks
25 +
26 +end=$(date +%s)
27 +runtime=$((end - start))
28 +echo "Completed in" $runtime "seconds"
29 +
30 +echo "Splitting dataset..."
31 +python3 - "$@" <<END
32 +import os
33 +import xml.etree.ElementTree as ET
34 +from os import getcwd
35 +
36 +sets = [('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
37 +
38 +classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog",
39 + "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
40 +
41 +
42 +def convert_box(size, box):
43 + dw = 1. / (size[0])
44 + dh = 1. / (size[1])
45 + x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
46 + return x * dw, y * dh, w * dw, h * dh
47 +
48 +
49 +def convert_annotation(year, image_id):
50 + in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml' % (year, image_id))
51 + out_file = open('VOCdevkit/VOC%s/labels/%s.txt' % (year, image_id), 'w')
52 + tree = ET.parse(in_file)
53 + root = tree.getroot()
54 + size = root.find('size')
55 + w = int(size.find('width').text)
56 + h = int(size.find('height').text)
57 +
58 + for obj in root.iter('object'):
59 + difficult = obj.find('difficult').text
60 + cls = obj.find('name').text
61 + if cls not in classes or int(difficult) == 1:
62 + continue
63 + cls_id = classes.index(cls)
64 + xmlbox = obj.find('bndbox')
65 + b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
66 + float(xmlbox.find('ymax').text))
67 + bb = convert_box((w, h), b)
68 + out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
69 +
70 +
71 +cwd = getcwd()
72 +for year, image_set in sets:
73 + if not os.path.exists('VOCdevkit/VOC%s/labels/' % year):
74 + os.makedirs('VOCdevkit/VOC%s/labels/' % year)
75 + image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt' % (year, image_set)).read().strip().split()
76 + list_file = open('%s_%s.txt' % (year, image_set), 'w')
77 + for image_id in image_ids:
78 + list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n' % (cwd, year, image_id))
79 + convert_annotation(year, image_id)
80 + list_file.close()
81 +END
82 +
83 +cat 2007_train.txt 2007_val.txt 2012_train.txt 2012_val.txt >train.txt
84 +cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt
85 +
86 +mkdir ../VOC ../VOC/images ../VOC/images/train ../VOC/images/val
87 +mkdir ../VOC/labels ../VOC/labels/train ../VOC/labels/val
88 +
89 +python3 - "$@" <<END
90 +import os
91 +
92 +print(os.path.exists('../tmp/train.txt'))
93 +with open('../tmp/train.txt', 'r') as f:
94 + for line in f.readlines():
95 + line = "/".join(line.split('/')[-5:]).strip()
96 + if os.path.exists("../" + line):
97 + os.system("cp ../" + line + " ../VOC/images/train")
98 +
99 + line = line.replace('JPEGImages', 'labels').replace('jpg', 'txt')
100 + if os.path.exists("../" + line):
101 + os.system("cp ../" + line + " ../VOC/labels/train")
102 +
103 +print(os.path.exists('../tmp/2007_test.txt'))
104 +with open('../tmp/2007_test.txt', 'r') as f:
105 + for line in f.readlines():
106 + line = "/".join(line.split('/')[-5:]).strip()
107 + if os.path.exists("../" + line):
108 + os.system("cp ../" + line + " ../VOC/images/val")
109 +
110 + line = line.replace('JPEGImages', 'labels').replace('jpg', 'txt')
111 + if os.path.exists("../" + line):
112 + os.system("cp ../" + line + " ../VOC/labels/val")
113 +END
114 +
115 +rm -rf ../tmp # remove temporary directory
116 +echo "VOC download done."
1 +# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset
2 +# Train command: python train.py --data visdrone.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /VisDrone
6 +# /yolov5
7 +
8 +
9 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 +train: ../VisDrone/VisDrone2019-DET-train/images # 6471 images
11 +val: ../VisDrone/VisDrone2019-DET-val/images # 548 images
12 +test: ../VisDrone/VisDrone2019-DET-test-dev/images # 1610 images
13 +
14 +# number of classes
15 +nc: 10
16 +
17 +# class names
18 +names: [ 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor' ]
19 +
20 +
21 +# download command/URL (optional) --------------------------------------------------------------------------------------
22 +download: |
23 + import os
24 + from pathlib import Path
25 +
26 + from utils.general import download
27 +
28 +
29 + def visdrone2yolo(dir):
30 + from PIL import Image
31 + from tqdm import tqdm
32 +
33 + def convert_box(size, box):
34 + # Convert VisDrone box to YOLO xywh box
35 + dw = 1. / size[0]
36 + dh = 1. / size[1]
37 + return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
38 +
39 + (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
40 + pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
41 + for f in pbar:
42 + img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
43 + lines = []
44 + with open(f, 'r') as file: # read annotation.txt
45 + for row in [x.split(',') for x in file.read().strip().splitlines()]:
46 + if row[4] == '0': # VisDrone 'ignored regions' class 0
47 + continue
48 + cls = int(row[5]) - 1
49 + box = convert_box(img_size, tuple(map(int, row[:4])))
50 + lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
51 + with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
52 + fl.writelines(lines) # write label.txt
53 +
54 +
55 + # Download
56 + dir = Path('../VisDrone') # dataset directory
57 + urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
58 + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
59 + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
60 + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
61 + download(urls, dir=dir)
62 +
63 + # Convert
64 + for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
65 + visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
1 +# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/
2 +# Train command: python train.py --data voc.yaml
3 +# Default dataset location is next to YOLOv5:
4 +# /parent_folder
5 +# /VOC
6 +# /yolov5
7 +
8 +
9 +# download command/URL (optional)
10 +download: bash data/scripts/get_voc.sh
11 +
12 +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 +train: ../VOC/images/train/ # 16551 images
14 +val: ../VOC/images/val/ # 4952 images
15 +
16 +# number of classes
17 +nc: 20
18 +
19 +# class names
20 +names: [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
21 + 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ]
1 +import argparse
2 +import time
3 +from pathlib import Path
4 +import subprocess
5 +
6 +import cv2
7 +import torch
8 +import torch.backends.cudnn as cudnn
9 +
10 +from yolo_module.yolov5.models.experimental import attempt_load
11 +from yolo_module.yolov5.utils.datasets import LoadImages, LoadStreams
12 +from yolo_module.yolov5.utils.general import (apply_classifier, check_img_size,
13 + check_imshow, check_requirements,
14 + increment_path, non_max_suppression,
15 + save_one_box, scale_coords, set_logging,
16 + strip_optimizer, xyxy2xywh,
17 + yolov5_in_syspath)
18 +from yolo_module.yolov5.utils.plots import colors, plot_one_box
19 +from yolo_module.yolov5.utils.torch_utils import (load_classifier, select_device,
20 + time_synchronized)
21 +
22 +
23 +
24 +def detect(opt):
25 + path = "rtmp://wj.khunet.net/stream/1234"
26 + cap = cv2.VideoCapture(path)
27 +
28 + # gather video info to ffmpeg
29 + fps = 5
30 + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
31 + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
32 + rtmp_url = "rtmp://wj.khunet.net/stream/after"
33 +
34 +# command and params for ffmpeg
35 + command = ['ffmpeg',
36 + '-y',
37 + '-f', 'rawvideo',
38 + '-vcodec', 'rawvideo',
39 + '-pix_fmt', 'bgr24',
40 + '-s', "{}x{}".format(width, height),
41 + '-r', str(fps),
42 + '-i', '-',
43 + '-c:v', 'libx264',
44 + '-pix_fmt', 'yuv420p',
45 + '-preset', 'ultrafast',
46 + '-f', 'flv',
47 + rtmp_url]
48 + rtmp_publisher = subprocess.Popen(command, stdin=subprocess.PIPE)
49 + source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
50 + save_img = not opt.nosave and not source.endswith('.txt') # save inference images
51 + webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
52 + ('rtsp://', 'rtmp://', 'http://', 'https://'))
53 +
54 + # Directories
55 + save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
56 + (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
57 +
58 + # Initialize
59 + set_logging()
60 + device = select_device(opt.device)
61 + half = device.type != 'cpu' # half precision only supported on CUDA
62 +
63 + # Load model
64 + model = attempt_load(weights, map_location=device) # load FP32 model
65 + stride = int(model.stride.max()) # model stride
66 + imgsz = check_img_size(imgsz, s=stride) # check img_size
67 + names = model.module.names if hasattr(model, 'module') else model.names # get class names
68 + if half:
69 + model.half() # to FP16
70 +
71 + # Second-stage classifier
72 + classify = False
73 + if classify:
74 + modelc = load_classifier(name='resnet101', n=2) # initialize
75 + with yolov5_in_syspath():
76 + modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
77 +
78 + # Set Dataloader
79 + vid_path, vid_writer = None, None
80 + if webcam:
81 + view_img = check_imshow()
82 + cudnn.benchmark = True # set True to speed up constant image size inference
83 + dataset = LoadStreams(source, img_size=imgsz, stride=stride)
84 + else:
85 + dataset = LoadImages(source, img_size=imgsz, stride=stride)
86 +
87 + # Run inference
88 + if device.type != 'cpu':
89 + model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
90 + t0 = time.time()
91 + for path, img, im0s, vid_cap in dataset:
92 + img = torch.from_numpy(img).to(device)
93 + img = img.half() if half else img.float() # uint8 to fp16/32
94 + img /= 255.0 # 0 - 255 to 0.0 - 1.0
95 + if img.ndimension() == 3:
96 + img = img.unsqueeze(0)
97 +
98 + # Inference
99 + t1 = time_synchronized()
100 + pred = model(img, augment=opt.augment)[0]
101 +
102 + # Apply NMS
103 + pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
104 + t2 = time_synchronized()
105 +
106 + # Apply Classifier
107 + if classify:
108 + pred = apply_classifier(pred, modelc, img, im0s)
109 +
110 + # Process detections
111 + for i, det in enumerate(pred): # detections per image
112 + if webcam: # batch_size >= 1
113 + p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
114 + else:
115 + p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
116 +
117 + p = Path(p) # to Path
118 + save_path = str(save_dir / p.name) # img.jpg
119 + txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
120 + s += '%gx%g ' % img.shape[2:] # print string
121 + gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
122 + imc = im0.copy() if opt.save_crop else im0 # for opt.save_crop
123 + if len(det):
124 + # Rescale boxes from img_size to im0 size
125 + det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
126 +
127 + # Print results
128 + for c in det[:, -1].unique():
129 + n = (det[:, -1] == c).sum() # detections per class
130 + s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
131 +
132 + # Write results
133 + for *xyxy, conf, cls in reversed(det):
134 + if save_txt: # Write to file
135 + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
136 + line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
137 + with open(txt_path + '.txt', 'a') as f:
138 + f.write(('%g ' * len(line)).rstrip() % line + '\n')
139 +
140 + if save_img or opt.save_crop or view_img: # Add bbox to image
141 + c = int(cls) # integer class
142 + label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
143 + plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
144 + if opt.save_crop:
145 + save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
146 +
147 + # Print time (inference + NMS)
148 + print(f'{s}Done. ({t2 - t1:.3f}s)')
149 + rtmp_publisher.stdin.write(im0.tobytes())
150 + # Stream results
151 + # if view_img:
152 +
153 + # cv2.waitKey(1)
154 + # # cv2.imshow(str(p), im0)
155 + # # cv2.waitKey(1) # 1 millisecond
156 + # # # print(type(im0))
157 +
158 +
159 + # Save results (image with detections)
160 + if save_img:
161 + if dataset.mode == 'image':
162 + cv2.imwrite(save_path, im0)
163 + else: # 'video' or 'stream'
164 + if vid_path != save_path: # new video
165 + vid_path = save_path
166 + if isinstance(vid_writer, cv2.VideoWriter):
167 + vid_writer.release() # release previous video writer
168 + if vid_cap: # video
169 + fps = vid_cap.get(cv2.CAP_PROP_FPS)
170 + w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
171 + h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
172 + else: # stream
173 + fps, w, h = 30, im0.shape[1], im0.shape[0]
174 + save_path += '.mp4'
175 + vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
176 + vid_writer.write(im0)
177 +
178 + if save_txt or save_img:
179 + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
180 + print(f"Results saved to {save_dir}{s}")
181 +
182 + print(f'Done. ({time.time() - t0:.3f}s)')
183 +
184 +
185 +def main():
186 + parser = argparse.ArgumentParser()
187 + parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
188 + parser.add_argument('--source', type=str, default='yolov5/data/images', help='source') # file/folder, 0 for webcam
189 + parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
190 + parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
191 + parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
192 + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
193 + parser.add_argument('--view-img', action='store_true', help='display results')
194 + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
195 + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
196 + parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
197 + parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
198 + parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
199 + parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
200 + parser.add_argument('--augment', action='store_true', help='augmented inference')
201 + parser.add_argument('--update', action='store_true', help='update all models')
202 + parser.add_argument('--project', default='runs/detect', help='save results to project/name')
203 + parser.add_argument('--name', default='exp', help='save results to project/name')
204 + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
205 + parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
206 + parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
207 + parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
208 + opt = parser.parse_args()
209 + print(opt)
210 + #check_requirements(exclude=('tensorboard', 'pycocotools', 'thop'))
211 +
212 + with torch.no_grad():
213 + if opt.update: # update all models (to fix SourceChangeWarning)
214 + for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
215 + detect(opt=opt)
216 + strip_optimizer(opt.weights)
217 + else:
218 + detect(opt=opt)
219 +
220 +if __name__ == '__main__':
221 + main()
1 +from pathlib import Path
2 +
3 +from yolo_module.yolov5.models.yolo import Model
4 +from yolo_module.yolov5.utils.general import set_logging, yolov5_in_syspath
5 +from yolo_module.yolov5.utils.google_utils import attempt_download
6 +from yolo_module.yolov5.utils.torch_utils import torch
7 +
8 +
9 +def load_model(model_path, device=None, autoshape=True, verbose=False):
10 + """
11 + Creates a specified YOLOv5 model
12 +
13 + Arguments:
14 + model_path (str): path of the model
15 + config_path (str): path of the config file
16 + device (str): select device that model will be loaded (cpu, cuda)
17 + pretrained (bool): load pretrained weights into the model
18 + autoshape (bool): make model ready for inference
19 + verbose (bool): if False, yolov5 logs will be silent
20 +
21 + Returns:
22 + pytorch model
23 +
24 + (Adapted from yolo_module.yolov5.hubconf.create)
25 + """
26 + # set logging
27 + set_logging(verbose=verbose)
28 +
29 + # set device if not given
30 + if not device:
31 + device = "cuda:0" if torch.cuda.is_available() else "cpu"
32 +
33 + attempt_download(model_path) # download if not found locally
34 + with yolov5_in_syspath():
35 + model = torch.load(model_path, map_location=torch.device(device))
36 + if isinstance(model, dict):
37 + model = model["model"] # load model
38 + hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
39 + hub_model.load_state_dict(model.float().state_dict()) # load state_dict
40 + hub_model.names = model.names # class names
41 + model = hub_model
42 +
43 + if autoshape:
44 + model = model.autoshape()
45 +
46 + return model
47 +
48 +
49 +class YOLOv5:
50 + def __init__(self, model_path, device=None, load_on_init=True):
51 + self.model_path = model_path
52 + self.device = device
53 + if load_on_init:
54 + Path(model_path).parents[0].mkdir(parents=True, exist_ok=True)
55 + self.model = load_model(model_path=model_path, device=device, autoshape=True)
56 + else:
57 + self.model = None
58 +
59 + def load_model(self):
60 + """
61 + Load yolov5 weight.
62 + """
63 + Path(self.model_path).parents[0].mkdir(parents=True, exist_ok=True)
64 + self.model = load_model(model_path=self.model_path, device=self.device, autoshape=True)
65 +
66 + def predict(self, image_list, size=640, augment=False):
67 + """
68 + Perform yolov5 prediction using loaded model weights.
69 +
70 + Returns results as a yolov5.models.common.Detections object.
71 + """
72 + assert self.model is not None, "before predict, you need to call .load_model()"
73 + results = self.model(imgs=image_list, size=size, augment=augment)
74 + return results
75 +
76 +if __name__ == "__main__":
77 + model_path = "yolov5/weights/yolov5s.pt"
78 + device = "cuda"
79 + model = load_model(model_path=model_path, config_path=None, device=device)
80 +
81 + from PIL import Image
82 + imgs = [Image.open(x) for x in Path("yolov5/data/images").glob("*.jpg")]
83 + results = model(imgs)
1 +"""YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
2 +
3 +Usage:
4 + import torch
5 + model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
6 +"""
7 +
8 +from pathlib import Path
9 +
10 +import torch
11 +
12 +from yolo_module.yolov5.models.yolo import Model, attempt_load
13 +from yolo_module.yolov5.utils.general import (check_requirements, set_logging,
14 + yolov5_in_syspath)
15 +from yolo_module.yolov5.utils.google_utils import attempt_download
16 +from yolo_module.yolov5.utils.torch_utils import select_device
17 +
18 +dependencies = ['torch', 'yaml']
19 +#check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('tensorboard', 'pycocotools', 'thop'))
20 +
21 +
22 +def create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
23 + """Creates a specified YOLOv5 model
24 +
25 + Arguments:
26 + name (str): name of model, i.e. 'yolov5s'
27 + pretrained (bool): load pretrained weights into the model
28 + channels (int): number of input channels
29 + classes (int): number of model classes
30 + autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
31 + verbose (bool): print all information to screen
32 +
33 + Returns:
34 + YOLOv5 pytorch model
35 + """
36 + set_logging(verbose=verbose)
37 + fname = Path(name).with_suffix('.pt') # checkpoint filename
38 + try:
39 + if pretrained and channels == 3 and classes == 80:
40 + model = attempt_load(fname, map_location=torch.device('cpu')) # download/load FP32 model
41 + else:
42 + cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
43 + model = Model(cfg, channels, classes) # create model
44 + if pretrained:
45 + attempt_download(fname) # download if not found locally
46 + with yolov5_in_syspath():
47 + ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
48 + msd = model.state_dict() # model state_dict
49 + csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
50 + csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
51 + model.load_state_dict(csd, strict=False) # load
52 + if len(ckpt['model'].names) == classes:
53 + model.names = ckpt['model'].names # set class names attribute
54 + if autoshape:
55 + model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
56 + device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
57 + return model.to(device)
58 +
59 + except Exception as e:
60 + help_url = 'https://github.com/ultralytics/yolov5/issues/36'
61 + s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url
62 + raise Exception(s) from e
63 +
64 +
65 +def custom(path='path/to/model.pt', autoshape=True, verbose=True):
66 + # YOLOv5 custom or local model
67 + return create(path, autoshape=autoshape, verbose=verbose)
68 +
69 +
70 +def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
71 + # YOLOv5-small model https://github.com/ultralytics/yolov5
72 + return create('yolov5s', pretrained, channels, classes, autoshape, verbose)
73 +
74 +
75 +def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
76 + # YOLOv5-medium model https://github.com/ultralytics/yolov5
77 + return create('yolov5m', pretrained, channels, classes, autoshape, verbose)
78 +
79 +
80 +def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
81 + # YOLOv5-large model https://github.com/ultralytics/yolov5
82 + return create('yolov5l', pretrained, channels, classes, autoshape, verbose)
83 +
84 +
85 +def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
86 + # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
87 + return create('yolov5x', pretrained, channels, classes, autoshape, verbose)
88 +
89 +
90 +def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
91 + # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
92 + return create('yolov5s6', pretrained, channels, classes, autoshape, verbose)
93 +
94 +
95 +def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
96 + # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
97 + return create('yolov5m6', pretrained, channels, classes, autoshape, verbose)
98 +
99 +
100 +def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
101 + # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
102 + return create('yolov5l6', pretrained, channels, classes, autoshape, verbose)
103 +
104 +
105 +def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
106 + # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
107 + return create('yolov5x6', pretrained, channels, classes, autoshape, verbose)
108 +
109 +
110 +if __name__ == '__main__':
111 + model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
112 + # model = custom(path='path/to/model.pt') # custom
113 +
114 + # Verify inference
115 + import cv2
116 + import numpy as np
117 + from PIL import Image
118 +
119 + imgs = ['data/images/zidane.jpg', # filename
120 + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI
121 + cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
122 + Image.open('data/images/bus.jpg'), # PIL
123 + np.zeros((320, 640, 3))] # numpy
124 +
125 + results = model(imgs) # batched inference
126 + results.print()
127 + results.save()
1 +# YOLOv5 common modules
2 +
3 +import math
4 +from copy import copy
5 +from pathlib import Path
6 +
7 +import numpy as np
8 +import pandas as pd
9 +import requests
10 +import torch
11 +import torch.nn as nn
12 +from PIL import Image
13 +from torch.cuda import amp
14 +from yolo_module.yolov5.utils.datasets import letterbox
15 +from yolo_module.yolov5.utils.general import (increment_path, make_divisible,
16 + non_max_suppression, save_one_box,
17 + scale_coords, xyxy2xywh)
18 +from yolo_module.yolov5.utils.plots import colors, plot_one_box
19 +from yolo_module.yolov5.utils.torch_utils import time_synchronized
20 +
21 +
22 +def autopad(k, p=None): # kernel, padding
23 + # Pad to 'same'
24 + if p is None:
25 + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
26 + return p
27 +
28 +
29 +def DWConv(c1, c2, k=1, s=1, act=True):
30 + # Depthwise convolution
31 + return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
32 +
33 +
34 +class Conv(nn.Module):
35 + # Standard convolution
36 + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
37 + super(Conv, self).__init__()
38 + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
39 + self.bn = nn.BatchNorm2d(c2)
40 + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
41 +
42 + def forward(self, x):
43 + return self.act(self.bn(self.conv(x)))
44 +
45 + def fuseforward(self, x):
46 + return self.act(self.conv(x))
47 +
48 +
49 +class TransformerLayer(nn.Module):
50 + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
51 + def __init__(self, c, num_heads):
52 + super().__init__()
53 + self.q = nn.Linear(c, c, bias=False)
54 + self.k = nn.Linear(c, c, bias=False)
55 + self.v = nn.Linear(c, c, bias=False)
56 + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
57 + self.fc1 = nn.Linear(c, c, bias=False)
58 + self.fc2 = nn.Linear(c, c, bias=False)
59 +
60 + def forward(self, x):
61 + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
62 + x = self.fc2(self.fc1(x)) + x
63 + return x
64 +
65 +
66 +class TransformerBlock(nn.Module):
67 + # Vision Transformer https://arxiv.org/abs/2010.11929
68 + def __init__(self, c1, c2, num_heads, num_layers):
69 + super().__init__()
70 + self.conv = None
71 + if c1 != c2:
72 + self.conv = Conv(c1, c2)
73 + self.linear = nn.Linear(c2, c2) # learnable position embedding
74 + self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
75 + self.c2 = c2
76 +
77 + def forward(self, x):
78 + if self.conv is not None:
79 + x = self.conv(x)
80 + b, _, w, h = x.shape
81 + p = x.flatten(2)
82 + p = p.unsqueeze(0)
83 + p = p.transpose(0, 3)
84 + p = p.squeeze(3)
85 + e = self.linear(p)
86 + x = p + e
87 +
88 + x = self.tr(x)
89 + x = x.unsqueeze(3)
90 + x = x.transpose(0, 3)
91 + x = x.reshape(b, self.c2, w, h)
92 + return x
93 +
94 +
95 +class Bottleneck(nn.Module):
96 + # Standard bottleneck
97 + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
98 + super(Bottleneck, self).__init__()
99 + c_ = int(c2 * e) # hidden channels
100 + self.cv1 = Conv(c1, c_, 1, 1)
101 + self.cv2 = Conv(c_, c2, 3, 1, g=g)
102 + self.add = shortcut and c1 == c2
103 +
104 + def forward(self, x):
105 + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
106 +
107 +
108 +class BottleneckCSP(nn.Module):
109 + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
110 + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
111 + super(BottleneckCSP, self).__init__()
112 + c_ = int(c2 * e) # hidden channels
113 + self.cv1 = Conv(c1, c_, 1, 1)
114 + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
115 + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
116 + self.cv4 = Conv(2 * c_, c2, 1, 1)
117 + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
118 + self.act = nn.LeakyReLU(0.1, inplace=True)
119 + self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
120 +
121 + def forward(self, x):
122 + y1 = self.cv3(self.m(self.cv1(x)))
123 + y2 = self.cv2(x)
124 + return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
125 +
126 +
127 +class C3(nn.Module):
128 + # CSP Bottleneck with 3 convolutions
129 + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
130 + super(C3, self).__init__()
131 + c_ = int(c2 * e) # hidden channels
132 + self.cv1 = Conv(c1, c_, 1, 1)
133 + self.cv2 = Conv(c1, c_, 1, 1)
134 + self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
135 + self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
136 + # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
137 +
138 + def forward(self, x):
139 + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
140 +
141 +
142 +class C3TR(C3):
143 + # C3 module with TransformerBlock()
144 + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
145 + super().__init__(c1, c2, n, shortcut, g, e)
146 + c_ = int(c2 * e)
147 + self.m = TransformerBlock(c_, c_, 4, n)
148 +
149 +
150 +class SPP(nn.Module):
151 + # Spatial pyramid pooling layer used in YOLOv3-SPP
152 + def __init__(self, c1, c2, k=(5, 9, 13)):
153 + super(SPP, self).__init__()
154 + c_ = c1 // 2 # hidden channels
155 + self.cv1 = Conv(c1, c_, 1, 1)
156 + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
157 + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
158 +
159 + def forward(self, x):
160 + x = self.cv1(x)
161 + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
162 +
163 +
164 +class Focus(nn.Module):
165 + # Focus wh information into c-space
166 + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
167 + super(Focus, self).__init__()
168 + self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
169 + # self.contract = Contract(gain=2)
170 +
171 + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
172 + return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
173 + # return self.conv(self.contract(x))
174 +
175 +
176 +class Contract(nn.Module):
177 + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
178 + def __init__(self, gain=2):
179 + super().__init__()
180 + self.gain = gain
181 +
182 + def forward(self, x):
183 + N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
184 + s = self.gain
185 + x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2)
186 + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
187 + return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40)
188 +
189 +
190 +class Expand(nn.Module):
191 + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
192 + def __init__(self, gain=2):
193 + super().__init__()
194 + self.gain = gain
195 +
196 + def forward(self, x):
197 + N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
198 + s = self.gain
199 + x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80)
200 + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
201 + return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160)
202 +
203 +
204 +class Concat(nn.Module):
205 + # Concatenate a list of tensors along dimension
206 + def __init__(self, dimension=1):
207 + super(Concat, self).__init__()
208 + self.d = dimension
209 +
210 + def forward(self, x):
211 + return torch.cat(x, self.d)
212 +
213 +
214 +class NMS(nn.Module):
215 + # Non-Maximum Suppression (NMS) module
216 + conf = 0.25 # confidence threshold
217 + iou = 0.45 # IoU threshold
218 + classes = None # (optional list) filter by class
219 +
220 + def __init__(self):
221 + super(NMS, self).__init__()
222 +
223 + def forward(self, x):
224 + return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
225 +
226 +
227 +class autoShape(nn.Module):
228 + # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
229 + conf = 0.25 # NMS confidence threshold
230 + iou = 0.45 # NMS IoU threshold
231 + classes = None # (optional list) filter by class
232 +
233 + def __init__(self, model):
234 + super(autoShape, self).__init__()
235 + self.model = model.eval()
236 +
237 + def autoshape(self):
238 + print('autoShape already enabled, skipping... ') # model already converted to model.autoshape()
239 + return self
240 +
241 + @torch.no_grad()
242 + def forward(self, imgs, size=640, augment=False, profile=False):
243 + # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
244 + # filename: imgs = 'data/images/zidane.jpg'
245 + # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg'
246 + # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
247 + # PIL: = Image.open('image.jpg') # HWC x(640,1280,3)
248 + # numpy: = np.zeros((640,1280,3)) # HWC
249 + # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
250 + # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
251 +
252 + t = [time_synchronized()]
253 + p = next(self.model.parameters()) # for device and type
254 + if isinstance(imgs, torch.Tensor): # torch
255 + with amp.autocast(enabled=p.device.type != 'cpu'):
256 + return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
257 +
258 + # Pre-process
259 + n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
260 + shape0, shape1, files = [], [], [] # image and inference shapes, filenames
261 + for i, im in enumerate(imgs):
262 + f = f'image{i}' # filename
263 + if isinstance(im, str): # filename or uri
264 + im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)), im
265 + elif isinstance(im, Image.Image): # PIL Image
266 + im, f = np.asarray(im), getattr(im, 'filename', f) or f
267 + files.append(Path(f).with_suffix('.jpg').name)
268 + if im.shape[0] < 5: # image in CHW
269 + im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
270 + im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input
271 + s = im.shape[:2] # HWC
272 + shape0.append(s) # image shape
273 + g = (size / max(s)) # gain
274 + shape1.append([y * g for y in s])
275 + imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
276 + shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
277 + x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
278 + x = np.stack(x, 0) if n > 1 else x[0][None] # stack
279 + x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
280 + x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
281 + t.append(time_synchronized())
282 +
283 + with amp.autocast(enabled=p.device.type != 'cpu'):
284 + # Inference
285 + y = self.model(x, augment, profile)[0] # forward
286 + t.append(time_synchronized())
287 +
288 + # Post-process
289 + y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS
290 + for i in range(n):
291 + scale_coords(shape1, y[i][:, :4], shape0[i])
292 +
293 + t.append(time_synchronized())
294 + return Detections(imgs, y, files, t, self.names, x.shape)
295 +
296 +
297 +class Detections:
298 + # detections class for YOLOv5 inference results
299 + def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
300 + super(Detections, self).__init__()
301 + d = pred[0].device # device
302 + gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
303 + self.imgs = imgs # list of images as numpy arrays
304 + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
305 + self.names = names # class names
306 + self.files = files # image filenames
307 + self.xyxy = pred # xyxy pixels
308 + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
309 + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
310 + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
311 + self.n = len(self.pred) # number of images (batch size)
312 + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
313 + self.s = shape # inference BCHW shape
314 +
315 + def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
316 + for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
317 + str = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '
318 + if pred is not None:
319 + for c in pred[:, -1].unique():
320 + n = (pred[:, -1] == c).sum() # detections per class
321 + str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
322 + if show or save or render or crop:
323 + for *box, conf, cls in pred: # xyxy, confidence, class
324 + label = f'{self.names[int(cls)]} {conf:.2f}'
325 + if crop:
326 + save_one_box(box, im, file=save_dir / 'crops' / self.names[int(cls)] / self.files[i])
327 + else: # all others
328 + plot_one_box(box, im, label=label, color=colors(cls))
329 +
330 + im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
331 + if pprint:
332 + print(str.rstrip(', '))
333 + if show:
334 + im.show(self.files[i]) # show
335 + if save:
336 + f = self.files[i]
337 + im.save(save_dir / f) # save
338 + print(f"{'Saved' * (i == 0)} {f}", end=',' if i < self.n - 1 else f' to {save_dir}\n')
339 + if render:
340 + self.imgs[i] = np.asarray(im)
341 +
342 + def print(self):
343 + self.display(pprint=True) # print results
344 + print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)
345 +
346 + def show(self):
347 + self.display(show=True) # show results
348 +
349 + def save(self, save_dir='runs/hub/exp'):
350 + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp', mkdir=True) # increment save_dir
351 + self.display(save=True, save_dir=save_dir) # save results
352 +
353 + def crop(self, save_dir='runs/hub/exp'):
354 + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp', mkdir=True) # increment save_dir
355 + self.display(crop=True, save_dir=save_dir) # crop results
356 + print(f'Saved results to {save_dir}\n')
357 +
358 + def render(self):
359 + self.display(render=True) # render results
360 + return self.imgs
361 +
362 + def pandas(self):
363 + # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
364 + new = copy(self) # return copy
365 + ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
366 + cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
367 + for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
368 + a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
369 + setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
370 + return new
371 +
372 + def tolist(self):
373 + # return a list of Detections objects, i.e. 'for result in results.tolist():'
374 + x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
375 + for d in x:
376 + for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
377 + setattr(d, k, getattr(d, k)[0]) # pop out of list
378 + return x
379 +
380 + def __len__(self):
381 + return self.n
382 +
383 +
384 +class Classify(nn.Module):
385 + # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
386 + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
387 + super(Classify, self).__init__()
388 + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
389 + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
390 + self.flat = nn.Flatten()
391 +
392 + def forward(self, x):
393 + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
394 + return self.flat(self.conv(z)) # flatten to x(b,c2)
1 +# YOLOv5 experimental modules
2 +
3 +import sys
4 +from pathlib import Path
5 +
6 +import numpy as np
7 +import torch
8 +import torch.nn as nn
9 +from yolo_module.yolov5.models.common import Conv, DWConv
10 +from yolo_module.yolov5.utils.general import yolov5_in_syspath
11 +from yolo_module.yolov5.utils.google_utils import attempt_download
12 +
13 +
14 +class CrossConv(nn.Module):
15 + # Cross Convolution Downsample
16 + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
17 + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
18 + super(CrossConv, self).__init__()
19 + c_ = int(c2 * e) # hidden channels
20 + self.cv1 = Conv(c1, c_, (1, k), (1, s))
21 + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
22 + self.add = shortcut and c1 == c2
23 +
24 + def forward(self, x):
25 + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
26 +
27 +
28 +class Sum(nn.Module):
29 + # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
30 + def __init__(self, n, weight=False): # n: number of inputs
31 + super(Sum, self).__init__()
32 + self.weight = weight # apply weights boolean
33 + self.iter = range(n - 1) # iter object
34 + if weight:
35 + self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
36 +
37 + def forward(self, x):
38 + y = x[0] # no weight
39 + if self.weight:
40 + w = torch.sigmoid(self.w) * 2
41 + for i in self.iter:
42 + y = y + x[i + 1] * w[i]
43 + else:
44 + for i in self.iter:
45 + y = y + x[i + 1]
46 + return y
47 +
48 +
49 +class GhostConv(nn.Module):
50 + # Ghost Convolution https://github.com/huawei-noah/ghostnet
51 + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
52 + super(GhostConv, self).__init__()
53 + c_ = c2 // 2 # hidden channels
54 + self.cv1 = Conv(c1, c_, k, s, None, g, act)
55 + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
56 +
57 + def forward(self, x):
58 + y = self.cv1(x)
59 + return torch.cat([y, self.cv2(y)], 1)
60 +
61 +
62 +class GhostBottleneck(nn.Module):
63 + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
64 + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
65 + super(GhostBottleneck, self).__init__()
66 + c_ = c2 // 2
67 + self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
68 + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
69 + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
70 + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
71 + Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
72 +
73 + def forward(self, x):
74 + return self.conv(x) + self.shortcut(x)
75 +
76 +
77 +class MixConv2d(nn.Module):
78 + # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
79 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
80 + super(MixConv2d, self).__init__()
81 + groups = len(k)
82 + if equal_ch: # equal c_ per group
83 + i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
84 + c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
85 + else: # equal weight.numel() per group
86 + b = [c2] + [0] * groups
87 + a = np.eye(groups + 1, groups, k=-1)
88 + a -= np.roll(a, 1, axis=1)
89 + a *= np.array(k) ** 2
90 + a[0] = 1
91 + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
92 +
93 + self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
94 + self.bn = nn.BatchNorm2d(c2)
95 + self.act = nn.LeakyReLU(0.1, inplace=True)
96 +
97 + def forward(self, x):
98 + return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
99 +
100 +
101 +class Ensemble(nn.ModuleList):
102 + # Ensemble of models
103 + def __init__(self):
104 + super(Ensemble, self).__init__()
105 +
106 + def forward(self, x, augment=False):
107 + y = []
108 + for module in self:
109 + y.append(module(x, augment)[0])
110 + # y = torch.stack(y).max(0)[0] # max ensemble
111 + # y = torch.stack(y).mean(0) # mean ensemble
112 + y = torch.cat(y, 1) # nms ensemble
113 + return y, None # inference, train output
114 +
115 +
116 +def attempt_load(weights, map_location=None, inplace=True):
117 + with yolov5_in_syspath():
118 + from models.yolo import Detect, Model
119 +
120 + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
121 + model = Ensemble()
122 +
123 + for w in weights if isinstance(weights, list) else [weights]:
124 + attempt_download(w)
125 + with yolov5_in_syspath():
126 + ckpt = torch.load(w, map_location=map_location) # load
127 + model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
128 +
129 + # Compatibility updates
130 + target_class_name_list = [class_.__name__ for class_ in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]] # yolov5 5.0.3 compatibility
131 + for m in model.modules():
132 + if type(m).__name__ in target_class_name_list:
133 + m.inplace = inplace # pytorch 1.7.0 compatibility
134 + elif type(m) is Conv:
135 + m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
136 +
137 + if len(model) == 1:
138 + return model[-1] # return model
139 + else:
140 + print(f'Ensemble created with {weights}\n')
141 + for k in ['names']:
142 + setattr(model, k, getattr(model[-1], k))
143 + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
144 + return model # return ensemble
1 +"""Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
2 +
3 +Usage:
4 + $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1
5 +"""
6 +
7 +import argparse
8 +import sys
9 +import time
10 +from pathlib import Path
11 +
12 +import torch
13 +import torch.nn as nn
14 +import yolov5.models as models
15 +from torch.utils.mobile_optimizer import optimize_for_mobile
16 +from yolo_module.yolov5.models.experimental import attempt_load
17 +from yolo_module.yolov5.utils.activations import Hardswish, SiLU
18 +from yolo_module.yolov5.utils.general import (check_img_size, check_requirements, colorstr,
19 + file_size, set_logging)
20 +from yolo_module.yolov5.utils.torch_utils import select_device
21 +
22 +#sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories
23 +
24 +
25 +
26 +def main():
27 + parser = argparse.ArgumentParser()
28 + parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
29 + parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
30 + parser.add_argument('--batch-size', type=int, default=1, help='batch size')
31 + parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
32 + parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
33 + parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
34 + parser.add_argument('--train', action='store_true', help='model.train() mode')
35 + parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only
36 + parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
37 + parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
38 + opt = parser.parse_args()
39 + opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
40 + print(opt)
41 + set_logging()
42 + t = time.time()
43 +
44 + # Load PyTorch model
45 + device = select_device(opt.device)
46 +
47 + model = attempt_load(opt.weights, map_location=device) # load FP32 model
48 + labels = model.names
49 +
50 + # Checks
51 + gs = int(max(model.stride)) # grid size (max stride)
52 + opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
53 + assert not (opt.device.lower() == "cpu" and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
54 +
55 + # Input
56 + img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
57 +
58 + # Update model
59 + if opt.half:
60 + img, model = img.half(), model.half() # to FP16
61 + if opt.train:
62 + model.train() # training mode (no grid construction in Detect layer)
63 + for k, m in model.named_modules():
64 + m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
65 + if isinstance(m, models.common.Conv): # assign export-friendly activations
66 + if isinstance(m.act, nn.Hardswish):
67 + m.act = Hardswish()
68 + elif isinstance(m.act, nn.SiLU):
69 + m.act = SiLU()
70 + elif isinstance(m, models.yolo.Detect):
71 + m.inplace = opt.inplace
72 + m.onnx_dynamic = opt.dynamic
73 + # m.forward = m.forward_export # assign forward (optional)
74 +
75 + for _ in range(2):
76 + y = model(img) # dry runs
77 + print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
78 +
79 + # TorchScript export -----------------------------------------------------------------------------------------------
80 + prefix = colorstr('TorchScript:')
81 + try:
82 + print(f'\n{prefix} starting export with torch {torch.__version__}...')
83 + f = opt.weights.replace('.pt', '.torchscript.pt') # filename
84 + ts = torch.jit.trace(model, img, strict=False)
85 + (optimize_for_mobile(ts) if opt.optimize else ts).save(f)
86 + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
87 + except Exception as e:
88 + print(f'{prefix} export failure: {e}')
89 +
90 + # ONNX export ------------------------------------------------------------------------------------------------------
91 + prefix = colorstr('ONNX:')
92 + try:
93 + import onnx
94 +
95 + print(f'{prefix} starting export with onnx {onnx.__version__}...')
96 + f = opt.weights.replace('.pt', '.onnx') # filename
97 + torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
98 + dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
99 + 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
100 +
101 + # Checks
102 + model_onnx = onnx.load(f) # load onnx model
103 + onnx.checker.check_model(model_onnx) # check onnx model
104 + # print(onnx.helper.printable_graph(model_onnx.graph)) # print
105 +
106 + # Simplify
107 + if opt.simplify:
108 + try:
109 + check_requirements(['onnx-simplifier'])
110 + import onnxsim
111 +
112 + print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
113 + model_onnx, check = onnxsim.simplify(model_onnx,
114 + dynamic_input_shape=opt.dynamic,
115 + input_shapes={'images': list(img.shape)} if opt.dynamic else None)
116 + assert check, 'assert check failed'
117 + onnx.save(model_onnx, f)
118 + except Exception as e:
119 + print(f'{prefix} simplifier failure: {e}')
120 + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
121 + except Exception as e:
122 + print(f'{prefix} export failure: {e}')
123 +
124 + # CoreML export ----------------------------------------------------------------------------------------------------
125 + prefix = colorstr('CoreML:')
126 + try:
127 + import coremltools as ct
128 +
129 + print(f'{prefix} starting export with coremltools {ct.__version__}...')
130 + model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
131 + f = opt.weights.replace('.pt', '.mlmodel') # filename
132 + model.save(f)
133 + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
134 + except Exception as e:
135 + print(f'{prefix} export failure: {e}')
136 +
137 + # Finish
138 + print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
139 +
140 +if __name__ == '__main__':
141 + main()
1 +# Default YOLOv5 anchors for COCO data
2 +
3 +
4 +# P5 -------------------------------------------------------------------------------------------------------------------
5 +# P5-640:
6 +anchors_p5_640:
7 + - [ 10,13, 16,30, 33,23 ] # P3/8
8 + - [ 30,61, 62,45, 59,119 ] # P4/16
9 + - [ 116,90, 156,198, 373,326 ] # P5/32
10 +
11 +
12 +# P6 -------------------------------------------------------------------------------------------------------------------
13 +# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
14 +anchors_p6_640:
15 + - [ 9,11, 21,19, 17,41 ] # P3/8
16 + - [ 43,32, 39,70, 86,64 ] # P4/16
17 + - [ 65,131, 134,130, 120,265 ] # P5/32
18 + - [ 282,180, 247,354, 512,387 ] # P6/64
19 +
20 +# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
21 +anchors_p6_1280:
22 + - [ 19,27, 44,40, 38,94 ] # P3/8
23 + - [ 96,68, 86,152, 180,137 ] # P4/16
24 + - [ 140,301, 303,264, 238,542 ] # P5/32
25 + - [ 436,615, 739,380, 925,792 ] # P6/64
26 +
27 +# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
28 +anchors_p6_1920:
29 + - [ 28,41, 67,59, 57,141 ] # P3/8
30 + - [ 144,103, 129,227, 270,205 ] # P4/16
31 + - [ 209,452, 455,396, 358,812 ] # P5/32
32 + - [ 653,922, 1109,570, 1387,1187 ] # P6/64
33 +
34 +
35 +# P7 -------------------------------------------------------------------------------------------------------------------
36 +# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
37 +anchors_p7_640:
38 + - [ 11,11, 13,30, 29,20 ] # P3/8
39 + - [ 30,46, 61,38, 39,92 ] # P4/16
40 + - [ 78,80, 146,66, 79,163 ] # P5/32
41 + - [ 149,150, 321,143, 157,303 ] # P6/64
42 + - [ 257,402, 359,290, 524,372 ] # P7/128
43 +
44 +# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
45 +anchors_p7_1280:
46 + - [ 19,22, 54,36, 32,77 ] # P3/8
47 + - [ 70,83, 138,71, 75,173 ] # P4/16
48 + - [ 165,159, 148,334, 375,151 ] # P5/32
49 + - [ 334,317, 251,626, 499,474 ] # P6/64
50 + - [ 750,326, 534,814, 1079,818 ] # P7/128
51 +
52 +# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
53 +anchors_p7_1920:
54 + - [ 29,34, 81,55, 47,115 ] # P3/8
55 + - [ 105,124, 207,107, 113,259 ] # P4/16
56 + - [ 247,238, 222,500, 563,227 ] # P5/32
57 + - [ 501,476, 376,939, 749,711 ] # P6/64
58 + - [ 1126,489, 801,1222, 1618,1227 ] # P7/128
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# darknet53 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Conv, [32, 3, 1]], # 0
16 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 + [-1, 1, Bottleneck, [64]],
18 + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 + [-1, 2, Bottleneck, [128]],
20 + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 + [-1, 8, Bottleneck, [256]],
22 + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 + [-1, 8, Bottleneck, [512]],
24 + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 + [-1, 4, Bottleneck, [1024]], # 10
26 + ]
27 +
28 +# YOLOv3-SPP head
29 +head:
30 + [[-1, 1, Bottleneck, [1024, False]],
31 + [-1, 1, SPP, [512, [5, 9, 13]]],
32 + [-1, 1, Conv, [1024, 3, 1]],
33 + [-1, 1, Conv, [512, 1, 1]],
34 + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 +
36 + [-2, 1, Conv, [256, 1, 1]],
37 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 + [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 + [-1, 1, Bottleneck, [512, False]],
40 + [-1, 1, Bottleneck, [512, False]],
41 + [-1, 1, Conv, [256, 1, 1]],
42 + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 +
44 + [-2, 1, Conv, [128, 1, 1]],
45 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 + [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 + [-1, 1, Bottleneck, [256, False]],
48 + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 +
50 + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,14, 23,27, 37,58] # P4/16
9 + - [81,82, 135,169, 344,319] # P5/32
10 +
11 +# YOLOv3-tiny backbone
12 +backbone:
13 + # [from, number, module, args]
14 + [[-1, 1, Conv, [16, 3, 1]], # 0
15 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16 + [-1, 1, Conv, [32, 3, 1]],
17 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18 + [-1, 1, Conv, [64, 3, 1]],
19 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20 + [-1, 1, Conv, [128, 3, 1]],
21 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22 + [-1, 1, Conv, [256, 3, 1]],
23 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24 + [-1, 1, Conv, [512, 3, 1]],
25 + [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26 + [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27 + ]
28 +
29 +# YOLOv3-tiny head
30 +head:
31 + [[-1, 1, Conv, [1024, 3, 1]],
32 + [-1, 1, Conv, [256, 1, 1]],
33 + [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
34 +
35 + [-2, 1, Conv, [128, 1, 1]],
36 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 + [[-1, 8], 1, Concat, [1]], # cat backbone P4
38 + [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
39 +
40 + [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
41 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# darknet53 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Conv, [32, 3, 1]], # 0
16 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 + [-1, 1, Bottleneck, [64]],
18 + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 + [-1, 2, Bottleneck, [128]],
20 + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 + [-1, 8, Bottleneck, [256]],
22 + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 + [-1, 8, Bottleneck, [512]],
24 + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 + [-1, 4, Bottleneck, [1024]], # 10
26 + ]
27 +
28 +# YOLOv3 head
29 +head:
30 + [[-1, 1, Bottleneck, [1024, False]],
31 + [-1, 1, Conv, [512, [1, 1]]],
32 + [-1, 1, Conv, [1024, 3, 1]],
33 + [-1, 1, Conv, [512, 1, 1]],
34 + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 +
36 + [-2, 1, Conv, [256, 1, 1]],
37 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 + [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 + [-1, 1, Bottleneck, [512, False]],
40 + [-1, 1, Bottleneck, [512, False]],
41 + [-1, 1, Conv, [256, 1, 1]],
42 + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 +
44 + [-2, 1, Conv, [128, 1, 1]],
45 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 + [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 + [-1, 1, Bottleneck, [256, False]],
48 + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 +
50 + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, Bottleneck, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, BottleneckCSP, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, BottleneckCSP, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 6, BottleneckCSP, [1024]], # 9
25 + ]
26 +
27 +# YOLOv5 FPN head
28 +head:
29 + [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
30 +
31 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
33 + [-1, 1, Conv, [512, 1, 1]],
34 + [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
35 +
36 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
38 + [-1, 1, Conv, [256, 1, 1]],
39 + [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
40 +
41 + [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors: 3
8 +
9 +# YOLOv5 backbone
10 +backbone:
11 + # [from, number, module, args]
12 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 + [ -1, 3, C3, [ 128 ] ],
15 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 + [ -1, 9, C3, [ 256 ] ],
17 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 + [ -1, 9, C3, [ 512 ] ],
19 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32
20 + [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ],
21 + [ -1, 3, C3, [ 1024, False ] ], # 9
22 + ]
23 +
24 +# YOLOv5 head
25 +head:
26 + [ [ -1, 1, Conv, [ 512, 1, 1 ] ],
27 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
28 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
29 + [ -1, 3, C3, [ 512, False ] ], # 13
30 +
31 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
32 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
33 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
34 + [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
35 +
36 + [ -1, 1, Conv, [ 128, 1, 1 ] ],
37 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
38 + [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2
39 + [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall)
40 +
41 + [ -1, 1, Conv, [ 128, 3, 2 ] ],
42 + [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3
43 + [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small)
44 +
45 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
46 + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
47 + [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium)
48 +
49 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
50 + [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5
51 + [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large)
52 +
53 + [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5)
54 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors: 3
8 +
9 +# YOLOv5 backbone
10 +backbone:
11 + # [from, number, module, args]
12 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 + [ -1, 3, C3, [ 128 ] ],
15 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 + [ -1, 9, C3, [ 256 ] ],
17 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 + [ -1, 9, C3, [ 512 ] ],
19 + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
20 + [ -1, 3, C3, [ 768 ] ],
21 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
22 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
23 + [ -1, 3, C3, [ 1024, False ] ], # 11
24 + ]
25 +
26 +# YOLOv5 head
27 +head:
28 + [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
29 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
30 + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
31 + [ -1, 3, C3, [ 768, False ] ], # 15
32 +
33 + [ -1, 1, Conv, [ 512, 1, 1 ] ],
34 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
35 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
36 + [ -1, 3, C3, [ 512, False ] ], # 19
37 +
38 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
39 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
40 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
41 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
42 +
43 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
44 + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
45 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
46 +
47 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
48 + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
49 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
50 +
51 + [ -1, 1, Conv, [ 768, 3, 2 ] ],
52 + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
53 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge)
54 +
55 + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
56 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors: 3
8 +
9 +# YOLOv5 backbone
10 +backbone:
11 + # [from, number, module, args]
12 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 + [ -1, 3, C3, [ 128 ] ],
15 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 + [ -1, 9, C3, [ 256 ] ],
17 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 + [ -1, 9, C3, [ 512 ] ],
19 + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
20 + [ -1, 3, C3, [ 768 ] ],
21 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
22 + [ -1, 3, C3, [ 1024 ] ],
23 + [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128
24 + [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ],
25 + [ -1, 3, C3, [ 1280, False ] ], # 13
26 + ]
27 +
28 +# YOLOv5 head
29 +head:
30 + [ [ -1, 1, Conv, [ 1024, 1, 1 ] ],
31 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
32 + [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6
33 + [ -1, 3, C3, [ 1024, False ] ], # 17
34 +
35 + [ -1, 1, Conv, [ 768, 1, 1 ] ],
36 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
37 + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
38 + [ -1, 3, C3, [ 768, False ] ], # 21
39 +
40 + [ -1, 1, Conv, [ 512, 1, 1 ] ],
41 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
42 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
43 + [ -1, 3, C3, [ 512, False ] ], # 25
44 +
45 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
46 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
47 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
48 + [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small)
49 +
50 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
51 + [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4
52 + [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium)
53 +
54 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
55 + [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5
56 + [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large)
57 +
58 + [ -1, 1, Conv, [ 768, 3, 2 ] ],
59 + [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6
60 + [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge)
61 +
62 + [ -1, 1, Conv, [ 1024, 3, 2 ] ],
63 + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7
64 + [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge)
65 +
66 + [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7)
67 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, BottleneckCSP, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, BottleneckCSP, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, BottleneckCSP, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 3, BottleneckCSP, [1024, False]], # 9
25 + ]
26 +
27 +# YOLOv5 PANet head
28 +head:
29 + [[-1, 1, Conv, [512, 1, 1]],
30 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 + [-1, 3, BottleneckCSP, [512, False]], # 13
33 +
34 + [-1, 1, Conv, [256, 1, 1]],
35 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 + [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38 +
39 + [-1, 1, Conv, [256, 3, 2]],
40 + [[-1, 14], 1, Concat, [1]], # cat head P4
41 + [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42 +
43 + [-1, 1, Conv, [512, 3, 2]],
44 + [[-1, 10], 1, Concat, [1]], # cat head P5
45 + [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46 +
47 + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [ 19,27, 44,40, 38,94 ] # P3/8
9 + - [ 96,68, 86,152, 180,137 ] # P4/16
10 + - [ 140,301, 303,264, 238,542 ] # P5/32
11 + - [ 436,615, 739,380, 925,792 ] # P6/64
12 +
13 +# YOLOv5 backbone
14 +backbone:
15 + # [from, number, module, args]
16 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 + [ -1, 3, C3, [ 128 ] ],
19 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 + [ -1, 9, C3, [ 256 ] ],
21 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 + [ -1, 9, C3, [ 512 ] ],
23 + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 + [ -1, 3, C3, [ 768 ] ],
25 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 + [ -1, 3, C3, [ 1024, False ] ], # 11
28 + ]
29 +
30 +# YOLOv5 head
31 +head:
32 + [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 + [ -1, 3, C3, [ 768, False ] ], # 15
36 +
37 + [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 + [ -1, 3, C3, [ 512, False ] ], # 19
41 +
42 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 +
47 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 +
51 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 +
55 + [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 +
59 + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 0.67 # model depth multiple
4 +width_multiple: 0.75 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [ 19,27, 44,40, 38,94 ] # P3/8
9 + - [ 96,68, 86,152, 180,137 ] # P4/16
10 + - [ 140,301, 303,264, 238,542 ] # P5/32
11 + - [ 436,615, 739,380, 925,792 ] # P6/64
12 +
13 +# YOLOv5 backbone
14 +backbone:
15 + # [from, number, module, args]
16 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 + [ -1, 3, C3, [ 128 ] ],
19 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 + [ -1, 9, C3, [ 256 ] ],
21 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 + [ -1, 9, C3, [ 512 ] ],
23 + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 + [ -1, 3, C3, [ 768 ] ],
25 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 + [ -1, 3, C3, [ 1024, False ] ], # 11
28 + ]
29 +
30 +# YOLOv5 head
31 +head:
32 + [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 + [ -1, 3, C3, [ 768, False ] ], # 15
36 +
37 + [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 + [ -1, 3, C3, [ 512, False ] ], # 19
41 +
42 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 +
47 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 +
51 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 +
55 + [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 +
59 + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 0.33 # model depth multiple
4 +width_multiple: 0.50 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, C3, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, C3, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, C3, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module
25 + ]
26 +
27 +# YOLOv5 head
28 +head:
29 + [[-1, 1, Conv, [512, 1, 1]],
30 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 + [-1, 3, C3, [512, False]], # 13
33 +
34 + [-1, 1, Conv, [256, 1, 1]],
35 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 + [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 +
39 + [-1, 1, Conv, [256, 3, 2]],
40 + [[-1, 14], 1, Concat, [1]], # cat head P4
41 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 +
43 + [-1, 1, Conv, [512, 3, 2]],
44 + [[-1, 10], 1, Concat, [1]], # cat head P5
45 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 +
47 + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 0.33 # model depth multiple
4 +width_multiple: 0.50 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [ 19,27, 44,40, 38,94 ] # P3/8
9 + - [ 96,68, 86,152, 180,137 ] # P4/16
10 + - [ 140,301, 303,264, 238,542 ] # P5/32
11 + - [ 436,615, 739,380, 925,792 ] # P6/64
12 +
13 +# YOLOv5 backbone
14 +backbone:
15 + # [from, number, module, args]
16 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 + [ -1, 3, C3, [ 128 ] ],
19 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 + [ -1, 9, C3, [ 256 ] ],
21 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 + [ -1, 9, C3, [ 512 ] ],
23 + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 + [ -1, 3, C3, [ 768 ] ],
25 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 + [ -1, 3, C3, [ 1024, False ] ], # 11
28 + ]
29 +
30 +# YOLOv5 head
31 +head:
32 + [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 + [ -1, 3, C3, [ 768, False ] ], # 15
36 +
37 + [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 + [ -1, 3, C3, [ 512, False ] ], # 19
41 +
42 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 +
47 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 +
51 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 +
55 + [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 +
59 + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.33 # model depth multiple
4 +width_multiple: 1.25 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [ 19,27, 44,40, 38,94 ] # P3/8
9 + - [ 96,68, 86,152, 180,137 ] # P4/16
10 + - [ 140,301, 303,264, 238,542 ] # P5/32
11 + - [ 436,615, 739,380, 925,792 ] # P6/64
12 +
13 +# YOLOv5 backbone
14 +backbone:
15 + # [from, number, module, args]
16 + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 + [ -1, 3, C3, [ 128 ] ],
19 + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 + [ -1, 9, C3, [ 256 ] ],
21 + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 + [ -1, 9, C3, [ 512 ] ],
23 + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 + [ -1, 3, C3, [ 768 ] ],
25 + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 + [ -1, 3, C3, [ 1024, False ] ], # 11
28 + ]
29 +
30 +# YOLOv5 head
31 +head:
32 + [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 + [ -1, 3, C3, [ 768, False ] ], # 15
36 +
37 + [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 + [ -1, 3, C3, [ 512, False ] ], # 19
41 +
42 + [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 +
47 + [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 +
51 + [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 +
55 + [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 +
59 + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 + ]
1 +# YOLOv5 YOLO-specific modules
2 +
3 +import argparse
4 +import logging
5 +import sys
6 +from copy import deepcopy
7 +from pathlib import Path
8 +
9 +#sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories
10 +logger = logging.getLogger(__name__)
11 +
12 +from yolo_module.yolov5.models.common import *
13 +from yolo_module.yolov5.models.experimental import *
14 +from yolo_module.yolov5.utils.autoanchor import check_anchor_order
15 +from yolo_module.yolov5.utils.general import check_file, make_divisible, set_logging
16 +from yolo_module.yolov5.utils.torch_utils import (copy_attr, fuse_conv_and_bn,
17 + initialize_weights, model_info,
18 + scale_img, select_device,
19 + time_synchronized)
20 +
21 +try:
22 + import thop # for FLOPS computation
23 +except ImportError:
24 + thop = None
25 +
26 +
27 +class Detect(nn.Module):
28 + stride = None # strides computed during build
29 + onnx_dynamic = False # ONNX export parameter
30 +
31 + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
32 + super(Detect, self).__init__()
33 + self.nc = nc # number of classes
34 + self.no = nc + 5 # number of outputs per anchor
35 + self.nl = len(anchors) # number of detection layers
36 + self.na = len(anchors[0]) // 2 # number of anchors
37 + self.grid = [torch.zeros(1)] * self.nl # init grid
38 + a = torch.tensor(anchors).float().view(self.nl, -1, 2)
39 + self.register_buffer('anchors', a) # shape(nl,na,2)
40 + self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
41 + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
42 + self.inplace = inplace # use in-place ops (e.g. slice assignment)
43 +
44 + def forward(self, x):
45 + # x = x.copy() # for profiling
46 + z = [] # inference output
47 + for i in range(self.nl):
48 + x[i] = self.m[i](x[i]) # conv
49 + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
50 + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
51 +
52 + if not self.training: # inference
53 + if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
54 + self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
55 +
56 + y = x[i].sigmoid()
57 + if self.inplace:
58 + y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
59 + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
60 + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
61 + xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
62 + wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
63 + y = torch.cat((xy, wh, y[..., 4:]), -1)
64 + z.append(y.view(bs, -1, self.no))
65 +
66 + return x if self.training else (torch.cat(z, 1), x)
67 +
68 + @staticmethod
69 + def _make_grid(nx=20, ny=20):
70 + yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
71 + return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
72 +
73 +
74 +class Model(nn.Module):
75 + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
76 + super(Model, self).__init__()
77 + if isinstance(cfg, dict):
78 + self.yaml = cfg # model dict
79 + else: # is *.yaml
80 + import yaml # for torch hub
81 + self.yaml_file = Path(cfg).name
82 + with open(cfg) as f:
83 + self.yaml = yaml.safe_load(f) # model dict
84 +
85 + # Define model
86 + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
87 + if nc and nc != self.yaml['nc']:
88 + logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
89 + self.yaml['nc'] = nc # override yaml value
90 + if anchors:
91 + logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
92 + self.yaml['anchors'] = round(anchors) # override yaml value
93 + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
94 + self.names = [str(i) for i in range(self.yaml['nc'])] # default names
95 + self.inplace = self.yaml.get('inplace', True)
96 + # logger.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
97 +
98 + # Build strides, anchors
99 + m = self.model[-1] # Detect()
100 + if isinstance(m, Detect):
101 + s = 256 # 2x min stride
102 + m.inplace = self.inplace
103 + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
104 + m.anchors /= m.stride.view(-1, 1, 1)
105 + check_anchor_order(m)
106 + self.stride = m.stride
107 + self._initialize_biases() # only run once
108 + # logger.info('Strides: %s' % m.stride.tolist())
109 +
110 + # Init weights, biases
111 + initialize_weights(self)
112 + self.info()
113 + logger.info('')
114 +
115 + def forward(self, x, augment=False, profile=False):
116 + if augment:
117 + return self.forward_augment(x) # augmented inference, None
118 + else:
119 + return self.forward_once(x, profile) # single-scale inference, train
120 +
121 + def forward_augment(self, x):
122 + img_size = x.shape[-2:] # height, width
123 + s = [1, 0.83, 0.67] # scales
124 + f = [None, 3, None] # flips (2-ud, 3-lr)
125 + y = [] # outputs
126 + for si, fi in zip(s, f):
127 + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
128 + yi = self.forward_once(xi)[0] # forward
129 + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
130 + yi = self._descale_pred(yi, fi, si, img_size)
131 + y.append(yi)
132 + return torch.cat(y, 1), None # augmented inference, train
133 +
134 + def forward_once(self, x, profile=False):
135 + y, dt = [], [] # outputs
136 + for m in self.model:
137 + if m.f != -1: # if not from previous layer
138 + 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
139 +
140 + if profile:
141 + o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS
142 + t = time_synchronized()
143 + for _ in range(10):
144 + _ = m(x)
145 + dt.append((time_synchronized() - t) * 100)
146 + if m == self.model[0]:
147 + logger.info(f"{'time (ms)':>10s} {'GFLOPS':>10s} {'params':>10s} {'module'}")
148 + logger.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
149 +
150 + x = m(x) # run
151 + y.append(x if m.i in self.save else None) # save output
152 +
153 + if profile:
154 + logger.info('%.1fms total' % sum(dt))
155 + return x
156 +
157 + def _descale_pred(self, p, flips, scale, img_size):
158 + # de-scale predictions following augmented inference (inverse operation)
159 + if self.inplace:
160 + p[..., :4] /= scale # de-scale
161 + if flips == 2:
162 + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
163 + elif flips == 3:
164 + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
165 + else:
166 + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
167 + if flips == 2:
168 + y = img_size[0] - y # de-flip ud
169 + elif flips == 3:
170 + x = img_size[1] - x # de-flip lr
171 + p = torch.cat((x, y, wh, p[..., 4:]), -1)
172 + return p
173 +
174 + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
175 + # https://arxiv.org/abs/1708.02002 section 3.3
176 + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
177 + m = self.model[-1] # Detect() module
178 + for mi, s in zip(m.m, m.stride): # from
179 + b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
180 + b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
181 + b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
182 + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
183 +
184 + def _print_biases(self):
185 + m = self.model[-1] # Detect() module
186 + for mi in m.m: # from
187 + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
188 + logger.info(
189 + ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
190 +
191 + # def _print_weights(self):
192 + # for m in self.model.modules():
193 + # if type(m) is Bottleneck:
194 + # logger.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
195 +
196 + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
197 + logger.info('Fusing layers... ')
198 + for m in self.model.modules():
199 + if type(m) is Conv and hasattr(m, 'bn'):
200 + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
201 + delattr(m, 'bn') # remove batchnorm
202 + m.forward = m.fuseforward # update forward
203 + self.info()
204 + return self
205 +
206 + def nms(self, mode=True): # add or remove NMS module
207 + present = type(self.model[-1]) is NMS # last layer is NMS
208 + if mode and not present:
209 + logger.info('Adding NMS... ')
210 + m = NMS() # module
211 + m.f = -1 # from
212 + m.i = self.model[-1].i + 1 # index
213 + self.model.add_module(name='%s' % m.i, module=m) # add
214 + self.eval()
215 + elif not mode and present:
216 + logger.info('Removing NMS... ')
217 + self.model = self.model[:-1] # remove
218 + return self
219 +
220 + def autoshape(self): # add autoShape module
221 + logger.info('Adding autoShape... ')
222 + m = autoShape(self) # wrap model
223 + copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
224 + return m
225 +
226 + def info(self, verbose=False, img_size=640): # print model information
227 + model_info(self, verbose, img_size)
228 +
229 +
230 +def parse_model(d, ch): # model_dict, input_channels(3)
231 + logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
232 + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
233 + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
234 + no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
235 +
236 + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
237 + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
238 + m = eval(m) if isinstance(m, str) else m # eval strings
239 + for j, a in enumerate(args):
240 + try:
241 + args[j] = eval(a) if isinstance(a, str) else a # eval strings
242 + except:
243 + pass
244 +
245 + n = max(round(n * gd), 1) if n > 1 else n # depth gain
246 + if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP,
247 + C3, C3TR]:
248 + c1, c2 = ch[f], args[0]
249 + if c2 != no: # if not output
250 + c2 = make_divisible(c2 * gw, 8)
251 +
252 + args = [c1, c2, *args[1:]]
253 + if m in [BottleneckCSP, C3, C3TR]:
254 + args.insert(2, n) # number of repeats
255 + n = 1
256 + elif m is nn.BatchNorm2d:
257 + args = [ch[f]]
258 + elif m is Concat:
259 + c2 = sum([ch[x] for x in f])
260 + elif m is Detect:
261 + args.append([ch[x] for x in f])
262 + if isinstance(args[1], int): # number of anchors
263 + args[1] = [list(range(args[1] * 2))] * len(f)
264 + elif m is Contract:
265 + c2 = ch[f] * args[0] ** 2
266 + elif m is Expand:
267 + c2 = ch[f] // args[0] ** 2
268 + else:
269 + c2 = ch[f]
270 +
271 + m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
272 + t = str(m)[8:-2].replace('__main__.', '') # module type
273 + np = sum([x.numel() for x in m_.parameters()]) # number params
274 + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
275 + logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
276 + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
277 + layers.append(m_)
278 + if i == 0:
279 + ch = []
280 + ch.append(c2)
281 + return nn.Sequential(*layers), sorted(save)
282 +
283 +
284 +if __name__ == '__main__':
285 + parser = argparse.ArgumentParser()
286 + parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
287 + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
288 + opt = parser.parse_args()
289 + opt.cfg = check_file(opt.cfg) # check file
290 + set_logging()
291 + device = select_device(opt.device)
292 +
293 + # Create model
294 + model = Model(opt.cfg).to(device)
295 + model.train()
296 +
297 + # Profile
298 + # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 320, 320).to(device)
299 + # y = model(img, profile=True)
300 +
301 + # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
302 + # from torch.utils.tensorboard import SummaryWriter
303 + # tb_writer = SummaryWriter('.')
304 + # logger.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
305 + # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
306 + # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.0 # model depth multiple
4 +width_multiple: 1.0 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, C3, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, C3, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, C3, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 3, C3, [1024, False]], # 9
25 + ]
26 +
27 +# YOLOv5 head
28 +head:
29 + [[-1, 1, Conv, [512, 1, 1]],
30 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 + [-1, 3, C3, [512, False]], # 13
33 +
34 + [-1, 1, Conv, [256, 1, 1]],
35 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 + [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 +
39 + [-1, 1, Conv, [256, 3, 2]],
40 + [[-1, 14], 1, Concat, [1]], # cat head P4
41 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 +
43 + [-1, 1, Conv, [512, 3, 2]],
44 + [[-1, 10], 1, Concat, [1]], # cat head P5
45 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 +
47 + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 0.67 # model depth multiple
4 +width_multiple: 0.75 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, C3, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, C3, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, C3, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 3, C3, [1024, False]], # 9
25 + ]
26 +
27 +# YOLOv5 head
28 +head:
29 + [[-1, 1, Conv, [512, 1, 1]],
30 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 + [-1, 3, C3, [512, False]], # 13
33 +
34 + [-1, 1, Conv, [256, 1, 1]],
35 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 + [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 +
39 + [-1, 1, Conv, [256, 3, 2]],
40 + [[-1, 14], 1, Concat, [1]], # cat head P4
41 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 +
43 + [-1, 1, Conv, [512, 3, 2]],
44 + [[-1, 10], 1, Concat, [1]], # cat head P5
45 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 +
47 + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 0.33 # model depth multiple
4 +width_multiple: 0.50 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, C3, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, C3, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, C3, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 3, C3, [1024, False]], # 9
25 + ]
26 +
27 +# YOLOv5 head
28 +head:
29 + [[-1, 1, Conv, [512, 1, 1]],
30 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 + [-1, 3, C3, [512, False]], # 13
33 +
34 + [-1, 1, Conv, [256, 1, 1]],
35 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 + [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 +
39 + [-1, 1, Conv, [256, 3, 2]],
40 + [[-1, 14], 1, Concat, [1]], # cat head P4
41 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 +
43 + [-1, 1, Conv, [512, 3, 2]],
44 + [[-1, 10], 1, Concat, [1]], # cat head P5
45 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 +
47 + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 + ]
1 +# parameters
2 +nc: 80 # number of classes
3 +depth_multiple: 1.33 # model depth multiple
4 +width_multiple: 1.25 # layer channel multiple
5 +
6 +# anchors
7 +anchors:
8 + - [10,13, 16,30, 33,23] # P3/8
9 + - [30,61, 62,45, 59,119] # P4/16
10 + - [116,90, 156,198, 373,326] # P5/32
11 +
12 +# YOLOv5 backbone
13 +backbone:
14 + # [from, number, module, args]
15 + [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 + [-1, 3, C3, [128]],
18 + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 + [-1, 9, C3, [256]],
20 + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 + [-1, 9, C3, [512]],
22 + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 + [-1, 1, SPP, [1024, [5, 9, 13]]],
24 + [-1, 3, C3, [1024, False]], # 9
25 + ]
26 +
27 +# YOLOv5 head
28 +head:
29 + [[-1, 1, Conv, [512, 1, 1]],
30 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 + [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 + [-1, 3, C3, [512, False]], # 13
33 +
34 + [-1, 1, Conv, [256, 1, 1]],
35 + [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 + [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 + [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 +
39 + [-1, 1, Conv, [256, 3, 2]],
40 + [[-1, 14], 1, Concat, [1]], # cat head P4
41 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 +
43 + [-1, 1, Conv, [512, 3, 2]],
44 + [[-1, 10], 1, Concat, [1]], # cat head P5
45 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 +
47 + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 + ]
1 +import argparse
2 +import json
3 +import os
4 +from pathlib import Path
5 +from threading import Thread
6 +
7 +import numpy as np
8 +import torch
9 +import yaml
10 +from tqdm import tqdm
11 +
12 +from yolo_module.yolov5.models.experimental import attempt_load
13 +from yolo_module.yolov5.utils.datasets import create_dataloader
14 +from yolo_module.yolov5.utils.general import (box_iou, check_dataset, check_file,
15 + check_img_size, check_requirements,
16 + coco80_to_coco91_class, colorstr,
17 + increment_path, non_max_suppression,
18 + scale_coords, set_logging, xywh2xyxy,
19 + xyxy2xywh)
20 +from yolo_module.yolov5.utils.metrics import ConfusionMatrix, ap_per_class
21 +from yolo_module.yolov5.utils.plots import output_to_target, plot_images, plot_study_txt
22 +from yolo_module.yolov5.utils.torch_utils import select_device, time_synchronized
23 +
24 +
25 +def test(data,
26 + weights=None,
27 + batch_size=32,
28 + imgsz=640,
29 + conf_thres=0.001,
30 + iou_thres=0.6, # for NMS
31 + save_json=False,
32 + single_cls=False,
33 + augment=False,
34 + verbose=False,
35 + model=None,
36 + dataloader=None,
37 + save_dir=Path(''), # for saving images
38 + save_txt=False, # for auto-labelling
39 + save_hybrid=False, # for hybrid auto-labelling
40 + save_conf=False, # save auto-label confidences
41 + plots=True,
42 + wandb_logger=None,
43 + compute_loss=None,
44 + half_precision=True,
45 + is_coco=False,
46 + opt=None):
47 + # Initialize/load model and set device
48 + training = model is not None
49 + if training: # called by train.py
50 + device = next(model.parameters()).device # get model device
51 +
52 + else: # called directly
53 + set_logging()
54 + device = select_device(opt.device, batch_size=batch_size)
55 +
56 + # Directories
57 + save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
58 + (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
59 +
60 + # Load model
61 + model = attempt_load(weights, map_location=device) # load FP32 model
62 + gs = max(int(model.stride.max()), 32) # grid size (max stride)
63 + imgsz = check_img_size(imgsz, s=gs) # check img_size
64 +
65 + # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
66 + # if device.type != 'cpu' and torch.cuda.device_count() > 1:
67 + # model = nn.DataParallel(model)
68 +
69 + # Half
70 + half = device.type != 'cpu' and half_precision # half precision only supported on CUDA
71 + if half:
72 + model.half()
73 +
74 + # Configure
75 + model.eval()
76 + if isinstance(data, str):
77 + is_coco = data.endswith('coco.yaml')
78 + with open(data) as f:
79 + data = yaml.safe_load(f)
80 + check_dataset(data) # check
81 + nc = 1 if single_cls else int(data['nc']) # number of classes
82 + iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
83 + niou = iouv.numel()
84 +
85 + # Logging
86 + log_imgs = 0
87 + if wandb_logger and wandb_logger.wandb:
88 + log_imgs = min(wandb_logger.log_imgs, 100)
89 + # Dataloader
90 + if not training:
91 + if device.type != 'cpu':
92 + model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
93 + task = opt.task if opt.task in ('train', 'val', 'test') else 'val' # path to train/val/test images
94 + dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True,
95 + prefix=colorstr(f'{task}: '))[0]
96 +
97 + seen = 0
98 + confusion_matrix = ConfusionMatrix(nc=nc)
99 + names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
100 + coco91class = coco80_to_coco91_class()
101 + s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
102 + p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
103 + loss = torch.zeros(3, device=device)
104 + jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
105 + for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
106 + img = img.to(device, non_blocking=True)
107 + img = img.half() if half else img.float() # uint8 to fp16/32
108 + img /= 255.0 # 0 - 255 to 0.0 - 1.0
109 + targets = targets.to(device)
110 + nb, _, height, width = img.shape # batch size, channels, height, width
111 +
112 + with torch.no_grad():
113 + # Run model
114 + t = time_synchronized()
115 + out, train_out = model(img, augment=augment) # inference and training outputs
116 + t0 += time_synchronized() - t
117 +
118 + # Compute loss
119 + if compute_loss:
120 + loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls
121 +
122 + # Run NMS
123 + targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
124 + lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
125 + t = time_synchronized()
126 + out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls)
127 + t1 += time_synchronized() - t
128 +
129 + # Statistics per image
130 + for si, pred in enumerate(out):
131 + labels = targets[targets[:, 0] == si, 1:]
132 + nl = len(labels)
133 + tcls = labels[:, 0].tolist() if nl else [] # target class
134 + path = Path(paths[si])
135 + seen += 1
136 +
137 + if len(pred) == 0:
138 + if nl:
139 + stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
140 + continue
141 +
142 + # Predictions
143 + if single_cls:
144 + pred[:, 5] = 0
145 + predn = pred.clone()
146 + scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred
147 +
148 + # Append to text file
149 + if save_txt:
150 + gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
151 + for *xyxy, conf, cls in predn.tolist():
152 + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
153 + line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
154 + with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:
155 + f.write(('%g ' * len(line)).rstrip() % line + '\n')
156 +
157 + # W&B logging - Media Panel Plots
158 + if len(wandb_images) < log_imgs and wandb_logger.current_epoch > 0: # Check for test operation
159 + if wandb_logger.current_epoch % wandb_logger.bbox_interval == 0:
160 + box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
161 + "class_id": int(cls),
162 + "box_caption": "%s %.3f" % (names[cls], conf),
163 + "scores": {"class_score": conf},
164 + "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
165 + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
166 + wandb_images.append(wandb_logger.wandb.Image(img[si], boxes=boxes, caption=path.name))
167 + wandb_logger.log_training_progress(predn, path, names) if wandb_logger and wandb_logger.wandb_run else None
168 +
169 + # Append to pycocotools JSON dictionary
170 + if save_json:
171 + # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
172 + image_id = int(path.stem) if path.stem.isnumeric() else path.stem
173 + box = xyxy2xywh(predn[:, :4]) # xywh
174 + box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
175 + for p, b in zip(pred.tolist(), box.tolist()):
176 + jdict.append({'image_id': image_id,
177 + 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
178 + 'bbox': [round(x, 3) for x in b],
179 + 'score': round(p[4], 5)})
180 +
181 + # Assign all predictions as incorrect
182 + correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
183 + if nl:
184 + detected = [] # target indices
185 + tcls_tensor = labels[:, 0]
186 +
187 + # target boxes
188 + tbox = xywh2xyxy(labels[:, 1:5])
189 + scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels
190 + if plots:
191 + confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1))
192 +
193 + # Per target class
194 + for cls in torch.unique(tcls_tensor):
195 + ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # target indices
196 + pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # prediction indices
197 +
198 + # Search for detections
199 + if pi.shape[0]:
200 + # Prediction to target ious
201 + ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices
202 +
203 + # Append detections
204 + detected_set = set()
205 + for j in (ious > iouv[0]).nonzero(as_tuple=False):
206 + d = ti[i[j]] # detected target
207 + if d.item() not in detected_set:
208 + detected_set.add(d.item())
209 + detected.append(d)
210 + correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
211 + if len(detected) == nl: # all targets already located in image
212 + break
213 +
214 + # Append statistics (correct, conf, pcls, tcls)
215 + stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
216 +
217 + # Plot images
218 + if plots and batch_i < 3:
219 + f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels
220 + Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
221 + f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions
222 + Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start()
223 +
224 + # Compute statistics
225 + stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
226 + if len(stats) and stats[0].any():
227 + p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
228 + ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
229 + mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
230 + nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
231 + else:
232 + nt = torch.zeros(1)
233 +
234 + # Print results
235 + pf = '%20s' + '%12i' * 2 + '%12.3g' * 4 # print format
236 + print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
237 +
238 + # Print results per class
239 + if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
240 + for i, c in enumerate(ap_class):
241 + print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
242 +
243 + # Print speeds
244 + t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
245 + if not training:
246 + print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
247 +
248 + # Plots
249 + if plots:
250 + confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
251 + if wandb_logger and wandb_logger.wandb:
252 + val_batches = [wandb_logger.wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]
253 + wandb_logger.log({"Validation": val_batches})
254 + if wandb_images:
255 + wandb_logger.log({"Bounding Box Debugger/Images": wandb_images})
256 +
257 + # Save JSON
258 + if save_json and len(jdict):
259 + w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
260 + anno_json = '../coco/annotations/instances_val2017.json' # annotations json
261 + pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
262 + print('\nEvaluating pycocotools mAP... saving %s...' % pred_json)
263 + with open(pred_json, 'w') as f:
264 + json.dump(jdict, f)
265 +
266 + try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
267 + from pycocotools.coco import COCO
268 + from pycocotools.cocoeval import COCOeval
269 +
270 + anno = COCO(anno_json) # init annotations api
271 + pred = anno.loadRes(pred_json) # init predictions api
272 + eval = COCOeval(anno, pred, 'bbox')
273 + if is_coco:
274 + eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
275 + eval.evaluate()
276 + eval.accumulate()
277 + eval.summarize()
278 + map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
279 + except Exception as e:
280 + print(f'pycocotools unable to run: {e}')
281 +
282 + # Return results
283 + model.float() # for training
284 + if not training:
285 + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
286 + print(f"Results saved to {save_dir}{s}")
287 + maps = np.zeros(nc) + map
288 + for i, c in enumerate(ap_class):
289 + maps[c] = ap[i]
290 + return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
291 +
292 +
293 +def main():
294 + parser = argparse.ArgumentParser(prog='test.py')
295 + parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
296 + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
297 + parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
298 + parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
299 + parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
300 + parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')
301 + parser.add_argument('--task', default='val', help='train, val, test, speed or study')
302 + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
303 + parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
304 + parser.add_argument('--augment', action='store_true', help='augmented inference')
305 + parser.add_argument('--verbose', action='store_true', help='report mAP by class')
306 + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
307 + parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
308 + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
309 + parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
310 + parser.add_argument('--project', default='runs/test', help='save to project/name')
311 + parser.add_argument('--name', default='exp', help='save to project/name')
312 + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
313 + opt = parser.parse_args()
314 + opt.save_json |= opt.data.endswith('coco.yaml')
315 + opt.data = check_file(opt.data) # check file
316 + print(opt)
317 + #check_requirements(exclude=('tensorboard', 'pycocotools', 'thop'))
318 +
319 + if opt.task in ('train', 'val', 'test'): # run normally
320 + test(opt.data,
321 + opt.weights,
322 + opt.batch_size,
323 + opt.img_size,
324 + opt.conf_thres,
325 + opt.iou_thres,
326 + opt.save_json,
327 + opt.single_cls,
328 + opt.augment,
329 + opt.verbose,
330 + save_txt=opt.save_txt | opt.save_hybrid,
331 + save_hybrid=opt.save_hybrid,
332 + save_conf=opt.save_conf,
333 + opt=opt
334 + )
335 +
336 + elif opt.task == 'speed': # speed benchmarks
337 + for w in opt.weights:
338 + test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False, opt=opt)
339 +
340 + elif opt.task == 'study': # run over a range of settings and save/plot
341 + # python test.py --task study --data coco.yaml --iou 0.7 --weights yolov5s.pt yolov5m.pt yolov5l.pt yolov5x.pt
342 + x = list(range(256, 1536 + 128, 128)) # x axis (image sizes)
343 + for w in opt.weights:
344 + f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to
345 + y = [] # y axis
346 + for i in x: # img-size
347 + print(f'\nRunning {f} point {i}...')
348 + r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,
349 + plots=False, opt=opt)
350 + y.append(r + t) # results and times
351 + np.savetxt(f, y, fmt='%10.4g') # save
352 + os.system('zip -r study.zip study_*.txt')
353 + plot_study_txt(x=x) # plot
354 +
355 +if __name__ == '__main__':
356 + main()
1 +import argparse
2 +import logging
3 +import math
4 +import os
5 +import random
6 +import time
7 +from copy import deepcopy
8 +from pathlib import Path
9 +from threading import Thread
10 +
11 +import numpy as np
12 +import torch.distributed as dist
13 +import torch.nn as nn
14 +import torch.nn.functional as F
15 +import torch.optim as optim
16 +import torch.optim.lr_scheduler as lr_scheduler
17 +import torch.utils.data
18 +import yaml
19 +from torch.cuda import amp
20 +from torch.nn.parallel import DistributedDataParallel as DDP
21 +from torch.utils.tensorboard import SummaryWriter
22 +from tqdm import tqdm
23 +
24 +import yolov5.test as test # import test.py to get mAP after each epoch
25 +from yolo_module.yolov5.models.experimental import attempt_load
26 +from yolo_module.yolov5.models.yolo import Model
27 +from yolo_module.yolov5.utils.autoanchor import check_anchors
28 +from yolo_module.yolov5.utils.datasets import create_dataloader
29 +from yolo_module.yolov5.utils.general import (check_dataset, check_file, check_git_status,
30 + check_img_size, check_requirements, colorstr,
31 + fitness, get_latest_run, increment_path,
32 + init_seeds, labels_to_class_weights,
33 + labels_to_image_weights, one_cycle,
34 + print_mutation, set_logging, strip_optimizer,
35 + yolov5_in_syspath)
36 +from yolo_module.yolov5.utils.google_utils import attempt_download
37 +from yolo_module.yolov5.utils.loss import ComputeLoss
38 +from yolo_module.yolov5.utils.neptuneai_logging.neptuneai_utils import NeptuneLogger
39 +from yolo_module.yolov5.utils.plots import (plot_evolution, plot_images, plot_labels,
40 + plot_results)
41 +from yolo_module.yolov5.utils.torch_utils import (ModelEMA, intersect_dicts, is_parallel,
42 + select_device,
43 + torch_distributed_zero_first)
44 +from yolo_module.yolov5.utils.wandb_logging.wandb_utils import (WandbLogger,
45 + check_wandb_resume)
46 +
47 +logger = logging.getLogger(__name__)
48 +
49 +
50 +def train(hyp, opt, device, tb_writer=None):
51 + logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
52 + save_dir, epochs, batch_size, total_batch_size, weights, rank = \
53 + Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
54 +
55 + # Directories
56 + wdir = save_dir / 'weights'
57 + wdir.mkdir(parents=True, exist_ok=True) # make dir
58 + last = wdir / 'last.pt'
59 + best = wdir / 'best.pt'
60 + results_file = save_dir / 'results.txt'
61 +
62 + # Save run settings
63 + with open(save_dir / 'hyp.yaml', 'w') as f:
64 + yaml.safe_dump(hyp, f, sort_keys=False)
65 + with open(save_dir / 'opt.yaml', 'w') as f:
66 + yaml.safe_dump(vars(opt), f, sort_keys=False)
67 +
68 + # Configure
69 + plots = not opt.evolve # create plots
70 + cuda = device.type != 'cpu'
71 + init_seeds(2 + rank)
72 + with open(opt.data) as f:
73 + data_dict = yaml.safe_load(f) # data dict
74 + is_coco = opt.data.endswith('coco.yaml')
75 +
76 + # Logging- Doing this before checking the dataset. Might update data_dict
77 + loggers = {'wandb': None} # loggers dict
78 + if rank in [-1, 0]:
79 + opt.hyp = hyp # add hyperparameters
80 + with yolov5_in_syspath():
81 + run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None
82 + wandb_logger = WandbLogger(opt, save_dir.stem, run_id, data_dict)
83 + neptune_logger = NeptuneLogger(opt, save_dir.stem, data_dict)
84 + loggers['wandb'] = wandb_logger.wandb
85 + data_dict = wandb_logger.data_dict
86 + if wandb_logger.wandb:
87 + weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming
88 +
89 + nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes
90 + names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
91 + assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
92 +
93 + # Model
94 + pretrained = weights.endswith('.pt')
95 + if pretrained:
96 + with torch_distributed_zero_first(rank):
97 + attempt_download(weights) # download if not found locally
98 + with yolov5_in_syspath():
99 + ckpt = torch.load(weights, map_location=device) # load checkpoint
100 +
101 + model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
102 + exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys
103 + state_dict = ckpt['model'].float().state_dict() # to FP32
104 + state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
105 + model.load_state_dict(state_dict, strict=False) # load
106 + logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
107 + else:
108 + model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
109 + with torch_distributed_zero_first(rank):
110 + check_dataset(data_dict) # check
111 + train_path = data_dict['train']
112 + test_path = data_dict['val']
113 +
114 + # Freeze
115 + freeze = [] # parameter names to freeze (full or partial)
116 + for k, v in model.named_parameters():
117 + v.requires_grad = True # train all layers
118 + if any(x in k for x in freeze):
119 + print('freezing %s' % k)
120 + v.requires_grad = False
121 +
122 + # Optimizer
123 + nbs = 64 # nominal batch size
124 + accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
125 + hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
126 + logger.info(f"Scaled weight_decay = {hyp['weight_decay']}")
127 +
128 + pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
129 + for k, v in model.named_modules():
130 + if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter):
131 + pg2.append(v.bias) # biases
132 + if isinstance(v, nn.BatchNorm2d):
133 + pg0.append(v.weight) # no decay
134 + elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter):
135 + pg1.append(v.weight) # apply decay
136 +
137 + if opt.adam:
138 + optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
139 + else:
140 + optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
141 +
142 + optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
143 + optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
144 + logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
145 + del pg0, pg1, pg2
146 +
147 + # Scheduler https://arxiv.org/pdf/1812.01187.pdf
148 + # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
149 + if opt.linear_lr:
150 + lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
151 + else:
152 + lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
153 + scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
154 + # plot_lr_scheduler(optimizer, scheduler, epochs)
155 +
156 + # EMA
157 + ema = ModelEMA(model) if rank in [-1, 0] else None
158 +
159 + # Resume
160 + start_epoch, best_fitness = 0, 0.0
161 + if pretrained:
162 + # Optimizer
163 + if ckpt['optimizer'] is not None:
164 + optimizer.load_state_dict(ckpt['optimizer'])
165 + best_fitness = ckpt['best_fitness']
166 +
167 + # EMA
168 + if ema and ckpt.get('ema'):
169 + ema.ema.load_state_dict(ckpt['ema'].float().state_dict())
170 + ema.updates = ckpt['updates']
171 +
172 + # Results
173 + if ckpt.get('training_results') is not None:
174 + results_file.write_text(ckpt['training_results']) # write results.txt
175 +
176 + # Epochs
177 + start_epoch = ckpt['epoch'] + 1
178 + if opt.resume:
179 + assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs)
180 + if epochs < start_epoch:
181 + logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
182 + (weights, ckpt['epoch'], epochs))
183 + epochs += ckpt['epoch'] # finetune additional epochs
184 +
185 + del ckpt, state_dict
186 +
187 + # Image sizes
188 + gs = max(int(model.stride.max()), 32) # grid size (max stride)
189 + nl = model.model[-1].nl # number of detection layers (used for scaling hyp['obj'])
190 + imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
191 +
192 + # DP mode
193 + if cuda and rank == -1 and torch.cuda.device_count() > 1:
194 + model = torch.nn.DataParallel(model)
195 +
196 + # SyncBatchNorm
197 + if opt.sync_bn and cuda and rank != -1:
198 + model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
199 + logger.info('Using SyncBatchNorm()')
200 +
201 + # Trainloader
202 + dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt,
203 + hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank,
204 + world_size=opt.world_size, workers=opt.workers,
205 + image_weights=opt.image_weights, quad=opt.quad, prefix=colorstr('train: '))
206 + mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
207 + nb = len(dataloader) # number of batches
208 + assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
209 +
210 + # Process 0
211 + if rank in [-1, 0]:
212 + testloader = create_dataloader(test_path, imgsz_test, batch_size * 2, gs, opt, # testloader
213 + hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True, rank=-1,
214 + world_size=opt.world_size, workers=opt.workers,
215 + pad=0.5, prefix=colorstr('val: '))[0]
216 +
217 + if not opt.resume:
218 + labels = np.concatenate(dataset.labels, 0)
219 + c = torch.tensor(labels[:, 0]) # classes
220 + # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
221 + # model._initialize_biases(cf.to(device))
222 + if plots:
223 + plot_labels(labels, names, save_dir, loggers)
224 + if tb_writer:
225 + tb_writer.add_histogram('classes', c, 0)
226 +
227 + # Anchors
228 + if not opt.noautoanchor:
229 + check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
230 + model.half().float() # pre-reduce anchor precision
231 +
232 + # DDP mode
233 + if cuda and rank != -1:
234 + model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank,
235 + # nn.MultiheadAttention incompatibility with DDP https://github.com/pytorch/pytorch/issues/26698
236 + find_unused_parameters=any(isinstance(layer, nn.MultiheadAttention) for layer in model.modules()))
237 +
238 + # Model parameters
239 + hyp['box'] *= 3. / nl # scale to layers
240 + hyp['cls'] *= nc / 80. * 3. / nl # scale to classes and layers
241 + hyp['obj'] *= (imgsz / 640) ** 2 * 3. / nl # scale to image size and layers
242 + hyp['label_smoothing'] = opt.label_smoothing
243 + model.nc = nc # attach number of classes to model
244 + model.hyp = hyp # attach hyperparameters to model
245 + model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou)
246 + model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
247 + model.names = names
248 +
249 + # Start training
250 + t0 = time.time()
251 + nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations)
252 + # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
253 + maps = np.zeros(nc) # mAP per class
254 + results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
255 + scheduler.last_epoch = start_epoch - 1 # do not move
256 + scaler = amp.GradScaler(enabled=cuda)
257 + compute_loss = ComputeLoss(model) # init loss class
258 + logger.info(f'Image sizes {imgsz} train, {imgsz_test} test\n'
259 + f'Using {dataloader.num_workers} dataloader workers\n'
260 + f'Logging results to {save_dir}\n'
261 + f'Starting training for {epochs} epochs...')
262 + for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
263 + model.train()
264 +
265 + # Update image weights (optional)
266 + if opt.image_weights:
267 + # Generate indices
268 + if rank in [-1, 0]:
269 + cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
270 + iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
271 + dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
272 + # Broadcast if DDP
273 + if rank != -1:
274 + indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int()
275 + dist.broadcast(indices, 0)
276 + if rank != 0:
277 + dataset.indices = indices.cpu().numpy()
278 +
279 + # Update mosaic border
280 + # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
281 + # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
282 +
283 + mloss = torch.zeros(4, device=device) # mean losses
284 + if rank != -1:
285 + dataloader.sampler.set_epoch(epoch)
286 + pbar = enumerate(dataloader)
287 + logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'labels', 'img_size'))
288 + if rank in [-1, 0]:
289 + pbar = tqdm(pbar, total=nb) # progress bar
290 + optimizer.zero_grad()
291 + for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
292 + ni = i + nb * epoch # number integrated batches (since train start)
293 + imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
294 +
295 + # Warmup
296 + if ni <= nw:
297 + xi = [0, nw] # x interp
298 + # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
299 + accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
300 + for j, x in enumerate(optimizer.param_groups):
301 + # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
302 + x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
303 + if 'momentum' in x:
304 + x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
305 +
306 + # Multi-scale
307 + if opt.multi_scale:
308 + sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
309 + sf = sz / max(imgs.shape[2:]) # scale factor
310 + if sf != 1:
311 + ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
312 + imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
313 +
314 + # Forward
315 + with amp.autocast(enabled=cuda):
316 + pred = model(imgs) # forward
317 + loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
318 + if rank != -1:
319 + loss *= opt.world_size # gradient averaged between devices in DDP mode
320 + if opt.quad:
321 + loss *= 4.
322 +
323 + # Backward
324 + scaler.scale(loss).backward()
325 +
326 + # Optimize
327 + if ni % accumulate == 0:
328 + scaler.step(optimizer) # optimizer.step
329 + scaler.update()
330 + optimizer.zero_grad()
331 + if ema:
332 + ema.update(model)
333 +
334 + # Print
335 + if rank in [-1, 0]:
336 + mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
337 + mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
338 + s = ('%10s' * 2 + '%10.4g' * 6) % (
339 + '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
340 + pbar.set_description(s)
341 +
342 + # Plot
343 + if plots and ni < 3:
344 + f = save_dir / f'train_batch{ni}.jpg' # filename
345 + Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
346 + # if tb_writer:
347 + # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
348 + # tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) # add model graph
349 + elif plots and ni == 10 and wandb_logger.wandb:
350 + wandb_logger.log({"Mosaics": [wandb_logger.wandb.Image(str(x), caption=x.name) for x in
351 + save_dir.glob('train*.jpg') if x.exists()]})
352 +
353 + # end batch ------------------------------------------------------------------------------------------------
354 + # end epoch ----------------------------------------------------------------------------------------------------
355 +
356 + # Scheduler
357 + lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard
358 + scheduler.step()
359 +
360 + # DDP process 0 or single-GPU
361 + if rank in [-1, 0]:
362 + # mAP
363 + ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride', 'class_weights'])
364 + final_epoch = epoch + 1 == epochs
365 + if not opt.notest or final_epoch: # Calculate mAP
366 + wandb_logger.current_epoch = neptune_logger.current_epoch = epoch + 1
367 + results, maps, times = test.test(data_dict,
368 + batch_size=batch_size * 2,
369 + imgsz=imgsz_test,
370 + model=ema.ema,
371 + single_cls=opt.single_cls,
372 + dataloader=testloader,
373 + save_dir=save_dir,
374 + verbose=nc < 50 and final_epoch,
375 + plots=plots and final_epoch,
376 + wandb_logger=wandb_logger,
377 + compute_loss=compute_loss,
378 + is_coco=is_coco)
379 +
380 + # Write
381 + with open(results_file, 'a') as f:
382 + f.write(s + '%10.4g' * 7 % results + '\n') # append metrics, val_loss
383 +
384 + # Log
385 + tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
386 + 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
387 + 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
388 + 'x/lr0', 'x/lr1', 'x/lr2'] # params
389 + if opt.mmdet_tags:
390 + tags = ['train/loss_bbox', 'train/loss_obj', 'train/loss_cls', # train loss
391 + 'val/precision', 'val/recall', 'val/bbox_mAP_50', 'val/bbox_mAP',
392 + 'val/loss_bbox', 'val/loss_obj', 'val/loss_cls', # val loss
393 + 'learning_rate_0', 'learning_rate_1', 'learning_rate_2'] # params
394 + for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags):
395 + if tb_writer:
396 + tb_writer.add_scalar(tag, x, epoch) # tensorboard
397 + if wandb_logger.wandb:
398 + wandb_logger.log({tag: x}) # W&B
399 + if neptune_logger.neptune_run:
400 + neptune_logger.log({tag: x})
401 +
402 + # Update best mAP
403 + fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
404 + if fi > best_fitness:
405 + best_fitness = fi
406 + wandb_logger.end_epoch(best_result=best_fitness == fi)
407 + neptune_logger.end_epoch(best_result=best_fitness == fi)
408 +
409 + # Save model
410 + if (not opt.nosave) or (final_epoch and not opt.evolve): # if save
411 + ckpt = {'epoch': epoch,
412 + 'best_fitness': best_fitness,
413 + 'training_results': results_file.read_text(),
414 + 'model': deepcopy(model.module if is_parallel(model) else model).half(),
415 + 'ema': deepcopy(ema.ema).half(),
416 + 'updates': ema.updates,
417 + 'optimizer': optimizer.state_dict(),
418 + 'wandb_id': wandb_logger.wandb_run.id if wandb_logger.wandb else None,
419 + 'neptune_id': neptune_logger.neptune_run['sys/id'].fetch() if neptune_logger.neptune_run else None}
420 +
421 + # Save last, best and delete
422 + with yolov5_in_syspath():
423 + torch.save(ckpt, last)
424 + if best_fitness == fi:
425 + with yolov5_in_syspath():
426 + torch.save(ckpt, best)
427 + if wandb_logger.wandb:
428 + if ((epoch + 1) % opt.save_period == 0 and not final_epoch) and opt.save_period != -1:
429 + wandb_logger.log_model(
430 + last.parent, opt, epoch, fi, best_model=best_fitness == fi)
431 + del ckpt
432 +
433 + # end epoch ----------------------------------------------------------------------------------------------------
434 + # end training
435 + if rank in [-1, 0]:
436 + # Plots
437 + if plots:
438 + plot_results(save_dir=save_dir) # save as results.png
439 + files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
440 + if wandb_logger.wandb:
441 + wandb_logger.log({"Results": [wandb_logger.wandb.Image(str(save_dir / f), caption=f) for f in files
442 + if (save_dir / f).exists()]})
443 + if neptune_logger.neptune_run:
444 + for f in files:
445 + if (save_dir / f).exists():
446 + neptune_logger.neptune_run['Results/{}'.format(f)].log(neptune_logger.neptune.types.File(str(save_dir / f)))
447 + # Test best.pt
448 + logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
449 + if opt.data.endswith('coco.yaml') and nc == 80: # if COCO
450 + for m in (last, best) if best.exists() else (last): # speed, mAP tests
451 + results, _, _ = test.test(opt.data,
452 + batch_size=batch_size * 2,
453 + imgsz=imgsz_test,
454 + conf_thres=0.001,
455 + iou_thres=0.7,
456 + model=attempt_load(m, device).half(),
457 + single_cls=opt.single_cls,
458 + dataloader=testloader,
459 + save_dir=save_dir,
460 + save_json=True,
461 + plots=False,
462 + is_coco=is_coco)
463 +
464 + # Strip optimizers
465 + final = best if best.exists() else last # final model
466 + for f in last, best:
467 + if f.exists():
468 + strip_optimizer(f) # strip optimizers
469 + if opt.bucket:
470 + os.system(f'gsutil cp {final} gs://{opt.bucket}/weights') # upload
471 + if wandb_logger.wandb and not opt.evolve: # Log the stripped model
472 + wandb_logger.wandb.log_artifact(str(final), type='model',
473 + name='run_' + wandb_logger.wandb_run.id + '_model',
474 + aliases=['last', 'best', 'stripped'])
475 + wandb_logger.finish_run()
476 + neptune_logger.finish_run()
477 + else:
478 + dist.destroy_process_group()
479 + torch.cuda.empty_cache()
480 + return results
481 +
482 +
483 +def main():
484 + parser = argparse.ArgumentParser()
485 + parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path')
486 + parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
487 + #parser.add_argument('--data', type=str, default='yolov5/data/coco128.yaml', help='data.yaml path')
488 + #parser.add_argument('--hyp', type=str, default='yolov5/data/hyp.scratch.yaml', help='hyperparameters path')
489 + parser.add_argument('--data', type=str, default='', help='data.yaml path')
490 + parser.add_argument('--hyp', type=str, default='', help='hyperparameters path')
491 + parser.add_argument('--epochs', type=int, default=300)
492 + parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
493 + parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
494 + parser.add_argument('--rect', action='store_true', help='rectangular training')
495 + parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
496 + parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
497 + parser.add_argument('--notest', action='store_true', help='only test final epoch')
498 + parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
499 + parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
500 + parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
501 + parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
502 + parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
503 + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
504 + parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
505 + parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
506 + parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
507 + parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
508 + parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
509 + parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
510 + parser.add_argument('--project', default='runs/train', help='save to project/name')
511 + parser.add_argument('--entity', default=None, help='W&B entity')
512 + parser.add_argument('--name', default='exp', help='save to project/name')
513 + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
514 + parser.add_argument('--quad', action='store_true', help='quad dataloader')
515 + parser.add_argument('--linear-lr', action='store_true', help='linear LR')
516 + parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
517 + parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
518 + parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
519 + parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
520 + parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
521 + parser.add_argument('--mmdet_tags', action='store_true', help='Log train/val tags in MMDetection format')
522 + parser.add_argument('--neptune_token', type=str, default="", help='neptune.ai api token')
523 + parser.add_argument('--neptune_project', type=str, default="", help='https://docs.neptune.ai/api-reference/neptune')
524 + opt = parser.parse_args()
525 +
526 + # Set DDP variables
527 + opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
528 + opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1
529 + set_logging(opt.global_rank)
530 + if opt.global_rank in [-1, 0]:
531 + check_git_status()
532 + #check_requirements(exclude=('pycocotools', 'thop'))
533 +
534 + # Resume
535 + wandb_run = check_wandb_resume(opt)
536 + if opt.resume and not wandb_run: # resume an interrupted run
537 + ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
538 + assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
539 + apriori = opt.global_rank, opt.local_rank
540 + with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
541 + opt = argparse.Namespace(**yaml.safe_load(f)) # replace
542 + opt.cfg, opt.weights, opt.resume, opt.batch_size, opt.global_rank, opt.local_rank = \
543 + '', ckpt, True, opt.total_batch_size, *apriori # reinstate
544 + logger.info('Resuming training from %s' % ckpt)
545 + else:
546 + opt.hyp = opt.hyp or str(Path(__file__).parent / 'data' / ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml'))
547 + opt.data = opt.data or str(Path(__file__).parent / 'data/coco128.yaml')
548 +
549 + opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
550 + assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
551 + opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
552 + opt.name = 'evolve' if opt.evolve else opt.name
553 + opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve))
554 +
555 + # DDP mode
556 + opt.total_batch_size = opt.batch_size
557 + device = select_device(opt.device, batch_size=opt.batch_size)
558 + if opt.local_rank != -1:
559 + assert torch.cuda.device_count() > opt.local_rank
560 + torch.cuda.set_device(opt.local_rank)
561 + device = torch.device('cuda', opt.local_rank)
562 + dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
563 + assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count'
564 + opt.batch_size = opt.total_batch_size // opt.world_size
565 +
566 + # Hyperparameters
567 + with open(opt.hyp) as f:
568 + hyp = yaml.safe_load(f) # load hyps
569 +
570 + # Train
571 + logger.info(opt)
572 + if not opt.evolve:
573 + tb_writer = None # init loggers
574 + if opt.global_rank in [-1, 0]:
575 + prefix = colorstr('tensorboard: ')
576 + logger.info(f"{prefix}Start with 'tensorboard --logdir {opt.project}', view at http://localhost:6006/")
577 + tb_writer = SummaryWriter(opt.save_dir) # Tensorboard
578 + train(hyp, opt, device, tb_writer)
579 +
580 + # Evolve hyperparameters (optional)
581 + else:
582 + # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
583 + meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
584 + 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
585 + 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
586 + 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
587 + 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
588 + 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
589 + 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
590 + 'box': (1, 0.02, 0.2), # box loss gain
591 + 'cls': (1, 0.2, 4.0), # cls loss gain
592 + 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
593 + 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
594 + 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
595 + 'iou_t': (0, 0.1, 0.7), # IoU training threshold
596 + 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
597 + 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
598 + 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
599 + 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
600 + 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
601 + 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
602 + 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
603 + 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
604 + 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
605 + 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
606 + 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
607 + 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
608 + 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
609 + 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
610 + 'mixup': (1, 0.0, 1.0)} # image mixup (probability)
611 +
612 + assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
613 + opt.notest, opt.nosave = True, True # only test/save final epoch
614 + # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
615 + yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here
616 + if opt.bucket:
617 + os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
618 +
619 + for _ in range(300): # generations to evolve
620 + if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate
621 + # Select parent(s)
622 + parent = 'single' # parent selection method: 'single' or 'weighted'
623 + x = np.loadtxt('evolve.txt', ndmin=2)
624 + n = min(5, len(x)) # number of previous results to consider
625 + x = x[np.argsort(-fitness(x))][:n] # top n mutations
626 + w = fitness(x) - fitness(x).min() # weights
627 + if parent == 'single' or len(x) == 1:
628 + # x = x[random.randint(0, n - 1)] # random selection
629 + x = x[random.choices(range(n), weights=w)[0]] # weighted selection
630 + elif parent == 'weighted':
631 + x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
632 +
633 + # Mutate
634 + mp, s = 0.8, 0.2 # mutation probability, sigma
635 + npr = np.random
636 + npr.seed(int(time.time()))
637 + g = np.array([x[0] for x in meta.values()]) # gains 0-1
638 + ng = len(meta)
639 + v = np.ones(ng)
640 + while all(v == 1): # mutate until a change occurs (prevent duplicates)
641 + v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
642 + for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
643 + hyp[k] = float(x[i + 7] * v[i]) # mutate
644 +
645 + # Constrain to limits
646 + for k, v in meta.items():
647 + hyp[k] = max(hyp[k], v[1]) # lower limit
648 + hyp[k] = min(hyp[k], v[2]) # upper limit
649 + hyp[k] = round(hyp[k], 5) # significant digits
650 +
651 + # Train mutation
652 + results = train(hyp.copy(), opt, device)
653 +
654 + # Write mutation results
655 + print_mutation(hyp.copy(), results, yaml_file, opt.bucket)
656 +
657 + # Plot results
658 + plot_evolution(yaml_file)
659 + print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n'
660 + f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}')
661 +
662 +if __name__ == '__main__':
663 + main()
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 +# Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
23 +class Mish(nn.Module):
24 + @staticmethod
25 + def forward(x):
26 + return x * F.softplus(x).tanh()
27 +
28 +
29 +class MemoryEfficientMish(nn.Module):
30 + class F(torch.autograd.Function):
31 + @staticmethod
32 + def forward(ctx, x):
33 + ctx.save_for_backward(x)
34 + return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
35 +
36 + @staticmethod
37 + def backward(ctx, grad_output):
38 + x = ctx.saved_tensors[0]
39 + sx = torch.sigmoid(x)
40 + fx = F.softplus(x).tanh()
41 + return grad_output * (fx + x * sx * (1 - fx * fx))
42 +
43 + def forward(self, x):
44 + return self.F.apply(x)
45 +
46 +
47 +# FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
48 +class FReLU(nn.Module):
49 + def __init__(self, c1, k=3): # ch_in, kernel
50 + super().__init__()
51 + self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
52 + self.bn = nn.BatchNorm2d(c1)
53 +
54 + def forward(self, x):
55 + return torch.max(x, self.bn(self.conv(x)))
56 +
57 +
58 +# ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
59 +class AconC(nn.Module):
60 + r""" ACON activation (activate or not).
61 + AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
62 + according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
63 + """
64 +
65 + def __init__(self, c1):
66 + super().__init__()
67 + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
68 + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
69 + self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
70 +
71 + def forward(self, x):
72 + dpx = (self.p1 - self.p2) * x
73 + return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
74 +
75 +
76 +class MetaAconC(nn.Module):
77 + r""" ACON activation (activate or not).
78 + MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
79 + according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
80 + """
81 +
82 + def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
83 + super().__init__()
84 + c2 = max(r, c1 // r)
85 + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
86 + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
87 + self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
88 + self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
89 + # self.bn1 = nn.BatchNorm2d(c2)
90 + # self.bn2 = nn.BatchNorm2d(c1)
91 +
92 + def forward(self, x):
93 + y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
94 + # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
95 + # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
96 + beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
97 + dpx = (self.p1 - self.p2) * x
98 + return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
1 +# Auto-anchor utils
2 +
3 +import numpy as np
4 +import torch
5 +import yaml
6 +from tqdm import tqdm
7 +from yolo_module.yolov5.utils.general import colorstr
8 +
9 +
10 +def check_anchor_order(m):
11 + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
12 + a = m.anchor_grid.prod(-1).view(-1) # anchor area
13 + da = a[-1] - a[0] # delta a
14 + ds = m.stride[-1] - m.stride[0] # delta s
15 + if da.sign() != ds.sign(): # same order
16 + print('Reversing anchor order')
17 + m.anchors[:] = m.anchors.flip(0)
18 + m.anchor_grid[:] = m.anchor_grid.flip(0)
19 +
20 +
21 +def check_anchors(dataset, model, thr=4.0, imgsz=640):
22 + # Check anchor fit to data, recompute if necessary
23 + prefix = colorstr('autoanchor: ')
24 + print(f'\n{prefix}Analyzing anchors... ', end='')
25 + m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
26 + shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
27 + scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
28 + wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
29 +
30 + def metric(k): # compute metric
31 + r = wh[:, None] / k[None]
32 + x = torch.min(r, 1. / r).min(2)[0] # ratio metric
33 + best = x.max(1)[0] # best_x
34 + aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
35 + bpr = (best > 1. / thr).float().mean() # best possible recall
36 + return bpr, aat
37 +
38 + anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
39 + bpr, aat = metric(anchors)
40 + print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
41 + if bpr < 0.98: # threshold to recompute
42 + print('. Attempting to improve anchors, please wait...')
43 + na = m.anchor_grid.numel() // 2 # number of anchors
44 + try:
45 + anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
46 + except Exception as e:
47 + print(f'{prefix}ERROR: {e}')
48 + new_bpr = metric(anchors)[0]
49 + if new_bpr > bpr: # replace anchors
50 + anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
51 + m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
52 + m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
53 + check_anchor_order(m)
54 + print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
55 + else:
56 + print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
57 + print('') # newline
58 +
59 +
60 +def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
61 + """ Creates kmeans-evolved anchors from training dataset
62 +
63 + Arguments:
64 + path: path to dataset *.yaml, or a loaded dataset
65 + n: number of anchors
66 + img_size: image size used for training
67 + thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
68 + gen: generations to evolve anchors using genetic algorithm
69 + verbose: print all results
70 +
71 + Return:
72 + k: kmeans evolved anchors
73 +
74 + Usage:
75 + from utils.autoanchor import *; _ = kmean_anchors()
76 + """
77 + from scipy.cluster.vq import kmeans
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.safe_load(f) # model dict
106 + from yolo_module.yolov5.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)
1 +# Resume all interrupted trainings in yolov5/ dir including DDP trainings
2 +# Usage: $ python utils/aws/resume.py
3 +
4 +import os
5 +import sys
6 +from pathlib import Path
7 +
8 +import torch
9 +import yaml
10 +from yolo_module.yolov5.utils.general import yolov5_in_syspath
11 +
12 +sys.path.append('./') # to run '$ python *.py' files in subdirectories
13 +
14 +port = 0 # --master_port
15 +path = Path('').resolve()
16 +
17 +for last in path.rglob('*/**/last.pt'):
18 + with yolov5_in_syspath():
19 + ckpt = torch.load(last)
20 + if ckpt['optimizer'] is None:
21 + continue
22 +
23 + # Load opt.yaml
24 + with open(last.parent.parent / 'opt.yaml') as f:
25 + opt = yaml.safe_load(f)
26 +
27 + # Get device count
28 + d = opt['device'].split(',') # devices
29 + nd = len(d) # number of devices
30 + ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
31 +
32 + if ddp: # multi-GPU
33 + port += 1
34 + cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}'
35 + else: # single-GPU
36 + cmd = f'python train.py --resume {last}'
37 +
38 + cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread
39 + print(cmd)
40 + os.system(cmd)
1 +# Dataset utils and dataloaders
2 +
3 +import glob
4 +import logging
5 +import math
6 +import os
7 +import random
8 +import shutil
9 +import time
10 +from itertools import repeat
11 +from multiprocessing.pool import ThreadPool
12 +from pathlib import Path
13 +from threading import Thread
14 +
15 +import cv2
16 +import numpy as np
17 +import torch
18 +import torch.nn.functional as F
19 +from PIL import ExifTags, Image
20 +from torch.utils.data import Dataset
21 +from tqdm import tqdm
22 +from yolo_module.yolov5.utils.general import (check_requirements, clean_str,
23 + resample_segments, segment2box,
24 + segments2boxes, xyn2xy, xywh2xyxy,
25 + xywhn2xyxy, xyxy2xywh, yolov5_in_syspath)
26 +from yolo_module.yolov5.utils.torch_utils import torch_distributed_zero_first
27 +
28 +# Parameters
29 +help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
30 +img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
31 +vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
32 +logger = logging.getLogger(__name__)
33 +
34 +# Get orientation exif tag
35 +for orientation in ExifTags.TAGS.keys():
36 + if ExifTags.TAGS[orientation] == 'Orientation':
37 + break
38 +
39 +
40 +def get_hash(files):
41 + # Returns a single hash value of a list of files
42 + return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
43 +
44 +
45 +def exif_size(img):
46 + # Returns exif-corrected PIL size
47 + s = img.size # (width, height)
48 + try:
49 + rotation = dict(img._getexif().items())[orientation]
50 + if rotation == 6: # rotation 270
51 + s = (s[1], s[0])
52 + elif rotation == 8: # rotation 90
53 + s = (s[1], s[0])
54 + except:
55 + pass
56 +
57 + return s
58 +
59 +
60 +def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
61 + rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):
62 + # Make sure only the first process in DDP process the dataset first, and the following others can use the cache
63 + with torch_distributed_zero_first(rank):
64 + dataset = LoadImagesAndLabels(path, imgsz, batch_size,
65 + augment=augment, # augment images
66 + hyp=hyp, # augmentation hyperparameters
67 + rect=rect, # rectangular training
68 + cache_images=cache,
69 + single_cls=opt.single_cls,
70 + stride=int(stride),
71 + pad=pad,
72 + image_weights=image_weights,
73 + prefix=prefix)
74 +
75 + batch_size = min(batch_size, len(dataset))
76 + nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers
77 + sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
78 + loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
79 + # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
80 + dataloader = loader(dataset,
81 + batch_size=batch_size,
82 + num_workers=nw,
83 + sampler=sampler,
84 + pin_memory=True,
85 + collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
86 + return dataloader, dataset
87 +
88 +
89 +class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
90 + """ Dataloader that reuses workers
91 +
92 + Uses same syntax as vanilla DataLoader
93 + """
94 +
95 + def __init__(self, *args, **kwargs):
96 + super().__init__(*args, **kwargs)
97 + object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
98 + self.iterator = super().__iter__()
99 +
100 + def __len__(self):
101 + return len(self.batch_sampler.sampler)
102 +
103 + def __iter__(self):
104 + for i in range(len(self)):
105 + yield next(self.iterator)
106 +
107 +
108 +class _RepeatSampler(object):
109 + """ Sampler that repeats forever
110 +
111 + Args:
112 + sampler (Sampler)
113 + """
114 +
115 + def __init__(self, sampler):
116 + self.sampler = sampler
117 +
118 + def __iter__(self):
119 + while True:
120 + yield from iter(self.sampler)
121 +
122 +
123 +class LoadImages: # for inference
124 + def __init__(self, path, img_size=640, stride=32):
125 + p = str(Path(path).absolute()) # os-agnostic absolute path
126 + if '*' in p:
127 + files = sorted(glob.glob(p, recursive=True)) # glob
128 + elif os.path.isdir(p):
129 + files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
130 + elif os.path.isfile(p):
131 + files = [p] # files
132 + else:
133 + raise Exception(f'ERROR: {p} does not exist')
134 +
135 + images = [x for x in files if x.split('.')[-1].lower() in img_formats]
136 + videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
137 + ni, nv = len(images), len(videos)
138 +
139 + self.img_size = img_size
140 + self.stride = stride
141 + self.files = images + videos
142 + self.nf = ni + nv # number of files
143 + self.video_flag = [False] * ni + [True] * nv
144 + self.mode = 'image'
145 + if any(videos):
146 + self.new_video(videos[0]) # new video
147 + else:
148 + self.cap = None
149 + assert self.nf > 0, f'No images or videos found in {p}. ' \
150 + f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
151 +
152 + def __iter__(self):
153 + self.count = 0
154 + return self
155 +
156 + def __next__(self):
157 + if self.count == self.nf:
158 + raise StopIteration
159 + path = self.files[self.count]
160 +
161 + if self.video_flag[self.count]:
162 + # Read video
163 + self.mode = 'video'
164 + ret_val, img0 = self.cap.read()
165 + if not ret_val:
166 + self.count += 1
167 + self.cap.release()
168 + if self.count == self.nf: # last video
169 + raise StopIteration
170 + else:
171 + path = self.files[self.count]
172 + self.new_video(path)
173 + ret_val, img0 = self.cap.read()
174 +
175 + self.frame += 1
176 + print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')
177 +
178 + else:
179 + # Read image
180 + self.count += 1
181 + img0 = cv2.imread(path) # BGR
182 + assert img0 is not None, 'Image Not Found ' + path
183 + print(f'image {self.count}/{self.nf} {path}: ', end='')
184 +
185 + # Padded resize
186 + img = letterbox(img0, self.img_size, stride=self.stride)[0]
187 +
188 + # Convert
189 + img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
190 + img = np.ascontiguousarray(img)
191 +
192 + return path, img, img0, self.cap
193 +
194 + def new_video(self, path):
195 + self.frame = 0
196 + self.cap = cv2.VideoCapture(path)
197 + self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
198 +
199 + def __len__(self):
200 + return self.nf # number of files
201 +
202 +
203 +class LoadWebcam: # for inference
204 + def __init__(self, pipe='0', img_size=640, stride=32):
205 + self.img_size = img_size
206 + self.stride = stride
207 +
208 + if pipe.isnumeric():
209 + pipe = eval(pipe) # local camera
210 + # pipe = 'rtsp://192.168.1.64/1' # IP camera
211 + # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login
212 + # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
213 +
214 + self.pipe = pipe
215 + self.cap = cv2.VideoCapture(pipe) # video capture object
216 + self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
217 +
218 + def __iter__(self):
219 + self.count = -1
220 + return self
221 +
222 + def __next__(self):
223 + self.count += 1
224 + if cv2.waitKey(1) == ord('q'): # q to quit
225 + self.cap.release()
226 + cv2.destroyAllWindows()
227 + raise StopIteration
228 +
229 + # Read frame
230 + if self.pipe == 0: # local camera
231 + ret_val, img0 = self.cap.read()
232 + img0 = cv2.flip(img0, 1) # flip left-right
233 + else: # IP camera
234 + n = 0
235 + while True:
236 + n += 1
237 + self.cap.grab()
238 + if n % 30 == 0: # skip frames
239 + ret_val, img0 = self.cap.retrieve()
240 + if ret_val:
241 + break
242 +
243 + # Print
244 + assert ret_val, f'Camera Error {self.pipe}'
245 + img_path = 'webcam.jpg'
246 + print(f'webcam {self.count}: ', end='')
247 +
248 + # Padded resize
249 + img = letterbox(img0, self.img_size, stride=self.stride)[0]
250 +
251 + # Convert
252 + img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
253 + img = np.ascontiguousarray(img)
254 +
255 + return img_path, img, img0, None
256 +
257 + def __len__(self):
258 + return 0
259 +
260 +
261 +class LoadStreams: # multiple IP or RTSP cameras
262 + def __init__(self, sources='streams.txt', img_size=640, stride=32):
263 + self.mode = 'stream'
264 + self.img_size = img_size
265 + self.stride = stride
266 +
267 + if os.path.isfile(sources):
268 + with open(sources, 'r') as f:
269 + sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
270 + else:
271 + sources = [sources]
272 +
273 + n = len(sources)
274 + self.imgs = [None] * n
275 + self.sources = [clean_str(x) for x in sources] # clean source names for later
276 + for i, s in enumerate(sources): # index, source
277 + # Start thread to read frames from video stream
278 + print(f'{i + 1}/{n}: {s}... ', end='')
279 + if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video
280 + check_requirements(('pafy', 'youtube_dl'))
281 + import pafy
282 + s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
283 + s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
284 + cap = cv2.VideoCapture(s)
285 + assert cap.isOpened(), f'Failed to open {s}'
286 + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
287 + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
288 + self.fps = cap.get(cv2.CAP_PROP_FPS) % 100
289 +
290 + _, self.imgs[i] = cap.read() # guarantee first frame
291 + thread = Thread(target=self.update, args=([i, cap]), daemon=True)
292 + print(f' success ({w}x{h} at {self.fps:.2f} FPS).')
293 + thread.start()
294 + print('') # newline
295 +
296 + # check for common shapes
297 + s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
298 + self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
299 + if not self.rect:
300 + print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
301 +
302 + def update(self, index, cap):
303 + # Read next stream frame in a daemon thread
304 + n = 0
305 + while cap.isOpened():
306 + n += 1
307 + # _, self.imgs[index] = cap.read()
308 + cap.grab()
309 + if n == 4: # read every 4th frame
310 + success, im = cap.retrieve()
311 + self.imgs[index] = im if success else self.imgs[index] * 0
312 + n = 0
313 + time.sleep(1 / self.fps) # wait time
314 +
315 + def __iter__(self):
316 + self.count = -1
317 + return self
318 +
319 + def __next__(self):
320 + self.count += 1
321 + img0 = self.imgs.copy()
322 + if cv2.waitKey(1) == ord('q'): # q to quit
323 + cv2.destroyAllWindows()
324 + raise StopIteration
325 +
326 + # Letterbox
327 + img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
328 +
329 + # Stack
330 + img = np.stack(img, 0)
331 +
332 + # Convert
333 + img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
334 + img = np.ascontiguousarray(img)
335 +
336 + return self.sources, img, img0, None
337 +
338 + def __len__(self):
339 + return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
340 +
341 +
342 +def img2label_paths(img_paths):
343 + # Define label paths as a function of image paths
344 + sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
345 + return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths]
346 +
347 +
348 +class LoadImagesAndLabels(Dataset): # for training/testing
349 + def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
350 + cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
351 + self.img_size = img_size
352 + self.augment = augment
353 + self.hyp = hyp
354 + self.image_weights = image_weights
355 + self.rect = False if image_weights else rect
356 + self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
357 + self.mosaic_border = [-img_size // 2, -img_size // 2]
358 + self.stride = stride
359 + self.path = path
360 +
361 + try:
362 + f = [] # image files
363 + for p in path if isinstance(path, list) else [path]:
364 + p = Path(p) # os-agnostic
365 + if p.is_dir(): # dir
366 + f += glob.glob(str(p / '**' / '*.*'), recursive=True)
367 + # f = list(p.rglob('**/*.*')) # pathlib
368 + elif p.is_file(): # file
369 + with open(p, 'r') as t:
370 + t = t.read().strip().splitlines()
371 + parent = str(p.parent) + os.sep
372 + f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
373 + # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
374 + else:
375 + raise Exception(f'{prefix}{p} does not exist')
376 + self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
377 + # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
378 + assert self.img_files, f'{prefix}No images found'
379 + except Exception as e:
380 + raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
381 +
382 + # Check cache
383 + self.label_files = img2label_paths(self.img_files) # labels
384 + cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
385 + if cache_path.is_file():
386 + with yolov5_in_syspath():
387 + cache, exists = torch.load(cache_path), True # load
388 + if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed
389 + cache, exists = self.cache_labels(cache_path, prefix), False # re-cache
390 + else:
391 + cache, exists = self.cache_labels(cache_path, prefix), False # cache
392 +
393 + # Display cache
394 + nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
395 + if exists:
396 + d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
397 + tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
398 + assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
399 +
400 + # Read cache
401 + cache.pop('hash') # remove hash
402 + cache.pop('version') # remove version
403 + labels, shapes, self.segments = zip(*cache.values())
404 + self.labels = list(labels)
405 + self.shapes = np.array(shapes, dtype=np.float64)
406 + self.img_files = list(cache.keys()) # update
407 + self.label_files = img2label_paths(cache.keys()) # update
408 + if single_cls:
409 + for x in self.labels:
410 + x[:, 0] = 0
411 +
412 + n = len(shapes) # number of images
413 + bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
414 + nb = bi[-1] + 1 # number of batches
415 + self.batch = bi # batch index of image
416 + self.n = n
417 + self.indices = range(n)
418 +
419 + # Rectangular Training
420 + if self.rect:
421 + # Sort by aspect ratio
422 + s = self.shapes # wh
423 + ar = s[:, 1] / s[:, 0] # aspect ratio
424 + irect = ar.argsort()
425 + self.img_files = [self.img_files[i] for i in irect]
426 + self.label_files = [self.label_files[i] for i in irect]
427 + self.labels = [self.labels[i] for i in irect]
428 + self.shapes = s[irect] # wh
429 + ar = ar[irect]
430 +
431 + # Set training image shapes
432 + shapes = [[1, 1]] * nb
433 + for i in range(nb):
434 + ari = ar[bi == i]
435 + mini, maxi = ari.min(), ari.max()
436 + if maxi < 1:
437 + shapes[i] = [maxi, 1]
438 + elif mini > 1:
439 + shapes[i] = [1, 1 / mini]
440 +
441 + self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
442 +
443 + # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
444 + self.imgs = [None] * n
445 + if cache_images:
446 + gb = 0 # Gigabytes of cached images
447 + self.img_hw0, self.img_hw = [None] * n, [None] * n
448 + results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) # 8 threads
449 + pbar = tqdm(enumerate(results), total=n)
450 + for i, x in pbar:
451 + self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i)
452 + gb += self.imgs[i].nbytes
453 + pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
454 + pbar.close()
455 +
456 + def cache_labels(self, path=Path('./labels.cache'), prefix=''):
457 + # Cache dataset labels, check images and read shapes
458 + x = {} # dict
459 + nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
460 + pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
461 + for i, (im_file, lb_file) in enumerate(pbar):
462 + try:
463 + # verify images
464 + im = Image.open(im_file)
465 + im.verify() # PIL verify
466 + shape = exif_size(im) # image size
467 + segments = [] # instance segments
468 + assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
469 + assert im.format.lower() in img_formats, f'invalid image format {im.format}'
470 +
471 + # verify labels
472 + if os.path.isfile(lb_file):
473 + nf += 1 # label found
474 + with open(lb_file, 'r') as f:
475 + l = [x.split() for x in f.read().strip().splitlines()]
476 + if any([len(x) > 8 for x in l]): # is segment
477 + classes = np.array([x[0] for x in l], dtype=np.float32)
478 + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
479 + l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
480 + l = np.array(l, dtype=np.float32)
481 + if len(l):
482 + assert l.shape[1] == 5, 'labels require 5 columns each'
483 + assert (l >= 0).all(), 'negative labels'
484 + assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
485 + assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
486 + else:
487 + ne += 1 # label empty
488 + l = np.zeros((0, 5), dtype=np.float32)
489 + else:
490 + nm += 1 # label missing
491 + l = np.zeros((0, 5), dtype=np.float32)
492 + x[im_file] = [l, shape, segments]
493 + except Exception as e:
494 + nc += 1
495 + logging.info(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')
496 +
497 + pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \
498 + f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
499 + pbar.close()
500 +
501 + if nf == 0:
502 + logging.info(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
503 +
504 + x['hash'] = get_hash(self.label_files + self.img_files)
505 + x['results'] = nf, nm, ne, nc, i + 1
506 + x['version'] = 0.1 # cache version
507 + try:
508 + with yolov5_in_syspath():
509 + torch.save(x, path) # save for next time
510 + logging.info(f'{prefix}New cache created: {path}')
511 + except Exception as e:
512 + logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable
513 + return x
514 +
515 + def __len__(self):
516 + return len(self.img_files)
517 +
518 + # def __iter__(self):
519 + # self.count = -1
520 + # print('ran dataset iter')
521 + # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
522 + # return self
523 +
524 + def __getitem__(self, index):
525 + index = self.indices[index] # linear, shuffled, or image_weights
526 +
527 + hyp = self.hyp
528 + mosaic = self.mosaic and random.random() < hyp['mosaic']
529 + if mosaic:
530 + # Load mosaic
531 + img, labels = load_mosaic(self, index)
532 + shapes = None
533 +
534 + # MixUp https://arxiv.org/pdf/1710.09412.pdf
535 + if random.random() < hyp['mixup']:
536 + img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))
537 + r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
538 + img = (img * r + img2 * (1 - r)).astype(np.uint8)
539 + labels = np.concatenate((labels, labels2), 0)
540 +
541 + else:
542 + # Load image
543 + img, (h0, w0), (h, w) = load_image(self, index)
544 +
545 + # Letterbox
546 + shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
547 + img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
548 + shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
549 +
550 + labels = self.labels[index].copy()
551 + if labels.size: # normalized xywh to pixel xyxy format
552 + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
553 +
554 + if self.augment:
555 + # Augment imagespace
556 + if not mosaic:
557 + img, labels = random_perspective(img, labels,
558 + degrees=hyp['degrees'],
559 + translate=hyp['translate'],
560 + scale=hyp['scale'],
561 + shear=hyp['shear'],
562 + perspective=hyp['perspective'])
563 +
564 + # Augment colorspace
565 + augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
566 +
567 + # Apply cutouts
568 + # if random.random() < 0.9:
569 + # labels = cutout(img, labels)
570 +
571 + nL = len(labels) # number of labels
572 + if nL:
573 + labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
574 + labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
575 + labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
576 +
577 + if self.augment:
578 + # flip up-down
579 + if random.random() < hyp['flipud']:
580 + img = np.flipud(img)
581 + if nL:
582 + labels[:, 2] = 1 - labels[:, 2]
583 +
584 + # flip left-right
585 + if random.random() < hyp['fliplr']:
586 + img = np.fliplr(img)
587 + if nL:
588 + labels[:, 1] = 1 - labels[:, 1]
589 +
590 + labels_out = torch.zeros((nL, 6))
591 + if nL:
592 + labels_out[:, 1:] = torch.from_numpy(labels)
593 +
594 + # Convert
595 + img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
596 + img = np.ascontiguousarray(img)
597 +
598 + return torch.from_numpy(img), labels_out, self.img_files[index], shapes
599 +
600 + @staticmethod
601 + def collate_fn(batch):
602 + img, label, path, shapes = zip(*batch) # transposed
603 + for i, l in enumerate(label):
604 + l[:, 0] = i # add target image index for build_targets()
605 + return torch.stack(img, 0), torch.cat(label, 0), path, shapes
606 +
607 + @staticmethod
608 + def collate_fn4(batch):
609 + img, label, path, shapes = zip(*batch) # transposed
610 + n = len(shapes) // 4
611 + img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
612 +
613 + ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
614 + wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
615 + s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
616 + for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
617 + i *= 4
618 + if random.random() < 0.5:
619 + im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
620 + 0].type(img[i].type())
621 + l = label[i]
622 + else:
623 + im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
624 + l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
625 + img4.append(im)
626 + label4.append(l)
627 +
628 + for i, l in enumerate(label4):
629 + l[:, 0] = i # add target image index for build_targets()
630 +
631 + return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
632 +
633 +
634 +# Ancillary functions --------------------------------------------------------------------------------------------------
635 +def load_image(self, index):
636 + # loads 1 image from dataset, returns img, original hw, resized hw
637 + img = self.imgs[index]
638 + if img is None: # not cached
639 + path = self.img_files[index]
640 + img = cv2.imread(path) # BGR
641 + assert img is not None, 'Image Not Found ' + path
642 + h0, w0 = img.shape[:2] # orig hw
643 + r = self.img_size / max(h0, w0) # ratio
644 + if r != 1: # if sizes are not equal
645 + img = cv2.resize(img, (int(w0 * r), int(h0 * r)),
646 + interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
647 + return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
648 + else:
649 + return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
650 +
651 +
652 +def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
653 + r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
654 + hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
655 + dtype = img.dtype # uint8
656 +
657 + x = np.arange(0, 256, dtype=np.int16)
658 + lut_hue = ((x * r[0]) % 180).astype(dtype)
659 + lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
660 + lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
661 +
662 + img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
663 + cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
664 +
665 +
666 +def hist_equalize(img, clahe=True, bgr=False):
667 + # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
668 + yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
669 + if clahe:
670 + c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
671 + yuv[:, :, 0] = c.apply(yuv[:, :, 0])
672 + else:
673 + yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
674 + return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
675 +
676 +
677 +def load_mosaic(self, index):
678 + # loads images in a 4-mosaic
679 +
680 + labels4, segments4 = [], []
681 + s = self.img_size
682 + yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
683 + indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
684 + for i, index in enumerate(indices):
685 + # Load image
686 + img, _, (h, w) = load_image(self, index)
687 +
688 + # place img in img4
689 + if i == 0: # top left
690 + img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
691 + x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
692 + x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
693 + elif i == 1: # top right
694 + x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
695 + x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
696 + elif i == 2: # bottom left
697 + x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
698 + x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
699 + elif i == 3: # bottom right
700 + x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
701 + x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
702 +
703 + img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
704 + padw = x1a - x1b
705 + padh = y1a - y1b
706 +
707 + # Labels
708 + labels, segments = self.labels[index].copy(), self.segments[index].copy()
709 + if labels.size:
710 + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
711 + segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
712 + labels4.append(labels)
713 + segments4.extend(segments)
714 +
715 + # Concat/clip labels
716 + labels4 = np.concatenate(labels4, 0)
717 + for x in (labels4[:, 1:], *segments4):
718 + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
719 + # img4, labels4 = replicate(img4, labels4) # replicate
720 +
721 + # Augment
722 + img4, labels4 = random_perspective(img4, labels4, segments4,
723 + degrees=self.hyp['degrees'],
724 + translate=self.hyp['translate'],
725 + scale=self.hyp['scale'],
726 + shear=self.hyp['shear'],
727 + perspective=self.hyp['perspective'],
728 + border=self.mosaic_border) # border to remove
729 +
730 + return img4, labels4
731 +
732 +
733 +def load_mosaic9(self, index):
734 + # loads images in a 9-mosaic
735 +
736 + labels9, segments9 = [], []
737 + s = self.img_size
738 + indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
739 + for i, index in enumerate(indices):
740 + # Load image
741 + img, _, (h, w) = load_image(self, index)
742 +
743 + # place img in img9
744 + if i == 0: # center
745 + img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
746 + h0, w0 = h, w
747 + c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
748 + elif i == 1: # top
749 + c = s, s - h, s + w, s
750 + elif i == 2: # top right
751 + c = s + wp, s - h, s + wp + w, s
752 + elif i == 3: # right
753 + c = s + w0, s, s + w0 + w, s + h
754 + elif i == 4: # bottom right
755 + c = s + w0, s + hp, s + w0 + w, s + hp + h
756 + elif i == 5: # bottom
757 + c = s + w0 - w, s + h0, s + w0, s + h0 + h
758 + elif i == 6: # bottom left
759 + c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
760 + elif i == 7: # left
761 + c = s - w, s + h0 - h, s, s + h0
762 + elif i == 8: # top left
763 + c = s - w, s + h0 - hp - h, s, s + h0 - hp
764 +
765 + padx, pady = c[:2]
766 + x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
767 +
768 + # Labels
769 + labels, segments = self.labels[index].copy(), self.segments[index].copy()
770 + if labels.size:
771 + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
772 + segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
773 + labels9.append(labels)
774 + segments9.extend(segments)
775 +
776 + # Image
777 + img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
778 + hp, wp = h, w # height, width previous
779 +
780 + # Offset
781 + yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
782 + img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
783 +
784 + # Concat/clip labels
785 + labels9 = np.concatenate(labels9, 0)
786 + labels9[:, [1, 3]] -= xc
787 + labels9[:, [2, 4]] -= yc
788 + c = np.array([xc, yc]) # centers
789 + segments9 = [x - c for x in segments9]
790 +
791 + for x in (labels9[:, 1:], *segments9):
792 + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
793 + # img9, labels9 = replicate(img9, labels9) # replicate
794 +
795 + # Augment
796 + img9, labels9 = random_perspective(img9, labels9, segments9,
797 + degrees=self.hyp['degrees'],
798 + translate=self.hyp['translate'],
799 + scale=self.hyp['scale'],
800 + shear=self.hyp['shear'],
801 + perspective=self.hyp['perspective'],
802 + border=self.mosaic_border) # border to remove
803 +
804 + return img9, labels9
805 +
806 +
807 +def replicate(img, labels):
808 + # Replicate labels
809 + h, w = img.shape[:2]
810 + boxes = labels[:, 1:].astype(int)
811 + x1, y1, x2, y2 = boxes.T
812 + s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
813 + for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
814 + x1b, y1b, x2b, y2b = boxes[i]
815 + bh, bw = y2b - y1b, x2b - x1b
816 + yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
817 + x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
818 + img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
819 + labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
820 +
821 + return img, labels
822 +
823 +
824 +def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
825 + # Resize and pad image while meeting stride-multiple constraints
826 + shape = img.shape[:2] # current shape [height, width]
827 + if isinstance(new_shape, int):
828 + new_shape = (new_shape, new_shape)
829 +
830 + # Scale ratio (new / old)
831 + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
832 + if not scaleup: # only scale down, do not scale up (for better test mAP)
833 + r = min(r, 1.0)
834 +
835 + # Compute padding
836 + ratio = r, r # width, height ratios
837 + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
838 + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
839 + if auto: # minimum rectangle
840 + dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
841 + elif scaleFill: # stretch
842 + dw, dh = 0.0, 0.0
843 + new_unpad = (new_shape[1], new_shape[0])
844 + ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
845 +
846 + dw /= 2 # divide padding into 2 sides
847 + dh /= 2
848 +
849 + if shape[::-1] != new_unpad: # resize
850 + img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
851 + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
852 + left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
853 + img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
854 + return img, ratio, (dw, dh)
855 +
856 +
857 +def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
858 + border=(0, 0)):
859 + # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
860 + # targets = [cls, xyxy]
861 +
862 + height = img.shape[0] + border[0] * 2 # shape(h,w,c)
863 + width = img.shape[1] + border[1] * 2
864 +
865 + # Center
866 + C = np.eye(3)
867 + C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
868 + C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
869 +
870 + # Perspective
871 + P = np.eye(3)
872 + P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
873 + P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
874 +
875 + # Rotation and Scale
876 + R = np.eye(3)
877 + a = random.uniform(-degrees, degrees)
878 + # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
879 + s = random.uniform(1 - scale, 1 + scale)
880 + # s = 2 ** random.uniform(-scale, scale)
881 + R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
882 +
883 + # Shear
884 + S = np.eye(3)
885 + S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
886 + S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
887 +
888 + # Translation
889 + T = np.eye(3)
890 + T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
891 + T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
892 +
893 + # Combined rotation matrix
894 + M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
895 + if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
896 + if perspective:
897 + img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
898 + else: # affine
899 + img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
900 +
901 + # Visualize
902 + # import matplotlib.pyplot as plt
903 + # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
904 + # ax[0].imshow(img[:, :, ::-1]) # base
905 + # ax[1].imshow(img2[:, :, ::-1]) # warped
906 +
907 + # Transform label coordinates
908 + n = len(targets)
909 + if n:
910 + use_segments = any(x.any() for x in segments)
911 + new = np.zeros((n, 4))
912 + if use_segments: # warp segments
913 + segments = resample_segments(segments) # upsample
914 + for i, segment in enumerate(segments):
915 + xy = np.ones((len(segment), 3))
916 + xy[:, :2] = segment
917 + xy = xy @ M.T # transform
918 + xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
919 +
920 + # clip
921 + new[i] = segment2box(xy, width, height)
922 +
923 + else: # warp boxes
924 + xy = np.ones((n * 4, 3))
925 + xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
926 + xy = xy @ M.T # transform
927 + xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
928 +
929 + # create new boxes
930 + x = xy[:, [0, 2, 4, 6]]
931 + y = xy[:, [1, 3, 5, 7]]
932 + new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
933 +
934 + # clip
935 + new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
936 + new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
937 +
938 + # filter candidates
939 + i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
940 + targets = targets[i]
941 + targets[:, 1:5] = new[i]
942 +
943 + return img, targets
944 +
945 +
946 +def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
947 + # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
948 + w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
949 + w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
950 + ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
951 + return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
952 +
953 +
954 +def cutout(image, labels):
955 + # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
956 + h, w = image.shape[:2]
957 +
958 + def bbox_ioa(box1, box2):
959 + # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
960 + box2 = box2.transpose()
961 +
962 + # Get the coordinates of bounding boxes
963 + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
964 + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
965 +
966 + # Intersection area
967 + inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
968 + (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
969 +
970 + # box2 area
971 + box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
972 +
973 + # Intersection over box2 area
974 + return inter_area / box2_area
975 +
976 + # create random masks
977 + scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
978 + for s in scales:
979 + mask_h = random.randint(1, int(h * s))
980 + mask_w = random.randint(1, int(w * s))
981 +
982 + # box
983 + xmin = max(0, random.randint(0, w) - mask_w // 2)
984 + ymin = max(0, random.randint(0, h) - mask_h // 2)
985 + xmax = min(w, xmin + mask_w)
986 + ymax = min(h, ymin + mask_h)
987 +
988 + # apply random color mask
989 + image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
990 +
991 + # return unobscured labels
992 + if len(labels) and s > 0.03:
993 + box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
994 + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
995 + labels = labels[ioa < 0.60] # remove >60% obscured labels
996 +
997 + return labels
998 +
999 +
1000 +def create_folder(path='./new'):
1001 + # Create folder
1002 + if os.path.exists(path):
1003 + shutil.rmtree(path) # delete output folder
1004 + os.makedirs(path) # make new output folder
1005 +
1006 +
1007 +def flatten_recursive(path='../coco128'):
1008 + # Flatten a recursive directory by bringing all files to top level
1009 + new_path = Path(path + '_flat')
1010 + create_folder(new_path)
1011 + for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
1012 + shutil.copyfile(file, new_path / Path(file).name)
1013 +
1014 +
1015 +def extract_boxes(path='../coco128/'): # from utils.datasets import *; extract_boxes('../coco128')
1016 + # Convert detection dataset into classification dataset, with one directory per class
1017 +
1018 + path = Path(path) # images dir
1019 + shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
1020 + files = list(path.rglob('*.*'))
1021 + n = len(files) # number of files
1022 + for im_file in tqdm(files, total=n):
1023 + if im_file.suffix[1:] in img_formats:
1024 + # image
1025 + im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
1026 + h, w = im.shape[:2]
1027 +
1028 + # labels
1029 + lb_file = Path(img2label_paths([str(im_file)])[0])
1030 + if Path(lb_file).exists():
1031 + with open(lb_file, 'r') as f:
1032 + lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
1033 +
1034 + for j, x in enumerate(lb):
1035 + c = int(x[0]) # class
1036 + f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
1037 + if not f.parent.is_dir():
1038 + f.parent.mkdir(parents=True)
1039 +
1040 + b = x[1:] * [w, h, w, h] # box
1041 + # b[2:] = b[2:].max() # rectangle to square
1042 + b[2:] = b[2:] * 1.2 + 3 # pad
1043 + b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
1044 +
1045 + b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
1046 + b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
1047 + assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
1048 +
1049 +
1050 +def autosplit(path='../coco128', weights=(0.9, 0.1, 0.0), annotated_only=False):
1051 + """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
1052 + Usage: from utils.datasets import *; autosplit('../coco128')
1053 + Arguments
1054 + path: Path to images directory
1055 + weights: Train, val, test weights (list)
1056 + annotated_only: Only use images with an annotated txt file
1057 + """
1058 + path = Path(path) # images dir
1059 + files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only
1060 + n = len(files) # number of files
1061 + indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
1062 +
1063 + txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
1064 + [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing
1065 +
1066 + print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
1067 + for i, img in tqdm(zip(indices, files), total=n):
1068 + if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
1069 + with open(path / txt[i], 'a') as f:
1070 + f.write(str(img) + '\n') # add image to txt file
1 +# YOLOv5 general utils
2 +import glob
3 +import logging
4 +import math
5 +import os
6 +import platform
7 +import random
8 +import re
9 +import subprocess
10 +import time
11 +from contextlib import contextmanager
12 +from itertools import repeat
13 +from multiprocessing.pool import ThreadPool
14 +from pathlib import Path
15 +
16 +import cv2
17 +import numpy as np
18 +import pandas as pd
19 +import pkg_resources as pkg
20 +import torch
21 +import torchvision
22 +import yaml
23 +from yolo_module.yolov5.utils.google_utils import gsutil_getsize
24 +from yolo_module.yolov5.utils.metrics import fitness
25 +from yolo_module.yolov5.utils.torch_utils import init_torch_seeds
26 +
27 +# Settings
28 +torch.set_printoptions(linewidth=320, precision=5, profile='long')
29 +np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
30 +pd.options.display.max_columns = 10
31 +cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
32 +os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads
33 +
34 +
35 +def set_logging(rank=-1, verbose=True):
36 + logging.basicConfig(
37 + format="%(message)s",
38 + level=logging.INFO if (verbose and rank in [-1, 0]) else logging.WARN)
39 +
40 +
41 +def init_seeds(seed=0):
42 + # Initialize random number generator (RNG) seeds
43 + random.seed(seed)
44 + np.random.seed(seed)
45 + init_torch_seeds(seed)
46 +
47 +
48 +def get_latest_run(search_dir='.'):
49 + # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
50 + last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
51 + return max(last_list, key=os.path.getctime) if last_list else ''
52 +
53 +
54 +def is_docker():
55 + # Is environment a Docker container
56 + return Path('/workspace').exists() # or Path('/.dockerenv').exists()
57 +
58 +
59 +def is_colab():
60 + # Is environment a Google Colab instance
61 + try:
62 + import google.colab
63 + return True
64 + except Exception as e:
65 + return False
66 +
67 +
68 +def emojis(str=''):
69 + # Return platform-dependent emoji-safe version of string
70 + return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
71 +
72 +
73 +def file_size(file):
74 + # Return file size in MB
75 + return Path(file).stat().st_size / 1e6
76 +
77 +
78 +def check_online():
79 + # Check internet connectivity
80 + import socket
81 + try:
82 + socket.create_connection(("1.1.1.1", 443), 5) # check host accesability
83 + return True
84 + except OSError:
85 + return False
86 +
87 +
88 +def check_git_status():
89 + # Recommend 'git pull' if code is out of date
90 + print(colorstr('github: '), end='')
91 + try:
92 + assert Path('.git').exists(), 'skipping check (not a git repository)'
93 + assert not is_docker(), 'skipping check (Docker image)'
94 + assert check_online(), 'skipping check (offline)'
95 +
96 + cmd = 'git fetch && git config --get remote.origin.url'
97 + url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url
98 + branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
99 + n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind
100 + if n > 0:
101 + s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \
102 + f"Use 'git pull' to update or 'git clone {url}' to download latest."
103 + else:
104 + s = f'up to date with {url} ✅'
105 + print(emojis(s)) # emoji-safe
106 + except Exception as e:
107 + print(e)
108 +
109 +
110 +def check_python(minimum='3.7.0', required=True):
111 + # Check current python version vs. required python version
112 + current = platform.python_version()
113 + result = pkg.parse_version(current) >= pkg.parse_version(minimum)
114 + if required:
115 + assert result, f'Python {minimum} required by YOLOv5, but Python {current} is currently installed'
116 + return result
117 +
118 +
119 +def check_requirements(requirements='requirements.txt', exclude=()):
120 + # Check installed dependencies meet requirements (pass *.txt file or list of packages)
121 + prefix = colorstr('red', 'bold', 'requirements:')
122 + check_python() # check python version
123 + if isinstance(requirements, (str, Path)): # requirements.txt file
124 + file = Path(requirements)
125 + if not file.exists():
126 + print(f"{prefix} {file.resolve()} not found, check failed.")
127 + return
128 + requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(file.open()) if x.name not in exclude]
129 + else: # list or tuple of packages
130 + requirements = [x for x in requirements if x not in exclude]
131 +
132 + n = 0 # number of packages updates
133 + for r in requirements:
134 + try:
135 + pkg.require(r)
136 + except Exception as e: # DistributionNotFound or VersionConflict if requirements not met
137 + n += 1
138 + print(f"{prefix} {r} not found and is required by YOLOv5, attempting auto-update...")
139 + print(subprocess.check_output(f"pip install '{r}'", shell=True).decode())
140 +
141 + if n: # if packages updated
142 + source = file.resolve() if 'file' in locals() else requirements
143 + s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
144 + f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
145 + print(emojis(s)) # emoji-safe
146 +
147 +
148 +def check_img_size(img_size, s=32):
149 + # Verify img_size is a multiple of stride s
150 + new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
151 + if new_size != img_size:
152 + print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))
153 + return new_size
154 +
155 +
156 +def check_imshow():
157 + # Check if environment supports image displays
158 + try:
159 + assert not is_docker(), 'cv2.imshow() is disabled in Docker environments'
160 + assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments'
161 + cv2.imshow('test', np.zeros((1, 1, 3)))
162 + cv2.waitKey(1)
163 + cv2.destroyAllWindows()
164 + cv2.waitKey(1)
165 + return True
166 + except Exception as e:
167 + print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')
168 + return False
169 +
170 +
171 +def check_file(file):
172 + # Search for file if not found
173 + if Path(file).is_file() or file == '':
174 + return file
175 + else:
176 + files = glob.glob('./**/' + file, recursive=True) # find file
177 + assert len(files), f'File Not Found: {file}' # assert file was found
178 + assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
179 + return files[0] # return file
180 +
181 +
182 +def check_dataset(dict):
183 + # Download dataset if not found locally
184 + val, s = dict.get('val'), dict.get('download')
185 + if val and len(val):
186 + val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
187 + if not all(x.exists() for x in val):
188 + print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])
189 + if s and len(s): # download script
190 + if s.startswith('http') and s.endswith('.zip'): # URL
191 + f = Path(s).name # filename
192 + print(f'Downloading {s} ...')
193 + torch.hub.download_url_to_file(s, f)
194 + r = os.system(f'unzip -q {f} -d ../ && rm {f}') # unzip
195 + elif s.startswith('bash '): # bash script
196 + print(f'Running {s} ...')
197 + r = os.system(s)
198 + else: # python script
199 + r = exec(s) # return None
200 + print('Dataset autodownload %s\n' % ('success' if r in (0, None) else 'failure')) # print result
201 + else:
202 + raise Exception('Dataset not found.')
203 +
204 +
205 +def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1):
206 + # Multi-threaded file download and unzip function
207 + def download_one(url, dir):
208 + # Download 1 file
209 + f = dir / Path(url).name # filename
210 + if not f.exists():
211 + print(f'Downloading {url} to {f}...')
212 + if curl:
213 + os.system(f"curl -L '{url}' -o '{f}' --retry 9 -C -") # curl download, retry and resume on fail
214 + else:
215 + torch.hub.download_url_to_file(url, f, progress=True) # torch download
216 + if unzip and f.suffix in ('.zip', '.gz'):
217 + print(f'Unzipping {f}...')
218 + if f.suffix == '.zip':
219 + s = f'unzip -qo {f} -d {dir} && rm {f}' # unzip -quiet -overwrite
220 + elif f.suffix == '.gz':
221 + s = f'tar xfz {f} --directory {f.parent}' # unzip
222 + if delete: # delete zip file after unzip
223 + s += f' && rm {f}'
224 + os.system(s)
225 +
226 + dir = Path(dir)
227 + dir.mkdir(parents=True, exist_ok=True) # make directory
228 + if threads > 1:
229 + pool = ThreadPool(threads)
230 + pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded
231 + pool.close()
232 + pool.join()
233 + else:
234 + for u in tuple(url) if isinstance(url, str) else url:
235 + download_one(u, dir)
236 +
237 +
238 +def make_divisible(x, divisor):
239 + # Returns x evenly divisible by divisor
240 + return math.ceil(x / divisor) * divisor
241 +
242 +
243 +def clean_str(s):
244 + # Cleans a string by replacing special characters with underscore _
245 + return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
246 +
247 +
248 +def one_cycle(y1=0.0, y2=1.0, steps=100):
249 + # lambda function for sinusoidal ramp from y1 to y2
250 + return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
251 +
252 +
253 +def colorstr(*input):
254 + # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
255 + *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
256 + colors = {'black': '\033[30m', # basic colors
257 + 'red': '\033[31m',
258 + 'green': '\033[32m',
259 + 'yellow': '\033[33m',
260 + 'blue': '\033[34m',
261 + 'magenta': '\033[35m',
262 + 'cyan': '\033[36m',
263 + 'white': '\033[37m',
264 + 'bright_black': '\033[90m', # bright colors
265 + 'bright_red': '\033[91m',
266 + 'bright_green': '\033[92m',
267 + 'bright_yellow': '\033[93m',
268 + 'bright_blue': '\033[94m',
269 + 'bright_magenta': '\033[95m',
270 + 'bright_cyan': '\033[96m',
271 + 'bright_white': '\033[97m',
272 + 'end': '\033[0m', # misc
273 + 'bold': '\033[1m',
274 + 'underline': '\033[4m'}
275 + return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
276 +
277 +
278 +def labels_to_class_weights(labels, nc=80):
279 + # Get class weights (inverse frequency) from training labels
280 + if labels[0] is None: # no labels loaded
281 + return torch.Tensor()
282 +
283 + labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
284 + classes = labels[:, 0].astype(np.int) # labels = [class xywh]
285 + weights = np.bincount(classes, minlength=nc) # occurrences per class
286 +
287 + # Prepend gridpoint count (for uCE training)
288 + # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
289 + # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
290 +
291 + weights[weights == 0] = 1 # replace empty bins with 1
292 + weights = 1 / weights # number of targets per class
293 + weights /= weights.sum() # normalize
294 + return torch.from_numpy(weights)
295 +
296 +
297 +def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
298 + # Produces image weights based on class_weights and image contents
299 + class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])
300 + image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
301 + # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
302 + return image_weights
303 +
304 +
305 +def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
306 + # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
307 + # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
308 + # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
309 + # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
310 + # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
311 + x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
312 + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
313 + 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
314 + return x
315 +
316 +
317 +def xyxy2xywh(x):
318 + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
319 + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
320 + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
321 + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
322 + y[:, 2] = x[:, 2] - x[:, 0] # width
323 + y[:, 3] = x[:, 3] - x[:, 1] # height
324 + return y
325 +
326 +
327 +def xywh2xyxy(x):
328 + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
329 + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
330 + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
331 + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
332 + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
333 + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
334 + return y
335 +
336 +
337 +def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
338 + # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
339 + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
340 + y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
341 + y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
342 + y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
343 + y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
344 + return y
345 +
346 +
347 +def xyn2xy(x, w=640, h=640, padw=0, padh=0):
348 + # Convert normalized segments into pixel segments, shape (n,2)
349 + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
350 + y[:, 0] = w * x[:, 0] + padw # top left x
351 + y[:, 1] = h * x[:, 1] + padh # top left y
352 + return y
353 +
354 +
355 +def segment2box(segment, width=640, height=640):
356 + # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
357 + x, y = segment.T # segment xy
358 + inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
359 + x, y, = x[inside], y[inside]
360 + return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
361 +
362 +
363 +def segments2boxes(segments):
364 + # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
365 + boxes = []
366 + for s in segments:
367 + x, y = s.T # segment xy
368 + boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
369 + return xyxy2xywh(np.array(boxes)) # cls, xywh
370 +
371 +
372 +def resample_segments(segments, n=1000):
373 + # Up-sample an (n,2) segment
374 + for i, s in enumerate(segments):
375 + x = np.linspace(0, len(s) - 1, n)
376 + xp = np.arange(len(s))
377 + segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
378 + return segments
379 +
380 +
381 +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
382 + # Rescale coords (xyxy) from img1_shape to img0_shape
383 + if ratio_pad is None: # calculate from img0_shape
384 + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
385 + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
386 + else:
387 + gain = ratio_pad[0][0]
388 + pad = ratio_pad[1]
389 +
390 + coords[:, [0, 2]] -= pad[0] # x padding
391 + coords[:, [1, 3]] -= pad[1] # y padding
392 + coords[:, :4] /= gain
393 + clip_coords(coords, img0_shape)
394 + return coords
395 +
396 +
397 +def clip_coords(boxes, img_shape):
398 + # Clip bounding xyxy bounding boxes to image shape (height, width)
399 + boxes[:, 0].clamp_(0, img_shape[1]) # x1
400 + boxes[:, 1].clamp_(0, img_shape[0]) # y1
401 + boxes[:, 2].clamp_(0, img_shape[1]) # x2
402 + boxes[:, 3].clamp_(0, img_shape[0]) # y2
403 +
404 +
405 +def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
406 + # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
407 + box2 = box2.T
408 +
409 + # Get the coordinates of bounding boxes
410 + if x1y1x2y2: # x1, y1, x2, y2 = box1
411 + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
412 + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
413 + else: # transform from xywh to xyxy
414 + b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
415 + b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
416 + b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
417 + b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
418 +
419 + # Intersection area
420 + inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
421 + (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
422 +
423 + # Union Area
424 + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
425 + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
426 + union = w1 * h1 + w2 * h2 - inter + eps
427 +
428 + iou = inter / union
429 + if GIoU or DIoU or CIoU:
430 + cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
431 + ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
432 + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
433 + c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
434 + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
435 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared
436 + if DIoU:
437 + return iou - rho2 / c2 # DIoU
438 + elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
439 + v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
440 + with torch.no_grad():
441 + alpha = v / (v - iou + (1 + eps))
442 + return iou - (rho2 / c2 + v * alpha) # CIoU
443 + else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
444 + c_area = cw * ch + eps # convex area
445 + return iou - (c_area - union) / c_area # GIoU
446 + else:
447 + return iou # IoU
448 +
449 +
450 +def box_iou(box1, box2):
451 + # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
452 + """
453 + Return intersection-over-union (Jaccard index) of boxes.
454 + Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
455 + Arguments:
456 + box1 (Tensor[N, 4])
457 + box2 (Tensor[M, 4])
458 + Returns:
459 + iou (Tensor[N, M]): the NxM matrix containing the pairwise
460 + IoU values for every element in boxes1 and boxes2
461 + """
462 +
463 + def box_area(box):
464 + # box = 4xn
465 + return (box[2] - box[0]) * (box[3] - box[1])
466 +
467 + area1 = box_area(box1.T)
468 + area2 = box_area(box2.T)
469 +
470 + # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
471 + inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
472 + return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
473 +
474 +
475 +def wh_iou(wh1, wh2):
476 + # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
477 + wh1 = wh1[:, None] # [N,1,2]
478 + wh2 = wh2[None] # [1,M,2]
479 + inter = torch.min(wh1, wh2).prod(2) # [N,M]
480 + return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
481 +
482 +
483 +def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
484 + labels=()):
485 + """Runs Non-Maximum Suppression (NMS) on inference results
486 +
487 + Returns:
488 + list of detections, on (n,6) tensor per image [xyxy, conf, cls]
489 + """
490 +
491 + nc = prediction.shape[2] - 5 # number of classes
492 + xc = prediction[..., 4] > conf_thres # candidates
493 +
494 + # Checks
495 + assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
496 + assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
497 +
498 + # Settings
499 + min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
500 + max_det = 300 # maximum number of detections per image
501 + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
502 + time_limit = 10.0 # seconds to quit after
503 + redundant = True # require redundant detections
504 + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
505 + merge = False # use merge-NMS
506 +
507 + t = time.time()
508 + output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
509 + for xi, x in enumerate(prediction): # image index, image inference
510 + # Apply constraints
511 + # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
512 + x = x[xc[xi]] # confidence
513 +
514 + # Cat apriori labels if autolabelling
515 + if labels and len(labels[xi]):
516 + l = labels[xi]
517 + v = torch.zeros((len(l), nc + 5), device=x.device)
518 + v[:, :4] = l[:, 1:5] # box
519 + v[:, 4] = 1.0 # conf
520 + v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
521 + x = torch.cat((x, v), 0)
522 +
523 + # If none remain process next image
524 + if not x.shape[0]:
525 + continue
526 +
527 + # Compute conf
528 + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
529 +
530 + # Box (center x, center y, width, height) to (x1, y1, x2, y2)
531 + box = xywh2xyxy(x[:, :4])
532 +
533 + # Detections matrix nx6 (xyxy, conf, cls)
534 + if multi_label:
535 + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
536 + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
537 + else: # best class only
538 + conf, j = x[:, 5:].max(1, keepdim=True)
539 + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
540 +
541 + # Filter by class
542 + if classes is not None:
543 + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
544 +
545 + # Apply finite constraint
546 + # if not torch.isfinite(x).all():
547 + # x = x[torch.isfinite(x).all(1)]
548 +
549 + # Check shape
550 + n = x.shape[0] # number of boxes
551 + if not n: # no boxes
552 + continue
553 + elif n > max_nms: # excess boxes
554 + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
555 +
556 + # Batched NMS
557 + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
558 + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
559 + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
560 + if i.shape[0] > max_det: # limit detections
561 + i = i[:max_det]
562 + if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
563 + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
564 + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
565 + weights = iou * scores[None] # box weights
566 + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
567 + if redundant:
568 + i = i[iou.sum(1) > 1] # require redundancy
569 +
570 + output[xi] = x[i]
571 + if (time.time() - t) > time_limit:
572 + print(f'WARNING: NMS time limit {time_limit}s exceeded')
573 + break # time limit exceeded
574 +
575 + return output
576 +
577 +
578 +def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
579 + # Strip optimizer from 'f' to finalize training, optionally save as 's'
580 + with yolov5_in_syspath():
581 + x = torch.load(f, map_location=torch.device('cpu'))
582 + if x.get('ema'):
583 + x['model'] = x['ema'] # replace model with ema
584 + for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys
585 + x[k] = None
586 + x['epoch'] = -1
587 + x['model'].half() # to FP16
588 + for p in x['model'].parameters():
589 + p.requires_grad = False
590 + with yolov5_in_syspath():
591 + torch.save(x, s or f)
592 + mb = os.path.getsize(s or f) / 1E6 # filesize
593 + print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB")
594 +
595 +
596 +def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
597 + # Print mutation results to evolve.txt (for use with train.py --evolve)
598 + a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
599 + b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
600 + c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
601 + print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
602 +
603 + if bucket:
604 + url = 'gs://%s/evolve.txt' % bucket
605 + if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0):
606 + os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local
607 +
608 + with open('evolve.txt', 'a') as f: # append result
609 + f.write(c + b + '\n')
610 + x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
611 + x = x[np.argsort(-fitness(x))] # sort
612 + np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
613 +
614 + # Save yaml
615 + for i, k in enumerate(hyp.keys()):
616 + hyp[k] = float(x[0, i + 7])
617 + with open(yaml_file, 'w') as f:
618 + results = tuple(x[0, :7])
619 + c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
620 + f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
621 + yaml.safe_dump(hyp, f, sort_keys=False)
622 +
623 + if bucket:
624 + os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload
625 +
626 +
627 +def apply_classifier(x, model, img, im0):
628 + # Apply a second stage classifier to yolo outputs
629 + im0 = [im0] if isinstance(im0, np.ndarray) else im0
630 + for i, d in enumerate(x): # per image
631 + if d is not None and len(d):
632 + d = d.clone()
633 +
634 + # Reshape and pad cutouts
635 + b = xyxy2xywh(d[:, :4]) # boxes
636 + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
637 + b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
638 + d[:, :4] = xywh2xyxy(b).long()
639 +
640 + # Rescale boxes from img_size to im0 size
641 + scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
642 +
643 + # Classes
644 + pred_cls1 = d[:, 5].long()
645 + ims = []
646 + for j, a in enumerate(d): # per item
647 + cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
648 + im = cv2.resize(cutout, (224, 224)) # BGR
649 + # cv2.imwrite('test%i.jpg' % j, cutout)
650 +
651 + im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
652 + im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
653 + im /= 255.0 # 0 - 255 to 0.0 - 1.0
654 + ims.append(im)
655 +
656 + pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
657 + x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
658 +
659 + return x
660 +
661 +
662 +def save_one_box(xyxy, im, file='image.jpg', gain=1.02, pad=10, square=False, BGR=False):
663 + # Save an image crop as {file} with crop size multiplied by {gain} and padded by {pad} pixels
664 + xyxy = torch.tensor(xyxy).view(-1, 4)
665 + b = xyxy2xywh(xyxy) # boxes
666 + if square:
667 + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
668 + b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
669 + xyxy = xywh2xyxy(b).long()
670 + clip_coords(xyxy, im.shape)
671 + crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2])]
672 + cv2.imwrite(str(increment_path(file, mkdir=True).with_suffix('.jpg')), crop if BGR else crop[..., ::-1])
673 +
674 +
675 +def increment_path(path, exist_ok=False, sep='', mkdir=False):
676 + # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
677 + path = Path(path) # os-agnostic
678 + if path.exists() and not exist_ok:
679 + suffix = path.suffix
680 + path = path.with_suffix('')
681 + dirs = glob.glob(f"{path}{sep}*") # similar paths
682 + matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
683 + i = [int(m.groups()[0]) for m in matches if m] # indices
684 + n = max(i) + 1 if i else 2 # increment number
685 + path = Path(f"{path}{sep}{n}{suffix}") # update path
686 + dir = path if path.suffix == '' else path.parent # directory
687 + if not dir.exists() and mkdir:
688 + dir.mkdir(parents=True, exist_ok=True) # make directory
689 + return path
690 +
691 +import contextlib
692 +import sys
693 +
694 +
695 +@contextlib.contextmanager
696 +def yolov5_in_syspath():
697 + """
698 + Temporarily add yolov5 folder to `sys.path`.
699 +
700 + torch.hub handles it in the same way: https://github.com/pytorch/pytorch/blob/75024e228ca441290b6a1c2e564300ad507d7af6/torch/hub.py#L387
701 +
702 + Proper fix for: #22, #134, #353, #1155, #1389, #1680, #2531, #3071
703 + No need for such workarounds: #869, #1052, #2949
704 + """
705 + yolov5_folder_dir = str(Path(__file__).parents[1].absolute())
706 + try:
707 + sys.path.insert(0, yolov5_folder_dir)
708 + yield
709 + finally:
710 + sys.path.remove(yolov5_folder_dir)
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='ultralytics/yolov5'):
20 + # Attempt file download if does not exist
21 + file = Path(str(file).strip().replace("'", ''))
22 +
23 + if not file.exists():
24 + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
25 + try:
26 + response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
27 + assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
28 + tag = response['tag_name'] # i.e. 'v1.0'
29 + except: # fallback plan
30 + assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
31 + 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
32 + try:
33 + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
34 + except:
35 + tag = 'v5.0' # current release
36 +
37 + name = file.name
38 + if name in assets:
39 + msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
40 + redundant = False # second download option
41 + try: # GitHub
42 + url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
43 + print(f'Downloading {url} to {file}...')
44 + torch.hub.download_url_to_file(url, file)
45 + assert file.exists() and file.stat().st_size > 1E6 # check
46 + except Exception as e: # GCP
47 + print(f'Download error: {e}')
48 + assert redundant, 'No secondary mirror'
49 + url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
50 + print(f'Downloading {url} to {file}...')
51 + os.system(f"curl -L '{url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
52 + finally:
53 + if not file.exists() or file.stat().st_size < 1E6: # check
54 + file.unlink(missing_ok=True) # remove partial downloads
55 + print(f'ERROR: Download failure: {msg}')
56 + print('')
57 + return
58 +
59 +
60 +def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
61 + # Downloads a file from Google Drive. from yolo_module.yolov5.utils.google_utils import *; gdrive_download()
62 + t = time.time()
63 + file = Path(file)
64 + cookie = Path('cookie') # gdrive cookie
65 + print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
66 + file.unlink(missing_ok=True) # remove existing file
67 + cookie.unlink(missing_ok=True) # remove existing cookie
68 +
69 + # Attempt file download
70 + out = "NUL" if platform.system() == "Windows" else "/dev/null"
71 + os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
72 + if os.path.exists('cookie'): # large file
73 + s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
74 + else: # small file
75 + s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
76 + r = os.system(s) # execute, capture return
77 + cookie.unlink(missing_ok=True) # remove existing cookie
78 +
79 + # Error check
80 + if r != 0:
81 + file.unlink(missing_ok=True) # remove partial
82 + print('Download error ') # raise Exception('Download error')
83 + return r
84 +
85 + # Unzip if archive
86 + if file.suffix == '.zip':
87 + print('unzipping... ', end='')
88 + os.system(f'unzip -q {file}') # unzip
89 + file.unlink() # remove zip to free space
90 +
91 + print(f'Done ({time.time() - t:.1f}s)')
92 + return r
93 +
94 +
95 +def get_token(cookie="./cookie"):
96 + with open(cookie) as f:
97 + for line in f:
98 + if "download" in line:
99 + return line.split()[-1]
100 + return ""
101 +
102 +# def upload_blob(bucket_name, source_file_name, destination_blob_name):
103 +# # Uploads a file to a bucket
104 +# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
105 +#
106 +# storage_client = storage.Client()
107 +# bucket = storage_client.get_bucket(bucket_name)
108 +# blob = bucket.blob(destination_blob_name)
109 +#
110 +# blob.upload_from_filename(source_file_name)
111 +#
112 +# print('File {} uploaded to {}.'.format(
113 +# source_file_name,
114 +# destination_blob_name))
115 +#
116 +#
117 +# def download_blob(bucket_name, source_blob_name, destination_file_name):
118 +# # Uploads a blob from a bucket
119 +# storage_client = storage.Client()
120 +# bucket = storage_client.get_bucket(bucket_name)
121 +# blob = bucket.blob(source_blob_name)
122 +#
123 +# blob.download_to_filename(destination_file_name)
124 +#
125 +# print('Blob {} downloaded to {}.'.format(
126 +# source_blob_name,
127 +# destination_file_name))
1 +# Loss functions
2 +
3 +import torch
4 +import torch.nn as nn
5 +from yolo_module.yolov5.utils.general import bbox_iou
6 +from yolo_module.yolov5.utils.torch_utils import is_parallel
7 +
8 +
9 +def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
10 + # return positive, negative label smoothing BCE targets
11 + return 1.0 - 0.5 * eps, 0.5 * eps
12 +
13 +
14 +class BCEBlurWithLogitsLoss(nn.Module):
15 + # BCEwithLogitLoss() with reduced missing label effects.
16 + def __init__(self, alpha=0.05):
17 + super(BCEBlurWithLogitsLoss, self).__init__()
18 + self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
19 + self.alpha = alpha
20 +
21 + def forward(self, pred, true):
22 + loss = self.loss_fcn(pred, true)
23 + pred = torch.sigmoid(pred) # prob from logits
24 + dx = pred - true # reduce only missing label effects
25 + # dx = (pred - true).abs() # reduce missing label and false label effects
26 + alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
27 + loss *= alpha_factor
28 + return loss.mean()
29 +
30 +
31 +class FocalLoss(nn.Module):
32 + # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
33 + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
34 + super(FocalLoss, self).__init__()
35 + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
36 + self.gamma = gamma
37 + self.alpha = alpha
38 + self.reduction = loss_fcn.reduction
39 + self.loss_fcn.reduction = 'none' # required to apply FL to each element
40 +
41 + def forward(self, pred, true):
42 + loss = self.loss_fcn(pred, true)
43 + # p_t = torch.exp(-loss)
44 + # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
45 +
46 + # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
47 + pred_prob = torch.sigmoid(pred) # prob from logits
48 + p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
49 + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
50 + modulating_factor = (1.0 - p_t) ** self.gamma
51 + loss *= alpha_factor * modulating_factor
52 +
53 + if self.reduction == 'mean':
54 + return loss.mean()
55 + elif self.reduction == 'sum':
56 + return loss.sum()
57 + else: # 'none'
58 + return loss
59 +
60 +
61 +class QFocalLoss(nn.Module):
62 + # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
63 + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
64 + super(QFocalLoss, self).__init__()
65 + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
66 + self.gamma = gamma
67 + self.alpha = alpha
68 + self.reduction = loss_fcn.reduction
69 + self.loss_fcn.reduction = 'none' # required to apply FL to each element
70 +
71 + def forward(self, pred, true):
72 + loss = self.loss_fcn(pred, true)
73 +
74 + pred_prob = torch.sigmoid(pred) # prob from logits
75 + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
76 + modulating_factor = torch.abs(true - pred_prob) ** self.gamma
77 + loss *= alpha_factor * modulating_factor
78 +
79 + if self.reduction == 'mean':
80 + return loss.mean()
81 + elif self.reduction == 'sum':
82 + return loss.sum()
83 + else: # 'none'
84 + return loss
85 +
86 +
87 +class ComputeLoss:
88 + # Compute losses
89 + def __init__(self, model, autobalance=False):
90 + super(ComputeLoss, self).__init__()
91 + device = next(model.parameters()).device # get model device
92 + h = model.hyp # hyperparameters
93 +
94 + # Define criteria
95 + BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
96 + BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
97 +
98 + # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
99 + self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
100 +
101 + # Focal loss
102 + g = h['fl_gamma'] # focal loss gamma
103 + if g > 0:
104 + BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
105 +
106 + det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
107 + self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
108 + self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
109 + self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
110 + for k in 'na', 'nc', 'nl', 'anchors':
111 + setattr(self, k, getattr(det, k))
112 +
113 + def __call__(self, p, targets): # predictions, targets, model
114 + device = targets.device
115 + lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
116 + tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
117 +
118 + # Losses
119 + for i, pi in enumerate(p): # layer index, layer predictions
120 + b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
121 + tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
122 +
123 + n = b.shape[0] # number of targets
124 + if n:
125 + ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
126 +
127 + # Regression
128 + pxy = ps[:, :2].sigmoid() * 2. - 0.5
129 + pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
130 + pbox = torch.cat((pxy, pwh), 1) # predicted box
131 + iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
132 + lbox += (1.0 - iou).mean() # iou loss
133 +
134 + # Objectness
135 + tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
136 +
137 + # Classification
138 + if self.nc > 1: # cls loss (only if multiple classes)
139 + t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
140 + t[range(n), tcls[i]] = self.cp
141 + lcls += self.BCEcls(ps[:, 5:], t) # BCE
142 +
143 + # Append targets to text file
144 + # with open('targets.txt', 'a') as file:
145 + # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
146 +
147 + obji = self.BCEobj(pi[..., 4], tobj)
148 + lobj += obji * self.balance[i] # obj loss
149 + if self.autobalance:
150 + self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
151 +
152 + if self.autobalance:
153 + self.balance = [x / self.balance[self.ssi] for x in self.balance]
154 + lbox *= self.hyp['box']
155 + lobj *= self.hyp['obj']
156 + lcls *= self.hyp['cls']
157 + bs = tobj.shape[0] # batch size
158 +
159 + loss = lbox + lobj + lcls
160 + return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
161 +
162 + def build_targets(self, p, targets):
163 + # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
164 + na, nt = self.na, targets.shape[0] # number of anchors, targets
165 + tcls, tbox, indices, anch = [], [], [], []
166 + gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
167 + ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
168 + targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
169 +
170 + g = 0.5 # bias
171 + off = torch.tensor([[0, 0],
172 + [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
173 + # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
174 + ], device=targets.device).float() * g # offsets
175 +
176 + for i in range(self.nl):
177 + anchors = self.anchors[i]
178 + gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
179 +
180 + # Match targets to anchors
181 + t = targets * gain
182 + if nt:
183 + # Matches
184 + r = t[:, :, 4:6] / anchors[:, None] # wh ratio
185 + j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
186 + # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
187 + t = t[j] # filter
188 +
189 + # Offsets
190 + gxy = t[:, 2:4] # grid xy
191 + gxi = gain[[2, 3]] - gxy # inverse
192 + j, k = ((gxy % 1. < g) & (gxy > 1.)).T
193 + l, m = ((gxi % 1. < g) & (gxi > 1.)).T
194 + j = torch.stack((torch.ones_like(j), j, k, l, m))
195 + t = t.repeat((5, 1, 1))[j]
196 + offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
197 + else:
198 + t = targets[0]
199 + offsets = 0
200 +
201 + # Define
202 + b, c = t[:, :2].long().T # image, class
203 + gxy = t[:, 2:4] # grid xy
204 + gwh = t[:, 4:6] # grid wh
205 + gij = (gxy - offsets).long()
206 + gi, gj = gij.T # grid xy indices
207 +
208 + # Append
209 + a = t[:, 6].long() # anchor indices
210 + indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
211 + tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
212 + anch.append(anchors[a]) # anchors
213 + tcls.append(c) # class
214 +
215 + return tcls, tbox, indices, anch
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[detection_classes[m1[j]], gc] += 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)
1 +from pathlib import Path
2 +
3 +from yolo_module.yolov5.utils.general import colorstr
4 +
5 +try:
6 + import neptune.new as neptune
7 +except ImportError:
8 + neptune = None
9 +
10 +
11 +class NeptuneLogger:
12 + def __init__(self, opt, name, data_dict, job_type='Training'):
13 + # Pre-training routine --
14 + self.job_type = job_type
15 + self.neptune, self.neptune_run, self.data_dict = neptune, None, data_dict
16 +
17 + if self.neptune and opt.neptune_token:
18 + self.neptune_run = neptune.init(api_token=opt.neptune_token,
19 + project=opt.neptune_project,
20 + name=name)
21 + if self.neptune_run:
22 + if self.job_type == 'Training':
23 + if not opt.resume:
24 + neptune_data_dict = data_dict
25 + self.neptune_run["opt"] = vars(opt)
26 + self.neptune_run["data_dict"] = neptune_data_dict
27 + self.data_dict = self.setup_training(data_dict)
28 + prefix = colorstr('neptune: ')
29 + print(f"{prefix}NeptuneAI logging initiated successfully.")
30 + else:
31 + #prefix = colorstr('neptune: ')
32 + #print(
33 + # f"{prefix}Install NeptuneAI for YOLOv5 logging with 'pip install neptune-client' (recommended)")
34 + pass
35 +
36 + def setup_training(self, data_dict):
37 + self.log_dict, self.current_epoch = {}, 0 # Logging Constants
38 + return data_dict
39 +
40 + def log(self, log_dict):
41 + if self.neptune_run:
42 + for key, value in log_dict.items():
43 + self.log_dict[key] = value
44 +
45 + def end_epoch(self, best_result=False):
46 + if self.neptune_run:
47 + for key, value in self.log_dict.items():
48 + self.neptune_run[key].log(value)
49 + self.log_dict = {}
50 +
51 + def finish_run(self):
52 + if self.neptune_run:
53 + if self.log_dict:
54 + for key, value in self.log_dict.items():
55 + self.neptune_run[key].log(value)
56 + self.neptune_run.stop()
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 yolo_module.yolov5.utils.general import xywh2xyxy, xyxy2xywh
20 +from yolo_module.yolov5.utils.metrics import fitness
21 +
22 +# Settings
23 +matplotlib.rc('font', **{'size': 11})
24 +matplotlib.use('Agg') # for writing to files only
25 +
26 +
27 +class Colors:
28 + # Ultralytics color palette https://ultralytics.com/
29 + def __init__(self):
30 + self.palette = [self.hex2rgb(c) for c in matplotlib.colors.TABLEAU_COLORS.values()]
31 + self.n = len(self.palette)
32 +
33 + def __call__(self, i, bgr=False):
34 + c = self.palette[int(i) % self.n]
35 + return (c[2], c[1], c[0]) if bgr else c
36 +
37 + @staticmethod
38 + def hex2rgb(h): # rgb order (PIL)
39 + return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
40 +
41 +
42 +colors = Colors() # create instance for 'from utils.plots import colors'
43 +
44 +
45 +def hist2d(x, y, n=100):
46 + # 2d histogram used in labels.png and evolve.png
47 + xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
48 + hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
49 + xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
50 + yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
51 + return np.log(hist[xidx, yidx])
52 +
53 +
54 +def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
55 + from scipy.signal import butter, filtfilt
56 +
57 + # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
58 + def butter_lowpass(cutoff, fs, order):
59 + nyq = 0.5 * fs
60 + normal_cutoff = cutoff / nyq
61 + return butter(order, normal_cutoff, btype='low', analog=False)
62 +
63 + b, a = butter_lowpass(cutoff, fs, order=order)
64 + return filtfilt(b, a, data) # forward-backward filter
65 +
66 +
67 +def plot_one_box(x, im, color=None, label=None, line_thickness=3):
68 + # Plots one bounding box on image 'im' using OpenCV
69 + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
70 + tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
71 + color = color or [random.randint(0, 255) for _ in range(3)]
72 + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
73 + # cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
74 + # 작업한 부분 시작
75 + roi = im[int(x[1]):int(x[3]), int(x[0]):int(x[2])]
76 + # applying a gaussian blur over this new rectangle area
77 + roi = cv2.GaussianBlur(roi, (199, 199), 30)
78 + # impose this blurred image on original image to get final image
79 + im[int(x[1]):int(x[3]), int(x[0]):int(x[2])] = roi
80 + # 작업한 부분 마무리
81 + # if label:
82 + # tf = max(tl - 1, 1) # font thickness
83 + # t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
84 + # c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
85 + # cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
86 + # cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
87 +
88 +
89 +def plot_one_box_PIL(box, im, color=None, label=None, line_thickness=None):
90 + # Plots one bounding box on image 'im' using PIL
91 + im = Image.fromarray(im)
92 + draw = ImageDraw.Draw(im)
93 + line_thickness = line_thickness or max(int(min(im.size) / 200), 2)
94 + draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
95 + if label:
96 + fontsize = max(round(max(im.size) / 40), 12)
97 + font = ImageFont.truetype("Arial.ttf", fontsize)
98 + txt_width, txt_height = font.getsize(label)
99 + draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
100 + draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
101 + return np.asarray(im)
102 +
103 +
104 +def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
105 + # Compares the two methods for width-height anchor multiplication
106 + # https://github.com/ultralytics/yolov3/issues/168
107 + x = np.arange(-4.0, 4.0, .1)
108 + ya = np.exp(x)
109 + yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
110 +
111 + fig = plt.figure(figsize=(6, 3), tight_layout=True)
112 + plt.plot(x, ya, '.-', label='YOLOv3')
113 + plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
114 + plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
115 + plt.xlim(left=-4, right=4)
116 + plt.ylim(bottom=0, top=6)
117 + plt.xlabel('input')
118 + plt.ylabel('output')
119 + plt.grid()
120 + plt.legend()
121 + fig.savefig('comparison.png', dpi=200)
122 +
123 +
124 +def output_to_target(output):
125 + # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
126 + targets = []
127 + for i, o in enumerate(output):
128 + for *box, conf, cls in o.cpu().numpy():
129 + targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
130 + return np.array(targets)
131 +
132 +
133 +def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
134 + # Plot image grid with labels
135 +
136 + if isinstance(images, torch.Tensor):
137 + images = images.cpu().float().numpy()
138 + if isinstance(targets, torch.Tensor):
139 + targets = targets.cpu().numpy()
140 +
141 + # un-normalise
142 + if np.max(images[0]) <= 1:
143 + images *= 255
144 +
145 + tl = 3 # line thickness
146 + tf = max(tl - 1, 1) # font thickness
147 + bs, _, h, w = images.shape # batch size, _, height, width
148 + bs = min(bs, max_subplots) # limit plot images
149 + ns = np.ceil(bs ** 0.5) # number of subplots (square)
150 +
151 + # Check if we should resize
152 + scale_factor = max_size / max(h, w)
153 + if scale_factor < 1:
154 + h = math.ceil(scale_factor * h)
155 + w = math.ceil(scale_factor * w)
156 +
157 + mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
158 + for i, img in enumerate(images):
159 + if i == max_subplots: # if last batch has fewer images than we expect
160 + break
161 +
162 + block_x = int(w * (i // ns))
163 + block_y = int(h * (i % ns))
164 +
165 + img = img.transpose(1, 2, 0)
166 + if scale_factor < 1:
167 + img = cv2.resize(img, (w, h))
168 +
169 + mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
170 + if len(targets) > 0:
171 + image_targets = targets[targets[:, 0] == i]
172 + boxes = xywh2xyxy(image_targets[:, 2:6]).T
173 + classes = image_targets[:, 1].astype('int')
174 + labels = image_targets.shape[1] == 6 # labels if no conf column
175 + conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
176 +
177 + if boxes.shape[1]:
178 + if boxes.max() <= 1.01: # if normalized with tolerance 0.01
179 + boxes[[0, 2]] *= w # scale to pixels
180 + boxes[[1, 3]] *= h
181 + elif scale_factor < 1: # absolute coords need scale if image scales
182 + boxes *= scale_factor
183 + boxes[[0, 2]] += block_x
184 + boxes[[1, 3]] += block_y
185 + for j, box in enumerate(boxes.T):
186 + cls = int(classes[j])
187 + color = colors(cls)
188 + cls = names[cls] if names else cls
189 + if labels or conf[j] > 0.25: # 0.25 conf thresh
190 + label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
191 + plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
192 +
193 + # Draw image filename labels
194 + if paths:
195 + label = Path(paths[i]).name[:40] # trim to 40 char
196 + t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
197 + cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
198 + lineType=cv2.LINE_AA)
199 +
200 + # Image border
201 + cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
202 +
203 + if fname:
204 + r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
205 + mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
206 + # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
207 + Image.fromarray(mosaic).save(fname) # PIL save
208 + return mosaic
209 +
210 +
211 +def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
212 + # Plot LR simulating training for full epochs
213 + optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
214 + y = []
215 + for _ in range(epochs):
216 + scheduler.step()
217 + y.append(optimizer.param_groups[0]['lr'])
218 + plt.plot(y, '.-', label='LR')
219 + plt.xlabel('epoch')
220 + plt.ylabel('LR')
221 + plt.grid()
222 + plt.xlim(0, epochs)
223 + plt.ylim(0)
224 + plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
225 + plt.close()
226 +
227 +
228 +def plot_test_txt(): # from utils.plots import *; plot_test()
229 + # Plot test.txt histograms
230 + x = np.loadtxt('test.txt', dtype=np.float32)
231 + box = xyxy2xywh(x[:, :4])
232 + cx, cy = box[:, 0], box[:, 1]
233 +
234 + fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
235 + ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
236 + ax.set_aspect('equal')
237 + plt.savefig('hist2d.png', dpi=300)
238 +
239 + fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
240 + ax[0].hist(cx, bins=600)
241 + ax[1].hist(cy, bins=600)
242 + plt.savefig('hist1d.png', dpi=200)
243 +
244 +
245 +def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
246 + # Plot targets.txt histograms
247 + x = np.loadtxt('targets.txt', dtype=np.float32).T
248 + s = ['x targets', 'y targets', 'width targets', 'height targets']
249 + fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
250 + ax = ax.ravel()
251 + for i in range(4):
252 + ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
253 + ax[i].legend()
254 + ax[i].set_title(s[i])
255 + plt.savefig('targets.jpg', dpi=200)
256 +
257 +
258 +def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
259 + # Plot study.txt generated by test.py
260 + fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
261 + # ax = ax.ravel()
262 +
263 + fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
264 + # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
265 + for f in sorted(Path(path).glob('study*.txt')):
266 + y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
267 + x = np.arange(y.shape[1]) if x is None else np.array(x)
268 + s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
269 + # for i in range(7):
270 + # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
271 + # ax[i].set_title(s[i])
272 +
273 + j = y[3].argmax() + 1
274 + ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
275 + label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
276 +
277 + ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
278 + 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
279 +
280 + ax2.grid(alpha=0.2)
281 + ax2.set_yticks(np.arange(20, 60, 5))
282 + ax2.set_xlim(0, 57)
283 + ax2.set_ylim(30, 55)
284 + ax2.set_xlabel('GPU Speed (ms/img)')
285 + ax2.set_ylabel('COCO AP val')
286 + ax2.legend(loc='lower right')
287 + plt.savefig(str(Path(path).name) + '.png', dpi=300)
288 +
289 +
290 +def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
291 + # plot dataset labels
292 + print('Plotting labels... ')
293 + c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
294 + nc = int(c.max() + 1) # number of classes
295 + x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
296 +
297 + # seaborn correlogram
298 + sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
299 + plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
300 + plt.close()
301 +
302 + # matplotlib labels
303 + matplotlib.use('svg') # faster
304 + ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
305 + ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
306 + ax[0].set_ylabel('instances')
307 + if 0 < len(names) < 30:
308 + ax[0].set_xticks(range(len(names)))
309 + ax[0].set_xticklabels(names, rotation=90, fontsize=10)
310 + else:
311 + ax[0].set_xlabel('classes')
312 + sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
313 + sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
314 +
315 + # rectangles
316 + labels[:, 1:3] = 0.5 # center
317 + labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
318 + img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
319 + for cls, *box in labels[:1000]:
320 + ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
321 + ax[1].imshow(img)
322 + ax[1].axis('off')
323 +
324 + for a in [0, 1, 2, 3]:
325 + for s in ['top', 'right', 'left', 'bottom']:
326 + ax[a].spines[s].set_visible(False)
327 +
328 + plt.savefig(save_dir / 'labels.jpg', dpi=200)
329 + matplotlib.use('Agg')
330 + plt.close()
331 +
332 + # loggers
333 + for k, v in loggers.items() or {}:
334 + if k == 'wandb' and v:
335 + v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
336 +
337 +
338 +def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
339 + # Plot hyperparameter evolution results in evolve.txt
340 + with open(yaml_file) as f:
341 + hyp = yaml.safe_load(f)
342 + x = np.loadtxt('evolve.txt', ndmin=2)
343 + f = fitness(x)
344 + # weights = (f - f.min()) ** 2 # for weighted results
345 + plt.figure(figsize=(10, 12), tight_layout=True)
346 + matplotlib.rc('font', **{'size': 8})
347 + for i, (k, v) in enumerate(hyp.items()):
348 + y = x[:, i + 7]
349 + # mu = (y * weights).sum() / weights.sum() # best weighted result
350 + mu = y[f.argmax()] # best single result
351 + plt.subplot(6, 5, i + 1)
352 + plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
353 + plt.plot(mu, f.max(), 'k+', markersize=15)
354 + plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
355 + if i % 5 != 0:
356 + plt.yticks([])
357 + print('%15s: %.3g' % (k, mu))
358 + plt.savefig('evolve.png', dpi=200)
359 + print('\nPlot saved as evolve.png')
360 +
361 +
362 +def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
363 + # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
364 + ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
365 + s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
366 + files = list(Path(save_dir).glob('frames*.txt'))
367 + for fi, f in enumerate(files):
368 + try:
369 + results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
370 + n = results.shape[1] # number of rows
371 + x = np.arange(start, min(stop, n) if stop else n)
372 + results = results[:, x]
373 + t = (results[0] - results[0].min()) # set t0=0s
374 + results[0] = x
375 + for i, a in enumerate(ax):
376 + if i < len(results):
377 + label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
378 + a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
379 + a.set_title(s[i])
380 + a.set_xlabel('time (s)')
381 + # if fi == len(files) - 1:
382 + # a.set_ylim(bottom=0)
383 + for side in ['top', 'right']:
384 + a.spines[side].set_visible(False)
385 + else:
386 + a.remove()
387 + except Exception as e:
388 + print('Warning: Plotting error for %s; %s' % (f, e))
389 +
390 + ax[1].legend()
391 + plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
392 +
393 +
394 +def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
395 + # Plot training 'results*.txt', overlaying train and val losses
396 + s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
397 + t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
398 + for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
399 + results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
400 + n = results.shape[1] # number of rows
401 + x = range(start, min(stop, n) if stop else n)
402 + fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
403 + ax = ax.ravel()
404 + for i in range(5):
405 + for j in [i, i + 5]:
406 + y = results[j, x]
407 + ax[i].plot(x, y, marker='.', label=s[j])
408 + # y_smooth = butter_lowpass_filtfilt(y)
409 + # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
410 +
411 + ax[i].set_title(t[i])
412 + ax[i].legend()
413 + ax[i].set_ylabel(f) if i == 0 else None # add filename
414 + fig.savefig(f.replace('.txt', '.png'), dpi=200)
415 +
416 +
417 +def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
418 + # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
419 + fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
420 + ax = ax.ravel()
421 + s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
422 + 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
423 + if bucket:
424 + # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
425 + files = ['results%g.txt' % x for x in id]
426 + c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
427 + os.system(c)
428 + else:
429 + files = list(Path(save_dir).glob('results*.txt'))
430 + assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
431 + for fi, f in enumerate(files):
432 + try:
433 + results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
434 + n = results.shape[1] # number of rows
435 + x = range(start, min(stop, n) if stop else n)
436 + for i in range(10):
437 + y = results[i, x]
438 + if i in [0, 1, 2, 5, 6, 7]:
439 + y[y == 0] = np.nan # don't show zero loss values
440 + # y /= y[0] # normalize
441 + label = labels[fi] if len(labels) else f.stem
442 + ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
443 + ax[i].set_title(s[i])
444 + # if i in [5, 6, 7]: # share train and val loss y axes
445 + # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
446 + except Exception as e:
447 + print('Warning: Plotting error for %s; %s' % (f, e))
448 +
449 + ax[1].legend()
450 + fig.savefig(Path(save_dir) / 'results.png', dpi=200)
1 +# YOLOv5 PyTorch utils
2 +
3 +import datetime
4 +import logging
5 +import math
6 +import os
7 +import pickle
8 +import platform
9 +import subprocess
10 +import sys
11 +import time
12 +from contextlib import contextmanager
13 +from copy import deepcopy
14 +from pathlib import Path
15 +
16 +import torch
17 +import torch.backends.cudnn as cudnn
18 +import torch.nn as nn
19 +import torch.nn.functional as F
20 +import torchvision
21 +
22 +try:
23 + import thop # for FLOPS computation
24 +except ImportError:
25 + thop = None
26 +logger = logging.getLogger(__name__)
27 +
28 +
29 +@contextmanager
30 +def torch_distributed_zero_first(local_rank: int):
31 + """
32 + Decorator to make all processes in distributed training wait for each local_master to do something.
33 + """
34 + if local_rank not in [-1, 0]:
35 + torch.distributed.barrier()
36 + yield
37 + if local_rank == 0:
38 + torch.distributed.barrier()
39 +
40 +
41 +def init_torch_seeds(seed=0):
42 + # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
43 + torch.manual_seed(seed)
44 + if seed == 0: # slower, more reproducible
45 + cudnn.benchmark, cudnn.deterministic = False, True
46 + else: # faster, less reproducible
47 + cudnn.benchmark, cudnn.deterministic = True, False
48 +
49 +
50 +def date_modified(path=__file__):
51 + # return human-readable file modification date, i.e. '2021-3-26'
52 + t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
53 + return f'{t.year}-{t.month}-{t.day}'
54 +
55 +
56 +def git_describe(path=Path(__file__).parent): # path must be a directory
57 + # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
58 + s = f'git -C {path} describe --tags --long --always'
59 + try:
60 + return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
61 + except subprocess.CalledProcessError as e:
62 + return '' # not a git repository
63 +
64 +
65 +def select_device(device='', batch_size=None):
66 + # device = 'cpu' or '0' or '0,1,2,3'
67 + s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
68 + cpu = device.lower() == 'cpu'
69 + if cpu:
70 + os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
71 + elif device: # non-cpu device requested
72 + os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
73 + assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
74 +
75 + cuda = not cpu and torch.cuda.is_available()
76 + if cuda:
77 + n = torch.cuda.device_count()
78 + if n > 1 and batch_size: # check that batch_size is compatible with device_count
79 + assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
80 + space = ' ' * len(s)
81 + for i, d in enumerate(device.split(',') if device else range(n)):
82 + p = torch.cuda.get_device_properties(i)
83 + s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
84 + else:
85 + s += 'CPU\n'
86 +
87 + logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
88 + return torch.device('cuda:0' if cuda else 'cpu')
89 +
90 +
91 +def time_synchronized():
92 + # pytorch-accurate time
93 + if torch.cuda.is_available():
94 + torch.cuda.synchronize()
95 + return time.time()
96 +
97 +
98 +def profile(x, ops, n=100, device=None):
99 + # profile a pytorch module or list of modules. Example usage:
100 + # x = torch.randn(16, 3, 640, 640) # input
101 + # m1 = lambda x: x * torch.sigmoid(x)
102 + # m2 = nn.SiLU()
103 + # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
104 +
105 + device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
106 + x = x.to(device)
107 + x.requires_grad = True
108 + print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
109 + print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
110 + for m in ops if isinstance(ops, list) else [ops]:
111 + m = m.to(device) if hasattr(m, 'to') else m # device
112 + m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
113 + dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
114 + try:
115 + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
116 + except:
117 + flops = 0
118 +
119 + for _ in range(n):
120 + t[0] = time_synchronized()
121 + y = m(x)
122 + t[1] = time_synchronized()
123 + try:
124 + _ = y.sum().backward()
125 + t[2] = time_synchronized()
126 + except: # no backward method
127 + t[2] = float('nan')
128 + dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
129 + dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
130 +
131 + s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
132 + s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
133 + p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
134 + print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
135 +
136 +
137 +def is_parallel(model):
138 + return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
139 +
140 +
141 +def intersect_dicts(da, db, exclude=()):
142 + # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
143 + 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}
144 +
145 +
146 +def initialize_weights(model):
147 + for m in model.modules():
148 + t = type(m)
149 + if t is nn.Conv2d:
150 + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
151 + elif t is nn.BatchNorm2d:
152 + m.eps = 1e-3
153 + m.momentum = 0.03
154 + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
155 + m.inplace = True
156 +
157 +
158 +def find_modules(model, mclass=nn.Conv2d):
159 + # Finds layer indices matching module class 'mclass'
160 + return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
161 +
162 +
163 +def sparsity(model):
164 + # Return global model sparsity
165 + a, b = 0., 0.
166 + for p in model.parameters():
167 + a += p.numel()
168 + b += (p == 0).sum()
169 + return b / a
170 +
171 +
172 +def prune(model, amount=0.3):
173 + # Prune model to requested global sparsity
174 + import torch.nn.utils.prune as prune
175 + print('Pruning model... ', end='')
176 + for name, m in model.named_modules():
177 + if isinstance(m, nn.Conv2d):
178 + prune.l1_unstructured(m, name='weight', amount=amount) # prune
179 + prune.remove(m, 'weight') # make permanent
180 + print(' %.3g global sparsity' % sparsity(model))
181 +
182 +
183 +def fuse_conv_and_bn(conv, bn):
184 + # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
185 + fusedconv = nn.Conv2d(conv.in_channels,
186 + conv.out_channels,
187 + kernel_size=conv.kernel_size,
188 + stride=conv.stride,
189 + padding=conv.padding,
190 + groups=conv.groups,
191 + bias=True).requires_grad_(False).to(conv.weight.device)
192 +
193 + # prepare filters
194 + w_conv = conv.weight.clone().view(conv.out_channels, -1)
195 + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
196 + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
197 +
198 + # prepare spatial bias
199 + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
200 + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
201 + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
202 +
203 + return fusedconv
204 +
205 +
206 +def model_info(model, verbose=False, img_size=640):
207 + # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
208 + n_p = sum(x.numel() for x in model.parameters()) # number parameters
209 + n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
210 + if verbose:
211 + print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
212 + for i, (name, p) in enumerate(model.named_parameters()):
213 + name = name.replace('module_list.', '')
214 + print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
215 + (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
216 +
217 + try: # FLOPS
218 + from thop import profile
219 + stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
220 + img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
221 + flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
222 + img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
223 + fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
224 + except (ImportError, Exception):
225 + fs = ''
226 +
227 + logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
228 +
229 +
230 +def load_classifier(name='resnet101', n=2):
231 + # Loads a pretrained model reshaped to n-class output
232 + model = torchvision.models.__dict__[name](pretrained=True)
233 +
234 + # ResNet model properties
235 + # input_size = [3, 224, 224]
236 + # input_space = 'RGB'
237 + # input_range = [0, 1]
238 + # mean = [0.485, 0.456, 0.406]
239 + # std = [0.229, 0.224, 0.225]
240 +
241 + # Reshape output to n classes
242 + filters = model.fc.weight.shape[1]
243 + model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
244 + model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
245 + model.fc.out_features = n
246 + return model
247 +
248 +
249 +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
250 + # scales img(bs,3,y,x) by ratio constrained to gs-multiple
251 + if ratio == 1.0:
252 + return img
253 + else:
254 + h, w = img.shape[2:]
255 + s = (int(h * ratio), int(w * ratio)) # new size
256 + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
257 + if not same_shape: # pad/crop img
258 + h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
259 + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
260 +
261 +
262 +def copy_attr(a, b, include=(), exclude=()):
263 + # Copy attributes from b to a, options to only include [...] and to exclude [...]
264 + for k, v in b.__dict__.items():
265 + if (len(include) and k not in include) or k.startswith('_') or k in exclude:
266 + continue
267 + else:
268 + setattr(a, k, v)
269 +
270 +
271 +class ModelEMA:
272 + """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
273 + Keep a moving average of everything in the model state_dict (parameters and buffers).
274 + This is intended to allow functionality like
275 + https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
276 + A smoothed version of the weights is necessary for some training schemes to perform well.
277 + This class is sensitive where it is initialized in the sequence of model init,
278 + GPU assignment and distributed training wrappers.
279 + """
280 +
281 + def __init__(self, model, decay=0.9999, updates=0):
282 + # Create EMA
283 + self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
284 + # if next(model.parameters()).device.type != 'cpu':
285 + # self.ema.half() # FP16 EMA
286 + self.updates = updates # number of EMA updates
287 + self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
288 + for p in self.ema.parameters():
289 + p.requires_grad_(False)
290 +
291 + def update(self, model):
292 + # Update EMA parameters
293 + with torch.no_grad():
294 + self.updates += 1
295 + d = self.decay(self.updates)
296 +
297 + msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
298 + for k, v in self.ema.state_dict().items():
299 + if v.dtype.is_floating_point:
300 + v *= d
301 + v += (1. - d) * msd[k].detach()
302 +
303 + def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
304 + # Update EMA attributes
305 + copy_attr(self.ema, model, include, exclude)
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.safe_load(f) # 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/coco128.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='YOLOv5', 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)
1 +import json
2 +import sys
3 +from pathlib import Path
4 +
5 +import torch
6 +import yaml
7 +from tqdm import tqdm
8 +#sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
9 +from yolo_module.yolov5.utils.datasets import LoadImagesAndLabels, img2label_paths
10 +from yolo_module.yolov5.utils.general import check_dataset, check_file, colorstr, xywh2xyxy
11 +
12 +try:
13 + import wandb
14 + from wandb import finish, init
15 +except ImportError:
16 + wandb = None
17 +
18 +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
19 +
20 +
21 +def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
22 + return from_string[len(prefix):]
23 +
24 +
25 +def check_wandb_config_file(data_config_file):
26 + wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
27 + if Path(wandb_config).is_file():
28 + return wandb_config
29 + return data_config_file
30 +
31 +
32 +def get_run_info(run_path):
33 + run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
34 + run_id = run_path.stem
35 + project = run_path.parent.stem
36 + model_artifact_name = 'run_' + run_id + '_model'
37 + return run_id, project, model_artifact_name
38 +
39 +
40 +def check_wandb_resume(opt):
41 + process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None
42 + if isinstance(opt.resume, str):
43 + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
44 + if opt.global_rank not in [-1, 0]: # For resuming DDP runs
45 + run_id, project, model_artifact_name = get_run_info(opt.resume)
46 + api = wandb.Api()
47 + artifact = api.artifact(project + '/' + model_artifact_name + ':latest')
48 + modeldir = artifact.download()
49 + opt.weights = str(Path(modeldir) / "last.pt")
50 + return True
51 + return None
52 +
53 +
54 +def process_wandb_config_ddp_mode(opt):
55 + with open(check_file(opt.data)) as f:
56 + data_dict = yaml.safe_load(f) # data dict
57 + train_dir, val_dir = None, None
58 + if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
59 + api = wandb.Api()
60 + train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
61 + train_dir = train_artifact.download()
62 + train_path = Path(train_dir) / 'data/images/'
63 + data_dict['train'] = str(train_path)
64 +
65 + if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
66 + api = wandb.Api()
67 + val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
68 + val_dir = val_artifact.download()
69 + val_path = Path(val_dir) / 'data/images/'
70 + data_dict['val'] = str(val_path)
71 + if train_dir or val_dir:
72 + ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
73 + with open(ddp_data_path, 'w') as f:
74 + yaml.safe_dump(data_dict, f)
75 + opt.data = ddp_data_path
76 +
77 +
78 +class WandbLogger():
79 + def __init__(self, opt, name, run_id, data_dict, job_type='Training'):
80 + # Pre-training routine --
81 + self.job_type = job_type
82 + self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict
83 + # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call
84 + if isinstance(opt.resume, str): # checks resume from artifact
85 + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
86 + run_id, project, model_artifact_name = get_run_info(opt.resume)
87 + model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
88 + assert wandb, 'install wandb to resume wandb runs'
89 + # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
90 + self.wandb_run = wandb.init(id=run_id, project=project, resume='allow')
91 + opt.resume = model_artifact_name
92 + elif self.wandb:
93 + self.wandb_run = wandb.init(config=opt,
94 + resume="allow",
95 + project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
96 + name=name,
97 + job_type=job_type,
98 + id=run_id) if not wandb.run else wandb.run
99 + if self.wandb_run:
100 + if self.job_type == 'Training':
101 + if not opt.resume:
102 + wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict
103 + # Info useful for resuming from artifacts
104 + self.wandb_run.config.opt = vars(opt)
105 + self.wandb_run.config.data_dict = wandb_data_dict
106 + self.data_dict = self.setup_training(opt, data_dict)
107 + if self.job_type == 'Dataset Creation':
108 + self.data_dict = self.check_and_upload_dataset(opt)
109 + else:
110 + prefix = colorstr('wandb: ')
111 + print(f"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)")
112 +
113 + def check_and_upload_dataset(self, opt):
114 + assert wandb, 'Install wandb to upload dataset'
115 + check_dataset(self.data_dict)
116 + config_path = self.log_dataset_artifact(check_file(opt.data),
117 + opt.single_cls,
118 + 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
119 + print("Created dataset config file ", config_path)
120 + with open(config_path) as f:
121 + wandb_data_dict = yaml.safe_load(f)
122 + return wandb_data_dict
123 +
124 + def setup_training(self, opt, data_dict):
125 + self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants
126 + self.bbox_interval = opt.bbox_interval
127 + if isinstance(opt.resume, str):
128 + modeldir, _ = self.download_model_artifact(opt)
129 + if modeldir:
130 + self.weights = Path(modeldir) / "last.pt"
131 + config = self.wandb_run.config
132 + opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
133 + self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \
134 + config.opt['hyp']
135 + data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume
136 + if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download
137 + self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
138 + opt.artifact_alias)
139 + self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
140 + opt.artifact_alias)
141 + self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None
142 + if self.train_artifact_path is not None:
143 + train_path = Path(self.train_artifact_path) / 'data/images/'
144 + data_dict['train'] = str(train_path)
145 + if self.val_artifact_path is not None:
146 + val_path = Path(self.val_artifact_path) / 'data/images/'
147 + data_dict['val'] = str(val_path)
148 + self.val_table = self.val_artifact.get("val")
149 + self.map_val_table_path()
150 + if self.val_artifact is not None:
151 + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
152 + self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
153 + if opt.bbox_interval == -1:
154 + self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
155 + return data_dict
156 +
157 + def download_dataset_artifact(self, path, alias):
158 + if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
159 + artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
160 + dataset_artifact = wandb.use_artifact(artifact_path.as_posix())
161 + assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
162 + datadir = dataset_artifact.download()
163 + return datadir, dataset_artifact
164 + return None, None
165 +
166 + def download_model_artifact(self, opt):
167 + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
168 + model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
169 + assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
170 + modeldir = model_artifact.download()
171 + epochs_trained = model_artifact.metadata.get('epochs_trained')
172 + total_epochs = model_artifact.metadata.get('total_epochs')
173 + assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % (
174 + total_epochs)
175 + return modeldir, model_artifact
176 + return None, None
177 +
178 + def log_model(self, path, opt, epoch, fitness_score, best_model=False):
179 + model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
180 + 'original_url': str(path),
181 + 'epochs_trained': epoch + 1,
182 + 'save period': opt.save_period,
183 + 'project': opt.project,
184 + 'total_epochs': opt.epochs,
185 + 'fitness_score': fitness_score
186 + })
187 + model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
188 + wandb.log_artifact(model_artifact,
189 + aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
190 + print("Saving model artifact on epoch ", epoch + 1)
191 +
192 + def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
193 + with open(data_file) as f:
194 + data = yaml.safe_load(f) # data dict
195 + nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
196 + names = {k: v for k, v in enumerate(names)} # to index dictionary
197 + self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
198 + data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None
199 + self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
200 + data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None
201 + if data.get('train'):
202 + data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
203 + if data.get('val'):
204 + data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
205 + path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path
206 + data.pop('download', None)
207 + with open(path, 'w') as f:
208 + yaml.safe_dump(data, f)
209 +
210 + if self.job_type == 'Training': # builds correct artifact pipeline graph
211 + self.wandb_run.use_artifact(self.val_artifact)
212 + self.wandb_run.use_artifact(self.train_artifact)
213 + self.val_artifact.wait()
214 + self.val_table = self.val_artifact.get('val')
215 + self.map_val_table_path()
216 + else:
217 + self.wandb_run.log_artifact(self.train_artifact)
218 + self.wandb_run.log_artifact(self.val_artifact)
219 + return path
220 +
221 + def map_val_table_path(self):
222 + self.val_table_map = {}
223 + print("Mapping dataset")
224 + for i, data in enumerate(tqdm(self.val_table.data)):
225 + self.val_table_map[data[3]] = data[0]
226 +
227 + def create_dataset_table(self, dataset, class_to_id, name='dataset'):
228 + # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
229 + artifact = wandb.Artifact(name=name, type="dataset")
230 + img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
231 + img_files = tqdm(dataset.img_files) if not img_files else img_files
232 + for img_file in img_files:
233 + if Path(img_file).is_dir():
234 + artifact.add_dir(img_file, name='data/images')
235 + labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
236 + artifact.add_dir(labels_path, name='data/labels')
237 + else:
238 + artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
239 + label_file = Path(img2label_paths([img_file])[0])
240 + artifact.add_file(str(label_file),
241 + name='data/labels/' + label_file.name) if label_file.exists() else None
242 + table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
243 + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
244 + for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
245 + box_data, img_classes = [], {}
246 + for cls, *xywh in labels[:, 1:].tolist():
247 + cls = int(cls)
248 + box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]},
249 + "class_id": cls,
250 + "box_caption": "%s" % (class_to_id[cls])})
251 + img_classes[cls] = class_to_id[cls]
252 + boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
253 + table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes),
254 + Path(paths).name)
255 + artifact.add(table, name)
256 + return artifact
257 +
258 + def log_training_progress(self, predn, path, names):
259 + if self.val_table and self.result_table:
260 + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
261 + box_data = []
262 + total_conf = 0
263 + for *xyxy, conf, cls in predn.tolist():
264 + if conf >= 0.25:
265 + box_data.append(
266 + {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
267 + "class_id": int(cls),
268 + "box_caption": "%s %.3f" % (names[cls], conf),
269 + "scores": {"class_score": conf},
270 + "domain": "pixel"})
271 + total_conf = total_conf + conf
272 + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
273 + id = self.val_table_map[Path(path).name]
274 + self.result_table.add_data(self.current_epoch,
275 + id,
276 + wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
277 + total_conf / max(1, len(box_data))
278 + )
279 +
280 + def log(self, log_dict):
281 + if self.wandb_run:
282 + for key, value in log_dict.items():
283 + self.log_dict[key] = value
284 +
285 + def end_epoch(self, best_result=False):
286 + if self.wandb_run:
287 + wandb.log(self.log_dict)
288 + self.log_dict = {}
289 + if self.result_artifact:
290 + train_results = wandb.JoinedTable(self.val_table, self.result_table, "id")
291 + self.result_artifact.add(train_results, 'result')
292 + wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch),
293 + ('best' if best_result else '')])
294 + self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
295 + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
296 +
297 + def finish_run(self):
298 + if self.wandb_run:
299 + if self.log_dict:
300 + wandb.log(self.log_dict)
301 + wandb.run.finish()