Upload 25 files
Browse files- CONTRIBUTING.md +98 -0
- LICENSE +674 -0
- README.md +11 -12
- app.py +432 -0
- appledd-yolov5s-800.pb +3 -0
- daisi.py +432 -0
- data.yaml +5 -0
- detect.py +257 -0
- export.py +618 -0
- hubconf.py +160 -0
- labels.txt +11 -0
- logo.jpg +0 -0
- mobilenetv2-apple-10-class-pytorch.pth +3 -0
- packages.txt +1 -0
- requirements.txt +15 -0
- sample.jpg +0 -0
- setup.cfg +59 -0
- temp_image.jpg +0 -0
- test.jpg +0 -0
- test1.jpg +0 -0
- test2.jpg +0 -0
- test3.jpg +0 -0
- train.py +633 -0
- unnamed.jpg +0 -0
- val.py +396 -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,12 @@
|
|
1 |
-
|
2 |
-
title: Appledd
|
3 |
-
emoji: 🐨
|
4 |
-
colorFrom: purple
|
5 |
-
colorTo: green
|
6 |
-
sdk: streamlit
|
7 |
-
sdk_version: 1.31.1
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: apache-2.0
|
11 |
-
---
|
12 |
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<h2>Welcome to Deep Diagnosis</h2>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
+
<p>
|
4 |
+
This app allows you to detect different apple diseases from leaf images.
|
5 |
+
|
6 |
+
<ul>
|
7 |
+
<li>Scab</li>
|
8 |
+
<li>Alternaria</li>
|
9 |
+
<li>MLB</li>
|
10 |
+
<li>Mossaic</li>
|
11 |
+
<li>Powdery Mildew</li>
|
12 |
+
<li>Necrosis</li>
|
app.py
ADDED
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import platform
|
4 |
+
import sys
|
5 |
+
import streamlit as st
|
6 |
+
import torch
|
7 |
+
import torch.backends.cudnn as cudnn
|
8 |
+
import numpy as np
|
9 |
+
from pathlib import Path
|
10 |
+
from PIL import Image
|
11 |
+
|
12 |
+
from torchvision import transforms, models
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
FILE = Path(__file__).resolve()
|
17 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
18 |
+
if str(ROOT) not in sys.path:
|
19 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
20 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
21 |
+
|
22 |
+
from models.common import DetectMultiBackend
|
23 |
+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
|
24 |
+
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
|
25 |
+
increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
|
26 |
+
from utils.plots import Annotator, colors, save_one_box
|
27 |
+
from utils.torch_utils import select_device, time_sync
|
28 |
+
|
29 |
+
weights="appledd-yolov5s-800.pb"
|
30 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
31 |
+
|
32 |
+
|
33 |
+
#### Class for classification model
|
34 |
+
import torch.nn as nn
|
35 |
+
import torch.nn.functional as F
|
36 |
+
class NaturalSceneClassification(nn.Module):
|
37 |
+
def __init__(self):
|
38 |
+
super().__init__()
|
39 |
+
self.network = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True)
|
40 |
+
|
41 |
+
self.network.fc = nn.Sequential(nn.Linear(2048, 512),
|
42 |
+
nn.ReLU(),
|
43 |
+
nn.Dropout(0.2),
|
44 |
+
nn.Linear(512, 10),
|
45 |
+
nn.Softmax(dim=1))
|
46 |
+
|
47 |
+
|
48 |
+
def forward(self, xb):
|
49 |
+
return self.network(xb)
|
50 |
+
|
51 |
+
def training_step(self, batch):
|
52 |
+
images, labels = batch
|
53 |
+
images, labels = images.to(device), labels.to(device)
|
54 |
+
out = self(images) # Generate predictions
|
55 |
+
loss = F.cross_entropy(out, labels) # Calculate loss
|
56 |
+
return loss
|
57 |
+
|
58 |
+
def validation_step(self, batch):
|
59 |
+
images, labels = batch
|
60 |
+
images, labels = images.to(device), labels.to(device)
|
61 |
+
out = self(images) # Generate predictions
|
62 |
+
loss = F.cross_entropy(out, labels) # Calculate loss
|
63 |
+
acc = accuracy(out, labels) # Calculate accuracy
|
64 |
+
return {'val_loss': loss.detach(), 'val_acc': acc}
|
65 |
+
|
66 |
+
def validation_epoch_end(self, outputs):
|
67 |
+
batch_losses = [x['val_loss'] for x in outputs]
|
68 |
+
epoch_loss = torch.stack(batch_losses).mean() # Combine losses
|
69 |
+
batch_accs = [x['val_acc'] for x in outputs]
|
70 |
+
epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies
|
71 |
+
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
|
72 |
+
|
73 |
+
def epoch_end(self, epoch, result):
|
74 |
+
print("Epoch [{}], train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format(
|
75 |
+
epoch, result['train_loss'], result['val_loss'], result['val_acc']))
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
def increase_contrast(image):
|
81 |
+
if isinstance(image, Image.Image):
|
82 |
+
# Convert the PIL image to a numpy array
|
83 |
+
image = np.array(image)
|
84 |
+
|
85 |
+
if not isinstance(image, np.ndarray):
|
86 |
+
raise ValueError("Input must be a valid numpy array")
|
87 |
+
|
88 |
+
# Convert the image to grayscale if it's in color
|
89 |
+
if len(image.shape) == 3:
|
90 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
91 |
+
|
92 |
+
# Calculate min and max values
|
93 |
+
min_val = image.min()
|
94 |
+
max_val = image.max()
|
95 |
+
|
96 |
+
if min_val == max_val:
|
97 |
+
return image # Avoid division by zero
|
98 |
+
|
99 |
+
# Apply contrast stretching
|
100 |
+
contrast_stretched = cv2.convertScaleAbs(image, alpha=255.0 / (max_val - min_val), beta=-min_val)
|
101 |
+
|
102 |
+
return contrast_stretched
|
103 |
+
|
104 |
+
def reduce_noise(image, kernel_size=(3, 3)):
|
105 |
+
# Apply Gaussian blur to reduce noise
|
106 |
+
blurred = cv2.GaussianBlur(image, kernel_size, 0)
|
107 |
+
|
108 |
+
return blurred
|
109 |
+
@torch.no_grad()
|
110 |
+
def run(
|
111 |
+
weights=ROOT / 'yolov5s.pt', # model.pt path(s)
|
112 |
+
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
|
113 |
+
data=ROOT / 'data.yaml', # dataset.yaml path
|
114 |
+
imgsz=(640, 640), # inference size (height, width)
|
115 |
+
conf_thres=0.25, # confidence threshold
|
116 |
+
iou_thres=0.45, # NMS IOU threshold
|
117 |
+
max_det=1000, # maximum detections per image
|
118 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
119 |
+
view_img=False, # show results
|
120 |
+
save_txt=False, # save results to *.txt
|
121 |
+
save_conf=False, # save confidences in --save-txt labels
|
122 |
+
save_crop=False, # save cropped prediction boxes
|
123 |
+
nosave=False, # do not save images/videos
|
124 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
125 |
+
agnostic_nms=False, # class-agnostic NMS
|
126 |
+
augment=False, # augmented inference
|
127 |
+
visualize=False, # visualize features
|
128 |
+
update=False, # update all models
|
129 |
+
project=ROOT / 'runs/detect', # save results to project/name
|
130 |
+
name='exp', # save results to project/name
|
131 |
+
exist_ok=True, # existing project/name ok, do not increment
|
132 |
+
line_thickness=2, # bounding box thickness (pixels)
|
133 |
+
hide_labels=False, # hide labels
|
134 |
+
hide_conf=False, # hide confidences
|
135 |
+
half=False, # use FP16 half-precision inference
|
136 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
137 |
+
|
138 |
+
upl_image: np.ndarray=None,
|
139 |
+
#return_type: list=["Image", "Labels"]
|
140 |
+
):
|
141 |
+
|
142 |
+
source = str(source)
|
143 |
+
save_img = not nosave and not source.endswith('.txt') # save inference images
|
144 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
145 |
+
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
146 |
+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
147 |
+
if is_url and is_file:
|
148 |
+
source = check_file(source) # download
|
149 |
+
|
150 |
+
# Directories
|
151 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
152 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
153 |
+
|
154 |
+
# Load model
|
155 |
+
device = select_device(device)
|
156 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
157 |
+
stride, names, pt = model.stride, model.names, model.pt
|
158 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
159 |
+
|
160 |
+
# Dataloader
|
161 |
+
if webcam:
|
162 |
+
view_img = check_imshow()
|
163 |
+
cudnn.benchmark = True # set True to speed up constant image size inference
|
164 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
|
165 |
+
bs = len(dataset) # batch_size
|
166 |
+
else:
|
167 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
|
168 |
+
bs = 1 # batch_size
|
169 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
170 |
+
|
171 |
+
# Run inference
|
172 |
+
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
|
173 |
+
seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
|
174 |
+
for path, im, im0s, vid_cap, s in dataset:
|
175 |
+
t1 = time_sync()
|
176 |
+
#im=upl_image
|
177 |
+
im = torch.from_numpy(im).to(device)
|
178 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
179 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
180 |
+
if len(im.shape) == 3:
|
181 |
+
im = im[None] # expand for batch dim
|
182 |
+
t2 = time_sync()
|
183 |
+
dt[0] += t2 - t1
|
184 |
+
# Contrast enhancement
|
185 |
+
# im = increase_contrast(im)
|
186 |
+
|
187 |
+
# # Noise reduction
|
188 |
+
# im = reduce_noise(im)
|
189 |
+
# Inference
|
190 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
191 |
+
pred = model(im, augment=augment, visualize=visualize)
|
192 |
+
t3 = time_sync()
|
193 |
+
dt[1] += t3 - t2
|
194 |
+
|
195 |
+
# NMS
|
196 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
197 |
+
dt[2] += time_sync() - t3
|
198 |
+
|
199 |
+
# Second-stage classifier (optional)
|
200 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
201 |
+
|
202 |
+
# Process predictions
|
203 |
+
for i, det in enumerate(pred): # per image
|
204 |
+
seen += 1
|
205 |
+
if webcam: # batch_size >= 1
|
206 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
207 |
+
s += f'{i}: '
|
208 |
+
else:
|
209 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
|
210 |
+
|
211 |
+
p = Path(p) # to Path
|
212 |
+
save_path = str(save_dir / p.name) # im.jpg
|
213 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
|
214 |
+
s += '%gx%g ' % im.shape[2:] # print string
|
215 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
216 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
217 |
+
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
218 |
+
if len(det):
|
219 |
+
# Rescale boxes from img_size to im0 size
|
220 |
+
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
|
221 |
+
|
222 |
+
# Print results
|
223 |
+
for c in det[:, -1].unique():
|
224 |
+
n = (det[:, -1] == c).sum() # detections per class
|
225 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
226 |
+
|
227 |
+
# Write results
|
228 |
+
for *xyxy, conf, cls in reversed(det):
|
229 |
+
if save_txt: # Write to file
|
230 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
231 |
+
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
232 |
+
with open(f'{txt_path}.txt', 'a') as f:
|
233 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
234 |
+
|
235 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
236 |
+
c = int(cls) # integer class
|
237 |
+
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
|
238 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
239 |
+
if save_crop:
|
240 |
+
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
|
241 |
+
|
242 |
+
# Stream results
|
243 |
+
im0 = annotator.result()
|
244 |
+
if view_img:
|
245 |
+
if platform.system() == 'Linux' and p not in windows:
|
246 |
+
windows.append(p)
|
247 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
248 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
249 |
+
cv2.imshow(str(p), im0)
|
250 |
+
cv2.waitKey(1) # 1 millisecond
|
251 |
+
|
252 |
+
# Save results (image with detections)
|
253 |
+
if save_img:
|
254 |
+
if dataset.mode == 'image':
|
255 |
+
#cv2.imwrite(save_path, im0)
|
256 |
+
print("Save")
|
257 |
+
else: # 'video' or 'stream'
|
258 |
+
if vid_path[i] != save_path: # new video
|
259 |
+
vid_path[i] = save_path
|
260 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
261 |
+
vid_writer[i].release() # release previous video writer
|
262 |
+
if vid_cap: # video
|
263 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
264 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
265 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
266 |
+
else: # stream
|
267 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
268 |
+
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
|
269 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
270 |
+
vid_writer[i].write(im0)
|
271 |
+
|
272 |
+
# Print time (inference-only)
|
273 |
+
LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
|
274 |
+
|
275 |
+
# Print results
|
276 |
+
t = tuple(x / seen * 1E3 for x in dt) # speeds per image
|
277 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
|
278 |
+
if save_txt or save_img:
|
279 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
280 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
281 |
+
if update:
|
282 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
283 |
+
im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)
|
284 |
+
return im0
|
285 |
+
|
286 |
+
|
287 |
+
def parse_opt():
|
288 |
+
parser = argparse.ArgumentParser()
|
289 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
|
290 |
+
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
|
291 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data.yaml', help='(optional) dataset.yaml path')
|
292 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[800], help='inference size h,w')
|
293 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
|
294 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
|
295 |
+
parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
|
296 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
297 |
+
parser.add_argument('--view-img', action='store_true', help='show results')
|
298 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
299 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
300 |
+
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
|
301 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
302 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
|
303 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
|
304 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
305 |
+
parser.add_argument('--visualize', action='store_true', help='visualize features')
|
306 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
307 |
+
parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
|
308 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
309 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
310 |
+
parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
|
311 |
+
parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
|
312 |
+
parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
|
313 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
314 |
+
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
315 |
+
opt = parser.parse_args()
|
316 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
317 |
+
print_args(vars(opt))
|
318 |
+
return opt
|
319 |
+
|
320 |
+
def classify(model,img):
|
321 |
+
img = img.to(device)
|
322 |
+
prediction = model(img)
|
323 |
+
sc, preds = torch.max(prediction, dim = 1)
|
324 |
+
return sc[0].item(),preds[0].item()
|
325 |
+
|
326 |
+
|
327 |
+
def main(opt,model,labels):
|
328 |
+
#check_requirements(exclude=('tensorboard', 'thop'))
|
329 |
+
#run(**vars(opt))
|
330 |
+
st.image("logo.jpg", caption="")
|
331 |
+
st.title("#Welcome to Deep Diagnosis")
|
332 |
+
# st.write("By: Dr. Asif Iqbal Khan")
|
333 |
+
st.markdown(
|
334 |
+
"""
|
335 |
+
This app allows you to detect different apple diseases from leaf images.
|
336 |
+
1) Scab
|
337 |
+
2) Alternaria
|
338 |
+
3) MLB
|
339 |
+
4) Mossaic
|
340 |
+
5) Powdery Mildew
|
341 |
+
6) Necrosis
|
342 |
+
"""
|
343 |
+
)
|
344 |
+
url="https://www.sciencedirect.com/science/article/abs/pii/S0168169922004100"
|
345 |
+
st.write("Link to the research paper: [link] (%s)" %url)
|
346 |
+
|
347 |
+
st.write("This app allows you to provide an image, and one of the most advanced Object Detection algorithms available will try to classify it for you. Upload your data to get started!")
|
348 |
+
|
349 |
+
with st.sidebar:
|
350 |
+
# st.image("logo.jpg", caption="")
|
351 |
+
uploaded_file = st.file_uploader("Choose an Image", type=["png","jpg","jpeg"])
|
352 |
+
return_types = st.multiselect("Select Return Type", ["Image", "Labels"], ["Image", "Labels"])
|
353 |
+
|
354 |
+
if not uploaded_file:
|
355 |
+
file_name = "sample.jpg"
|
356 |
+
st.write("Upload apple leaf image to detect diseases")
|
357 |
+
st.image("sample.jpg", caption='Sample Image',width=400)
|
358 |
+
|
359 |
+
else:
|
360 |
+
file_name = uploaded_file.name
|
361 |
+
|
362 |
+
#image = np.array(Image.open(image_file_buffer))
|
363 |
+
#Saving upload
|
364 |
+
file_details = {"filename":uploaded_file.name, "filetype":uploaded_file.type,"filesize":uploaded_file.size}
|
365 |
+
#st.write(file_details)
|
366 |
+
with open(file_name,"wb") as f:
|
367 |
+
f.write((uploaded_file).getbuffer())
|
368 |
+
|
369 |
+
img = Image.open(uploaded_file)
|
370 |
+
if img.format.lower() != "jpeg" or img.format.lower() !="jpg" :
|
371 |
+
# Convert the image to RGB format (JPEG-compatible) and save as a temporary JPEG file
|
372 |
+
img = img.convert("RGB")
|
373 |
+
temp_jpeg_file = "temp_image.jpg"
|
374 |
+
img.save(temp_jpeg_file, "JPEG")
|
375 |
+
|
376 |
+
img.close()
|
377 |
+
|
378 |
+
# Load the temporary JPEG file for processing
|
379 |
+
img = Image.open(temp_jpeg_file)
|
380 |
+
|
381 |
+
|
382 |
+
|
383 |
+
img = transforms.Resize((360,360))(img)
|
384 |
+
img = transforms.ToTensor()(img)
|
385 |
+
img = img.unsqueeze(0).to(device)
|
386 |
+
res=classify(model,img)
|
387 |
+
|
388 |
+
|
389 |
+
lb=labels[res[1]]
|
390 |
+
sc=res[0]
|
391 |
+
st.write(lb+" "+str(sc))
|
392 |
+
if(lb=="noleaf"):
|
393 |
+
st.write("Invalid image! Try Some other image")
|
394 |
+
elif(lb=="healthy"):
|
395 |
+
st.write("Looks healthy to me")
|
396 |
+
elif(lb=="demaged"):
|
397 |
+
st.write("No recognizable disease found")
|
398 |
+
else:
|
399 |
+
if(sc>7):
|
400 |
+
final_result = run(weights,file_name)
|
401 |
+
st.image(final_result, caption='Diseases Detected', width=400)
|
402 |
+
|
403 |
+
else:
|
404 |
+
st.write("No disease detected")
|
405 |
+
|
406 |
+
#final_result = run(weights,file_name)
|
407 |
+
#st.image(final_result, caption='Diseases Detected')
|
408 |
+
os.remove(file_name)
|
409 |
+
#Remove the temporary JPEG file after processing
|
410 |
+
os.remove(temp_jpeg_file)
|
411 |
+
|
412 |
+
|
413 |
+
|
414 |
+
if __name__ == "__main__":
|
415 |
+
opt = parse_opt()
|
416 |
+
model=NaturalSceneClassification()
|
417 |
+
model=torch.load("mobilenetv2-apple-10-class-pytorch.pth",map_location=device )
|
418 |
+
model.eval()
|
419 |
+
|
420 |
+
labels=[]
|
421 |
+
with open("labels.txt") as file:
|
422 |
+
for line in file:
|
423 |
+
line = line.strip() #or some other preprocessing
|
424 |
+
labels.append(line) #st
|
425 |
+
main(opt,model,labels)
|
426 |
+
|
427 |
+
|
428 |
+
|
429 |
+
|
430 |
+
|
431 |
+
|
432 |
+
|
appledd-yolov5s-800.pb
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c9fef9826dd03a8fe5a44740f97181a0765016650d143dd7e92c44c4f662d403
|
3 |
+
size 28324751
|
daisi.py
ADDED
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import platform
|
4 |
+
import sys
|
5 |
+
import streamlit as st
|
6 |
+
import torch
|
7 |
+
import torch.backends.cudnn as cudnn
|
8 |
+
import numpy as np
|
9 |
+
from pathlib import Path
|
10 |
+
from PIL import Image
|
11 |
+
|
12 |
+
from torchvision import transforms, models
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
FILE = Path(__file__).resolve()
|
17 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
18 |
+
if str(ROOT) not in sys.path:
|
19 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
20 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
21 |
+
|
22 |
+
from models.common import DetectMultiBackend
|
23 |
+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
|
24 |
+
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
|
25 |
+
increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
|
26 |
+
from utils.plots import Annotator, colors, save_one_box
|
27 |
+
from utils.torch_utils import select_device, time_sync
|
28 |
+
|
29 |
+
weights="appledd-yolov5s-800.pb"
|
30 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
31 |
+
|
32 |
+
|
33 |
+
#### Class for classification model
|
34 |
+
import torch.nn as nn
|
35 |
+
import torch.nn.functional as F
|
36 |
+
class NaturalSceneClassification(nn.Module):
|
37 |
+
def __init__(self):
|
38 |
+
super().__init__()
|
39 |
+
self.network = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True)
|
40 |
+
|
41 |
+
self.network.fc = nn.Sequential(nn.Linear(2048, 512),
|
42 |
+
nn.ReLU(),
|
43 |
+
nn.Dropout(0.2),
|
44 |
+
nn.Linear(512, 10),
|
45 |
+
nn.Softmax(dim=1))
|
46 |
+
|
47 |
+
|
48 |
+
def forward(self, xb):
|
49 |
+
return self.network(xb)
|
50 |
+
|
51 |
+
def training_step(self, batch):
|
52 |
+
images, labels = batch
|
53 |
+
images, labels = images.to(device), labels.to(device)
|
54 |
+
out = self(images) # Generate predictions
|
55 |
+
loss = F.cross_entropy(out, labels) # Calculate loss
|
56 |
+
return loss
|
57 |
+
|
58 |
+
def validation_step(self, batch):
|
59 |
+
images, labels = batch
|
60 |
+
images, labels = images.to(device), labels.to(device)
|
61 |
+
out = self(images) # Generate predictions
|
62 |
+
loss = F.cross_entropy(out, labels) # Calculate loss
|
63 |
+
acc = accuracy(out, labels) # Calculate accuracy
|
64 |
+
return {'val_loss': loss.detach(), 'val_acc': acc}
|
65 |
+
|
66 |
+
def validation_epoch_end(self, outputs):
|
67 |
+
batch_losses = [x['val_loss'] for x in outputs]
|
68 |
+
epoch_loss = torch.stack(batch_losses).mean() # Combine losses
|
69 |
+
batch_accs = [x['val_acc'] for x in outputs]
|
70 |
+
epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies
|
71 |
+
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
|
72 |
+
|
73 |
+
def epoch_end(self, epoch, result):
|
74 |
+
print("Epoch [{}], train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format(
|
75 |
+
epoch, result['train_loss'], result['val_loss'], result['val_acc']))
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
def increase_contrast(image):
|
81 |
+
if isinstance(image, Image.Image):
|
82 |
+
# Convert the PIL image to a numpy array
|
83 |
+
image = np.array(image)
|
84 |
+
|
85 |
+
if not isinstance(image, np.ndarray):
|
86 |
+
raise ValueError("Input must be a valid numpy array")
|
87 |
+
|
88 |
+
# Convert the image to grayscale if it's in color
|
89 |
+
if len(image.shape) == 3:
|
90 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
91 |
+
|
92 |
+
# Calculate min and max values
|
93 |
+
min_val = image.min()
|
94 |
+
max_val = image.max()
|
95 |
+
|
96 |
+
if min_val == max_val:
|
97 |
+
return image # Avoid division by zero
|
98 |
+
|
99 |
+
# Apply contrast stretching
|
100 |
+
contrast_stretched = cv2.convertScaleAbs(image, alpha=255.0 / (max_val - min_val), beta=-min_val)
|
101 |
+
|
102 |
+
return contrast_stretched
|
103 |
+
|
104 |
+
def reduce_noise(image, kernel_size=(3, 3)):
|
105 |
+
# Apply Gaussian blur to reduce noise
|
106 |
+
blurred = cv2.GaussianBlur(image, kernel_size, 0)
|
107 |
+
|
108 |
+
return blurred
|
109 |
+
@torch.no_grad()
|
110 |
+
def run(
|
111 |
+
weights=ROOT / 'yolov5s.pt', # model.pt path(s)
|
112 |
+
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
|
113 |
+
data=ROOT / 'data.yaml', # dataset.yaml path
|
114 |
+
imgsz=(640, 640), # inference size (height, width)
|
115 |
+
conf_thres=0.25, # confidence threshold
|
116 |
+
iou_thres=0.45, # NMS IOU threshold
|
117 |
+
max_det=1000, # maximum detections per image
|
118 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
119 |
+
view_img=False, # show results
|
120 |
+
save_txt=False, # save results to *.txt
|
121 |
+
save_conf=False, # save confidences in --save-txt labels
|
122 |
+
save_crop=False, # save cropped prediction boxes
|
123 |
+
nosave=False, # do not save images/videos
|
124 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
125 |
+
agnostic_nms=False, # class-agnostic NMS
|
126 |
+
augment=False, # augmented inference
|
127 |
+
visualize=False, # visualize features
|
128 |
+
update=False, # update all models
|
129 |
+
project=ROOT / 'runs/detect', # save results to project/name
|
130 |
+
name='exp', # save results to project/name
|
131 |
+
exist_ok=True, # existing project/name ok, do not increment
|
132 |
+
line_thickness=2, # bounding box thickness (pixels)
|
133 |
+
hide_labels=False, # hide labels
|
134 |
+
hide_conf=False, # hide confidences
|
135 |
+
half=False, # use FP16 half-precision inference
|
136 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
137 |
+
|
138 |
+
upl_image: np.ndarray=None,
|
139 |
+
#return_type: list=["Image", "Labels"]
|
140 |
+
):
|
141 |
+
|
142 |
+
source = str(source)
|
143 |
+
save_img = not nosave and not source.endswith('.txt') # save inference images
|
144 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
145 |
+
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
146 |
+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
147 |
+
if is_url and is_file:
|
148 |
+
source = check_file(source) # download
|
149 |
+
|
150 |
+
# Directories
|
151 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
152 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
153 |
+
|
154 |
+
# Load model
|
155 |
+
device = select_device(device)
|
156 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
157 |
+
stride, names, pt = model.stride, model.names, model.pt
|
158 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
159 |
+
|
160 |
+
# Dataloader
|
161 |
+
if webcam:
|
162 |
+
view_img = check_imshow()
|
163 |
+
cudnn.benchmark = True # set True to speed up constant image size inference
|
164 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
|
165 |
+
bs = len(dataset) # batch_size
|
166 |
+
else:
|
167 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
|
168 |
+
bs = 1 # batch_size
|
169 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
170 |
+
|
171 |
+
# Run inference
|
172 |
+
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
|
173 |
+
seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
|
174 |
+
for path, im, im0s, vid_cap, s in dataset:
|
175 |
+
t1 = time_sync()
|
176 |
+
#im=upl_image
|
177 |
+
im = torch.from_numpy(im).to(device)
|
178 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
179 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
180 |
+
if len(im.shape) == 3:
|
181 |
+
im = im[None] # expand for batch dim
|
182 |
+
t2 = time_sync()
|
183 |
+
dt[0] += t2 - t1
|
184 |
+
# Contrast enhancement
|
185 |
+
# im = increase_contrast(im)
|
186 |
+
|
187 |
+
# # Noise reduction
|
188 |
+
# im = reduce_noise(im)
|
189 |
+
# Inference
|
190 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
191 |
+
pred = model(im, augment=augment, visualize=visualize)
|
192 |
+
t3 = time_sync()
|
193 |
+
dt[1] += t3 - t2
|
194 |
+
|
195 |
+
# NMS
|
196 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
197 |
+
dt[2] += time_sync() - t3
|
198 |
+
|
199 |
+
# Second-stage classifier (optional)
|
200 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
201 |
+
|
202 |
+
# Process predictions
|
203 |
+
for i, det in enumerate(pred): # per image
|
204 |
+
seen += 1
|
205 |
+
if webcam: # batch_size >= 1
|
206 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
207 |
+
s += f'{i}: '
|
208 |
+
else:
|
209 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
|
210 |
+
|
211 |
+
p = Path(p) # to Path
|
212 |
+
save_path = str(save_dir / p.name) # im.jpg
|
213 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
|
214 |
+
s += '%gx%g ' % im.shape[2:] # print string
|
215 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
216 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
217 |
+
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
218 |
+
if len(det):
|
219 |
+
# Rescale boxes from img_size to im0 size
|
220 |
+
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
|
221 |
+
|
222 |
+
# Print results
|
223 |
+
for c in det[:, -1].unique():
|
224 |
+
n = (det[:, -1] == c).sum() # detections per class
|
225 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
226 |
+
|
227 |
+
# Write results
|
228 |
+
for *xyxy, conf, cls in reversed(det):
|
229 |
+
if save_txt: # Write to file
|
230 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
231 |
+
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
232 |
+
with open(f'{txt_path}.txt', 'a') as f:
|
233 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
234 |
+
|
235 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
236 |
+
c = int(cls) # integer class
|
237 |
+
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
|
238 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
239 |
+
if save_crop:
|
240 |
+
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
|
241 |
+
|
242 |
+
# Stream results
|
243 |
+
im0 = annotator.result()
|
244 |
+
if view_img:
|
245 |
+
if platform.system() == 'Linux' and p not in windows:
|
246 |
+
windows.append(p)
|
247 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
248 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
249 |
+
cv2.imshow(str(p), im0)
|
250 |
+
cv2.waitKey(1) # 1 millisecond
|
251 |
+
|
252 |
+
# Save results (image with detections)
|
253 |
+
if save_img:
|
254 |
+
if dataset.mode == 'image':
|
255 |
+
#cv2.imwrite(save_path, im0)
|
256 |
+
print("Save")
|
257 |
+
else: # 'video' or 'stream'
|
258 |
+
if vid_path[i] != save_path: # new video
|
259 |
+
vid_path[i] = save_path
|
260 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
261 |
+
vid_writer[i].release() # release previous video writer
|
262 |
+
if vid_cap: # video
|
263 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
264 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
265 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
266 |
+
else: # stream
|
267 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
268 |
+
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
|
269 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
270 |
+
vid_writer[i].write(im0)
|
271 |
+
|
272 |
+
# Print time (inference-only)
|
273 |
+
LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
|
274 |
+
|
275 |
+
# Print results
|
276 |
+
t = tuple(x / seen * 1E3 for x in dt) # speeds per image
|
277 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
|
278 |
+
if save_txt or save_img:
|
279 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
280 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
281 |
+
if update:
|
282 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
283 |
+
im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)
|
284 |
+
return im0
|
285 |
+
|
286 |
+
|
287 |
+
def parse_opt():
|
288 |
+
parser = argparse.ArgumentParser()
|
289 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
|
290 |
+
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
|
291 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data.yaml', help='(optional) dataset.yaml path')
|
292 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[800], help='inference size h,w')
|
293 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
|
294 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
|
295 |
+
parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
|
296 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
297 |
+
parser.add_argument('--view-img', action='store_true', help='show results')
|
298 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
299 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
300 |
+
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
|
301 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
302 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
|
303 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
|
304 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
305 |
+
parser.add_argument('--visualize', action='store_true', help='visualize features')
|
306 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
307 |
+
parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
|
308 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
309 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
310 |
+
parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
|
311 |
+
parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
|
312 |
+
parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
|
313 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
314 |
+
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
315 |
+
opt = parser.parse_args()
|
316 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
317 |
+
print_args(vars(opt))
|
318 |
+
return opt
|
319 |
+
|
320 |
+
def classify(model,img):
|
321 |
+
img = img.to(device)
|
322 |
+
prediction = model(img)
|
323 |
+
sc, preds = torch.max(prediction, dim = 1)
|
324 |
+
return sc[0].item(),preds[0].item()
|
325 |
+
|
326 |
+
|
327 |
+
def main(opt,model,labels):
|
328 |
+
#check_requirements(exclude=('tensorboard', 'thop'))
|
329 |
+
#run(**vars(opt))
|
330 |
+
st.image("logo.jpg", caption="")
|
331 |
+
st.title("#Welcome to Deep Diagnosis")
|
332 |
+
# st.write("By: Dr. Asif Iqbal Khan")
|
333 |
+
st.markdown(
|
334 |
+
"""
|
335 |
+
This app allows you to detect different apple diseases from leaf images.
|
336 |
+
1) Scab
|
337 |
+
2) Alternaria
|
338 |
+
3) MLB
|
339 |
+
4) Mossaic
|
340 |
+
5) Powdery Mildew
|
341 |
+
6) Necrosis
|
342 |
+
"""
|
343 |
+
)
|
344 |
+
url="https://www.sciencedirect.com/science/article/abs/pii/S0168169922004100"
|
345 |
+
st.write("Link to the research paper: [link] (%s)" %url)
|
346 |
+
|
347 |
+
st.write("This app allows you to provide an image, and one of the most advanced Object Detection algorithms available will try to classify it for you. Upload your data to get started!")
|
348 |
+
|
349 |
+
with st.sidebar:
|
350 |
+
# st.image("logo.jpg", caption="")
|
351 |
+
uploaded_file = st.file_uploader("Choose an Image", type=["png","jpg","jpeg"])
|
352 |
+
return_types = st.multiselect("Select Return Type", ["Image", "Labels"], ["Image", "Labels"])
|
353 |
+
|
354 |
+
if not uploaded_file:
|
355 |
+
file_name = "sample.jpg"
|
356 |
+
st.write("Upload apple leaf image to detect diseases")
|
357 |
+
st.image("sample.jpg", caption='Sample Image',width=400)
|
358 |
+
|
359 |
+
else:
|
360 |
+
file_name = uploaded_file.name
|
361 |
+
|
362 |
+
#image = np.array(Image.open(image_file_buffer))
|
363 |
+
#Saving upload
|
364 |
+
file_details = {"filename":uploaded_file.name, "filetype":uploaded_file.type,"filesize":uploaded_file.size}
|
365 |
+
#st.write(file_details)
|
366 |
+
with open(file_name,"wb") as f:
|
367 |
+
f.write((uploaded_file).getbuffer())
|
368 |
+
|
369 |
+
img = Image.open(uploaded_file)
|
370 |
+
if img.format.lower() != "jpeg" or img.format.lower() !="jpg" :
|
371 |
+
# Convert the image to RGB format (JPEG-compatible) and save as a temporary JPEG file
|
372 |
+
img = img.convert("RGB")
|
373 |
+
temp_jpeg_file = "temp_image.jpg"
|
374 |
+
img.save(temp_jpeg_file, "JPEG")
|
375 |
+
|
376 |
+
img.close()
|
377 |
+
|
378 |
+
# Load the temporary JPEG file for processing
|
379 |
+
img = Image.open(temp_jpeg_file)
|
380 |
+
|
381 |
+
|
382 |
+
|
383 |
+
img = transforms.Resize((360,360))(img)
|
384 |
+
img = transforms.ToTensor()(img)
|
385 |
+
img = img.unsqueeze(0).to(device)
|
386 |
+
res=classify(model,img)
|
387 |
+
|
388 |
+
|
389 |
+
lb=labels[res[1]]
|
390 |
+
sc=res[0]
|
391 |
+
st.write(lb+" "+str(sc))
|
392 |
+
if(lb=="noleaf"):
|
393 |
+
st.write("Invalid image! Try Some other image")
|
394 |
+
elif(lb=="healthy"):
|
395 |
+
st.write("Looks healthy to me")
|
396 |
+
elif(lb=="demaged"):
|
397 |
+
st.write("No recognizable disease found")
|
398 |
+
else:
|
399 |
+
if(sc>7):
|
400 |
+
final_result = run(weights,file_name)
|
401 |
+
st.image(final_result, caption='Diseases Detected', width=400)
|
402 |
+
|
403 |
+
else:
|
404 |
+
st.write("No disease detected")
|
405 |
+
|
406 |
+
#final_result = run(weights,file_name)
|
407 |
+
#st.image(final_result, caption='Diseases Detected')
|
408 |
+
os.remove(file_name)
|
409 |
+
#Remove the temporary JPEG file after processing
|
410 |
+
os.remove(temp_jpeg_file)
|
411 |
+
|
412 |
+
|
413 |
+
|
414 |
+
if __name__ == "__main__":
|
415 |
+
opt = parse_opt()
|
416 |
+
model=NaturalSceneClassification()
|
417 |
+
model=torch.load("mobilenetv2-apple-10-class-pytorch.pth",map_location=device )
|
418 |
+
model.eval()
|
419 |
+
|
420 |
+
labels=[]
|
421 |
+
with open("labels.txt") as file:
|
422 |
+
for line in file:
|
423 |
+
line = line.strip() #or some other preprocessing
|
424 |
+
labels.append(line) #st
|
425 |
+
main(opt,model,labels)
|
426 |
+
|
427 |
+
|
428 |
+
|
429 |
+
|
430 |
+
|
431 |
+
|
432 |
+
|
data.yaml
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
train: ../apple/train/images
|
2 |
+
val: ../apple/valid/images
|
3 |
+
|
4 |
+
nc: 7
|
5 |
+
names: ['alternaria', 'insect', 'mlb', 'mossaic', 'necrosis', 'pwm', 'scab']
|
detect.py
ADDED
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 platform
|
30 |
+
import sys
|
31 |
+
from pathlib import Path
|
32 |
+
|
33 |
+
import torch
|
34 |
+
import torch.backends.cudnn as cudnn
|
35 |
+
|
36 |
+
FILE = Path(__file__).resolve()
|
37 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
38 |
+
if str(ROOT) not in sys.path:
|
39 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
40 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
41 |
+
|
42 |
+
from models.common import DetectMultiBackend
|
43 |
+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
|
44 |
+
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
|
45 |
+
increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
|
46 |
+
from utils.plots import Annotator, colors, save_one_box
|
47 |
+
from utils.torch_utils import select_device, time_sync
|
48 |
+
|
49 |
+
|
50 |
+
@torch.no_grad()
|
51 |
+
def run(
|
52 |
+
weights=ROOT / 'yolov5s.pt', # model.pt path(s)
|
53 |
+
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
|
54 |
+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
55 |
+
imgsz=(640, 640), # inference size (height, width)
|
56 |
+
conf_thres=0.25, # confidence threshold
|
57 |
+
iou_thres=0.45, # NMS IOU threshold
|
58 |
+
max_det=1000, # maximum detections per image
|
59 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
60 |
+
view_img=False, # show results
|
61 |
+
save_txt=False, # save results to *.txt
|
62 |
+
save_conf=False, # save confidences in --save-txt labels
|
63 |
+
save_crop=False, # save cropped prediction boxes
|
64 |
+
nosave=False, # do not save images/videos
|
65 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
66 |
+
agnostic_nms=False, # class-agnostic NMS
|
67 |
+
augment=False, # augmented inference
|
68 |
+
visualize=False, # visualize features
|
69 |
+
update=False, # update all models
|
70 |
+
project=ROOT / 'runs/detect', # save results to project/name
|
71 |
+
name='exp', # save results to project/name
|
72 |
+
exist_ok=False, # existing project/name ok, do not increment
|
73 |
+
line_thickness=3, # bounding box thickness (pixels)
|
74 |
+
hide_labels=False, # hide labels
|
75 |
+
hide_conf=False, # hide confidences
|
76 |
+
half=False, # use FP16 half-precision inference
|
77 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
78 |
+
):
|
79 |
+
source = str(source)
|
80 |
+
save_img = not nosave and not source.endswith('.txt') # save inference images
|
81 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
82 |
+
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
83 |
+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
84 |
+
if is_url and is_file:
|
85 |
+
source = check_file(source) # download
|
86 |
+
|
87 |
+
# Directories
|
88 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
89 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
90 |
+
|
91 |
+
# Load model
|
92 |
+
device = select_device(device)
|
93 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
94 |
+
stride, names, pt = model.stride, model.names, model.pt
|
95 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
96 |
+
|
97 |
+
# Dataloader
|
98 |
+
if webcam:
|
99 |
+
view_img = check_imshow()
|
100 |
+
cudnn.benchmark = True # set True to speed up constant image size inference
|
101 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
|
102 |
+
bs = len(dataset) # batch_size
|
103 |
+
else:
|
104 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
|
105 |
+
bs = 1 # batch_size
|
106 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
107 |
+
|
108 |
+
# Run inference
|
109 |
+
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
|
110 |
+
seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
|
111 |
+
for path, im, im0s, vid_cap, s in dataset:
|
112 |
+
t1 = time_sync()
|
113 |
+
im = torch.from_numpy(im).to(device)
|
114 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
115 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
116 |
+
if len(im.shape) == 3:
|
117 |
+
im = im[None] # expand for batch dim
|
118 |
+
t2 = time_sync()
|
119 |
+
dt[0] += t2 - t1
|
120 |
+
|
121 |
+
# Inference
|
122 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
123 |
+
pred = model(im, augment=augment, visualize=visualize)
|
124 |
+
t3 = time_sync()
|
125 |
+
dt[1] += t3 - t2
|
126 |
+
|
127 |
+
# NMS
|
128 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
129 |
+
dt[2] += time_sync() - t3
|
130 |
+
|
131 |
+
# Second-stage classifier (optional)
|
132 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
133 |
+
|
134 |
+
# Process predictions
|
135 |
+
for i, det in enumerate(pred): # per image
|
136 |
+
seen += 1
|
137 |
+
if webcam: # batch_size >= 1
|
138 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
139 |
+
s += f'{i}: '
|
140 |
+
else:
|
141 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
|
142 |
+
|
143 |
+
p = Path(p) # to Path
|
144 |
+
save_path = str(save_dir / p.name) # im.jpg
|
145 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
|
146 |
+
s += '%gx%g ' % im.shape[2:] # print string
|
147 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
148 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
149 |
+
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
150 |
+
if len(det):
|
151 |
+
# Rescale boxes from img_size to im0 size
|
152 |
+
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
|
153 |
+
|
154 |
+
# Print results
|
155 |
+
for c in det[:, -1].unique():
|
156 |
+
n = (det[:, -1] == c).sum() # detections per class
|
157 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
158 |
+
|
159 |
+
# Write results
|
160 |
+
for *xyxy, conf, cls in reversed(det):
|
161 |
+
if save_txt: # Write to file
|
162 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
163 |
+
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
164 |
+
with open(f'{txt_path}.txt', 'a') as f:
|
165 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
166 |
+
|
167 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
168 |
+
c = int(cls) # integer class
|
169 |
+
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
|
170 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
171 |
+
if save_crop:
|
172 |
+
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
|
173 |
+
|
174 |
+
# Stream results
|
175 |
+
im0 = annotator.result()
|
176 |
+
if view_img:
|
177 |
+
if platform.system() == 'Linux' and p not in windows:
|
178 |
+
windows.append(p)
|
179 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
180 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
181 |
+
cv2.imshow(str(p), im0)
|
182 |
+
cv2.waitKey(1) # 1 millisecond
|
183 |
+
|
184 |
+
# Save results (image with detections)
|
185 |
+
if save_img:
|
186 |
+
if dataset.mode == 'image':
|
187 |
+
cv2.imwrite(save_path, im0)
|
188 |
+
else: # 'video' or 'stream'
|
189 |
+
if vid_path[i] != save_path: # new video
|
190 |
+
vid_path[i] = save_path
|
191 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
192 |
+
vid_writer[i].release() # release previous video writer
|
193 |
+
if vid_cap: # video
|
194 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
195 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
196 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
197 |
+
else: # stream
|
198 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
199 |
+
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
|
200 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
201 |
+
vid_writer[i].write(im0)
|
202 |
+
|
203 |
+
# Print time (inference-only)
|
204 |
+
LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
|
205 |
+
|
206 |
+
# Print results
|
207 |
+
t = tuple(x / seen * 1E3 for x in dt) # speeds per image
|
208 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
|
209 |
+
if save_txt or save_img:
|
210 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
211 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
212 |
+
if update:
|
213 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
214 |
+
|
215 |
+
|
216 |
+
def parse_opt():
|
217 |
+
parser = argparse.ArgumentParser()
|
218 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
|
219 |
+
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
|
220 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
|
221 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
|
222 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
|
223 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
|
224 |
+
parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
|
225 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
226 |
+
parser.add_argument('--view-img', action='store_true', help='show results')
|
227 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
228 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
229 |
+
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
|
230 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
231 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
|
232 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
|
233 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
234 |
+
parser.add_argument('--visualize', action='store_true', help='visualize features')
|
235 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
236 |
+
parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
|
237 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
238 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
239 |
+
parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
|
240 |
+
parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
|
241 |
+
parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
|
242 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
243 |
+
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
244 |
+
opt = parser.parse_args()
|
245 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
246 |
+
print_args(vars(opt))
|
247 |
+
return opt
|
248 |
+
|
249 |
+
|
250 |
+
def main(opt):
|
251 |
+
check_requirements(exclude=('tensorboard', 'thop'))
|
252 |
+
run(**vars(opt))
|
253 |
+
|
254 |
+
|
255 |
+
if __name__ == "__main__":
|
256 |
+
opt = parse_opt()
|
257 |
+
main(opt)
|
export.py
ADDED
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, check_yaml,
|
71 |
+
colorstr, 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 |
+
cuda = torch.cuda.is_available()
|
156 |
+
check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1'))
|
157 |
+
import onnxsim
|
158 |
+
|
159 |
+
LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
160 |
+
model_onnx, check = onnxsim.simplify(model_onnx)
|
161 |
+
assert check, 'assert check failed'
|
162 |
+
onnx.save(model_onnx, f)
|
163 |
+
except Exception as e:
|
164 |
+
LOGGER.info(f'{prefix} simplifier failure: {e}')
|
165 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
166 |
+
return f
|
167 |
+
except Exception as e:
|
168 |
+
LOGGER.info(f'{prefix} export failure: {e}')
|
169 |
+
|
170 |
+
|
171 |
+
def export_openvino(model, file, half, prefix=colorstr('OpenVINO:')):
|
172 |
+
# YOLOv5 OpenVINO export
|
173 |
+
try:
|
174 |
+
check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
175 |
+
import openvino.inference_engine as ie
|
176 |
+
|
177 |
+
LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
|
178 |
+
f = str(file).replace('.pt', f'_openvino_model{os.sep}')
|
179 |
+
|
180 |
+
cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
|
181 |
+
subprocess.check_output(cmd.split()) # export
|
182 |
+
with open(Path(f) / file.with_suffix('.yaml').name, 'w') as g:
|
183 |
+
yaml.dump({'stride': int(max(model.stride)), 'names': model.names}, g) # add metadata.yaml
|
184 |
+
|
185 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
186 |
+
return f
|
187 |
+
except Exception as e:
|
188 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
189 |
+
|
190 |
+
|
191 |
+
def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
|
192 |
+
# YOLOv5 CoreML export
|
193 |
+
try:
|
194 |
+
check_requirements(('coremltools',))
|
195 |
+
import coremltools as ct
|
196 |
+
|
197 |
+
LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
|
198 |
+
f = file.with_suffix('.mlmodel')
|
199 |
+
|
200 |
+
ts = torch.jit.trace(model, im, strict=False) # TorchScript model
|
201 |
+
ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
|
202 |
+
bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
|
203 |
+
if bits < 32:
|
204 |
+
if platform.system() == 'Darwin': # quantization only supported on macOS
|
205 |
+
with warnings.catch_warnings():
|
206 |
+
warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
|
207 |
+
ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
|
208 |
+
else:
|
209 |
+
print(f'{prefix} quantization only supported on macOS, skipping...')
|
210 |
+
ct_model.save(f)
|
211 |
+
|
212 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
213 |
+
return ct_model, f
|
214 |
+
except Exception as e:
|
215 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
216 |
+
return None, None
|
217 |
+
|
218 |
+
|
219 |
+
def export_engine(model, im, file, train, half, dynamic, simplify, workspace=4, verbose=False):
|
220 |
+
# YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
|
221 |
+
prefix = colorstr('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, dynamic, 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, dynamic, 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 |
+
if dynamic:
|
268 |
+
if im.shape[0] <= 1:
|
269 |
+
LOGGER.warning(f"{prefix}WARNING: --dynamic model requires maximum --batch-size argument")
|
270 |
+
profile = builder.create_optimization_profile()
|
271 |
+
for inp in inputs:
|
272 |
+
profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape)
|
273 |
+
config.add_optimization_profile(profile)
|
274 |
+
|
275 |
+
LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}')
|
276 |
+
if builder.platform_has_fast_fp16 and half:
|
277 |
+
config.set_flag(trt.BuilderFlag.FP16)
|
278 |
+
with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
|
279 |
+
t.write(engine.serialize())
|
280 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
281 |
+
return f
|
282 |
+
except Exception as e:
|
283 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
284 |
+
|
285 |
+
|
286 |
+
def export_saved_model(model,
|
287 |
+
im,
|
288 |
+
file,
|
289 |
+
dynamic,
|
290 |
+
tf_nms=False,
|
291 |
+
agnostic_nms=False,
|
292 |
+
topk_per_class=100,
|
293 |
+
topk_all=100,
|
294 |
+
iou_thres=0.45,
|
295 |
+
conf_thres=0.25,
|
296 |
+
keras=False,
|
297 |
+
prefix=colorstr('TensorFlow SavedModel:')):
|
298 |
+
# YOLOv5 TensorFlow SavedModel export
|
299 |
+
try:
|
300 |
+
import tensorflow as tf
|
301 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
302 |
+
|
303 |
+
from models.tf import TFDetect, TFModel
|
304 |
+
|
305 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
306 |
+
f = str(file).replace('.pt', '_saved_model')
|
307 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
308 |
+
|
309 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
310 |
+
im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
|
311 |
+
_ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
312 |
+
inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
|
313 |
+
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
314 |
+
keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
|
315 |
+
keras_model.trainable = False
|
316 |
+
keras_model.summary()
|
317 |
+
if keras:
|
318 |
+
keras_model.save(f, save_format='tf')
|
319 |
+
else:
|
320 |
+
spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
|
321 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
322 |
+
m = m.get_concrete_function(spec)
|
323 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
324 |
+
tfm = tf.Module()
|
325 |
+
tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
|
326 |
+
tfm.__call__(im)
|
327 |
+
tf.saved_model.save(tfm,
|
328 |
+
f,
|
329 |
+
options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
|
330 |
+
if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
|
331 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
332 |
+
return keras_model, f
|
333 |
+
except Exception as e:
|
334 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
335 |
+
return None, None
|
336 |
+
|
337 |
+
|
338 |
+
def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
|
339 |
+
# YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
|
340 |
+
try:
|
341 |
+
import tensorflow as tf
|
342 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
343 |
+
|
344 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
345 |
+
f = file.with_suffix('.pb')
|
346 |
+
|
347 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
348 |
+
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
|
349 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
350 |
+
frozen_func.graph.as_graph_def()
|
351 |
+
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
|
352 |
+
|
353 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
354 |
+
return f
|
355 |
+
except Exception as e:
|
356 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
357 |
+
|
358 |
+
|
359 |
+
def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
|
360 |
+
# YOLOv5 TensorFlow Lite export
|
361 |
+
try:
|
362 |
+
import tensorflow as tf
|
363 |
+
|
364 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
365 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
366 |
+
f = str(file).replace('.pt', '-fp16.tflite')
|
367 |
+
|
368 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
|
369 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
|
370 |
+
converter.target_spec.supported_types = [tf.float16]
|
371 |
+
converter.optimizations = [tf.lite.Optimize.DEFAULT]
|
372 |
+
if int8:
|
373 |
+
from models.tf import representative_dataset_gen
|
374 |
+
dataset = LoadImages(check_dataset(check_yaml(data))['train'], img_size=imgsz, auto=False)
|
375 |
+
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
|
376 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
377 |
+
converter.target_spec.supported_types = []
|
378 |
+
converter.inference_input_type = tf.uint8 # or tf.int8
|
379 |
+
converter.inference_output_type = tf.uint8 # or tf.int8
|
380 |
+
converter.experimental_new_quantizer = True
|
381 |
+
f = str(file).replace('.pt', '-int8.tflite')
|
382 |
+
if nms or agnostic_nms:
|
383 |
+
converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
|
384 |
+
|
385 |
+
tflite_model = converter.convert()
|
386 |
+
open(f, "wb").write(tflite_model)
|
387 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
388 |
+
return f
|
389 |
+
except Exception as e:
|
390 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
391 |
+
|
392 |
+
|
393 |
+
def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
|
394 |
+
# YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
|
395 |
+
try:
|
396 |
+
cmd = 'edgetpu_compiler --version'
|
397 |
+
help_url = 'https://coral.ai/docs/edgetpu/compiler/'
|
398 |
+
assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
|
399 |
+
if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
|
400 |
+
LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
|
401 |
+
sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
|
402 |
+
for c in (
|
403 |
+
'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
|
404 |
+
'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
|
405 |
+
'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
|
406 |
+
subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
|
407 |
+
ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
|
408 |
+
|
409 |
+
LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
|
410 |
+
f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
|
411 |
+
f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
|
412 |
+
|
413 |
+
cmd = f"edgetpu_compiler -s -d -k 10 --out_dir {file.parent} {f_tfl}"
|
414 |
+
subprocess.run(cmd.split(), check=True)
|
415 |
+
|
416 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
417 |
+
return f
|
418 |
+
except Exception as e:
|
419 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
420 |
+
|
421 |
+
|
422 |
+
def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
|
423 |
+
# YOLOv5 TensorFlow.js export
|
424 |
+
try:
|
425 |
+
check_requirements(('tensorflowjs',))
|
426 |
+
import re
|
427 |
+
|
428 |
+
import tensorflowjs as tfjs
|
429 |
+
|
430 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
|
431 |
+
f = str(file).replace('.pt', '_web_model') # js dir
|
432 |
+
f_pb = file.with_suffix('.pb') # *.pb path
|
433 |
+
f_json = f'{f}/model.json' # *.json path
|
434 |
+
|
435 |
+
cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
|
436 |
+
f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
|
437 |
+
subprocess.run(cmd.split())
|
438 |
+
|
439 |
+
with open(f_json) as j:
|
440 |
+
json = j.read()
|
441 |
+
with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
|
442 |
+
subst = re.sub(
|
443 |
+
r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
|
444 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
445 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
446 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
|
447 |
+
r'"Identity_1": {"name": "Identity_1"}, '
|
448 |
+
r'"Identity_2": {"name": "Identity_2"}, '
|
449 |
+
r'"Identity_3": {"name": "Identity_3"}}}', json)
|
450 |
+
j.write(subst)
|
451 |
+
|
452 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
453 |
+
return f
|
454 |
+
except Exception as e:
|
455 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
456 |
+
|
457 |
+
|
458 |
+
@torch.no_grad()
|
459 |
+
def run(
|
460 |
+
data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
|
461 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
462 |
+
imgsz=(640, 640), # image (height, width)
|
463 |
+
batch_size=1, # batch size
|
464 |
+
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
465 |
+
include=('torchscript', 'onnx'), # include formats
|
466 |
+
half=False, # FP16 half-precision export
|
467 |
+
inplace=False, # set YOLOv5 Detect() inplace=True
|
468 |
+
train=False, # model.train() mode
|
469 |
+
keras=False, # use Keras
|
470 |
+
optimize=False, # TorchScript: optimize for mobile
|
471 |
+
int8=False, # CoreML/TF INT8 quantization
|
472 |
+
dynamic=False, # ONNX/TF/TensorRT: dynamic axes
|
473 |
+
simplify=False, # ONNX: simplify model
|
474 |
+
opset=12, # ONNX: opset version
|
475 |
+
verbose=False, # TensorRT: verbose log
|
476 |
+
workspace=4, # TensorRT: workspace size (GB)
|
477 |
+
nms=False, # TF: add NMS to model
|
478 |
+
agnostic_nms=False, # TF: add agnostic NMS to model
|
479 |
+
topk_per_class=100, # TF.js NMS: topk per class to keep
|
480 |
+
topk_all=100, # TF.js NMS: topk for all classes to keep
|
481 |
+
iou_thres=0.45, # TF.js NMS: IoU threshold
|
482 |
+
conf_thres=0.25, # TF.js NMS: confidence threshold
|
483 |
+
):
|
484 |
+
t = time.time()
|
485 |
+
include = [x.lower() for x in include] # to lowercase
|
486 |
+
fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
|
487 |
+
flags = [x in include for x in fmts]
|
488 |
+
assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
|
489 |
+
jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
|
490 |
+
file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
|
491 |
+
|
492 |
+
# Load PyTorch model
|
493 |
+
device = select_device(device)
|
494 |
+
if half:
|
495 |
+
assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
|
496 |
+
assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
|
497 |
+
model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
|
498 |
+
nc, names = model.nc, model.names # number of classes, class names
|
499 |
+
|
500 |
+
# Checks
|
501 |
+
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
|
502 |
+
assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
|
503 |
+
if optimize:
|
504 |
+
assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'
|
505 |
+
|
506 |
+
# Input
|
507 |
+
gs = int(max(model.stride)) # grid size (max stride)
|
508 |
+
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
|
509 |
+
im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
|
510 |
+
|
511 |
+
# Update model
|
512 |
+
model.train() if train else model.eval() # training mode = no Detect() layer grid construction
|
513 |
+
for k, m in model.named_modules():
|
514 |
+
if isinstance(m, Detect):
|
515 |
+
m.inplace = inplace
|
516 |
+
m.onnx_dynamic = dynamic
|
517 |
+
m.export = True
|
518 |
+
|
519 |
+
for _ in range(2):
|
520 |
+
y = model(im) # dry runs
|
521 |
+
if half and not coreml:
|
522 |
+
im, model = im.half(), model.half() # to FP16
|
523 |
+
shape = tuple(y[0].shape) # model output shape
|
524 |
+
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
|
525 |
+
|
526 |
+
# Exports
|
527 |
+
f = [''] * 10 # exported filenames
|
528 |
+
warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
|
529 |
+
if jit:
|
530 |
+
f[0] = export_torchscript(model, im, file, optimize)
|
531 |
+
if engine: # TensorRT required before ONNX
|
532 |
+
f[1] = export_engine(model, im, file, train, half, dynamic, simplify, workspace, verbose)
|
533 |
+
if onnx or xml: # OpenVINO requires ONNX
|
534 |
+
f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
|
535 |
+
if xml: # OpenVINO
|
536 |
+
f[3] = export_openvino(model, file, half)
|
537 |
+
if coreml:
|
538 |
+
_, f[4] = export_coreml(model, im, file, int8, half)
|
539 |
+
|
540 |
+
# TensorFlow Exports
|
541 |
+
if any((saved_model, pb, tflite, edgetpu, tfjs)):
|
542 |
+
if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
|
543 |
+
check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
|
544 |
+
assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
|
545 |
+
model, f[5] = export_saved_model(model.cpu(),
|
546 |
+
im,
|
547 |
+
file,
|
548 |
+
dynamic,
|
549 |
+
tf_nms=nms or agnostic_nms or tfjs,
|
550 |
+
agnostic_nms=agnostic_nms or tfjs,
|
551 |
+
topk_per_class=topk_per_class,
|
552 |
+
topk_all=topk_all,
|
553 |
+
iou_thres=iou_thres,
|
554 |
+
conf_thres=conf_thres,
|
555 |
+
keras=keras)
|
556 |
+
if pb or tfjs: # pb prerequisite to tfjs
|
557 |
+
f[6] = export_pb(model, file)
|
558 |
+
if tflite or edgetpu:
|
559 |
+
f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
|
560 |
+
if edgetpu:
|
561 |
+
f[8] = export_edgetpu(file)
|
562 |
+
if tfjs:
|
563 |
+
f[9] = export_tfjs(file)
|
564 |
+
|
565 |
+
# Finish
|
566 |
+
f = [str(x) for x in f if x] # filter out '' and None
|
567 |
+
if any(f):
|
568 |
+
h = '--half' if half else '' # --half FP16 inference arg
|
569 |
+
LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
|
570 |
+
f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
|
571 |
+
f"\nDetect: python detect.py --weights {f[-1]} {h}"
|
572 |
+
f"\nValidate: python val.py --weights {f[-1]} {h}"
|
573 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
|
574 |
+
f"\nVisualize: https://netron.app")
|
575 |
+
return f # return list of exported files/dirs
|
576 |
+
|
577 |
+
|
578 |
+
def parse_opt():
|
579 |
+
parser = argparse.ArgumentParser()
|
580 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
581 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
|
582 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
|
583 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
584 |
+
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
585 |
+
parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
|
586 |
+
parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
|
587 |
+
parser.add_argument('--train', action='store_true', help='model.train() mode')
|
588 |
+
parser.add_argument('--keras', action='store_true', help='TF: use Keras')
|
589 |
+
parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
|
590 |
+
parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
|
591 |
+
parser.add_argument('--dynamic', action='store_true', help='ONNX/TF/TensorRT: dynamic axes')
|
592 |
+
parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
|
593 |
+
parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
|
594 |
+
parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
|
595 |
+
parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
|
596 |
+
parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
|
597 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
|
598 |
+
parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
|
599 |
+
parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
|
600 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
|
601 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
|
602 |
+
parser.add_argument('--include',
|
603 |
+
nargs='+',
|
604 |
+
default=['torchscript', 'onnx'],
|
605 |
+
help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
|
606 |
+
opt = parser.parse_args()
|
607 |
+
print_args(vars(opt))
|
608 |
+
return opt
|
609 |
+
|
610 |
+
|
611 |
+
def main(opt):
|
612 |
+
for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
|
613 |
+
run(**vars(opt))
|
614 |
+
|
615 |
+
|
616 |
+
if __name__ == "__main__":
|
617 |
+
opt = parse_opt()
|
618 |
+
main(opt)
|
hubconf.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.experimental import attempt_load
|
33 |
+
from models.yolo import Model
|
34 |
+
from utils.downloads import attempt_download
|
35 |
+
from utils.general import LOGGER, check_requirements, intersect_dicts, logging
|
36 |
+
from utils.torch_utils import select_device
|
37 |
+
|
38 |
+
if not verbose:
|
39 |
+
LOGGER.setLevel(logging.WARNING)
|
40 |
+
check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
|
41 |
+
name = Path(name)
|
42 |
+
path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
|
43 |
+
try:
|
44 |
+
device = select_device(device)
|
45 |
+
if pretrained and channels == 3 and classes == 80:
|
46 |
+
try:
|
47 |
+
model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
|
48 |
+
if autoshape:
|
49 |
+
model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
|
50 |
+
except Exception:
|
51 |
+
model = attempt_load(path, device=device, fuse=False) # arbitrary model
|
52 |
+
else:
|
53 |
+
cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
|
54 |
+
model = Model(cfg, channels, classes) # create model
|
55 |
+
if pretrained:
|
56 |
+
ckpt = torch.load(attempt_download(path), map_location=device) # load
|
57 |
+
csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
|
58 |
+
csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
|
59 |
+
model.load_state_dict(csd, strict=False) # load
|
60 |
+
if len(ckpt['model'].names) == classes:
|
61 |
+
model.names = ckpt['model'].names # set class names attribute
|
62 |
+
if not verbose:
|
63 |
+
LOGGER.setLevel(logging.INFO) # reset to default
|
64 |
+
return model.to(device)
|
65 |
+
|
66 |
+
except Exception as e:
|
67 |
+
help_url = 'https://github.com/ultralytics/yolov5/issues/36'
|
68 |
+
s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
|
69 |
+
raise Exception(s) from e
|
70 |
+
|
71 |
+
|
72 |
+
def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
|
73 |
+
# YOLOv5 custom or local model
|
74 |
+
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
|
75 |
+
|
76 |
+
|
77 |
+
def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
78 |
+
# YOLOv5-nano model https://github.com/ultralytics/yolov5
|
79 |
+
return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
|
80 |
+
|
81 |
+
|
82 |
+
def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
83 |
+
# YOLOv5-small model https://github.com/ultralytics/yolov5
|
84 |
+
return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
|
85 |
+
|
86 |
+
|
87 |
+
def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
88 |
+
# YOLOv5-medium model https://github.com/ultralytics/yolov5
|
89 |
+
return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
|
90 |
+
|
91 |
+
|
92 |
+
def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
93 |
+
# YOLOv5-large model https://github.com/ultralytics/yolov5
|
94 |
+
return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
|
95 |
+
|
96 |
+
|
97 |
+
def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
98 |
+
# YOLOv5-xlarge model https://github.com/ultralytics/yolov5
|
99 |
+
return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
|
100 |
+
|
101 |
+
|
102 |
+
def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
103 |
+
# YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
|
104 |
+
return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
|
105 |
+
|
106 |
+
|
107 |
+
def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
108 |
+
# YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
|
109 |
+
return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
|
110 |
+
|
111 |
+
|
112 |
+
def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
113 |
+
# YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
|
114 |
+
return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
|
115 |
+
|
116 |
+
|
117 |
+
def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
118 |
+
# YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
|
119 |
+
return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
|
120 |
+
|
121 |
+
|
122 |
+
def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
123 |
+
# YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
|
124 |
+
return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
|
125 |
+
|
126 |
+
|
127 |
+
if __name__ == '__main__':
|
128 |
+
import argparse
|
129 |
+
from pathlib import Path
|
130 |
+
|
131 |
+
import numpy as np
|
132 |
+
from PIL import Image
|
133 |
+
|
134 |
+
from utils.general import cv2, print_args
|
135 |
+
|
136 |
+
# Argparser
|
137 |
+
parser = argparse.ArgumentParser()
|
138 |
+
parser.add_argument('--model', type=str, default='yolov5s', help='model name')
|
139 |
+
opt = parser.parse_args()
|
140 |
+
print_args(vars(opt))
|
141 |
+
|
142 |
+
# Model
|
143 |
+
model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
|
144 |
+
# model = custom(path='path/to/model.pt') # custom
|
145 |
+
|
146 |
+
# Images
|
147 |
+
imgs = [
|
148 |
+
'data/images/zidane.jpg', # filename
|
149 |
+
Path('data/images/zidane.jpg'), # Path
|
150 |
+
'https://ultralytics.com/images/zidane.jpg', # URI
|
151 |
+
cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
|
152 |
+
Image.open('data/images/bus.jpg'), # PIL
|
153 |
+
np.zeros((320, 640, 3))] # numpy
|
154 |
+
|
155 |
+
# Inference
|
156 |
+
results = model(imgs, size=320) # batched inference
|
157 |
+
|
158 |
+
# Results
|
159 |
+
results.print()
|
160 |
+
results.save()
|
labels.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
alternaria
|
2 |
+
demaged
|
3 |
+
healthy
|
4 |
+
insect
|
5 |
+
mlb
|
6 |
+
mossaic
|
7 |
+
multiple
|
8 |
+
necrosis
|
9 |
+
noleaf
|
10 |
+
powdery-mildew
|
11 |
+
scab
|
logo.jpg
ADDED
mobilenetv2-apple-10-class-pytorch.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b2f870dfd9a345418d055f3e5380b61c046d0dbbd13a5c40f2d0e9efb35ecbac
|
3 |
+
size 18510789
|
packages.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
libgl1
|
requirements.txt
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
opencv_python
|
2 |
+
torchvision
|
3 |
+
torch
|
4 |
+
numpy
|
5 |
+
thop
|
6 |
+
streamlit # for app
|
7 |
+
pycocotools
|
8 |
+
tqdm
|
9 |
+
addict
|
10 |
+
Pillow
|
11 |
+
PyYAML
|
12 |
+
tools
|
13 |
+
seaborn
|
14 |
+
pandas
|
15 |
+
tensorflow
|
sample.jpg
ADDED
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
|
temp_image.jpg
ADDED
test.jpg
ADDED
test1.jpg
ADDED
test2.jpg
ADDED
test3.jpg
ADDED
train.py
ADDED
@@ -0,0 +1,633 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, is_url
|
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 |
+
smart_resume, 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 |
+
opt.hyp = hyp.copy() # for saving hyps to checkpoints
|
81 |
+
|
82 |
+
# Save run settings
|
83 |
+
if not evolve:
|
84 |
+
with open(save_dir / 'hyp.yaml', 'w') as f:
|
85 |
+
yaml.safe_dump(hyp, f, sort_keys=False)
|
86 |
+
with open(save_dir / 'opt.yaml', 'w') as f:
|
87 |
+
yaml.safe_dump(vars(opt), f, sort_keys=False)
|
88 |
+
|
89 |
+
# Loggers
|
90 |
+
data_dict = None
|
91 |
+
if RANK in {-1, 0}:
|
92 |
+
loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
|
93 |
+
if loggers.clearml:
|
94 |
+
data_dict = loggers.clearml.data_dict # None if no ClearML dataset or filled in by ClearML
|
95 |
+
if loggers.wandb:
|
96 |
+
data_dict = loggers.wandb.data_dict
|
97 |
+
if resume:
|
98 |
+
weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
|
99 |
+
|
100 |
+
# Register actions
|
101 |
+
for k in methods(loggers):
|
102 |
+
callbacks.register_action(k, callback=getattr(loggers, k))
|
103 |
+
|
104 |
+
# Config
|
105 |
+
plots = not evolve and not opt.noplots # create plots
|
106 |
+
cuda = device.type != 'cpu'
|
107 |
+
init_seeds(opt.seed + 1 + RANK, deterministic=True)
|
108 |
+
with torch_distributed_zero_first(LOCAL_RANK):
|
109 |
+
data_dict = data_dict or check_dataset(data) # check if None
|
110 |
+
train_path, val_path = data_dict['train'], data_dict['val']
|
111 |
+
nc = 1 if single_cls else int(data_dict['nc']) # number of classes
|
112 |
+
names = ['item'] if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
|
113 |
+
assert len(names) == nc, f'{len(names)} names found for nc={nc} dataset in {data}' # check
|
114 |
+
is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset
|
115 |
+
|
116 |
+
# Model
|
117 |
+
check_suffix(weights, '.pt') # check weights
|
118 |
+
pretrained = weights.endswith('.pt')
|
119 |
+
if pretrained:
|
120 |
+
with torch_distributed_zero_first(LOCAL_RANK):
|
121 |
+
weights = attempt_download(weights) # download if not found locally
|
122 |
+
ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak
|
123 |
+
model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
|
124 |
+
exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
|
125 |
+
csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
|
126 |
+
csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
|
127 |
+
model.load_state_dict(csd, strict=False) # load
|
128 |
+
LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
|
129 |
+
else:
|
130 |
+
model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
|
131 |
+
amp = check_amp(model) # check AMP
|
132 |
+
|
133 |
+
# Freeze
|
134 |
+
freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
|
135 |
+
for k, v in model.named_parameters():
|
136 |
+
v.requires_grad = True # train all layers
|
137 |
+
# v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results)
|
138 |
+
if any(x in k for x in freeze):
|
139 |
+
LOGGER.info(f'freezing {k}')
|
140 |
+
v.requires_grad = False
|
141 |
+
|
142 |
+
# Image size
|
143 |
+
gs = max(int(model.stride.max()), 32) # grid size (max stride)
|
144 |
+
imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
|
145 |
+
|
146 |
+
# Batch size
|
147 |
+
if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
|
148 |
+
batch_size = check_train_batch_size(model, imgsz, amp)
|
149 |
+
loggers.on_params_update({"batch_size": batch_size})
|
150 |
+
|
151 |
+
# Optimizer
|
152 |
+
nbs = 64 # nominal batch size
|
153 |
+
accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
|
154 |
+
hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
|
155 |
+
optimizer = smart_optimizer(model, opt.optimizer, hyp['lr0'], hyp['momentum'], hyp['weight_decay'])
|
156 |
+
|
157 |
+
# Scheduler
|
158 |
+
if opt.cos_lr:
|
159 |
+
lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
|
160 |
+
else:
|
161 |
+
lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
|
162 |
+
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
|
163 |
+
|
164 |
+
# EMA
|
165 |
+
ema = ModelEMA(model) if RANK in {-1, 0} else None
|
166 |
+
|
167 |
+
# Resume
|
168 |
+
best_fitness, start_epoch = 0.0, 0
|
169 |
+
if pretrained:
|
170 |
+
best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
|
171 |
+
del ckpt, csd
|
172 |
+
|
173 |
+
# DP mode
|
174 |
+
if cuda and RANK == -1 and torch.cuda.device_count() > 1:
|
175 |
+
LOGGER.warning('WARNING: DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n'
|
176 |
+
'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.')
|
177 |
+
model = torch.nn.DataParallel(model)
|
178 |
+
|
179 |
+
# SyncBatchNorm
|
180 |
+
if opt.sync_bn and cuda and RANK != -1:
|
181 |
+
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
|
182 |
+
LOGGER.info('Using SyncBatchNorm()')
|
183 |
+
|
184 |
+
# Trainloader
|
185 |
+
train_loader, dataset = create_dataloader(train_path,
|
186 |
+
imgsz,
|
187 |
+
batch_size // WORLD_SIZE,
|
188 |
+
gs,
|
189 |
+
single_cls,
|
190 |
+
hyp=hyp,
|
191 |
+
augment=True,
|
192 |
+
cache=None if opt.cache == 'val' else opt.cache,
|
193 |
+
rect=opt.rect,
|
194 |
+
rank=LOCAL_RANK,
|
195 |
+
workers=workers,
|
196 |
+
image_weights=opt.image_weights,
|
197 |
+
quad=opt.quad,
|
198 |
+
prefix=colorstr('train: '),
|
199 |
+
shuffle=True)
|
200 |
+
labels = np.concatenate(dataset.labels, 0)
|
201 |
+
mlc = int(labels[:, 0].max()) # max label class
|
202 |
+
assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
|
203 |
+
|
204 |
+
# Process 0
|
205 |
+
if RANK in {-1, 0}:
|
206 |
+
val_loader = create_dataloader(val_path,
|
207 |
+
imgsz,
|
208 |
+
batch_size // WORLD_SIZE * 2,
|
209 |
+
gs,
|
210 |
+
single_cls,
|
211 |
+
hyp=hyp,
|
212 |
+
cache=None if noval else opt.cache,
|
213 |
+
rect=True,
|
214 |
+
rank=-1,
|
215 |
+
workers=workers * 2,
|
216 |
+
pad=0.5,
|
217 |
+
prefix=colorstr('val: '))[0]
|
218 |
+
|
219 |
+
if not resume:
|
220 |
+
if plots:
|
221 |
+
plot_labels(labels, names, save_dir)
|
222 |
+
|
223 |
+
# Anchors
|
224 |
+
if not opt.noautoanchor:
|
225 |
+
check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
|
226 |
+
model.half().float() # pre-reduce anchor precision
|
227 |
+
|
228 |
+
callbacks.run('on_pretrain_routine_end')
|
229 |
+
|
230 |
+
# DDP mode
|
231 |
+
if cuda and RANK != -1:
|
232 |
+
model = smart_DDP(model)
|
233 |
+
|
234 |
+
# Model attributes
|
235 |
+
nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
|
236 |
+
hyp['box'] *= 3 / nl # scale to layers
|
237 |
+
hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers
|
238 |
+
hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
|
239 |
+
hyp['label_smoothing'] = opt.label_smoothing
|
240 |
+
model.nc = nc # attach number of classes to model
|
241 |
+
model.hyp = hyp # attach hyperparameters to model
|
242 |
+
model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
|
243 |
+
model.names = names
|
244 |
+
|
245 |
+
# Start training
|
246 |
+
t0 = time.time()
|
247 |
+
nb = len(train_loader) # number of batches
|
248 |
+
nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
|
249 |
+
# nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
|
250 |
+
last_opt_step = -1
|
251 |
+
maps = np.zeros(nc) # mAP per class
|
252 |
+
results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
|
253 |
+
scheduler.last_epoch = start_epoch - 1 # do not move
|
254 |
+
scaler = torch.cuda.amp.GradScaler(enabled=amp)
|
255 |
+
stopper, stop = EarlyStopping(patience=opt.patience), False
|
256 |
+
compute_loss = ComputeLoss(model) # init loss class
|
257 |
+
callbacks.run('on_train_start')
|
258 |
+
LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
|
259 |
+
f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
|
260 |
+
f"Logging results to {colorstr('bold', save_dir)}\n"
|
261 |
+
f'Starting training for {epochs} epochs...')
|
262 |
+
for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
|
263 |
+
callbacks.run('on_train_epoch_start')
|
264 |
+
model.train()
|
265 |
+
|
266 |
+
# Update image weights (optional, single-GPU only)
|
267 |
+
if opt.image_weights:
|
268 |
+
cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
|
269 |
+
iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
|
270 |
+
dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
|
271 |
+
|
272 |
+
# Update mosaic border (optional)
|
273 |
+
# b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
|
274 |
+
# dataset.mosaic_border = [b - imgsz, -b] # height, width borders
|
275 |
+
|
276 |
+
mloss = torch.zeros(3, device=device) # mean losses
|
277 |
+
if RANK != -1:
|
278 |
+
train_loader.sampler.set_epoch(epoch)
|
279 |
+
pbar = enumerate(train_loader)
|
280 |
+
LOGGER.info(('\n' + '%10s' * 7) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'labels', 'img_size'))
|
281 |
+
if RANK in {-1, 0}:
|
282 |
+
pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
|
283 |
+
optimizer.zero_grad()
|
284 |
+
for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
|
285 |
+
callbacks.run('on_train_batch_start')
|
286 |
+
ni = i + nb * epoch # number integrated batches (since train start)
|
287 |
+
imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
|
288 |
+
|
289 |
+
# Warmup
|
290 |
+
if ni <= nw:
|
291 |
+
xi = [0, nw] # x interp
|
292 |
+
# compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
|
293 |
+
accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
|
294 |
+
for j, x in enumerate(optimizer.param_groups):
|
295 |
+
# bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
|
296 |
+
x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 0 else 0.0, x['initial_lr'] * lf(epoch)])
|
297 |
+
if 'momentum' in x:
|
298 |
+
x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
|
299 |
+
|
300 |
+
# Multi-scale
|
301 |
+
if opt.multi_scale:
|
302 |
+
sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
|
303 |
+
sf = sz / max(imgs.shape[2:]) # scale factor
|
304 |
+
if sf != 1:
|
305 |
+
ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
|
306 |
+
imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
|
307 |
+
|
308 |
+
# Forward
|
309 |
+
with torch.cuda.amp.autocast(amp):
|
310 |
+
pred = model(imgs) # forward
|
311 |
+
loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
|
312 |
+
if RANK != -1:
|
313 |
+
loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
|
314 |
+
if opt.quad:
|
315 |
+
loss *= 4.
|
316 |
+
|
317 |
+
# Backward
|
318 |
+
scaler.scale(loss).backward()
|
319 |
+
|
320 |
+
# Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
|
321 |
+
if ni - last_opt_step >= accumulate:
|
322 |
+
scaler.unscale_(optimizer) # unscale gradients
|
323 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
|
324 |
+
scaler.step(optimizer) # optimizer.step
|
325 |
+
scaler.update()
|
326 |
+
optimizer.zero_grad()
|
327 |
+
if ema:
|
328 |
+
ema.update(model)
|
329 |
+
last_opt_step = ni
|
330 |
+
|
331 |
+
# Log
|
332 |
+
if RANK in {-1, 0}:
|
333 |
+
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
|
334 |
+
mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
|
335 |
+
pbar.set_description(('%10s' * 2 + '%10.4g' * 5) %
|
336 |
+
(f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
|
337 |
+
callbacks.run('on_train_batch_end', ni, model, imgs, targets, paths, plots)
|
338 |
+
if callbacks.stop_training:
|
339 |
+
return
|
340 |
+
# end batch ------------------------------------------------------------------------------------------------
|
341 |
+
|
342 |
+
# Scheduler
|
343 |
+
lr = [x['lr'] for x in optimizer.param_groups] # for loggers
|
344 |
+
scheduler.step()
|
345 |
+
|
346 |
+
if RANK in {-1, 0}:
|
347 |
+
# mAP
|
348 |
+
callbacks.run('on_train_epoch_end', epoch=epoch)
|
349 |
+
ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
|
350 |
+
final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
|
351 |
+
if not noval or final_epoch: # Calculate mAP
|
352 |
+
results, maps, _ = val.run(data_dict,
|
353 |
+
batch_size=batch_size // WORLD_SIZE * 2,
|
354 |
+
imgsz=imgsz,
|
355 |
+
half=amp,
|
356 |
+
model=ema.ema,
|
357 |
+
single_cls=single_cls,
|
358 |
+
dataloader=val_loader,
|
359 |
+
save_dir=save_dir,
|
360 |
+
plots=False,
|
361 |
+
callbacks=callbacks,
|
362 |
+
compute_loss=compute_loss)
|
363 |
+
|
364 |
+
# Update best mAP
|
365 |
+
fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
|
366 |
+
stop = stopper(epoch=epoch, fitness=fi) # early stop check
|
367 |
+
if fi > best_fitness:
|
368 |
+
best_fitness = fi
|
369 |
+
log_vals = list(mloss) + list(results) + lr
|
370 |
+
callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
|
371 |
+
|
372 |
+
# Save model
|
373 |
+
if (not nosave) or (final_epoch and not evolve): # if save
|
374 |
+
ckpt = {
|
375 |
+
'epoch': epoch,
|
376 |
+
'best_fitness': best_fitness,
|
377 |
+
'model': deepcopy(de_parallel(model)).half(),
|
378 |
+
'ema': deepcopy(ema.ema).half(),
|
379 |
+
'updates': ema.updates,
|
380 |
+
'optimizer': optimizer.state_dict(),
|
381 |
+
'wandb_id': loggers.wandb.wandb_run.id if loggers.wandb else None,
|
382 |
+
'opt': vars(opt),
|
383 |
+
'date': datetime.now().isoformat()}
|
384 |
+
|
385 |
+
# Save last, best and delete
|
386 |
+
torch.save(ckpt, last)
|
387 |
+
if best_fitness == fi:
|
388 |
+
torch.save(ckpt, best)
|
389 |
+
if opt.save_period > 0 and epoch % opt.save_period == 0:
|
390 |
+
torch.save(ckpt, w / f'epoch{epoch}.pt')
|
391 |
+
del ckpt
|
392 |
+
callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
|
393 |
+
|
394 |
+
# EarlyStopping
|
395 |
+
if RANK != -1: # if DDP training
|
396 |
+
broadcast_list = [stop if RANK == 0 else None]
|
397 |
+
dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
|
398 |
+
if RANK != 0:
|
399 |
+
stop = broadcast_list[0]
|
400 |
+
if stop:
|
401 |
+
break # must break all DDP ranks
|
402 |
+
|
403 |
+
# end epoch ----------------------------------------------------------------------------------------------------
|
404 |
+
# end training -----------------------------------------------------------------------------------------------------
|
405 |
+
if RANK in {-1, 0}:
|
406 |
+
LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
|
407 |
+
for f in last, best:
|
408 |
+
if f.exists():
|
409 |
+
strip_optimizer(f) # strip optimizers
|
410 |
+
if f is best:
|
411 |
+
LOGGER.info(f'\nValidating {f}...')
|
412 |
+
results, _, _ = val.run(
|
413 |
+
data_dict,
|
414 |
+
batch_size=batch_size // WORLD_SIZE * 2,
|
415 |
+
imgsz=imgsz,
|
416 |
+
model=attempt_load(f, device).half(),
|
417 |
+
iou_thres=0.65 if is_coco else 0.60, # best pycocotools results at 0.65
|
418 |
+
single_cls=single_cls,
|
419 |
+
dataloader=val_loader,
|
420 |
+
save_dir=save_dir,
|
421 |
+
save_json=is_coco,
|
422 |
+
verbose=True,
|
423 |
+
plots=plots,
|
424 |
+
callbacks=callbacks,
|
425 |
+
compute_loss=compute_loss) # val best model with plots
|
426 |
+
if is_coco:
|
427 |
+
callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
|
428 |
+
|
429 |
+
callbacks.run('on_train_end', last, best, plots, epoch, results)
|
430 |
+
|
431 |
+
torch.cuda.empty_cache()
|
432 |
+
return results
|
433 |
+
|
434 |
+
|
435 |
+
def parse_opt(known=False):
|
436 |
+
parser = argparse.ArgumentParser()
|
437 |
+
parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path')
|
438 |
+
parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
|
439 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
440 |
+
parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
|
441 |
+
parser.add_argument('--epochs', type=int, default=300)
|
442 |
+
parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
|
443 |
+
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
|
444 |
+
parser.add_argument('--rect', action='store_true', help='rectangular training')
|
445 |
+
parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
|
446 |
+
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
|
447 |
+
parser.add_argument('--noval', action='store_true', help='only validate final epoch')
|
448 |
+
parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
|
449 |
+
parser.add_argument('--noplots', action='store_true', help='save no plot files')
|
450 |
+
parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
|
451 |
+
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
|
452 |
+
parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
|
453 |
+
parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
|
454 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
455 |
+
parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
|
456 |
+
parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
|
457 |
+
parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
|
458 |
+
parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
|
459 |
+
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
|
460 |
+
parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name')
|
461 |
+
parser.add_argument('--name', default='exp', help='save to project/name')
|
462 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
463 |
+
parser.add_argument('--quad', action='store_true', help='quad dataloader')
|
464 |
+
parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
|
465 |
+
parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
|
466 |
+
parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
|
467 |
+
parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
|
468 |
+
parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
|
469 |
+
parser.add_argument('--seed', type=int, default=0, help='Global training seed')
|
470 |
+
parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
|
471 |
+
|
472 |
+
# Weights & Biases arguments
|
473 |
+
parser.add_argument('--entity', default=None, help='W&B: Entity')
|
474 |
+
parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option')
|
475 |
+
parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval')
|
476 |
+
parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use')
|
477 |
+
|
478 |
+
return parser.parse_known_args()[0] if known else parser.parse_args()
|
479 |
+
|
480 |
+
|
481 |
+
def main(opt, callbacks=Callbacks()):
|
482 |
+
# Checks
|
483 |
+
if RANK in {-1, 0}:
|
484 |
+
print_args(vars(opt))
|
485 |
+
check_git_status()
|
486 |
+
check_requirements(exclude=['thop'])
|
487 |
+
|
488 |
+
# Resume
|
489 |
+
if opt.resume and not (check_wandb_resume(opt) or opt.evolve): # resume from specified or most recent last.pt
|
490 |
+
last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
|
491 |
+
opt_yaml = last.parent.parent / 'opt.yaml' # train options yaml
|
492 |
+
opt_data = opt.data # original dataset
|
493 |
+
if opt_yaml.is_file():
|
494 |
+
with open(opt_yaml, errors='ignore') as f:
|
495 |
+
d = yaml.safe_load(f)
|
496 |
+
else:
|
497 |
+
d = torch.load(last, map_location='cpu')['opt']
|
498 |
+
opt = argparse.Namespace(**d) # replace
|
499 |
+
opt.cfg, opt.weights, opt.resume = '', str(last), True # reinstate
|
500 |
+
if is_url(opt_data):
|
501 |
+
opt.data = check_file(opt_data) # avoid HUB resume auth timeout
|
502 |
+
else:
|
503 |
+
opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \
|
504 |
+
check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks
|
505 |
+
assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
|
506 |
+
if opt.evolve:
|
507 |
+
if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve
|
508 |
+
opt.project = str(ROOT / 'runs/evolve')
|
509 |
+
opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
|
510 |
+
if opt.name == 'cfg':
|
511 |
+
opt.name = Path(opt.cfg).stem # use model.yaml as name
|
512 |
+
opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
|
513 |
+
|
514 |
+
# DDP mode
|
515 |
+
device = select_device(opt.device, batch_size=opt.batch_size)
|
516 |
+
if LOCAL_RANK != -1:
|
517 |
+
msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
|
518 |
+
assert not opt.image_weights, f'--image-weights {msg}'
|
519 |
+
assert not opt.evolve, f'--evolve {msg}'
|
520 |
+
assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size'
|
521 |
+
assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
|
522 |
+
assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
|
523 |
+
torch.cuda.set_device(LOCAL_RANK)
|
524 |
+
device = torch.device('cuda', LOCAL_RANK)
|
525 |
+
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
|
526 |
+
|
527 |
+
# Train
|
528 |
+
if not opt.evolve:
|
529 |
+
train(opt.hyp, opt, device, callbacks)
|
530 |
+
|
531 |
+
# Evolve hyperparameters (optional)
|
532 |
+
else:
|
533 |
+
# Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
|
534 |
+
meta = {
|
535 |
+
'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
|
536 |
+
'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
|
537 |
+
'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
|
538 |
+
'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
|
539 |
+
'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
|
540 |
+
'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
|
541 |
+
'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
|
542 |
+
'box': (1, 0.02, 0.2), # box loss gain
|
543 |
+
'cls': (1, 0.2, 4.0), # cls loss gain
|
544 |
+
'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
|
545 |
+
'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
|
546 |
+
'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
|
547 |
+
'iou_t': (0, 0.1, 0.7), # IoU training threshold
|
548 |
+
'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
|
549 |
+
'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
|
550 |
+
'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
|
551 |
+
'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
|
552 |
+
'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
|
553 |
+
'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
|
554 |
+
'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
|
555 |
+
'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
|
556 |
+
'scale': (1, 0.0, 0.9), # image scale (+/- gain)
|
557 |
+
'shear': (1, 0.0, 10.0), # image shear (+/- deg)
|
558 |
+
'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
|
559 |
+
'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
|
560 |
+
'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
|
561 |
+
'mosaic': (1, 0.0, 1.0), # image mixup (probability)
|
562 |
+
'mixup': (1, 0.0, 1.0), # image mixup (probability)
|
563 |
+
'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability)
|
564 |
+
|
565 |
+
with open(opt.hyp, errors='ignore') as f:
|
566 |
+
hyp = yaml.safe_load(f) # load hyps dict
|
567 |
+
if 'anchors' not in hyp: # anchors commented in hyp.yaml
|
568 |
+
hyp['anchors'] = 3
|
569 |
+
if opt.noautoanchor:
|
570 |
+
del hyp['anchors'], meta['anchors']
|
571 |
+
opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
|
572 |
+
# ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
|
573 |
+
evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv'
|
574 |
+
if opt.bucket:
|
575 |
+
os.system(f'gsutil cp gs://{opt.bucket}/evolve.csv {evolve_csv}') # download evolve.csv if exists
|
576 |
+
|
577 |
+
for _ in range(opt.evolve): # generations to evolve
|
578 |
+
if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
|
579 |
+
# Select parent(s)
|
580 |
+
parent = 'single' # parent selection method: 'single' or 'weighted'
|
581 |
+
x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
|
582 |
+
n = min(5, len(x)) # number of previous results to consider
|
583 |
+
x = x[np.argsort(-fitness(x))][:n] # top n mutations
|
584 |
+
w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0)
|
585 |
+
if parent == 'single' or len(x) == 1:
|
586 |
+
# x = x[random.randint(0, n - 1)] # random selection
|
587 |
+
x = x[random.choices(range(n), weights=w)[0]] # weighted selection
|
588 |
+
elif parent == 'weighted':
|
589 |
+
x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
|
590 |
+
|
591 |
+
# Mutate
|
592 |
+
mp, s = 0.8, 0.2 # mutation probability, sigma
|
593 |
+
npr = np.random
|
594 |
+
npr.seed(int(time.time()))
|
595 |
+
g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
|
596 |
+
ng = len(meta)
|
597 |
+
v = np.ones(ng)
|
598 |
+
while all(v == 1): # mutate until a change occurs (prevent duplicates)
|
599 |
+
v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
|
600 |
+
for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
|
601 |
+
hyp[k] = float(x[i + 7] * v[i]) # mutate
|
602 |
+
|
603 |
+
# Constrain to limits
|
604 |
+
for k, v in meta.items():
|
605 |
+
hyp[k] = max(hyp[k], v[1]) # lower limit
|
606 |
+
hyp[k] = min(hyp[k], v[2]) # upper limit
|
607 |
+
hyp[k] = round(hyp[k], 5) # significant digits
|
608 |
+
|
609 |
+
# Train mutation
|
610 |
+
results = train(hyp.copy(), opt, device, callbacks)
|
611 |
+
callbacks = Callbacks()
|
612 |
+
# Write mutation results
|
613 |
+
print_mutation(results, hyp.copy(), save_dir, opt.bucket)
|
614 |
+
|
615 |
+
# Plot results
|
616 |
+
plot_evolve(evolve_csv)
|
617 |
+
LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n'
|
618 |
+
f"Results saved to {colorstr('bold', save_dir)}\n"
|
619 |
+
f'Usage example: $ python train.py --hyp {evolve_yaml}')
|
620 |
+
|
621 |
+
|
622 |
+
def run(**kwargs):
|
623 |
+
# Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
|
624 |
+
opt = parse_opt(True)
|
625 |
+
for k, v in kwargs.items():
|
626 |
+
setattr(opt, k, v)
|
627 |
+
main(opt)
|
628 |
+
return opt
|
629 |
+
|
630 |
+
|
631 |
+
if __name__ == "__main__":
|
632 |
+
opt = parse_opt()
|
633 |
+
main(opt)
|
unnamed.jpg
ADDED
val.py
ADDED
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Validate a trained YOLOv5 model accuracy on a custom dataset
|
4 |
+
|
5 |
+
Usage:
|
6 |
+
$ python path/to/val.py --weights yolov5s.pt --data coco128.yaml --img 640
|
7 |
+
|
8 |
+
Usage - formats:
|
9 |
+
$ python path/to/val.py --weights yolov5s.pt # PyTorch
|
10 |
+
yolov5s.torchscript # TorchScript
|
11 |
+
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
12 |
+
yolov5s.xml # OpenVINO
|
13 |
+
yolov5s.engine # TensorRT
|
14 |
+
yolov5s.mlmodel # CoreML (macOS-only)
|
15 |
+
yolov5s_saved_model # TensorFlow SavedModel
|
16 |
+
yolov5s.pb # TensorFlow GraphDef
|
17 |
+
yolov5s.tflite # TensorFlow Lite
|
18 |
+
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
19 |
+
"""
|
20 |
+
|
21 |
+
import argparse
|
22 |
+
import json
|
23 |
+
import os
|
24 |
+
import sys
|
25 |
+
from pathlib import Path
|
26 |
+
|
27 |
+
import numpy as np
|
28 |
+
import torch
|
29 |
+
from tqdm import tqdm
|
30 |
+
|
31 |
+
FILE = Path(__file__).resolve()
|
32 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
33 |
+
if str(ROOT) not in sys.path:
|
34 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
35 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
36 |
+
|
37 |
+
from models.common import DetectMultiBackend
|
38 |
+
from utils.callbacks import Callbacks
|
39 |
+
from utils.dataloaders import create_dataloader
|
40 |
+
from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_yaml,
|
41 |
+
coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args,
|
42 |
+
scale_coords, xywh2xyxy, xyxy2xywh)
|
43 |
+
from utils.metrics import ConfusionMatrix, ap_per_class, box_iou
|
44 |
+
from utils.plots import output_to_target, plot_images, plot_val_study
|
45 |
+
from utils.torch_utils import select_device, time_sync
|
46 |
+
|
47 |
+
|
48 |
+
def save_one_txt(predn, save_conf, shape, file):
|
49 |
+
# Save one txt result
|
50 |
+
gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
|
51 |
+
for *xyxy, conf, cls in predn.tolist():
|
52 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
53 |
+
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
54 |
+
with open(file, 'a') as f:
|
55 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
56 |
+
|
57 |
+
|
58 |
+
def save_one_json(predn, jdict, path, class_map):
|
59 |
+
# Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
|
60 |
+
image_id = int(path.stem) if path.stem.isnumeric() else path.stem
|
61 |
+
box = xyxy2xywh(predn[:, :4]) # xywh
|
62 |
+
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
|
63 |
+
for p, b in zip(predn.tolist(), box.tolist()):
|
64 |
+
jdict.append({
|
65 |
+
'image_id': image_id,
|
66 |
+
'category_id': class_map[int(p[5])],
|
67 |
+
'bbox': [round(x, 3) for x in b],
|
68 |
+
'score': round(p[4], 5)})
|
69 |
+
|
70 |
+
|
71 |
+
def process_batch(detections, labels, iouv):
|
72 |
+
"""
|
73 |
+
Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format.
|
74 |
+
Arguments:
|
75 |
+
detections (Array[N, 6]), x1, y1, x2, y2, conf, class
|
76 |
+
labels (Array[M, 5]), class, x1, y1, x2, y2
|
77 |
+
Returns:
|
78 |
+
correct (Array[N, 10]), for 10 IoU levels
|
79 |
+
"""
|
80 |
+
correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool)
|
81 |
+
iou = box_iou(labels[:, 1:], detections[:, :4])
|
82 |
+
correct_class = labels[:, 0:1] == detections[:, 5]
|
83 |
+
for i in range(len(iouv)):
|
84 |
+
x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match
|
85 |
+
if x[0].shape[0]:
|
86 |
+
matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou]
|
87 |
+
if x[0].shape[0] > 1:
|
88 |
+
matches = matches[matches[:, 2].argsort()[::-1]]
|
89 |
+
matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
|
90 |
+
# matches = matches[matches[:, 2].argsort()[::-1]]
|
91 |
+
matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
|
92 |
+
correct[matches[:, 1].astype(int), i] = True
|
93 |
+
return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
|
94 |
+
|
95 |
+
|
96 |
+
@torch.no_grad()
|
97 |
+
def run(
|
98 |
+
data,
|
99 |
+
weights=None, # model.pt path(s)
|
100 |
+
batch_size=32, # batch size
|
101 |
+
imgsz=640, # inference size (pixels)
|
102 |
+
conf_thres=0.001, # confidence threshold
|
103 |
+
iou_thres=0.6, # NMS IoU threshold
|
104 |
+
task='val', # train, val, test, speed or study
|
105 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
106 |
+
workers=8, # max dataloader workers (per RANK in DDP mode)
|
107 |
+
single_cls=False, # treat as single-class dataset
|
108 |
+
augment=False, # augmented inference
|
109 |
+
verbose=False, # verbose output
|
110 |
+
save_txt=False, # save results to *.txt
|
111 |
+
save_hybrid=False, # save label+prediction hybrid results to *.txt
|
112 |
+
save_conf=False, # save confidences in --save-txt labels
|
113 |
+
save_json=False, # save a COCO-JSON results file
|
114 |
+
project=ROOT / 'runs/val', # save to project/name
|
115 |
+
name='exp', # save to project/name
|
116 |
+
exist_ok=False, # existing project/name ok, do not increment
|
117 |
+
half=True, # use FP16 half-precision inference
|
118 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
119 |
+
model=None,
|
120 |
+
dataloader=None,
|
121 |
+
save_dir=Path(''),
|
122 |
+
plots=True,
|
123 |
+
callbacks=Callbacks(),
|
124 |
+
compute_loss=None,
|
125 |
+
):
|
126 |
+
# Initialize/load model and set device
|
127 |
+
training = model is not None
|
128 |
+
if training: # called by train.py
|
129 |
+
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
|
130 |
+
half &= device.type != 'cpu' # half precision only supported on CUDA
|
131 |
+
model.half() if half else model.float()
|
132 |
+
else: # called directly
|
133 |
+
device = select_device(device, batch_size=batch_size)
|
134 |
+
|
135 |
+
# Directories
|
136 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
137 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
138 |
+
|
139 |
+
# Load model
|
140 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
141 |
+
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
|
142 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
143 |
+
half = model.fp16 # FP16 supported on limited backends with CUDA
|
144 |
+
if engine:
|
145 |
+
batch_size = model.batch_size
|
146 |
+
else:
|
147 |
+
device = model.device
|
148 |
+
if not (pt or jit):
|
149 |
+
batch_size = 1 # export.py models default to batch-size 1
|
150 |
+
LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
|
151 |
+
|
152 |
+
# Data
|
153 |
+
data = check_dataset(data) # check
|
154 |
+
|
155 |
+
# Configure
|
156 |
+
model.eval()
|
157 |
+
cuda = device.type != 'cpu'
|
158 |
+
is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset
|
159 |
+
nc = 1 if single_cls else int(data['nc']) # number of classes
|
160 |
+
iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95
|
161 |
+
niou = iouv.numel()
|
162 |
+
|
163 |
+
# Dataloader
|
164 |
+
if not training:
|
165 |
+
if pt and not single_cls: # check --weights are trained on --data
|
166 |
+
ncm = model.model.nc
|
167 |
+
assert ncm == nc, f'{weights} ({ncm} classes) trained on different --data than what you passed ({nc} ' \
|
168 |
+
f'classes). Pass correct combination of --weights and --data that are trained together.'
|
169 |
+
model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup
|
170 |
+
pad = 0.0 if task in ('speed', 'benchmark') else 0.5
|
171 |
+
rect = False if task == 'benchmark' else pt # square inference for benchmarks
|
172 |
+
task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
|
173 |
+
dataloader = create_dataloader(data[task],
|
174 |
+
imgsz,
|
175 |
+
batch_size,
|
176 |
+
stride,
|
177 |
+
single_cls,
|
178 |
+
pad=pad,
|
179 |
+
rect=rect,
|
180 |
+
workers=workers,
|
181 |
+
prefix=colorstr(f'{task}: '))[0]
|
182 |
+
|
183 |
+
seen = 0
|
184 |
+
confusion_matrix = ConfusionMatrix(nc=nc)
|
185 |
+
names = dict(enumerate(model.names if hasattr(model, 'names') else model.module.names))
|
186 |
+
class_map = coco80_to_coco91_class() if is_coco else list(range(1000))
|
187 |
+
s = ('%20s' + '%11s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
|
188 |
+
dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
|
189 |
+
loss = torch.zeros(3, device=device)
|
190 |
+
jdict, stats, ap, ap_class = [], [], [], []
|
191 |
+
callbacks.run('on_val_start')
|
192 |
+
pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
|
193 |
+
for batch_i, (im, targets, paths, shapes) in enumerate(pbar):
|
194 |
+
callbacks.run('on_val_batch_start')
|
195 |
+
t1 = time_sync()
|
196 |
+
if cuda:
|
197 |
+
im = im.to(device, non_blocking=True)
|
198 |
+
targets = targets.to(device)
|
199 |
+
im = im.half() if half else im.float() # uint8 to fp16/32
|
200 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
201 |
+
nb, _, height, width = im.shape # batch size, channels, height, width
|
202 |
+
t2 = time_sync()
|
203 |
+
dt[0] += t2 - t1
|
204 |
+
|
205 |
+
# Inference
|
206 |
+
out, train_out = model(im) if training else model(im, augment=augment, val=True) # inference, loss outputs
|
207 |
+
dt[1] += time_sync() - t2
|
208 |
+
|
209 |
+
# Loss
|
210 |
+
if compute_loss:
|
211 |
+
loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls
|
212 |
+
|
213 |
+
# NMS
|
214 |
+
targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels
|
215 |
+
lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
|
216 |
+
t3 = time_sync()
|
217 |
+
out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls)
|
218 |
+
dt[2] += time_sync() - t3
|
219 |
+
|
220 |
+
# Metrics
|
221 |
+
for si, pred in enumerate(out):
|
222 |
+
labels = targets[targets[:, 0] == si, 1:]
|
223 |
+
nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions
|
224 |
+
path, shape = Path(paths[si]), shapes[si][0]
|
225 |
+
correct = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init
|
226 |
+
seen += 1
|
227 |
+
|
228 |
+
if npr == 0:
|
229 |
+
if nl:
|
230 |
+
stats.append((correct, *torch.zeros((2, 0), device=device), labels[:, 0]))
|
231 |
+
if plots:
|
232 |
+
confusion_matrix.process_batch(detections=None, labels=labels[:, 0])
|
233 |
+
continue
|
234 |
+
|
235 |
+
# Predictions
|
236 |
+
if single_cls:
|
237 |
+
pred[:, 5] = 0
|
238 |
+
predn = pred.clone()
|
239 |
+
scale_coords(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred
|
240 |
+
|
241 |
+
# Evaluate
|
242 |
+
if nl:
|
243 |
+
tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
|
244 |
+
scale_coords(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels
|
245 |
+
labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
|
246 |
+
correct = process_batch(predn, labelsn, iouv)
|
247 |
+
if plots:
|
248 |
+
confusion_matrix.process_batch(predn, labelsn)
|
249 |
+
stats.append((correct, pred[:, 4], pred[:, 5], labels[:, 0])) # (correct, conf, pcls, tcls)
|
250 |
+
|
251 |
+
# Save/log
|
252 |
+
if save_txt:
|
253 |
+
save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')
|
254 |
+
if save_json:
|
255 |
+
save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary
|
256 |
+
callbacks.run('on_val_image_end', pred, predn, path, names, im[si])
|
257 |
+
|
258 |
+
# Plot images
|
259 |
+
if plots and batch_i < 3:
|
260 |
+
plot_images(im, targets, paths, save_dir / f'val_batch{batch_i}_labels.jpg', names) # labels
|
261 |
+
plot_images(im, output_to_target(out), paths, save_dir / f'val_batch{batch_i}_pred.jpg', names) # pred
|
262 |
+
|
263 |
+
callbacks.run('on_val_batch_end')
|
264 |
+
|
265 |
+
# Compute metrics
|
266 |
+
stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpy
|
267 |
+
if len(stats) and stats[0].any():
|
268 |
+
tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
|
269 |
+
ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
|
270 |
+
mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
|
271 |
+
nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class
|
272 |
+
|
273 |
+
# Print results
|
274 |
+
pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format
|
275 |
+
LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
|
276 |
+
if nt.sum() == 0:
|
277 |
+
LOGGER.warning(f'WARNING: no labels found in {task} set, can not compute metrics without labels ⚠️')
|
278 |
+
|
279 |
+
# Print results per class
|
280 |
+
if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
|
281 |
+
for i, c in enumerate(ap_class):
|
282 |
+
LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
|
283 |
+
|
284 |
+
# Print speeds
|
285 |
+
t = tuple(x / seen * 1E3 for x in dt) # speeds per image
|
286 |
+
if not training:
|
287 |
+
shape = (batch_size, 3, imgsz, imgsz)
|
288 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t)
|
289 |
+
|
290 |
+
# Plots
|
291 |
+
if plots:
|
292 |
+
confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
|
293 |
+
callbacks.run('on_val_end')
|
294 |
+
|
295 |
+
# Save JSON
|
296 |
+
if save_json and len(jdict):
|
297 |
+
w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
|
298 |
+
anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json
|
299 |
+
pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
|
300 |
+
LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...')
|
301 |
+
with open(pred_json, 'w') as f:
|
302 |
+
json.dump(jdict, f)
|
303 |
+
|
304 |
+
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
|
305 |
+
check_requirements(['pycocotools'])
|
306 |
+
from pycocotools.coco import COCO
|
307 |
+
from pycocotools.cocoeval import COCOeval
|
308 |
+
|
309 |
+
anno = COCO(anno_json) # init annotations api
|
310 |
+
pred = anno.loadRes(pred_json) # init predictions api
|
311 |
+
eval = COCOeval(anno, pred, 'bbox')
|
312 |
+
if is_coco:
|
313 |
+
eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluate
|
314 |
+
eval.evaluate()
|
315 |
+
eval.accumulate()
|
316 |
+
eval.summarize()
|
317 |
+
map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
|
318 |
+
except Exception as e:
|
319 |
+
LOGGER.info(f'pycocotools unable to run: {e}')
|
320 |
+
|
321 |
+
# Return results
|
322 |
+
model.float() # for training
|
323 |
+
if not training:
|
324 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
325 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
326 |
+
maps = np.zeros(nc) + map
|
327 |
+
for i, c in enumerate(ap_class):
|
328 |
+
maps[c] = ap[i]
|
329 |
+
return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
|
330 |
+
|
331 |
+
|
332 |
+
def parse_opt():
|
333 |
+
parser = argparse.ArgumentParser()
|
334 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
335 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
|
336 |
+
parser.add_argument('--batch-size', type=int, default=32, help='batch size')
|
337 |
+
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
|
338 |
+
parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold')
|
339 |
+
parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold')
|
340 |
+
parser.add_argument('--task', default='val', help='train, val, test, speed or study')
|
341 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
342 |
+
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
|
343 |
+
parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
|
344 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
345 |
+
parser.add_argument('--verbose', action='store_true', help='report mAP by class')
|
346 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
347 |
+
parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
|
348 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
349 |
+
parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file')
|
350 |
+
parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name')
|
351 |
+
parser.add_argument('--name', default='exp', help='save to project/name')
|
352 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
353 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
354 |
+
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
355 |
+
opt = parser.parse_args()
|
356 |
+
opt.data = check_yaml(opt.data) # check YAML
|
357 |
+
opt.save_json |= opt.data.endswith('coco.yaml')
|
358 |
+
opt.save_txt |= opt.save_hybrid
|
359 |
+
print_args(vars(opt))
|
360 |
+
return opt
|
361 |
+
|
362 |
+
|
363 |
+
def main(opt):
|
364 |
+
check_requirements(requirements=ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
|
365 |
+
|
366 |
+
if opt.task in ('train', 'val', 'test'): # run normally
|
367 |
+
if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466
|
368 |
+
LOGGER.info(f'WARNING: confidence threshold {opt.conf_thres} > 0.001 produces invalid results ⚠️')
|
369 |
+
run(**vars(opt))
|
370 |
+
|
371 |
+
else:
|
372 |
+
weights = opt.weights if isinstance(opt.weights, list) else [opt.weights]
|
373 |
+
opt.half = True # FP16 for fastest results
|
374 |
+
if opt.task == 'speed': # speed benchmarks
|
375 |
+
# python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt...
|
376 |
+
opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False
|
377 |
+
for opt.weights in weights:
|
378 |
+
run(**vars(opt), plots=False)
|
379 |
+
|
380 |
+
elif opt.task == 'study': # speed vs mAP benchmarks
|
381 |
+
# python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt...
|
382 |
+
for opt.weights in weights:
|
383 |
+
f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt' # filename to save to
|
384 |
+
x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis
|
385 |
+
for opt.imgsz in x: # img-size
|
386 |
+
LOGGER.info(f'\nRunning {f} --imgsz {opt.imgsz}...')
|
387 |
+
r, _, t = run(**vars(opt), plots=False)
|
388 |
+
y.append(r + t) # results and times
|
389 |
+
np.savetxt(f, y, fmt='%10.4g') # save
|
390 |
+
os.system('zip -r study.zip study_*.txt')
|
391 |
+
plot_val_study(x=x) # plot
|
392 |
+
|
393 |
+
|
394 |
+
if __name__ == "__main__":
|
395 |
+
opt = parse_opt()
|
396 |
+
main(opt)
|