SamDaLamb commited on
Commit
1e4b791
·
verified ·
1 Parent(s): ce1fd37

Upload 15 files

Browse files
Files changed (15) hide show
  1. CONTRIBUTING.md +98 -0
  2. LICENSE +674 -0
  3. README.md +302 -13
  4. data.yaml +149 -0
  5. detect.py +256 -0
  6. empty.py +29 -0
  7. export.py +610 -0
  8. hubconf.py +145 -0
  9. optimizer.py +27 -0
  10. requirements.txt +42 -8
  11. run.py +7 -0
  12. setup.cfg +59 -0
  13. test.py +1 -0
  14. test1.py +0 -0
  15. test2.py +654 -0
CONTRIBUTING.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Contributing to YOLOv5 🚀
2
+
3
+ We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
4
+
5
+ - Reporting a bug
6
+ - Discussing the current state of the code
7
+ - Submitting a fix
8
+ - Proposing a new feature
9
+ - Becoming a maintainer
10
+
11
+ YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
12
+ helping push the frontiers of what's possible in AI 😃!
13
+
14
+ ## Submitting a Pull Request (PR) 🛠️
15
+
16
+ Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
17
+
18
+ ### 1. Select File to Update
19
+
20
+ Select `requirements.txt` to update by clicking on it in GitHub.
21
+
22
+ <p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
23
+
24
+ ### 2. Click 'Edit this file'
25
+
26
+ Button is in top-right corner.
27
+
28
+ <p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
29
+
30
+ ### 3. Make Changes
31
+
32
+ Change `matplotlib` version from `3.2.2` to `3.3`.
33
+
34
+ <p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
35
+
36
+ ### 4. Preview Changes and Submit PR
37
+
38
+ Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
39
+ for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
40
+ changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
41
+
42
+ <p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
43
+
44
+ ### PR recommendations
45
+
46
+ To allow your work to be integrated as seamlessly as possible, we advise you to:
47
+
48
+ - ✅ Verify your PR is **up-to-date with upstream/master.** If your PR is behind upstream/master an
49
+ automatic [GitHub Actions](https://github.com/ultralytics/yolov5/blob/master/.github/workflows/rebase.yml) merge may
50
+ be attempted by writing /rebase in a new comment, or by running the following code, replacing 'feature' with the name
51
+ of your local branch:
52
+
53
+ ```bash
54
+ git remote add upstream https://github.com/ultralytics/yolov5.git
55
+ git fetch upstream
56
+ # git checkout feature # <--- replace 'feature' with local branch name
57
+ git merge upstream/master
58
+ git push -u origin -f
59
+ ```
60
+
61
+ - ✅ Verify all Continuous Integration (CI) **checks are passing**.
62
+ - ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
63
+ but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
64
+
65
+ ## Submitting a Bug Report 🐛
66
+
67
+ If you spot a problem with YOLOv5 please submit a Bug Report!
68
+
69
+ For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few
70
+ short guidelines below to help users provide what we need in order to get started.
71
+
72
+ When asking a question, people will be better able to provide help if you provide **code** that they can easily
73
+ understand and use to **reproduce** the problem. This is referred to by community members as creating
74
+ a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
75
+ the problem should be:
76
+
77
+ - ✅ **Minimal** – Use as little code as possible that still produces the same problem
78
+ - ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
79
+ - ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
80
+
81
+ In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
82
+ should be:
83
+
84
+ - ✅ **Current** – Verify that your code is up-to-date with current
85
+ GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
86
+ copy to ensure your problem has not already been resolved by previous commits.
87
+ - ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this
88
+ repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
89
+
90
+ If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛
91
+ **Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing
92
+ a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
93
+ understand and diagnose your problem.
94
+
95
+ ## License
96
+
97
+ By contributing, you agree that your contributions will be licensed under
98
+ the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/)
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>.
README.md CHANGED
@@ -1,13 +1,302 @@
1
- ---
2
- title: ValorantTracker
3
- emoji: 🔥
4
- colorFrom: gray
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.15.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <p>
3
+ <a align="left" href="https://ultralytics.com/yolov5" target="_blank">
4
+ <img width="850" src="https://github.com/ultralytics/yolov5/releases/download/v1.0/splash.jpg"></a>
5
+ </p>
6
+
7
+ English | [简体中文](.github/README_cn.md)
8
+ <br>
9
+ <div>
10
+ <a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="CI CPU testing"></a>
11
+ <a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
12
+ <a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
13
+ <br>
14
+ <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
15
+ <a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
16
+ <a href="https://join.slack.com/t/ultralytics/shared_invite/zt-w29ei8bp-jczz7QYUmDtgo6r6KcMIAg"><img src="https://img.shields.io/badge/Slack-Join_Forum-blue.svg?logo=slack" alt="Join Forum"></a>
17
+ </div>
18
+
19
+ <br>
20
+ <p>
21
+ YOLOv5 🚀 is a family of object detection architectures and models pretrained on the COCO dataset, and represents <a href="https://ultralytics.com">Ultralytics</a>
22
+ open-source research into future vision AI methods, incorporating lessons learned and best practices evolved over thousands of hours of research and development.
23
+ </p>
24
+
25
+ <div align="center">
26
+ <a href="https://github.com/ultralytics">
27
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-github.png" width="2%"/>
28
+ </a>
29
+ <img width="2%" />
30
+ <a href="https://www.linkedin.com/company/ultralytics">
31
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-linkedin.png" width="2%"/>
32
+ </a>
33
+ <img width="2%" />
34
+ <a href="https://twitter.com/ultralytics">
35
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-twitter.png" width="2%"/>
36
+ </a>
37
+ <img width="2%" />
38
+ <a href="https://www.producthunt.com/@glenn_jocher">
39
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-producthunt.png" width="2%"/>
40
+ </a>
41
+ <img width="2%" />
42
+ <a href="https://youtube.com/ultralytics">
43
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-youtube.png" width="2%"/>
44
+ </a>
45
+ <img width="2%" />
46
+ <a href="https://www.facebook.com/ultralytics">
47
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-facebook.png" width="2%"/>
48
+ </a>
49
+ <img width="2%" />
50
+ <a href="https://www.instagram.com/ultralytics/">
51
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-instagram.png" width="2%"/>
52
+ </a>
53
+ </div>
54
+
55
+ <!--
56
+ <a align="center" href="https://ultralytics.com/yolov5" target="_blank">
57
+ <img width="800" src="https://github.com/ultralytics/yolov5/releases/download/v1.0/banner-api.png"></a>
58
+ -->
59
+
60
+ </div>
61
+
62
+ ## <div align="center">Documentation</div>
63
+
64
+ See the [YOLOv5 Docs](https://docs.ultralytics.com) for full documentation on training, testing and deployment.
65
+
66
+ ## <div align="center">Quick Start Examples</div>
67
+
68
+ <details open>
69
+ <summary>Install</summary>
70
+
71
+ Clone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a
72
+ [**Python>=3.7.0**](https://www.python.org/) environment, including
73
+ [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).
74
+
75
+ ```bash
76
+ git clone https://github.com/ultralytics/yolov5 # clone
77
+ cd yolov5
78
+ pip install -r requirements.txt # install
79
+ ```
80
+
81
+ </details>
82
+
83
+ <details open>
84
+ <summary>Inference</summary>
85
+
86
+ YOLOv5 [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest
87
+ YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).
88
+
89
+ ```python
90
+ import torch
91
+
92
+ # Model
93
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5n - yolov5x6, custom
94
+
95
+ # Images
96
+ img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
97
+
98
+ # Inference
99
+ results = model(img)
100
+
101
+ # Results
102
+ results.print() # or .show(), .save(), .crop(), .pandas(), etc.
103
+ ```
104
+
105
+ </details>
106
+
107
+ <details>
108
+ <summary>Inference with detect.py</summary>
109
+
110
+ `detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from
111
+ the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
112
+
113
+ ```bash
114
+ python detect.py --source 0 # webcam
115
+ img.jpg # image
116
+ vid.mp4 # video
117
+ path/ # directory
118
+ path/*.jpg # glob
119
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
120
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
121
+ ```
122
+
123
+ </details>
124
+
125
+ <details>
126
+ <summary>Training</summary>
127
+
128
+ The commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh)
129
+ results. [Models](https://github.com/ultralytics/yolov5/tree/master/models)
130
+ and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest
131
+ YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are
132
+ 1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://github.com/ultralytics/yolov5/issues/475) times faster). Use the
133
+ largest `--batch-size` possible, or pass `--batch-size -1` for
134
+ YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB.
135
+
136
+ ```bash
137
+ python train.py --data coco.yaml --cfg yolov5n.yaml --weights '' --batch-size 128
138
+ yolov5s 64
139
+ yolov5m 40
140
+ yolov5l 24
141
+ yolov5x 16
142
+ ```
143
+
144
+ <img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
145
+
146
+ </details>
147
+
148
+ <details open>
149
+ <summary>Tutorials</summary>
150
+
151
+ - [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data)  🚀 RECOMMENDED
152
+ - [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results)  ☘️
153
+ RECOMMENDED
154
+ - [Weights & Biases Logging](https://github.com/ultralytics/yolov5/issues/1289)  🌟 NEW
155
+ - [Roboflow for Datasets, Labeling, and Active Learning](https://github.com/ultralytics/yolov5/issues/4975)  🌟 NEW
156
+ - [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475)
157
+ - [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36)  ⭐ NEW
158
+ - [TFLite, ONNX, CoreML, TensorRT Export](https://github.com/ultralytics/yolov5/issues/251) 🚀
159
+ - [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303)
160
+ - [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318)
161
+ - [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304)
162
+ - [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607)
163
+ - [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314)  ⭐ NEW
164
+ - [Architecture Summary](https://github.com/ultralytics/yolov5/issues/6998)  ⭐ NEW
165
+
166
+ </details>
167
+
168
+ ## <div align="center">Environments</div>
169
+
170
+ Get started in seconds with our verified environments. Click each icon below for details.
171
+
172
+ <div align="center">
173
+ <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
174
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-colab-small.png" width="15%"/>
175
+ </a>
176
+ <a href="https://www.kaggle.com/ultralytics/yolov5">
177
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-kaggle-small.png" width="15%"/>
178
+ </a>
179
+ <a href="https://hub.docker.com/r/ultralytics/yolov5">
180
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-docker-small.png" width="15%"/>
181
+ </a>
182
+ <a href="https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart">
183
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-aws-small.png" width="15%"/>
184
+ </a>
185
+ <a href="https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart">
186
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-gcp-small.png" width="15%"/>
187
+ </a>
188
+ </div>
189
+
190
+ ## <div align="center">Integrations</div>
191
+
192
+ <div align="center">
193
+ <a href="https://wandb.ai/site?utm_campaign=repo_yolo_readme">
194
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-wb-long.png" width="49%"/>
195
+ </a>
196
+ <a href="https://roboflow.com/?ref=ultralytics">
197
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-roboflow-long.png" width="49%"/>
198
+ </a>
199
+ </div>
200
+
201
+ |Weights and Biases|Roboflow ⭐ NEW|
202
+ |:-:|:-:|
203
+ |Automatically track and visualize all your YOLOv5 training runs in the cloud with [Weights & Biases](https://wandb.ai/site?utm_campaign=repo_yolo_readme)|Label and export your custom datasets directly to YOLOv5 for training with [Roboflow](https://roboflow.com/?ref=ultralytics) |
204
+
205
+ <!-- ## <div align="center">Compete and Win</div>
206
+
207
+ We are super excited about our first-ever Ultralytics YOLOv5 🚀 EXPORT Competition with **$10,000** in cash prizes!
208
+
209
+ <p align="center">
210
+ <a href="https://github.com/ultralytics/yolov5/discussions/3213">
211
+ <img width="850" src="https://github.com/ultralytics/yolov5/releases/download/v1.0/banner-export-competition.png"></a>
212
+ </p> -->
213
+
214
+ ## <div align="center">Why YOLOv5</div>
215
+
216
+ <p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040763-93c22a27-347c-4e3c-847a-8094621d3f4e.png"></p>
217
+ <details>
218
+ <summary>YOLOv5-P5 640 Figure (click to expand)</summary>
219
+
220
+ <p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040757-ce0934a3-06a6-43dc-a979-2edbbd69ea0e.png"></p>
221
+ </details>
222
+ <details>
223
+ <summary>Figure Notes (click to expand)</summary>
224
+
225
+ - **COCO AP val** denotes [email protected]:0.95 metric measured on the 5000-image [COCO val2017](http://cocodataset.org) dataset over various inference sizes from 256 to 1536.
226
+ - **GPU Speed** measures average inference time per image on [COCO val2017](http://cocodataset.org) dataset using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100 instance at batch-size 32.
227
+ - **EfficientDet** data from [google/automl](https://github.com/google/automl) at batch size 8.
228
+ - **Reproduce** by `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
229
+
230
+ </details>
231
+
232
+ ### Pretrained Checkpoints
233
+
234
+ |Model |size<br><sup>(pixels) |mAP<sup>val<br>0.5:0.95 |mAP<sup>val<br>0.5 |Speed<br><sup>CPU b1<br>(ms) |Speed<br><sup>V100 b1<br>(ms) |Speed<br><sup>V100 b32<br>(ms) |params<br><sup>(M) |FLOPs<br><sup>@640 (B)
235
+ |--- |--- |--- |--- |--- |--- |--- |--- |---
236
+ |[YOLOv5n][assets] |640 |28.0 |45.7 |**45** |**6.3**|**0.6**|**1.9**|**4.5**
237
+ |[YOLOv5s][assets] |640 |37.4 |56.8 |98 |6.4 |0.9 |7.2 |16.5
238
+ |[YOLOv5m][assets] |640 |45.4 |64.1 |224 |8.2 |1.7 |21.2 |49.0
239
+ |[YOLOv5l][assets] |640 |49.0 |67.3 |430 |10.1 |2.7 |46.5 |109.1
240
+ |[YOLOv5x][assets] |640 |50.7 |68.9 |766 |12.1 |4.8 |86.7 |205.7
241
+ | | | | | | | | |
242
+ |[YOLOv5n6][assets] |1280 |36.0 |54.4 |153 |8.1 |2.1 |3.2 |4.6
243
+ |[YOLOv5s6][assets] |1280 |44.8 |63.7 |385 |8.2 |3.6 |12.6 |16.8
244
+ |[YOLOv5m6][assets] |1280 |51.3 |69.3 |887 |11.1 |6.8 |35.7 |50.0
245
+ |[YOLOv5l6][assets] |1280 |53.7 |71.3 |1784 |15.8 |10.5 |76.8 |111.4
246
+ |[YOLOv5x6][assets]<br>+ [TTA][TTA]|1280<br>1536 |55.0<br>**55.8** |72.7<br>**72.7** |3136<br>- |26.2<br>- |19.4<br>- |140.7<br>- |209.8<br>-
247
+
248
+ <details>
249
+ <summary>Table Notes (click to expand)</summary>
250
+
251
+ - All checkpoints are trained to 300 epochs with default settings. Nano and Small models use [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyps, all others use [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml).
252
+ - **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.<br>Reproduce by `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
253
+ - **Speed** averaged over COCO val images using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) instance. NMS times (~1 ms/img) not included.<br>Reproduce by `python val.py --data coco.yaml --img 640 --task speed --batch 1`
254
+ - **TTA** [Test Time Augmentation](https://github.com/ultralytics/yolov5/issues/303) includes reflection and scale augmentations.<br>Reproduce by `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
255
+
256
+ </details>
257
+
258
+ ## <div align="center">Contribute</div>
259
+
260
+ We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible. Please see our [Contributing Guide](CONTRIBUTING.md) to get started, and fill out the [YOLOv5 Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experiences. Thank you to all our contributors!
261
+
262
+ <a href="https://github.com/ultralytics/yolov5/graphs/contributors"><img src="https://opencollective.com/ultralytics/contributors.svg?width=990" /></a>
263
+
264
+ ## <div align="center">Contact</div>
265
+
266
+ For YOLOv5 bugs and feature requests please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For business inquiries or
267
+ professional support requests please visit [https://ultralytics.com/contact](https://ultralytics.com/contact).
268
+
269
+ <br>
270
+
271
+ <div align="center">
272
+ <a href="https://github.com/ultralytics">
273
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-github.png" width="3%"/>
274
+ </a>
275
+ <img width="3%" />
276
+ <a href="https://www.linkedin.com/company/ultralytics">
277
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-linkedin.png" width="3%"/>
278
+ </a>
279
+ <img width="3%" />
280
+ <a href="https://twitter.com/ultralytics">
281
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-twitter.png" width="3%"/>
282
+ </a>
283
+ <img width="3%" />
284
+ <a href="https://www.producthunt.com/@glenn_jocher">
285
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-producthunt.png" width="3%"/>
286
+ </a>
287
+ <img width="3%" />
288
+ <a href="https://youtube.com/ultralytics">
289
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-youtube.png" width="3%"/>
290
+ </a>
291
+ <img width="3%" />
292
+ <a href="https://www.facebook.com/ultralytics">
293
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-facebook.png" width="3%"/>
294
+ </a>
295
+ <img width="3%" />
296
+ <a href="https://www.instagram.com/ultralytics/">
297
+ <img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-instagram.png" width="3%"/>
298
+ </a>
299
+ </div>
300
+
301
+ [assets]: https://github.com/ultralytics/yolov5/releases
302
+ [tta]: https://github.com/ultralytics/yolov5/issues/303
data.yaml ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _wandb:
2
+ value:
3
+ cli_version: 0.19.2
4
+ m: []
5
+ python_version: 3.11.11
6
+ t:
7
+ "1":
8
+ - 2
9
+ - 1
10
+ - 3
11
+ - 12
12
+ - 41
13
+ - 49
14
+ - 55
15
+ - 105
16
+ "2":
17
+ - 2
18
+ - 1
19
+ - 3
20
+ - 12
21
+ - 41
22
+ - 49
23
+ - 55
24
+ - 105
25
+ "3":
26
+ - 13
27
+ - 16
28
+ - 23
29
+ - 55
30
+ "4": 3.11.11
31
+ "5": 0.19.2
32
+ "8":
33
+ - 5
34
+ "12": 0.19.2
35
+ "13": linux-x86_64
36
+ artifact_alias:
37
+ value: latest
38
+ batch_size:
39
+ value: 16
40
+ bbox_interval:
41
+ value: -1
42
+ bucket:
43
+ value: ""
44
+ cache:
45
+ value: ram
46
+ cfg:
47
+ value: ./models/custom_yolov5s.yaml
48
+ cos_lr:
49
+ value: false
50
+ data:
51
+ value: /content/yolov5/data.yaml
52
+ device:
53
+ value: ""
54
+ entity:
55
+ value: null
56
+ epochs:
57
+ value: 100
58
+ evolve:
59
+ value: null
60
+ exist_ok:
61
+ value: false
62
+ freeze:
63
+ value:
64
+ - 0
65
+ hyp:
66
+ value:
67
+ anchor_t: 4
68
+ box: 0.05
69
+ cls: 0.5
70
+ cls_pw: 1
71
+ copy_paste: 0
72
+ degrees: 0
73
+ fl_gamma: 0
74
+ fliplr: 0.5
75
+ flipud: 0
76
+ hsv_h: 0.015
77
+ hsv_s: 0.7
78
+ hsv_v: 0.4
79
+ iou_t: 0.2
80
+ lr0: 0.01
81
+ lrf: 0.01
82
+ mixup: 0
83
+ momentum: 0.937
84
+ mosaic: 1
85
+ obj: 1
86
+ obj_pw: 1
87
+ perspective: 0
88
+ scale: 0.5
89
+ shear: 0
90
+ translate: 0.1
91
+ warmup_bias_lr: 0.1
92
+ warmup_epochs: 3
93
+ warmup_momentum: 0.8
94
+ weight_decay: 0.0005
95
+ image_weights:
96
+ value: false
97
+ imgsz:
98
+ value: 416
99
+ label_smoothing:
100
+ value: 0
101
+ local_rank:
102
+ value: -1
103
+ multi_scale:
104
+ value: false
105
+ name:
106
+ value: yolov5s_results
107
+ noautoanchor:
108
+ value: false
109
+ noplots:
110
+ value: false
111
+ nosave:
112
+ value: false
113
+ noval:
114
+ value: false
115
+ optimizer:
116
+ value: SGD
117
+ patience:
118
+ value: 100
119
+ project:
120
+ value: runs/train
121
+ quad:
122
+ value: false
123
+ rect:
124
+ value: false
125
+ resume:
126
+ value: false
127
+ save_dir:
128
+ value: runs/train/yolov5s_results2
129
+ save_period:
130
+ value: -1
131
+ seed:
132
+ value: 0
133
+ single_cls:
134
+ value: false
135
+ sync_bn:
136
+ value: false
137
+ upload_dataset:
138
+ value: false
139
+ weights:
140
+ value: ""
141
+ workers:
142
+ value: 8
143
+
144
+ train: train/images
145
+ val: valid/images
146
+ test: test/images
147
+
148
+ nc: 1
149
+ names: ['0']
detect.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Run inference on images, videos, directories, streams, etc.
4
+
5
+ Usage - sources:
6
+ $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
7
+ img.jpg # image
8
+ vid.mp4 # video
9
+ path/ # directory
10
+ path/*.jpg # glob
11
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
12
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
13
+
14
+ Usage - formats:
15
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
16
+ yolov5s.torchscript # TorchScript
17
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
18
+ yolov5s.xml # OpenVINO
19
+ yolov5s.engine # TensorRT
20
+ yolov5s.mlmodel # CoreML (macOS-only)
21
+ yolov5s_saved_model # TensorFlow SavedModel
22
+ yolov5s.pb # TensorFlow GraphDef
23
+ yolov5s.tflite # TensorFlow Lite
24
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
25
+ """
26
+
27
+ import argparse
28
+ import os
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ import torch
33
+ import torch.backends.cudnn as cudnn
34
+
35
+ FILE = Path(__file__).resolve()
36
+ ROOT = FILE.parents[0] # YOLOv5 root directory
37
+ if str(ROOT) not in sys.path:
38
+ sys.path.append(str(ROOT)) # add ROOT to PATH
39
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
40
+
41
+ from models.common import DetectMultiBackend
42
+ from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
43
+ from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
44
+ increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
45
+ from utils.plots import Annotator, colors, save_one_box
46
+ from utils.torch_utils import select_device, time_sync
47
+
48
+
49
+ @torch.no_grad()
50
+ def run(
51
+ weights=ROOT / 'yolov5s.pt', # model.pt path(s)
52
+ source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
53
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
54
+ imgsz=(640, 640), # inference size (height, width)
55
+ conf_thres=0.25, # confidence threshold
56
+ iou_thres=0.45, # NMS IOU threshold
57
+ max_det=1000, # maximum detections per image
58
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
59
+ view_img=False, # show results
60
+ save_txt=False, # save results to *.txt
61
+ save_conf=False, # save confidences in --save-txt labels
62
+ save_crop=False, # save cropped prediction boxes
63
+ nosave=False, # do not save images/videos
64
+ classes=None, # filter by class: --class 0, or --class 0 2 3
65
+ agnostic_nms=False, # class-agnostic NMS
66
+ augment=False, # augmented inference
67
+ visualize=False, # visualize features
68
+ update=False, # update all models
69
+ project=ROOT / 'runs/detect', # save results to project/name
70
+ name='exp', # save results to project/name
71
+ exist_ok=False, # existing project/name ok, do not increment
72
+ line_thickness=3, # bounding box thickness (pixels)
73
+ hide_labels=False, # hide labels
74
+ hide_conf=False, # hide confidences
75
+ half=False, # use FP16 half-precision inference
76
+ dnn=False, # use OpenCV DNN for ONNX inference
77
+ ):
78
+ source = str(source)
79
+ save_img = not nosave and not source.endswith('.txt') # save inference images
80
+ is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
81
+ is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
82
+ webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
83
+ if is_url and is_file:
84
+ source = check_file(source) # download
85
+
86
+ # Directories
87
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
88
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
89
+
90
+ # Load model
91
+ device = select_device(device)
92
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
93
+ stride, names, pt = model.stride, model.names, model.pt
94
+ imgsz = check_img_size(imgsz, s=stride) # check image size
95
+
96
+ # Dataloader
97
+ if webcam:
98
+ view_img = check_imshow()
99
+ cudnn.benchmark = True # set True to speed up constant image size inference
100
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
101
+ bs = len(dataset) # batch_size
102
+ else:
103
+ dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
104
+ bs = 1 # batch_size
105
+ vid_path, vid_writer = [None] * bs, [None] * bs
106
+
107
+ # Run inference
108
+ model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
109
+ seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
110
+ for path, im, im0s, vid_cap, s in dataset:
111
+ t1 = time_sync()
112
+ im = torch.from_numpy(im).to(device)
113
+ im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
114
+ im /= 255 # 0 - 255 to 0.0 - 1.0
115
+ if len(im.shape) == 3:
116
+ im = im[None] # expand for batch dim
117
+ t2 = time_sync()
118
+ dt[0] += t2 - t1
119
+
120
+ # Inference
121
+ visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
122
+ pred = model(im, augment=augment, visualize=visualize)
123
+ t3 = time_sync()
124
+ dt[1] += t3 - t2
125
+
126
+ # NMS
127
+ pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
128
+ dt[2] += time_sync() - t3
129
+
130
+ # Second-stage classifier (optional)
131
+ # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
132
+
133
+ # Process predictions
134
+ for i, det in enumerate(pred): # per image
135
+ seen += 1
136
+ if webcam: # batch_size >= 1
137
+ p, im0, frame = path[i], im0s[i].copy(), dataset.count
138
+ s += f'{i}: '
139
+ else:
140
+ p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
141
+
142
+ p = Path(p) # to Path
143
+ save_path = str(save_dir / p.name) # im.jpg
144
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
145
+ s += '%gx%g ' % im.shape[2:] # print string
146
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
147
+ imc = im0.copy() if save_crop else im0 # for save_crop
148
+ annotator = Annotator(im0, line_width=line_thickness, example=str(names))
149
+ if len(det):
150
+ # Rescale boxes from img_size to im0 size
151
+ det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
152
+
153
+ # Print results
154
+ for c in det[:, -1].unique():
155
+ n = (det[:, -1] == c).sum() # detections per class
156
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
157
+
158
+ # Write results
159
+ for *xyxy, conf, cls in reversed(det):
160
+ if save_txt: # Write to file
161
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
162
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
163
+ with open(f'{txt_path}.txt', 'a') as f:
164
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
165
+
166
+ if save_img or save_crop or view_img: # Add bbox to image
167
+ c = int(cls) # integer class
168
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
169
+ annotator.box_label(xyxy, label, color=colors(c, True))
170
+ if save_crop:
171
+ save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
172
+
173
+ # Stream results
174
+ im0 = annotator.result()
175
+ if view_img:
176
+ if p not in windows:
177
+ windows.append(p)
178
+ cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
179
+ cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
180
+ cv2.imshow(str(p), im0)
181
+ cv2.waitKey(1) # 1 millisecond
182
+
183
+ # Save results (image with detections)
184
+ if save_img:
185
+ if dataset.mode == 'image':
186
+ cv2.imwrite(save_path, im0)
187
+ else: # 'video' or 'stream'
188
+ if vid_path[i] != save_path: # new video
189
+ vid_path[i] = save_path
190
+ if isinstance(vid_writer[i], cv2.VideoWriter):
191
+ vid_writer[i].release() # release previous video writer
192
+ if vid_cap: # video
193
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
194
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
195
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
196
+ else: # stream
197
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
198
+ save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
199
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
200
+ vid_writer[i].write(im0)
201
+
202
+ # Print time (inference-only)
203
+ LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
204
+
205
+ # Print results
206
+ t = tuple(x / seen * 1E3 for x in dt) # speeds per image
207
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
208
+ if save_txt or save_img:
209
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
210
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
211
+ if update:
212
+ strip_optimizer(weights) # update model (to fix SourceChangeWarning)
213
+
214
+
215
+ def parse_opt():
216
+ parser = argparse.ArgumentParser()
217
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
218
+ parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
219
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
220
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
221
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
222
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
223
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
224
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
225
+ parser.add_argument('--view-img', action='store_true', help='show results')
226
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
227
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
228
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
229
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
230
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
231
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
232
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
233
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
234
+ parser.add_argument('--update', action='store_true', help='update all models')
235
+ parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
236
+ parser.add_argument('--name', default='exp', help='save results to project/name')
237
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
238
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
239
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
240
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
241
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
242
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
243
+ opt = parser.parse_args()
244
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
245
+ print_args(vars(opt))
246
+ return opt
247
+
248
+
249
+ def main(opt):
250
+ check_requirements(exclude=('tensorboard', 'thop'))
251
+ run(**vars(opt))
252
+
253
+
254
+ if __name__ == "__main__":
255
+ opt = parse_opt()
256
+ main(opt)
empty.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ remo_count=0
3
+ temp = []
4
+
5
+
6
+ txt_names = os.listdir("./data/test/labels/") # dir of txt files
7
+ for x in txt_names:
8
+ with open('./data/test/labels/' + x, 'r') as file: # openeing txt files
9
+ lines = file.readlines()
10
+ if len(lines) == 0: # if thee txt file is empty
11
+ file_name = os.path.splitext(x)[0] # save file name without suffic
12
+ temp.append('./data/test/labels/'+ x) # add the txt file name to a list cus it is still open
13
+ print('./data/test/labels/'+ x)
14
+ try:
15
+ os.remove('./data/test/images/'+ file_name + '.jpg') # remove the img file that corresonds to the txt file
16
+ except:
17
+ print('Could not find the jpg version')
18
+ remo_count += 1
19
+ file.close()
20
+
21
+ for i in temp:
22
+
23
+ os.remove(i) # remove all empty txt files
24
+
25
+
26
+ print(remo_count)
27
+
28
+
29
+
export.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+
23
+ Usage:
24
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
25
+
26
+ Inference:
27
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
28
+ yolov5s.torchscript # TorchScript
29
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
30
+ yolov5s.xml # OpenVINO
31
+ yolov5s.engine # TensorRT
32
+ yolov5s.mlmodel # CoreML (macOS-only)
33
+ yolov5s_saved_model # TensorFlow SavedModel
34
+ yolov5s.pb # TensorFlow GraphDef
35
+ yolov5s.tflite # TensorFlow Lite
36
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
37
+
38
+ TensorFlow.js:
39
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
40
+ $ npm install
41
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
42
+ $ npm start
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import platform
49
+ import subprocess
50
+ import sys
51
+ import time
52
+ import warnings
53
+ from pathlib import Path
54
+
55
+ import pandas as pd
56
+ import torch
57
+ import yaml
58
+ from torch.utils.mobile_optimizer import optimize_for_mobile
59
+
60
+ FILE = Path(__file__).resolve()
61
+ ROOT = FILE.parents[0] # YOLOv5 root directory
62
+ if str(ROOT) not in sys.path:
63
+ sys.path.append(str(ROOT)) # add ROOT to PATH
64
+ if platform.system() != 'Windows':
65
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
66
+
67
+ from models.experimental import attempt_load
68
+ from models.yolo import Detect
69
+ from utils.dataloaders import LoadImages
70
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
71
+ file_size, print_args, url2file)
72
+ from utils.torch_utils import select_device
73
+
74
+
75
+ def export_formats():
76
+ # YOLOv5 export formats
77
+ x = [
78
+ ['PyTorch', '-', '.pt', True, True],
79
+ ['TorchScript', 'torchscript', '.torchscript', True, True],
80
+ ['ONNX', 'onnx', '.onnx', True, True],
81
+ ['OpenVINO', 'openvino', '_openvino_model', True, False],
82
+ ['TensorRT', 'engine', '.engine', False, True],
83
+ ['CoreML', 'coreml', '.mlmodel', True, False],
84
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
85
+ ['TensorFlow GraphDef', 'pb', '.pb', True, True],
86
+ ['TensorFlow Lite', 'tflite', '.tflite', True, False],
87
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
88
+ ['TensorFlow.js', 'tfjs', '_web_model', False, False],]
89
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
90
+
91
+
92
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
93
+ # YOLOv5 TorchScript model export
94
+ try:
95
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
96
+ f = file.with_suffix('.torchscript')
97
+
98
+ ts = torch.jit.trace(model, im, strict=False)
99
+ d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
100
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
101
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
102
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
103
+ else:
104
+ ts.save(str(f), _extra_files=extra_files)
105
+
106
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
107
+ return f
108
+ except Exception as e:
109
+ LOGGER.info(f'{prefix} export failure: {e}')
110
+
111
+
112
+ def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
113
+ # YOLOv5 ONNX export
114
+ try:
115
+ check_requirements(('onnx',))
116
+ import onnx
117
+
118
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
119
+ f = file.with_suffix('.onnx')
120
+
121
+ torch.onnx.export(
122
+ model.cpu() if dynamic else model, # --dynamic only compatible with cpu
123
+ im.cpu() if dynamic else im,
124
+ f,
125
+ verbose=False,
126
+ opset_version=opset,
127
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
128
+ do_constant_folding=not train,
129
+ input_names=['images'],
130
+ output_names=['output'],
131
+ dynamic_axes={
132
+ 'images': {
133
+ 0: 'batch',
134
+ 2: 'height',
135
+ 3: 'width'}, # shape(1,3,640,640)
136
+ 'output': {
137
+ 0: 'batch',
138
+ 1: 'anchors'} # shape(1,25200,85)
139
+ } if dynamic else None)
140
+
141
+ # Checks
142
+ model_onnx = onnx.load(f) # load onnx model
143
+ onnx.checker.check_model(model_onnx) # check onnx model
144
+
145
+ # Metadata
146
+ d = {'stride': int(max(model.stride)), 'names': model.names}
147
+ for k, v in d.items():
148
+ meta = model_onnx.metadata_props.add()
149
+ meta.key, meta.value = k, str(v)
150
+ onnx.save(model_onnx, f)
151
+
152
+ # Simplify
153
+ if simplify:
154
+ try:
155
+ check_requirements(('onnx-simplifier',))
156
+ import onnxsim
157
+
158
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
159
+ model_onnx, check = onnxsim.simplify(model_onnx,
160
+ dynamic_input_shape=dynamic,
161
+ input_shapes={'images': list(im.shape)} if dynamic else None)
162
+ assert check, 'assert check failed'
163
+ onnx.save(model_onnx, f)
164
+ except Exception as e:
165
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
166
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
167
+ return f
168
+ except Exception as e:
169
+ LOGGER.info(f'{prefix} export failure: {e}')
170
+
171
+
172
+ def export_openvino(model, file, half, prefix=colorstr('OpenVINO:')):
173
+ # YOLOv5 OpenVINO export
174
+ try:
175
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
176
+ import openvino.inference_engine as ie
177
+
178
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
179
+ f = str(file).replace('.pt', f'_openvino_model{os.sep}')
180
+
181
+ cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
182
+ subprocess.check_output(cmd.split()) # export
183
+ with open(Path(f) / file.with_suffix('.yaml').name, 'w') as g:
184
+ yaml.dump({'stride': int(max(model.stride)), 'names': model.names}, g) # add metadata.yaml
185
+
186
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
187
+ return f
188
+ except Exception as e:
189
+ LOGGER.info(f'\n{prefix} export failure: {e}')
190
+
191
+
192
+ def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
193
+ # YOLOv5 CoreML export
194
+ try:
195
+ check_requirements(('coremltools',))
196
+ import coremltools as ct
197
+
198
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
199
+ f = file.with_suffix('.mlmodel')
200
+
201
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
202
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
203
+ bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
204
+ if bits < 32:
205
+ if platform.system() == 'Darwin': # quantization only supported on macOS
206
+ with warnings.catch_warnings():
207
+ warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
208
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
209
+ else:
210
+ print(f'{prefix} quantization only supported on macOS, skipping...')
211
+ ct_model.save(f)
212
+
213
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
214
+ return ct_model, f
215
+ except Exception as e:
216
+ LOGGER.info(f'\n{prefix} export failure: {e}')
217
+ return None, None
218
+
219
+
220
+ def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
221
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
222
+ try:
223
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
224
+ try:
225
+ import tensorrt as trt
226
+ except Exception:
227
+ if platform.system() == 'Linux':
228
+ check_requirements(('nvidia-tensorrt',), cmds=('-U --index-url https://pypi.ngc.nvidia.com',))
229
+ import tensorrt as trt
230
+
231
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
232
+ grid = model.model[-1].anchor_grid
233
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
234
+ export_onnx(model, im, file, 12, train, False, simplify) # opset 12
235
+ model.model[-1].anchor_grid = grid
236
+ else: # TensorRT >= 8
237
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
238
+ export_onnx(model, im, file, 13, train, False, simplify) # opset 13
239
+ onnx = file.with_suffix('.onnx')
240
+
241
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
242
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
243
+ f = file.with_suffix('.engine') # TensorRT engine file
244
+ logger = trt.Logger(trt.Logger.INFO)
245
+ if verbose:
246
+ logger.min_severity = trt.Logger.Severity.VERBOSE
247
+
248
+ builder = trt.Builder(logger)
249
+ config = builder.create_builder_config()
250
+ config.max_workspace_size = workspace * 1 << 30
251
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
252
+
253
+ flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
254
+ network = builder.create_network(flag)
255
+ parser = trt.OnnxParser(network, logger)
256
+ if not parser.parse_from_file(str(onnx)):
257
+ raise RuntimeError(f'failed to load ONNX file: {onnx}')
258
+
259
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
260
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
261
+ LOGGER.info(f'{prefix} Network Description:')
262
+ for inp in inputs:
263
+ LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
264
+ for out in outputs:
265
+ LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
266
+
267
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}')
268
+ if builder.platform_has_fast_fp16 and half:
269
+ config.set_flag(trt.BuilderFlag.FP16)
270
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
271
+ t.write(engine.serialize())
272
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
273
+ return f
274
+ except Exception as e:
275
+ LOGGER.info(f'\n{prefix} export failure: {e}')
276
+
277
+
278
+ def export_saved_model(model,
279
+ im,
280
+ file,
281
+ dynamic,
282
+ tf_nms=False,
283
+ agnostic_nms=False,
284
+ topk_per_class=100,
285
+ topk_all=100,
286
+ iou_thres=0.45,
287
+ conf_thres=0.25,
288
+ keras=False,
289
+ prefix=colorstr('TensorFlow SavedModel:')):
290
+ # YOLOv5 TensorFlow SavedModel export
291
+ try:
292
+ import tensorflow as tf
293
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
294
+
295
+ from models.tf import TFDetect, TFModel
296
+
297
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
298
+ f = str(file).replace('.pt', '_saved_model')
299
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
300
+
301
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
302
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
303
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
304
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
305
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
306
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
307
+ keras_model.trainable = False
308
+ keras_model.summary()
309
+ if keras:
310
+ keras_model.save(f, save_format='tf')
311
+ else:
312
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
313
+ m = tf.function(lambda x: keras_model(x)) # full model
314
+ m = m.get_concrete_function(spec)
315
+ frozen_func = convert_variables_to_constants_v2(m)
316
+ tfm = tf.Module()
317
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
318
+ tfm.__call__(im)
319
+ tf.saved_model.save(tfm,
320
+ f,
321
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
322
+ if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
323
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
324
+ return keras_model, f
325
+ except Exception as e:
326
+ LOGGER.info(f'\n{prefix} export failure: {e}')
327
+ return None, None
328
+
329
+
330
+ def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
331
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
332
+ try:
333
+ import tensorflow as tf
334
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
335
+
336
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
337
+ f = file.with_suffix('.pb')
338
+
339
+ m = tf.function(lambda x: keras_model(x)) # full model
340
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
341
+ frozen_func = convert_variables_to_constants_v2(m)
342
+ frozen_func.graph.as_graph_def()
343
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
344
+
345
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
346
+ return f
347
+ except Exception as e:
348
+ LOGGER.info(f'\n{prefix} export failure: {e}')
349
+
350
+
351
+ def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
352
+ # YOLOv5 TensorFlow Lite export
353
+ try:
354
+ import tensorflow as tf
355
+
356
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
357
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
358
+ f = str(file).replace('.pt', '-fp16.tflite')
359
+
360
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
361
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
362
+ converter.target_spec.supported_types = [tf.float16]
363
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
364
+ if int8:
365
+ from models.tf import representative_dataset_gen
366
+ dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
367
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
368
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
369
+ converter.target_spec.supported_types = []
370
+ converter.inference_input_type = tf.uint8 # or tf.int8
371
+ converter.inference_output_type = tf.uint8 # or tf.int8
372
+ converter.experimental_new_quantizer = True
373
+ f = str(file).replace('.pt', '-int8.tflite')
374
+ if nms or agnostic_nms:
375
+ converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
376
+
377
+ tflite_model = converter.convert()
378
+ open(f, "wb").write(tflite_model)
379
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
380
+ return f
381
+ except Exception as e:
382
+ LOGGER.info(f'\n{prefix} export failure: {e}')
383
+
384
+
385
+ def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
386
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
387
+ try:
388
+ cmd = 'edgetpu_compiler --version'
389
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
390
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
391
+ if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
392
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
393
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
394
+ for c in (
395
+ 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
396
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
397
+ 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
398
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
399
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
400
+
401
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
402
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
403
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
404
+
405
+ cmd = f"edgetpu_compiler -s -o {file.parent} {f_tfl}"
406
+ subprocess.run(cmd.split(), check=True)
407
+
408
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
409
+ return f
410
+ except Exception as e:
411
+ LOGGER.info(f'\n{prefix} export failure: {e}')
412
+
413
+
414
+ def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
415
+ # YOLOv5 TensorFlow.js export
416
+ try:
417
+ check_requirements(('tensorflowjs',))
418
+ import re
419
+
420
+ import tensorflowjs as tfjs
421
+
422
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
423
+ f = str(file).replace('.pt', '_web_model') # js dir
424
+ f_pb = file.with_suffix('.pb') # *.pb path
425
+ f_json = f'{f}/model.json' # *.json path
426
+
427
+ cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
428
+ f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
429
+ subprocess.run(cmd.split())
430
+
431
+ with open(f_json) as j:
432
+ json = j.read()
433
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
434
+ subst = re.sub(
435
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
436
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
437
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
438
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
439
+ r'"Identity_1": {"name": "Identity_1"}, '
440
+ r'"Identity_2": {"name": "Identity_2"}, '
441
+ r'"Identity_3": {"name": "Identity_3"}}}', json)
442
+ j.write(subst)
443
+
444
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
445
+ return f
446
+ except Exception as e:
447
+ LOGGER.info(f'\n{prefix} export failure: {e}')
448
+
449
+
450
+ @torch.no_grad()
451
+ def run(
452
+ data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
453
+ weights=ROOT / 'yolov5s.pt', # weights path
454
+ imgsz=(640, 640), # image (height, width)
455
+ batch_size=1, # batch size
456
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
457
+ include=('torchscript', 'onnx'), # include formats
458
+ half=False, # FP16 half-precision export
459
+ inplace=False, # set YOLOv5 Detect() inplace=True
460
+ train=False, # model.train() mode
461
+ keras=False, # use Keras
462
+ optimize=False, # TorchScript: optimize for mobile
463
+ int8=False, # CoreML/TF INT8 quantization
464
+ dynamic=False, # ONNX/TF: dynamic axes
465
+ simplify=False, # ONNX: simplify model
466
+ opset=12, # ONNX: opset version
467
+ verbose=False, # TensorRT: verbose log
468
+ workspace=4, # TensorRT: workspace size (GB)
469
+ nms=False, # TF: add NMS to model
470
+ agnostic_nms=False, # TF: add agnostic NMS to model
471
+ topk_per_class=100, # TF.js NMS: topk per class to keep
472
+ topk_all=100, # TF.js NMS: topk for all classes to keep
473
+ iou_thres=0.45, # TF.js NMS: IoU threshold
474
+ conf_thres=0.25, # TF.js NMS: confidence threshold
475
+ ):
476
+ t = time.time()
477
+ include = [x.lower() for x in include] # to lowercase
478
+ fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
479
+ flags = [x in include for x in fmts]
480
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
481
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
482
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
483
+
484
+ # Load PyTorch model
485
+ device = select_device(device)
486
+ if half:
487
+ assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
488
+ assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
489
+ model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
490
+ nc, names = model.nc, model.names # number of classes, class names
491
+
492
+ # Checks
493
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
494
+ assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
495
+ if optimize:
496
+ assert device.type != 'cuda', '--optimize not compatible with cuda devices, i.e. use --device cpu'
497
+
498
+ # Input
499
+ gs = int(max(model.stride)) # grid size (max stride)
500
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
501
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
502
+
503
+ # Update model
504
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
505
+ for k, m in model.named_modules():
506
+ if isinstance(m, Detect):
507
+ m.inplace = inplace
508
+ m.onnx_dynamic = dynamic
509
+ m.export = True
510
+
511
+ for _ in range(2):
512
+ y = model(im) # dry runs
513
+ if half and not coreml:
514
+ im, model = im.half(), model.half() # to FP16
515
+ shape = tuple(y[0].shape) # model output shape
516
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
517
+
518
+ # Exports
519
+ f = [''] * 10 # exported filenames
520
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
521
+ if jit:
522
+ f[0] = export_torchscript(model, im, file, optimize)
523
+ if engine: # TensorRT required before ONNX
524
+ f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
525
+ if onnx or xml: # OpenVINO requires ONNX
526
+ f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
527
+ if xml: # OpenVINO
528
+ f[3] = export_openvino(model, file, half)
529
+ if coreml:
530
+ _, f[4] = export_coreml(model, im, file, int8, half)
531
+
532
+ # TensorFlow Exports
533
+ if any((saved_model, pb, tflite, edgetpu, tfjs)):
534
+ if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
535
+ check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
536
+ assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
537
+ model, f[5] = export_saved_model(model.cpu(),
538
+ im,
539
+ file,
540
+ dynamic,
541
+ tf_nms=nms or agnostic_nms or tfjs,
542
+ agnostic_nms=agnostic_nms or tfjs,
543
+ topk_per_class=topk_per_class,
544
+ topk_all=topk_all,
545
+ iou_thres=iou_thres,
546
+ conf_thres=conf_thres,
547
+ keras=keras)
548
+ if pb or tfjs: # pb prerequisite to tfjs
549
+ f[6] = export_pb(model, file)
550
+ if tflite or edgetpu:
551
+ f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
552
+ if edgetpu:
553
+ f[8] = export_edgetpu(file)
554
+ if tfjs:
555
+ f[9] = export_tfjs(file)
556
+
557
+ # Finish
558
+ f = [str(x) for x in f if x] # filter out '' and None
559
+ if any(f):
560
+ h = '--half' if half else '' # --half FP16 inference arg
561
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
562
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
563
+ f"\nDetect: python detect.py --weights {f[-1]} {h}"
564
+ f"\nValidate: python val.py --weights {f[-1]} {h}"
565
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
566
+ f"\nVisualize: https://netron.app")
567
+ return f # return list of exported files/dirs
568
+
569
+
570
+ def parse_opt():
571
+ parser = argparse.ArgumentParser()
572
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
573
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
574
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
575
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
576
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
577
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
578
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
579
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
580
+ parser.add_argument('--keras', action='store_true', help='TF: use Keras')
581
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
582
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
583
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
584
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
585
+ parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
586
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
587
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
588
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
589
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
590
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
591
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
592
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
593
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
594
+ parser.add_argument('--include',
595
+ nargs='+',
596
+ default=['torchscript', 'onnx'],
597
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
598
+ opt = parser.parse_args()
599
+ print_args(vars(opt))
600
+ return opt
601
+
602
+
603
+ def main(opt):
604
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
605
+ run(**vars(opt))
606
+
607
+
608
+ if __name__ == "__main__":
609
+ opt = parse_opt()
610
+ main(opt)
hubconf.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
4
+
5
+ Usage:
6
+ import torch
7
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
8
+ model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch
9
+ """
10
+
11
+ import torch
12
+
13
+
14
+ def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
15
+ """Creates or loads a YOLOv5 model
16
+
17
+ Arguments:
18
+ name (str): model name 'yolov5s' or path 'path/to/best.pt'
19
+ pretrained (bool): load pretrained weights into the model
20
+ channels (int): number of input channels
21
+ classes (int): number of model classes
22
+ autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
23
+ verbose (bool): print all information to screen
24
+ device (str, torch.device, None): device to use for model parameters
25
+
26
+ Returns:
27
+ YOLOv5 model
28
+ """
29
+ from pathlib import Path
30
+
31
+ from models.common import AutoShape, DetectMultiBackend
32
+ from models.yolo import Model
33
+ from utils.downloads import attempt_download
34
+ from utils.general import LOGGER, check_requirements, intersect_dicts, logging
35
+ from utils.torch_utils import select_device
36
+
37
+ if not verbose:
38
+ LOGGER.setLevel(logging.WARNING)
39
+ check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
40
+ name = Path(name)
41
+ path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
42
+ try:
43
+ device = select_device(device)
44
+
45
+ if pretrained and channels == 3 and classes == 80:
46
+ model = DetectMultiBackend(path, device=device, fuse=autoshape) # download/load FP32 model
47
+ # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model
48
+ else:
49
+ cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
50
+ model = Model(cfg, channels, classes) # create model
51
+ if pretrained:
52
+ ckpt = torch.load(attempt_download(path), map_location=device) # load
53
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
54
+ csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
55
+ model.load_state_dict(csd, strict=False) # load
56
+ if len(ckpt['model'].names) == classes:
57
+ model.names = ckpt['model'].names # set class names attribute
58
+ if autoshape:
59
+ model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
60
+ return model.to(device)
61
+
62
+ except Exception as e:
63
+ help_url = 'https://github.com/ultralytics/yolov5/issues/36'
64
+ s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
65
+ raise Exception(s) from e
66
+
67
+
68
+ def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
69
+ # YOLOv5 custom or local model
70
+ return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
71
+
72
+
73
+ def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
74
+ # YOLOv5-nano model https://github.com/ultralytics/yolov5
75
+ return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
76
+
77
+
78
+ def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
79
+ # YOLOv5-small model https://github.com/ultralytics/yolov5
80
+ return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
81
+
82
+
83
+ def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
84
+ # YOLOv5-medium model https://github.com/ultralytics/yolov5
85
+ return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
86
+
87
+
88
+ def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
89
+ # YOLOv5-large model https://github.com/ultralytics/yolov5
90
+ return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
91
+
92
+
93
+ def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
94
+ # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
95
+ return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
96
+
97
+
98
+ def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
99
+ # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
100
+ return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
101
+
102
+
103
+ def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
104
+ # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
105
+ return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
106
+
107
+
108
+ def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
109
+ # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
110
+ return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
111
+
112
+
113
+ def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
114
+ # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
115
+ return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
116
+
117
+
118
+ def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
119
+ # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
120
+ return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
121
+
122
+
123
+ if __name__ == '__main__':
124
+ model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
125
+ # model = custom(path='path/to/model.pt') # custom
126
+
127
+ # Verify inference
128
+ from pathlib import Path
129
+
130
+ import numpy as np
131
+ from PIL import Image
132
+
133
+ from utils.general import cv2
134
+
135
+ imgs = [
136
+ 'data/images/zidane.jpg', # filename
137
+ Path('data/images/zidane.jpg'), # Path
138
+ 'https://ultralytics.com/images/zidane.jpg', # URI
139
+ cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
140
+ Image.open('data/images/bus.jpg'), # PIL
141
+ np.zeros((320, 640, 3))] # numpy
142
+
143
+ results = model(imgs, size=320) # batched inference
144
+ results.print()
145
+ results.save()
optimizer.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+
4
+ count = 0
5
+ next = False
6
+ saves = list()
7
+ directory = input("folder name:")
8
+
9
+ print(os.listdir('./'+ directory + '/'))
10
+ file_names = os.listdir('./'+ directory + '/')
11
+ print(os.path.splitext(file_names[1])[1])
12
+
13
+ file_names.reverse() # so .txt is first
14
+
15
+
16
+ for x in file_names:
17
+ if next == True:
18
+ next = False
19
+ continue
20
+ if os.path.splitext(x)[1] == ".txt":
21
+ next = True
22
+ continue
23
+
24
+ count+=1
25
+ os.remove('./'+ directory + '/' + x)
26
+
27
+ print( "You removed", count, " files")
requirements.txt CHANGED
@@ -1,8 +1,42 @@
1
- torch==2.2.0
2
- numpy==1.26.4
3
- opencv-python
4
- torchvision
5
- matplotlib
6
- seaborn
7
-
8
- Pyrebase4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 requirements
2
+ # Usage: pip install -r requirements.txt
3
+
4
+ # Base ----------------------------------------
5
+ matplotlib>=3.2.2
6
+ numpy>=1.18.5
7
+ opencv-python>=4.1.1
8
+ Pillow>=7.1.2
9
+ PyYAML>=5.3.1
10
+ requests>=2.23.0
11
+ scipy>=1.4.1
12
+ torch>=1.7.0
13
+ torchvision>=0.8.1
14
+ tqdm>=4.64.0
15
+ protobuf<4.21.3 # https://github.com/ultralytics/yolov5/issues/8012
16
+
17
+ # Logging -------------------------------------
18
+ tensorboard>=2.4.1
19
+ # wandb
20
+
21
+ # Plotting ------------------------------------
22
+ pandas>=1.1.4
23
+ seaborn>=0.11.0
24
+
25
+ # Export --------------------------------------
26
+ # coremltools>=4.1 # CoreML export
27
+ # onnx>=1.9.0 # ONNX export
28
+ # onnx-simplifier>=0.3.6 # ONNX simplifier
29
+ # nvidia-pyindex # TensorRT export
30
+ # nvidia-tensorrt # TensorRT export
31
+ # scikit-learn==0.19.2 # CoreML quantization
32
+ # tensorflow>=2.4.1 # TFLite export
33
+ # tensorflowjs>=3.9.0 # TF.js export
34
+ # openvino-dev # OpenVINO export
35
+
36
+ # Extras --------------------------------------
37
+ ipython # interactive notebook
38
+ psutil # system utilization
39
+ thop>=0.1.1 # FLOPs computation
40
+ # albumentations>=1.0.3
41
+ # pycocotools>=2.0 # COCO mAP
42
+ # roboflow
run.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # train yolov5s on custom data for 100 epochs
2
+ # time its performance
3
+ import os
4
+
5
+ os.environ['KMP_DUPLICATE_LIB_OK']='True'
6
+ python test.py
7
+ # python train.py --img 208 --batch 16 --epochs 100 --data ./data.yaml --cfg ./models/custom_yolov5s.yaml --weights 'C:\Users\Samuel\Downloads\yolov5\runs\train\yolov5s_results19\weights\best' --name yolov5s_results --cache
setup.cfg ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project-wide configuration file, can be used for package metadata and other toll configurations
2
+ # Example usage: global configuration for PEP8 (via flake8) setting or default pytest arguments
3
+ # Local usage: pip install pre-commit, pre-commit run --all-files
4
+
5
+ [metadata]
6
+ license_file = LICENSE
7
+ description_file = README.md
8
+
9
+
10
+ [tool:pytest]
11
+ norecursedirs =
12
+ .git
13
+ dist
14
+ build
15
+ addopts =
16
+ --doctest-modules
17
+ --durations=25
18
+ --color=yes
19
+
20
+
21
+ [flake8]
22
+ max-line-length = 120
23
+ exclude = .tox,*.egg,build,temp
24
+ select = E,W,F
25
+ doctests = True
26
+ verbose = 2
27
+ # https://pep8.readthedocs.io/en/latest/intro.html#error-codes
28
+ format = pylint
29
+ # see: https://www.flake8rules.com/
30
+ ignore =
31
+ E731 # Do not assign a lambda expression, use a def
32
+ F405 # name may be undefined, or defined from star imports: module
33
+ E402 # module level import not at top of file
34
+ F401 # module imported but unused
35
+ W504 # line break after binary operator
36
+ E127 # continuation line over-indented for visual indent
37
+ W504 # line break after binary operator
38
+ E231 # missing whitespace after ‘,’, ‘;’, or ‘:’
39
+ E501 # line too long
40
+ F403 # ‘from module import *’ used; unable to detect undefined names
41
+
42
+
43
+ [isort]
44
+ # https://pycqa.github.io/isort/docs/configuration/options.html
45
+ line_length = 120
46
+ # see: https://pycqa.github.io/isort/docs/configuration/multi_line_output_modes.html
47
+ multi_line_output = 0
48
+
49
+
50
+ [yapf]
51
+ based_on_style = pep8
52
+ spaces_before_comment = 2
53
+ COLUMN_LIMIT = 120
54
+ COALESCE_BRACKETS = True
55
+ SPACES_AROUND_POWER_OPERATOR = True
56
+ SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET = False
57
+ SPLIT_BEFORE_CLOSING_BRACKET = False
58
+ SPLIT_BEFORE_FIRST_ARGUMENT = False
59
+ # EACH_DICT_ENTRY_ON_SEPARATE_LINE = False
test.py ADDED
@@ -0,0 +1 @@
 
 
1
+ print('ds')
test1.py ADDED
File without changes
test2.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Train a YOLOv5 model on a custom dataset.
4
+
5
+ Models and datasets download automatically from the latest YOLOv5 release.
6
+ Models: https://github.com/ultralytics/yolov5/tree/master/models
7
+ Datasets: https://github.com/ultralytics/yolov5/tree/master/data
8
+ Tutorial: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data
9
+
10
+ Usage:
11
+ $ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (RECOMMENDED)
12
+ $ python path/to/train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch
13
+ """
14
+
15
+ import argparse
16
+ import math
17
+ import os
18
+ import random
19
+ import sys
20
+ import time
21
+ from copy import deepcopy
22
+ from datetime import datetime
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.distributed as dist
28
+ import torch.nn as nn
29
+ import yaml
30
+ from torch.optim import lr_scheduler
31
+ from tqdm import tqdm
32
+
33
+ FILE = Path(__file__).resolve()
34
+ ROOT = FILE.parents[0] # YOLOv5 root directory
35
+ if str(ROOT) not in sys.path:
36
+ sys.path.append(str(ROOT)) # add ROOT to PATH
37
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
38
+
39
+ import val # for end-of-epoch mAP
40
+ from models.experimental import attempt_load
41
+ from models.yolo import Model
42
+ from utils.autoanchor import check_anchors
43
+ from utils.autobatch import check_train_batch_size
44
+ from utils.callbacks import Callbacks
45
+ from utils.dataloaders import create_dataloader
46
+ from utils.downloads import attempt_download
47
+ from utils.general import (LOGGER, check_amp, check_dataset, check_file, check_git_status, check_img_size,
48
+ check_requirements, check_suffix, check_yaml, colorstr, get_latest_run, increment_path,
49
+ init_seeds, intersect_dicts, labels_to_class_weights, labels_to_image_weights, methods,
50
+ one_cycle, print_args, print_mutation, strip_optimizer)
51
+ from utils.loggers import Loggers
52
+ from utils.loggers.wandb.wandb_utils import check_wandb_resume
53
+ from utils.loss import ComputeLoss
54
+ from utils.metrics import fitness
55
+ from utils.plots import plot_evolve, plot_labels
56
+ from utils.torch_utils import (EarlyStopping, ModelEMA, de_parallel, select_device, smart_DDP, smart_optimizer,
57
+ torch_distributed_zero_first)
58
+
59
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
60
+ RANK = int(os.getenv('RANK', -1))
61
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
62
+
63
+
64
+ def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hyp dictionary
65
+ save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \
66
+ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \
67
+ opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze
68
+ callbacks.run('on_pretrain_routine_start')
69
+
70
+ # Directories
71
+ w = save_dir / 'weights' # weights dir
72
+ (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
73
+ last, best = w / 'last.pt', w / 'best.pt'
74
+
75
+ # Hyperparameters
76
+ if isinstance(hyp, str):
77
+ with open(hyp, errors='ignore') as f:
78
+ hyp = yaml.safe_load(f) # load hyps dict
79
+ LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
80
+
81
+ # Save run settings
82
+ if not evolve:
83
+ with open(save_dir / 'hyp.yaml', 'w') as f:
84
+ yaml.safe_dump(hyp, f, sort_keys=False)
85
+ with open(save_dir / 'opt.yaml', 'w') as f:
86
+ yaml.safe_dump(vars(opt), f, sort_keys=False)
87
+
88
+ # Loggers
89
+ data_dict = {'train': '/content/yolov5/train',
90
+ 'val': '/content/yolov5/valid',
91
+ 'test': '/content/yolov5/test',
92
+
93
+ 'nc': 1,
94
+ 'names': ['enemy'],
95
+
96
+ 'roboflow':{
97
+ 'workspace': 'notsam-jqwtl',
98
+ 'project': 'my-valorant',
99
+ 'version': 5,
100
+ 'license': 'CC BY 4.0',
101
+ 'url': 'https://universe.roboflow.com/notsam-jqwtl/my-valorant/dataset/5'}}
102
+ if RANK in {-1, 0}:
103
+ loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
104
+ if loggers.wandb:
105
+ data_dict = loggers.wandb.data_dict
106
+ if resume:
107
+ weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
108
+
109
+ # Register actions
110
+ for k in methods(loggers):
111
+ callbacks.register_action(k, callback=getattr(loggers, k))
112
+
113
+ # Config
114
+ plots = not evolve and not opt.noplots # create plots
115
+ cuda = device.type != 'cpu'
116
+ init_seeds(opt.seed + 1 + RANK, deterministic=True)
117
+ with torch_distributed_zero_first(LOCAL_RANK):
118
+ data_dict = data_dict or check_dataset(data) # check if None
119
+ train_path, val_path = data_dict['train'], data_dict['val']
120
+ nc = 1 if single_cls else int(data_dict['nc']) # number of classes
121
+ names = ['item'] if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
122
+ assert len(names) == nc, f'{len(names)} names found for nc={nc} dataset in {data}' # check
123
+ is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset
124
+
125
+ # Model
126
+ check_suffix(weights, '.pt') # check weights
127
+ pretrained = weights.endswith('.pt')
128
+ if pretrained:
129
+ with torch_distributed_zero_first(LOCAL_RANK):
130
+ weights = attempt_download(weights) # download if not found locally
131
+ ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak
132
+ model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
133
+ exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
134
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
135
+ csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
136
+ model.load_state_dict(csd, strict=False) # load
137
+ LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
138
+ else:
139
+ model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
140
+ amp = check_amp(model) # check AMP
141
+
142
+ # Freeze
143
+ freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
144
+ for k, v in model.named_parameters():
145
+ v.requires_grad = True # train all layers
146
+ if any(x in k for x in freeze):
147
+ LOGGER.info(f'freezing {k}')
148
+ v.requires_grad = False
149
+
150
+ # Image size
151
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
152
+ imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
153
+
154
+ # Batch size
155
+ if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
156
+ batch_size = check_train_batch_size(model, imgsz, amp)
157
+ loggers.on_params_update({"batch_size": batch_size})
158
+
159
+ # Optimizer
160
+ nbs = 64 # nominal batch size
161
+ accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
162
+ hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
163
+ LOGGER.info(f"Scaled weight_decay = {hyp['weight_decay']}")
164
+ optimizer = smart_optimizer(model, opt.optimizer, hyp['lr0'], hyp['momentum'], hyp['weight_decay'])
165
+
166
+ # Scheduler
167
+ if opt.cos_lr:
168
+ lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
169
+ else:
170
+ lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
171
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
172
+
173
+ # EMA
174
+ ema = ModelEMA(model) if RANK in {-1, 0} else None
175
+
176
+ # Resume
177
+ start_epoch, best_fitness = 0, 0.0
178
+ if pretrained:
179
+ # Optimizer
180
+ if ckpt['optimizer'] is not None:
181
+ optimizer.load_state_dict(ckpt['optimizer'])
182
+ best_fitness = ckpt['best_fitness']
183
+
184
+ # EMA
185
+ if ema and ckpt.get('ema'):
186
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict())
187
+ ema.updates = ckpt['updates']
188
+
189
+ # Epochs
190
+ start_epoch = ckpt['epoch'] + 1
191
+ if resume:
192
+ assert start_epoch > 0, f'{weights} training to {epochs} epochs is finished, nothing to resume.'
193
+ if epochs < start_epoch:
194
+ LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.")
195
+ epochs += ckpt['epoch'] # finetune additional epochs
196
+
197
+ del ckpt, csd
198
+
199
+ # DP mode
200
+ if cuda and RANK == -1 and torch.cuda.device_count() > 1:
201
+ LOGGER.warning('WARNING: DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n'
202
+ 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.')
203
+ model = torch.nn.DataParallel(model)
204
+
205
+ # SyncBatchNorm
206
+ if opt.sync_bn and cuda and RANK != -1:
207
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
208
+ LOGGER.info('Using SyncBatchNorm()')
209
+
210
+ # Trainloader
211
+ train_loader, dataset = create_dataloader(train_path,
212
+ imgsz,
213
+ batch_size // WORLD_SIZE,
214
+ gs,
215
+ single_cls,
216
+ hyp=hyp,
217
+ augment=True,
218
+ cache=None if opt.cache == 'val' else opt.cache,
219
+ rect=opt.rect,
220
+ rank=LOCAL_RANK,
221
+ workers=workers,
222
+ image_weights=opt.image_weights,
223
+ quad=opt.quad,
224
+ prefix=colorstr('train: '),
225
+ shuffle=True)
226
+ mlc = int(np.concatenate(dataset.labels, 0)[:, 0].max()) # max label class
227
+ nb = len(train_loader) # number of batches
228
+ assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
229
+
230
+ # Process 0
231
+ if RANK in {-1, 0}:
232
+ val_loader = create_dataloader(val_path,
233
+ imgsz,
234
+ batch_size // WORLD_SIZE * 2,
235
+ gs,
236
+ single_cls,
237
+ hyp=hyp,
238
+ cache=None if noval else opt.cache,
239
+ rect=True,
240
+ rank=-1,
241
+ workers=workers * 2,
242
+ pad=0.5,
243
+ prefix=colorstr('val: '))[0]
244
+
245
+ if not resume:
246
+ labels = np.concatenate(dataset.labels, 0)
247
+ # c = torch.tensor(labels[:, 0]) # classes
248
+ # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
249
+ # model._initialize_biases(cf.to(device))
250
+ if plots:
251
+ plot_labels(labels, names, save_dir)
252
+
253
+ # Anchors
254
+ if not opt.noautoanchor:
255
+ check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
256
+ model.half().float() # pre-reduce anchor precision
257
+
258
+ callbacks.run('on_pretrain_routine_end')
259
+
260
+ # DDP mode
261
+ if cuda and RANK != -1:
262
+ model = smart_DDP(model)
263
+
264
+ # Model attributes
265
+ nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
266
+ hyp['box'] *= 3 / nl # scale to layers
267
+ hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers
268
+ hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
269
+ hyp['label_smoothing'] = opt.label_smoothing
270
+ model.nc = nc # attach number of classes to model
271
+ model.hyp = hyp # attach hyperparameters to model
272
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
273
+ model.names = names
274
+
275
+ # Start training
276
+ t0 = time.time()
277
+ nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
278
+ # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
279
+ last_opt_step = -1
280
+ maps = np.zeros(nc) # mAP per class
281
+ results = (0, 0, 0, 0, 0, 0, 0) # P, R, [email protected], [email protected], val_loss(box, obj, cls)
282
+ scheduler.last_epoch = start_epoch - 1 # do not move
283
+ scaler = torch.cuda.amp.GradScaler(enabled=amp)
284
+ stopper, stop = EarlyStopping(patience=opt.patience), False
285
+ compute_loss = ComputeLoss(model) # init loss class
286
+ callbacks.run('on_train_start')
287
+ LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
288
+ f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
289
+ f"Logging results to {colorstr('bold', save_dir)}\n"
290
+ f'Starting training for {epochs} epochs...')
291
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
292
+ callbacks.run('on_train_epoch_start')
293
+ model.train()
294
+
295
+ # Update image weights (optional, single-GPU only)
296
+ if opt.image_weights:
297
+ cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
298
+ iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
299
+ dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
300
+
301
+ # Update mosaic border (optional)
302
+ # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
303
+ # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
304
+
305
+ mloss = torch.zeros(3, device=device) # mean losses
306
+ if RANK != -1:
307
+ train_loader.sampler.set_epoch(epoch)
308
+ pbar = enumerate(train_loader)
309
+ LOGGER.info(('\n' + '%10s' * 7) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'labels', 'img_size'))
310
+ if RANK in {-1, 0}:
311
+ pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
312
+ optimizer.zero_grad()
313
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
314
+ callbacks.run('on_train_batch_start')
315
+ ni = i + nb * epoch # number integrated batches (since train start)
316
+ imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
317
+
318
+ # Warmup
319
+ if ni <= nw:
320
+ xi = [0, nw] # x interp
321
+ # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
322
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
323
+ for j, x in enumerate(optimizer.param_groups):
324
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
325
+ x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 0 else 0.0, x['initial_lr'] * lf(epoch)])
326
+ if 'momentum' in x:
327
+ x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
328
+
329
+ # Multi-scale
330
+ if opt.multi_scale:
331
+ sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
332
+ sf = sz / max(imgs.shape[2:]) # scale factor
333
+ if sf != 1:
334
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
335
+ imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
336
+
337
+ # Forward
338
+ with torch.cuda.amp.autocast(amp):
339
+ pred = model(imgs) # forward
340
+ loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
341
+ if RANK != -1:
342
+ loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
343
+ if opt.quad:
344
+ loss *= 4.
345
+
346
+ # Backward
347
+ scaler.scale(loss).backward()
348
+
349
+ # Optimize
350
+ if ni - last_opt_step >= accumulate:
351
+ scaler.step(optimizer) # optimizer.step
352
+ scaler.update()
353
+ optimizer.zero_grad()
354
+ if ema:
355
+ ema.update(model)
356
+ last_opt_step = ni
357
+
358
+ # Log
359
+ if RANK in {-1, 0}:
360
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
361
+ mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
362
+ pbar.set_description(('%10s' * 2 + '%10.4g' * 5) %
363
+ (f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
364
+ callbacks.run('on_train_batch_end', ni, model, imgs, targets, paths, plots)
365
+ if callbacks.stop_training:
366
+ return
367
+ # end batch ------------------------------------------------------------------------------------------------
368
+
369
+ # Scheduler
370
+ lr = [x['lr'] for x in optimizer.param_groups] # for loggers
371
+ scheduler.step()
372
+
373
+ if RANK in {-1, 0}:
374
+ # mAP
375
+ callbacks.run('on_train_epoch_end', epoch=epoch)
376
+ ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
377
+ final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
378
+ if not noval or final_epoch: # Calculate mAP
379
+ results, maps, _ = val.run(data_dict,
380
+ batch_size=batch_size // WORLD_SIZE * 2,
381
+ imgsz=imgsz,
382
+ model=ema.ema,
383
+ single_cls=single_cls,
384
+ dataloader=val_loader,
385
+ save_dir=save_dir,
386
+ plots=False,
387
+ callbacks=callbacks,
388
+ compute_loss=compute_loss)
389
+
390
+ # Update best mAP
391
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, [email protected], [email protected]]
392
+ stop = stopper(epoch=epoch, fitness=fi) # early stop check
393
+ if fi > best_fitness:
394
+ best_fitness = fi
395
+ log_vals = list(mloss) + list(results) + lr
396
+ callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
397
+
398
+ # Save model
399
+ if (not nosave) or (final_epoch and not evolve): # if save
400
+ ckpt = {
401
+ 'epoch': epoch,
402
+ 'best_fitness': best_fitness,
403
+ 'model': deepcopy(de_parallel(model)).half(),
404
+ 'ema': deepcopy(ema.ema).half(),
405
+ 'updates': ema.updates,
406
+ 'optimizer': optimizer.state_dict(),
407
+ 'wandb_id': loggers.wandb.wandb_run.id if loggers.wandb else None,
408
+ 'date': datetime.now().isoformat()}
409
+
410
+ # Save last, best and delete
411
+ torch.save(ckpt, last)
412
+ if best_fitness == fi:
413
+ torch.save(ckpt, best)
414
+ if opt.save_period > 0 and epoch % opt.save_period == 0:
415
+ torch.save(ckpt, w / f'epoch{epoch}.pt')
416
+ del ckpt
417
+ callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
418
+
419
+ # EarlyStopping
420
+ if RANK != -1: # if DDP training
421
+ broadcast_list = [stop if RANK == 0 else None]
422
+ dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
423
+ if RANK != 0:
424
+ stop = broadcast_list[0]
425
+ if stop:
426
+ break # must break all DDP ranks
427
+
428
+ # end epoch ----------------------------------------------------------------------------------------------------
429
+ # end training -----------------------------------------------------------------------------------------------------
430
+ if RANK in {-1, 0}:
431
+ LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
432
+ for f in last, best:
433
+ if f.exists():
434
+ strip_optimizer(f) # strip optimizers
435
+ if f is best:
436
+ LOGGER.info(f'\nValidating {f}...')
437
+ results, _, _ = val.run(
438
+ data_dict,
439
+ batch_size=batch_size // WORLD_SIZE * 2,
440
+ imgsz=imgsz,
441
+ model=attempt_load(f, device).half(),
442
+ iou_thres=0.65 if is_coco else 0.60, # best pycocotools results at 0.65
443
+ single_cls=single_cls,
444
+ dataloader=val_loader,
445
+ save_dir=save_dir,
446
+ save_json=is_coco,
447
+ verbose=True,
448
+ plots=plots,
449
+ callbacks=callbacks,
450
+ compute_loss=compute_loss) # val best model with plots
451
+ if is_coco:
452
+ callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
453
+
454
+ callbacks.run('on_train_end', last, best, plots, epoch, results)
455
+
456
+ torch.cuda.empty_cache()
457
+ return results
458
+
459
+
460
+ def parse_opt(known=False):
461
+ parser = argparse.ArgumentParser()
462
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path')
463
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
464
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
465
+ parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
466
+ parser.add_argument('--epochs', type=int, default=300)
467
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
468
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
469
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
470
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
471
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
472
+ parser.add_argument('--noval', action='store_true', help='only validate final epoch')
473
+ parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
474
+ parser.add_argument('--noplots', action='store_true', help='save no plot files')
475
+ parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
476
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
477
+ parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
478
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
479
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
480
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
481
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
482
+ parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
483
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
484
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
485
+ parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name')
486
+ parser.add_argument('--name', default='exp', help='save to project/name')
487
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
488
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
489
+ parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
490
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
491
+ parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
492
+ parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
493
+ parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
494
+ parser.add_argument('--seed', type=int, default=0, help='Global training seed')
495
+ parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
496
+
497
+ # Weights & Biases arguments
498
+ parser.add_argument('--entity', default=None, help='W&B: Entity')
499
+ parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option')
500
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval')
501
+ parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use')
502
+
503
+ opt = parser.parse_known_args()[0] if known else parser.parse_args()
504
+ return opt
505
+
506
+
507
+ def main(opt, callbacks=Callbacks()):
508
+ # Checks
509
+ if RANK in {-1, 0}:
510
+ print_args(vars(opt))
511
+ check_git_status()
512
+ check_requirements(exclude=['thop'])
513
+
514
+ # Resume
515
+ if opt.resume and not check_wandb_resume(opt) and not opt.evolve: # resume an interrupted run
516
+ ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
517
+ assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
518
+ with open(Path(ckpt).parent.parent / 'opt.yaml', errors='ignore') as f:
519
+ opt = argparse.Namespace(**yaml.safe_load(f)) # replace
520
+ opt.cfg, opt.weights, opt.resume = '', ckpt, True # reinstate
521
+ LOGGER.info(f'Resuming training from {ckpt}')
522
+ else:
523
+ opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \
524
+ check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks
525
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
526
+ if opt.evolve:
527
+ if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve
528
+ opt.project = str(ROOT / 'runs/evolve')
529
+ opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
530
+ if opt.name == 'cfg':
531
+ opt.name = Path(opt.cfg).stem # use model.yaml as name
532
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
533
+
534
+ # DDP mode
535
+ device = select_device(opt.device, batch_size=opt.batch_size)
536
+ if LOCAL_RANK != -1:
537
+ msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
538
+ assert not opt.image_weights, f'--image-weights {msg}'
539
+ assert not opt.evolve, f'--evolve {msg}'
540
+ assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size'
541
+ assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
542
+ assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
543
+ torch.cuda.set_device(LOCAL_RANK)
544
+ device = torch.device('cuda', LOCAL_RANK)
545
+ dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
546
+
547
+ # Train
548
+ if not opt.evolve:
549
+ train(opt.hyp, opt, device, callbacks)
550
+ if WORLD_SIZE > 1 and RANK == 0:
551
+ LOGGER.info('Destroying process group... ')
552
+ dist.destroy_process_group()
553
+
554
+ # Evolve hyperparameters (optional)
555
+ else:
556
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
557
+ meta = {
558
+ 'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
559
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
560
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
561
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
562
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
563
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
564
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
565
+ 'box': (1, 0.02, 0.2), # box loss gain
566
+ 'cls': (1, 0.2, 4.0), # cls loss gain
567
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
568
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
569
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
570
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
571
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
572
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
573
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
574
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
575
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
576
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
577
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
578
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
579
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
580
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
581
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
582
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
583
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
584
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
585
+ 'mixup': (1, 0.0, 1.0), # image mixup (probability)
586
+ 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability)
587
+
588
+ with open(opt.hyp, errors='ignore') as f:
589
+ hyp = yaml.safe_load(f) # load hyps dict
590
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
591
+ hyp['anchors'] = 3
592
+ opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
593
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
594
+ evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv'
595
+ if opt.bucket:
596
+ os.system(f'gsutil cp gs://{opt.bucket}/evolve.csv {evolve_csv}') # download evolve.csv if exists
597
+
598
+ for _ in range(opt.evolve): # generations to evolve
599
+ if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
600
+ # Select parent(s)
601
+ parent = 'single' # parent selection method: 'single' or 'weighted'
602
+ x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
603
+ n = min(5, len(x)) # number of previous results to consider
604
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
605
+ w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0)
606
+ if parent == 'single' or len(x) == 1:
607
+ # x = x[random.randint(0, n - 1)] # random selection
608
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
609
+ elif parent == 'weighted':
610
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
611
+
612
+ # Mutate
613
+ mp, s = 0.8, 0.2 # mutation probability, sigma
614
+ npr = np.random
615
+ npr.seed(int(time.time()))
616
+ g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
617
+ ng = len(meta)
618
+ v = np.ones(ng)
619
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
620
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
621
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
622
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
623
+
624
+ # Constrain to limits
625
+ for k, v in meta.items():
626
+ hyp[k] = max(hyp[k], v[1]) # lower limit
627
+ hyp[k] = min(hyp[k], v[2]) # upper limit
628
+ hyp[k] = round(hyp[k], 5) # significant digits
629
+
630
+ # Train mutation
631
+ results = train(hyp.copy(), opt, device, callbacks)
632
+ callbacks = Callbacks()
633
+ # Write mutation results
634
+ print_mutation(results, hyp.copy(), save_dir, opt.bucket)
635
+
636
+ # Plot results
637
+ plot_evolve(evolve_csv)
638
+ LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n'
639
+ f"Results saved to {colorstr('bold', save_dir)}\n"
640
+ f'Usage example: $ python train.py --hyp {evolve_yaml}')
641
+
642
+
643
+ def run(**kwargs):
644
+ # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
645
+ opt = parse_opt(True)
646
+ for k, v in kwargs.items():
647
+ setattr(opt, k, v)
648
+ main(opt)
649
+ return opt
650
+
651
+
652
+ if __name__ == "__main__":
653
+ opt = parse_opt()
654
+ main(opt)