Showing
60 changed files
with
8610 additions
and
0 deletions
YOLOv5/.dockerignore
0 → 100644
1 | +# Repo-specific DockerIgnore ------------------------------------------------------------------------------------------- | ||
2 | +#.git | ||
3 | +.cache | ||
4 | +.idea | ||
5 | +runs | ||
6 | +output | ||
7 | +coco | ||
8 | +storage.googleapis.com | ||
9 | + | ||
10 | +data/samples/* | ||
11 | +**/results*.txt | ||
12 | +*.jpg | ||
13 | + | ||
14 | +# Neural Network weights ----------------------------------------------------------------------------------------------- | ||
15 | +**/*.weights | ||
16 | +**/*.pt | ||
17 | +**/*.pth | ||
18 | +**/*.onnx | ||
19 | +**/*.mlmodel | ||
20 | +**/*.torchscript | ||
21 | + | ||
22 | + | ||
23 | +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- | ||
24 | +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- | ||
25 | + | ||
26 | + | ||
27 | +# GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- | ||
28 | +# Byte-compiled / optimized / DLL files | ||
29 | +__pycache__/ | ||
30 | +*.py[cod] | ||
31 | +*$py.class | ||
32 | + | ||
33 | +# C extensions | ||
34 | +*.so | ||
35 | + | ||
36 | +# Distribution / packaging | ||
37 | +.Python | ||
38 | +env/ | ||
39 | +build/ | ||
40 | +develop-eggs/ | ||
41 | +dist/ | ||
42 | +downloads/ | ||
43 | +eggs/ | ||
44 | +.eggs/ | ||
45 | +lib/ | ||
46 | +lib64/ | ||
47 | +parts/ | ||
48 | +sdist/ | ||
49 | +var/ | ||
50 | +wheels/ | ||
51 | +*.egg-info/ | ||
52 | +wandb/ | ||
53 | +.installed.cfg | ||
54 | +*.egg | ||
55 | + | ||
56 | +# PyInstaller | ||
57 | +# Usually these files are written by a python script from a template | ||
58 | +# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
59 | +*.manifest | ||
60 | +*.spec | ||
61 | + | ||
62 | +# Installer logs | ||
63 | +pip-log.txt | ||
64 | +pip-delete-this-directory.txt | ||
65 | + | ||
66 | +# Unit test / coverage reports | ||
67 | +htmlcov/ | ||
68 | +.tox/ | ||
69 | +.coverage | ||
70 | +.coverage.* | ||
71 | +.cache | ||
72 | +nosetests.xml | ||
73 | +coverage.xml | ||
74 | +*.cover | ||
75 | +.hypothesis/ | ||
76 | + | ||
77 | +# Translations | ||
78 | +*.mo | ||
79 | +*.pot | ||
80 | + | ||
81 | +# Django stuff: | ||
82 | +*.log | ||
83 | +local_settings.py | ||
84 | + | ||
85 | +# Flask stuff: | ||
86 | +instance/ | ||
87 | +.webassets-cache | ||
88 | + | ||
89 | +# Scrapy stuff: | ||
90 | +.scrapy | ||
91 | + | ||
92 | +# Sphinx documentation | ||
93 | +docs/_build/ | ||
94 | + | ||
95 | +# PyBuilder | ||
96 | +target/ | ||
97 | + | ||
98 | +# Jupyter Notebook | ||
99 | +.ipynb_checkpoints | ||
100 | + | ||
101 | +# pyenv | ||
102 | +.python-version | ||
103 | + | ||
104 | +# celery beat schedule file | ||
105 | +celerybeat-schedule | ||
106 | + | ||
107 | +# SageMath parsed files | ||
108 | +*.sage.py | ||
109 | + | ||
110 | +# dotenv | ||
111 | +.env | ||
112 | + | ||
113 | +# virtualenv | ||
114 | +.venv* | ||
115 | +venv*/ | ||
116 | +ENV*/ | ||
117 | + | ||
118 | +# Spyder project settings | ||
119 | +.spyderproject | ||
120 | +.spyproject | ||
121 | + | ||
122 | +# Rope project settings | ||
123 | +.ropeproject | ||
124 | + | ||
125 | +# mkdocs documentation | ||
126 | +/site | ||
127 | + | ||
128 | +# mypy | ||
129 | +.mypy_cache/ | ||
130 | + | ||
131 | + | ||
132 | +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- | ||
133 | + | ||
134 | +# General | ||
135 | +.DS_Store | ||
136 | +.AppleDouble | ||
137 | +.LSOverride | ||
138 | + | ||
139 | +# Icon must end with two \r | ||
140 | +Icon | ||
141 | +Icon? | ||
142 | + | ||
143 | +# Thumbnails | ||
144 | +._* | ||
145 | + | ||
146 | +# Files that might appear in the root of a volume | ||
147 | +.DocumentRevisions-V100 | ||
148 | +.fseventsd | ||
149 | +.Spotlight-V100 | ||
150 | +.TemporaryItems | ||
151 | +.Trashes | ||
152 | +.VolumeIcon.icns | ||
153 | +.com.apple.timemachine.donotpresent | ||
154 | + | ||
155 | +# Directories potentially created on remote AFP share | ||
156 | +.AppleDB | ||
157 | +.AppleDesktop | ||
158 | +Network Trash Folder | ||
159 | +Temporary Items | ||
160 | +.apdisk | ||
161 | + | ||
162 | + | ||
163 | +# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore | ||
164 | +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm | ||
165 | +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 | ||
166 | + | ||
167 | +# User-specific stuff: | ||
168 | +.idea/* | ||
169 | +.idea/**/workspace.xml | ||
170 | +.idea/**/tasks.xml | ||
171 | +.idea/dictionaries | ||
172 | +.html # Bokeh Plots | ||
173 | +.pg # TensorFlow Frozen Graphs | ||
174 | +.avi # videos | ||
175 | + | ||
176 | +# Sensitive or high-churn files: | ||
177 | +.idea/**/dataSources/ | ||
178 | +.idea/**/dataSources.ids | ||
179 | +.idea/**/dataSources.local.xml | ||
180 | +.idea/**/sqlDataSources.xml | ||
181 | +.idea/**/dynamic.xml | ||
182 | +.idea/**/uiDesigner.xml | ||
183 | + | ||
184 | +# Gradle: | ||
185 | +.idea/**/gradle.xml | ||
186 | +.idea/**/libraries | ||
187 | + | ||
188 | +# CMake | ||
189 | +cmake-build-debug/ | ||
190 | +cmake-build-release/ | ||
191 | + | ||
192 | +# Mongo Explorer plugin: | ||
193 | +.idea/**/mongoSettings.xml | ||
194 | + | ||
195 | +## File-based project format: | ||
196 | +*.iws | ||
197 | + | ||
198 | +## Plugin-specific files: | ||
199 | + | ||
200 | +# IntelliJ | ||
201 | +out/ | ||
202 | + | ||
203 | +# mpeltonen/sbt-idea plugin | ||
204 | +.idea_modules/ | ||
205 | + | ||
206 | +# JIRA plugin | ||
207 | +atlassian-ide-plugin.xml | ||
208 | + | ||
209 | +# Cursive Clojure plugin | ||
210 | +.idea/replstate.xml | ||
211 | + | ||
212 | +# Crashlytics plugin (for Android Studio and IntelliJ) | ||
213 | +com_crashlytics_export_strings.xml | ||
214 | +crashlytics.properties | ||
215 | +crashlytics-build.properties | ||
216 | +fabric.properties |
YOLOv5/.gitattributes
0 → 100644
YOLOv5/.gitignore
0 → 100644
1 | +# Repo-specific GitIgnore ---------------------------------------------------------------------------------------------- | ||
2 | +*.jpg | ||
3 | +*.jpeg | ||
4 | +*.png | ||
5 | +*.bmp | ||
6 | +*.tif | ||
7 | +*.tiff | ||
8 | +*.heic | ||
9 | +*.JPG | ||
10 | +*.JPEG | ||
11 | +*.PNG | ||
12 | +*.BMP | ||
13 | +*.TIF | ||
14 | +*.TIFF | ||
15 | +*.HEIC | ||
16 | +*.mp4 | ||
17 | +*.mov | ||
18 | +*.MOV | ||
19 | +*.avi | ||
20 | +*.data | ||
21 | +*.json | ||
22 | + | ||
23 | +*.cfg | ||
24 | +!cfg/yolov3*.cfg | ||
25 | + | ||
26 | +storage.googleapis.com | ||
27 | +runs/* | ||
28 | +data/* | ||
29 | +!data/images/zidane.jpg | ||
30 | +!data/images/bus.jpg | ||
31 | +!data/coco.names | ||
32 | +!data/coco_paper.names | ||
33 | +!data/coco.data | ||
34 | +!data/coco_*.data | ||
35 | +!data/coco_*.txt | ||
36 | +!data/trainvalno5k.shapes | ||
37 | +!data/*.sh | ||
38 | + | ||
39 | +pycocotools/* | ||
40 | +results*.txt | ||
41 | +gcp_test*.sh | ||
42 | + | ||
43 | +# Datasets ------------------------------------------------------------------------------------------------------------- | ||
44 | +coco/ | ||
45 | +coco128/ | ||
46 | +VOC/ | ||
47 | + | ||
48 | +# MATLAB GitIgnore ----------------------------------------------------------------------------------------------------- | ||
49 | +*.m~ | ||
50 | +*.mat | ||
51 | +!targets*.mat | ||
52 | + | ||
53 | +# Neural Network weights ----------------------------------------------------------------------------------------------- | ||
54 | +*.weights | ||
55 | +*.pt | ||
56 | +*.onnx | ||
57 | +*.mlmodel | ||
58 | +*.torchscript | ||
59 | +darknet53.conv.74 | ||
60 | +yolov3-tiny.conv.15 | ||
61 | + | ||
62 | +# GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- | ||
63 | +# Byte-compiled / optimized / DLL files | ||
64 | +__pycache__/ | ||
65 | +*.py[cod] | ||
66 | +*$py.class | ||
67 | + | ||
68 | +# C extensions | ||
69 | +*.so | ||
70 | + | ||
71 | +# Distribution / packaging | ||
72 | +.Python | ||
73 | +env/ | ||
74 | +build/ | ||
75 | +develop-eggs/ | ||
76 | +dist/ | ||
77 | +downloads/ | ||
78 | +eggs/ | ||
79 | +.eggs/ | ||
80 | +lib/ | ||
81 | +lib64/ | ||
82 | +parts/ | ||
83 | +sdist/ | ||
84 | +var/ | ||
85 | +wheels/ | ||
86 | +*.egg-info/ | ||
87 | +wandb/ | ||
88 | +.installed.cfg | ||
89 | +*.egg | ||
90 | + | ||
91 | + | ||
92 | +# PyInstaller | ||
93 | +# Usually these files are written by a python script from a template | ||
94 | +# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
95 | +*.manifest | ||
96 | +*.spec | ||
97 | + | ||
98 | +# Installer logs | ||
99 | +pip-log.txt | ||
100 | +pip-delete-this-directory.txt | ||
101 | + | ||
102 | +# Unit test / coverage reports | ||
103 | +htmlcov/ | ||
104 | +.tox/ | ||
105 | +.coverage | ||
106 | +.coverage.* | ||
107 | +.cache | ||
108 | +nosetests.xml | ||
109 | +coverage.xml | ||
110 | +*.cover | ||
111 | +.hypothesis/ | ||
112 | + | ||
113 | +# Translations | ||
114 | +*.mo | ||
115 | +*.pot | ||
116 | + | ||
117 | +# Django stuff: | ||
118 | +*.log | ||
119 | +local_settings.py | ||
120 | + | ||
121 | +# Flask stuff: | ||
122 | +instance/ | ||
123 | +.webassets-cache | ||
124 | + | ||
125 | +# Scrapy stuff: | ||
126 | +.scrapy | ||
127 | + | ||
128 | +# Sphinx documentation | ||
129 | +docs/_build/ | ||
130 | + | ||
131 | +# PyBuilder | ||
132 | +target/ | ||
133 | + | ||
134 | +# Jupyter Notebook | ||
135 | +.ipynb_checkpoints | ||
136 | + | ||
137 | +# pyenv | ||
138 | +.python-version | ||
139 | + | ||
140 | +# celery beat schedule file | ||
141 | +celerybeat-schedule | ||
142 | + | ||
143 | +# SageMath parsed files | ||
144 | +*.sage.py | ||
145 | + | ||
146 | +# dotenv | ||
147 | +.env | ||
148 | + | ||
149 | +# virtualenv | ||
150 | +.venv* | ||
151 | +venv*/ | ||
152 | +ENV*/ | ||
153 | + | ||
154 | +# Spyder project settings | ||
155 | +.spyderproject | ||
156 | +.spyproject | ||
157 | + | ||
158 | +# Rope project settings | ||
159 | +.ropeproject | ||
160 | + | ||
161 | +# mkdocs documentation | ||
162 | +/site | ||
163 | + | ||
164 | +# mypy | ||
165 | +.mypy_cache/ | ||
166 | + | ||
167 | + | ||
168 | +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- | ||
169 | + | ||
170 | +# General | ||
171 | +.DS_Store | ||
172 | +.AppleDouble | ||
173 | +.LSOverride | ||
174 | + | ||
175 | +# Icon must end with two \r | ||
176 | +Icon | ||
177 | +Icon? | ||
178 | + | ||
179 | +# Thumbnails | ||
180 | +._* | ||
181 | + | ||
182 | +# Files that might appear in the root of a volume | ||
183 | +.DocumentRevisions-V100 | ||
184 | +.fseventsd | ||
185 | +.Spotlight-V100 | ||
186 | +.TemporaryItems | ||
187 | +.Trashes | ||
188 | +.VolumeIcon.icns | ||
189 | +.com.apple.timemachine.donotpresent | ||
190 | + | ||
191 | +# Directories potentially created on remote AFP share | ||
192 | +.AppleDB | ||
193 | +.AppleDesktop | ||
194 | +Network Trash Folder | ||
195 | +Temporary Items | ||
196 | +.apdisk | ||
197 | + | ||
198 | + | ||
199 | +# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore | ||
200 | +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm | ||
201 | +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 | ||
202 | + | ||
203 | +# User-specific stuff: | ||
204 | +.idea/* | ||
205 | +.idea/**/workspace.xml | ||
206 | +.idea/**/tasks.xml | ||
207 | +.idea/dictionaries | ||
208 | +.html # Bokeh Plots | ||
209 | +.pg # TensorFlow Frozen Graphs | ||
210 | +.avi # videos | ||
211 | + | ||
212 | +# Sensitive or high-churn files: | ||
213 | +.idea/**/dataSources/ | ||
214 | +.idea/**/dataSources.ids | ||
215 | +.idea/**/dataSources.local.xml | ||
216 | +.idea/**/sqlDataSources.xml | ||
217 | +.idea/**/dynamic.xml | ||
218 | +.idea/**/uiDesigner.xml | ||
219 | + | ||
220 | +# Gradle: | ||
221 | +.idea/**/gradle.xml | ||
222 | +.idea/**/libraries | ||
223 | + | ||
224 | +# CMake | ||
225 | +cmake-build-debug/ | ||
226 | +cmake-build-release/ | ||
227 | + | ||
228 | +# Mongo Explorer plugin: | ||
229 | +.idea/**/mongoSettings.xml | ||
230 | + | ||
231 | +## File-based project format: | ||
232 | +*.iws | ||
233 | + | ||
234 | +## Plugin-specific files: | ||
235 | + | ||
236 | +# IntelliJ | ||
237 | +out/ | ||
238 | + | ||
239 | +# mpeltonen/sbt-idea plugin | ||
240 | +.idea_modules/ | ||
241 | + | ||
242 | +# JIRA plugin | ||
243 | +atlassian-ide-plugin.xml | ||
244 | + | ||
245 | +# Cursive Clojure plugin | ||
246 | +.idea/replstate.xml | ||
247 | + | ||
248 | +# Crashlytics plugin (for Android Studio and IntelliJ) | ||
249 | +com_crashlytics_export_strings.xml | ||
250 | +crashlytics.properties | ||
251 | +crashlytics-build.properties | ||
252 | +fabric.properties |
YOLOv5/Dockerfile
0 → 100644
1 | +# Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch | ||
2 | +FROM nvcr.io/nvidia/pytorch:21.03-py3 | ||
3 | + | ||
4 | +# Install linux packages | ||
5 | +RUN apt update && apt install -y zip htop screen libgl1-mesa-glx | ||
6 | + | ||
7 | +# Install python dependencies | ||
8 | +COPY requirements.txt . | ||
9 | +RUN python -m pip install --upgrade pip | ||
10 | +RUN pip uninstall -y nvidia-tensorboard nvidia-tensorboard-plugin-dlprof | ||
11 | +RUN pip install --no-cache -r requirements.txt coremltools onnx gsutil notebook | ||
12 | + | ||
13 | +# Create working directory | ||
14 | +RUN mkdir -p /usr/src/app | ||
15 | +WORKDIR /usr/src/app | ||
16 | + | ||
17 | +# Copy contents | ||
18 | +COPY . /usr/src/app | ||
19 | + | ||
20 | +# Set environment variables | ||
21 | +ENV HOME=/usr/src/app | ||
22 | + | ||
23 | + | ||
24 | +# --------------------------------------------------- Extras Below --------------------------------------------------- | ||
25 | + | ||
26 | +# Build and Push | ||
27 | +# t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t | ||
28 | +# for v in {300..303}; do t=ultralytics/coco:v$v && sudo docker build -t $t . && sudo docker push $t; done | ||
29 | + | ||
30 | +# Pull and Run | ||
31 | +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t | ||
32 | + | ||
33 | +# Pull and Run with local directory access | ||
34 | +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/coco:/usr/src/coco $t | ||
35 | + | ||
36 | +# Kill all | ||
37 | +# sudo docker kill $(sudo docker ps -q) | ||
38 | + | ||
39 | +# Kill all image-based | ||
40 | +# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest) | ||
41 | + | ||
42 | +# Bash into running container | ||
43 | +# sudo docker exec -it 5a9b5863d93d bash | ||
44 | + | ||
45 | +# Bash into stopped container | ||
46 | +# id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash | ||
47 | + | ||
48 | +# Send weights to GCP | ||
49 | +# python -c "from utils.general import *; strip_optimizer('runs/train/exp0_*/weights/best.pt', 'tmp.pt')" && gsutil cp tmp.pt gs://*.pt | ||
50 | + | ||
51 | +# Clean up | ||
52 | +# docker system prune -a --volumes |
YOLOv5/LICENSE
0 → 100644
1 | +GNU GENERAL PUBLIC LICENSE | ||
2 | + Version 3, 29 June 2007 | ||
3 | + | ||
4 | + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> | ||
5 | + Everyone is permitted to copy and distribute verbatim copies | ||
6 | + of this license document, but changing it is not allowed. | ||
7 | + | ||
8 | + Preamble | ||
9 | + | ||
10 | + The GNU General Public License is a free, copyleft license for | ||
11 | +software and other kinds of works. | ||
12 | + | ||
13 | + The licenses for most software and other practical works are designed | ||
14 | +to take away your freedom to share and change the works. By contrast, | ||
15 | +the GNU General Public License is intended to guarantee your freedom to | ||
16 | +share and change all versions of a program--to make sure it remains free | ||
17 | +software for all its users. We, the Free Software Foundation, use the | ||
18 | +GNU General Public License for most of our software; it applies also to | ||
19 | +any other work released this way by its authors. You can apply it to | ||
20 | +your programs, too. | ||
21 | + | ||
22 | + When we speak of free software, we are referring to freedom, not | ||
23 | +price. Our General Public Licenses are designed to make sure that you | ||
24 | +have the freedom to distribute copies of free software (and charge for | ||
25 | +them if you wish), that you receive source code or can get it if you | ||
26 | +want it, that you can change the software or use pieces of it in new | ||
27 | +free programs, and that you know you can do these things. | ||
28 | + | ||
29 | + To protect your rights, we need to prevent others from denying you | ||
30 | +these rights or asking you to surrender the rights. Therefore, you have | ||
31 | +certain responsibilities if you distribute copies of the software, or if | ||
32 | +you modify it: responsibilities to respect the freedom of others. | ||
33 | + | ||
34 | + For example, if you distribute copies of such a program, whether | ||
35 | +gratis or for a fee, you must pass on to the recipients the same | ||
36 | +freedoms that you received. You must make sure that they, too, receive | ||
37 | +or can get the source code. And you must show them these terms so they | ||
38 | +know their rights. | ||
39 | + | ||
40 | + Developers that use the GNU GPL protect your rights with two steps: | ||
41 | +(1) assert copyright on the software, and (2) offer you this License | ||
42 | +giving you legal permission to copy, distribute and/or modify it. | ||
43 | + | ||
44 | + For the developers' and authors' protection, the GPL clearly explains | ||
45 | +that there is no warranty for this free software. For both users' and | ||
46 | +authors' sake, the GPL requires that modified versions be marked as | ||
47 | +changed, so that their problems will not be attributed erroneously to | ||
48 | +authors of previous versions. | ||
49 | + | ||
50 | + Some devices are designed to deny users access to install or run | ||
51 | +modified versions of the software inside them, although the manufacturer | ||
52 | +can do so. This is fundamentally incompatible with the aim of | ||
53 | +protecting users' freedom to change the software. The systematic | ||
54 | +pattern of such abuse occurs in the area of products for individuals to | ||
55 | +use, which is precisely where it is most unacceptable. Therefore, we | ||
56 | +have designed this version of the GPL to prohibit the practice for those | ||
57 | +products. If such problems arise substantially in other domains, we | ||
58 | +stand ready to extend this provision to those domains in future versions | ||
59 | +of the GPL, as needed to protect the freedom of users. | ||
60 | + | ||
61 | + Finally, every program is threatened constantly by software patents. | ||
62 | +States should not allow patents to restrict development and use of | ||
63 | +software on general-purpose computers, but in those that do, we wish to | ||
64 | +avoid the special danger that patents applied to a free program could | ||
65 | +make it effectively proprietary. To prevent this, the GPL assures that | ||
66 | +patents cannot be used to render the program non-free. | ||
67 | + | ||
68 | + The precise terms and conditions for copying, distribution and | ||
69 | +modification follow. | ||
70 | + | ||
71 | + TERMS AND CONDITIONS | ||
72 | + | ||
73 | + 0. Definitions. | ||
74 | + | ||
75 | + "This License" refers to version 3 of the GNU General Public License. | ||
76 | + | ||
77 | + "Copyright" also means copyright-like laws that apply to other kinds of | ||
78 | +works, such as semiconductor masks. | ||
79 | + | ||
80 | + "The Program" refers to any copyrightable work licensed under this | ||
81 | +License. Each licensee is addressed as "you". "Licensees" and | ||
82 | +"recipients" may be individuals or organizations. | ||
83 | + | ||
84 | + To "modify" a work means to copy from or adapt all or part of the work | ||
85 | +in a fashion requiring copyright permission, other than the making of an | ||
86 | +exact copy. The resulting work is called a "modified version" of the | ||
87 | +earlier work or a work "based on" the earlier work. | ||
88 | + | ||
89 | + A "covered work" means either the unmodified Program or a work based | ||
90 | +on the Program. | ||
91 | + | ||
92 | + To "propagate" a work means to do anything with it that, without | ||
93 | +permission, would make you directly or secondarily liable for | ||
94 | +infringement under applicable copyright law, except executing it on a | ||
95 | +computer or modifying a private copy. Propagation includes copying, | ||
96 | +distribution (with or without modification), making available to the | ||
97 | +public, and in some countries other activities as well. | ||
98 | + | ||
99 | + To "convey" a work means any kind of propagation that enables other | ||
100 | +parties to make or receive copies. Mere interaction with a user through | ||
101 | +a computer network, with no transfer of a copy, is not conveying. | ||
102 | + | ||
103 | + An interactive user interface displays "Appropriate Legal Notices" | ||
104 | +to the extent that it includes a convenient and prominently visible | ||
105 | +feature that (1) displays an appropriate copyright notice, and (2) | ||
106 | +tells the user that there is no warranty for the work (except to the | ||
107 | +extent that warranties are provided), that licensees may convey the | ||
108 | +work under this License, and how to view a copy of this License. If | ||
109 | +the interface presents a list of user commands or options, such as a | ||
110 | +menu, a prominent item in the list meets this criterion. | ||
111 | + | ||
112 | + 1. Source Code. | ||
113 | + | ||
114 | + The "source code" for a work means the preferred form of the work | ||
115 | +for making modifications to it. "Object code" means any non-source | ||
116 | +form of a work. | ||
117 | + | ||
118 | + A "Standard Interface" means an interface that either is an official | ||
119 | +standard defined by a recognized standards body, or, in the case of | ||
120 | +interfaces specified for a particular programming language, one that | ||
121 | +is widely used among developers working in that language. | ||
122 | + | ||
123 | + The "System Libraries" of an executable work include anything, other | ||
124 | +than the work as a whole, that (a) is included in the normal form of | ||
125 | +packaging a Major Component, but which is not part of that Major | ||
126 | +Component, and (b) serves only to enable use of the work with that | ||
127 | +Major Component, or to implement a Standard Interface for which an | ||
128 | +implementation is available to the public in source code form. A | ||
129 | +"Major Component", in this context, means a major essential component | ||
130 | +(kernel, window system, and so on) of the specific operating system | ||
131 | +(if any) on which the executable work runs, or a compiler used to | ||
132 | +produce the work, or an object code interpreter used to run it. | ||
133 | + | ||
134 | + The "Corresponding Source" for a work in object code form means all | ||
135 | +the source code needed to generate, install, and (for an executable | ||
136 | +work) run the object code and to modify the work, including scripts to | ||
137 | +control those activities. However, it does not include the work's | ||
138 | +System Libraries, or general-purpose tools or generally available free | ||
139 | +programs which are used unmodified in performing those activities but | ||
140 | +which are not part of the work. For example, Corresponding Source | ||
141 | +includes interface definition files associated with source files for | ||
142 | +the work, and the source code for shared libraries and dynamically | ||
143 | +linked subprograms that the work is specifically designed to require, | ||
144 | +such as by intimate data communication or control flow between those | ||
145 | +subprograms and other parts of the work. | ||
146 | + | ||
147 | + The Corresponding Source need not include anything that users | ||
148 | +can regenerate automatically from other parts of the Corresponding | ||
149 | +Source. | ||
150 | + | ||
151 | + The Corresponding Source for a work in source code form is that | ||
152 | +same work. | ||
153 | + | ||
154 | + 2. Basic Permissions. | ||
155 | + | ||
156 | + All rights granted under this License are granted for the term of | ||
157 | +copyright on the Program, and are irrevocable provided the stated | ||
158 | +conditions are met. This License explicitly affirms your unlimited | ||
159 | +permission to run the unmodified Program. The output from running a | ||
160 | +covered work is covered by this License only if the output, given its | ||
161 | +content, constitutes a covered work. This License acknowledges your | ||
162 | +rights of fair use or other equivalent, as provided by copyright law. | ||
163 | + | ||
164 | + You may make, run and propagate covered works that you do not | ||
165 | +convey, without conditions so long as your license otherwise remains | ||
166 | +in force. You may convey covered works to others for the sole purpose | ||
167 | +of having them make modifications exclusively for you, or provide you | ||
168 | +with facilities for running those works, provided that you comply with | ||
169 | +the terms of this License in conveying all material for which you do | ||
170 | +not control copyright. Those thus making or running the covered works | ||
171 | +for you must do so exclusively on your behalf, under your direction | ||
172 | +and control, on terms that prohibit them from making any copies of | ||
173 | +your copyrighted material outside their relationship with you. | ||
174 | + | ||
175 | + Conveying under any other circumstances is permitted solely under | ||
176 | +the conditions stated below. Sublicensing is not allowed; section 10 | ||
177 | +makes it unnecessary. | ||
178 | + | ||
179 | + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. | ||
180 | + | ||
181 | + No covered work shall be deemed part of an effective technological | ||
182 | +measure under any applicable law fulfilling obligations under article | ||
183 | +11 of the WIPO copyright treaty adopted on 20 December 1996, or | ||
184 | +similar laws prohibiting or restricting circumvention of such | ||
185 | +measures. | ||
186 | + | ||
187 | + When you convey a covered work, you waive any legal power to forbid | ||
188 | +circumvention of technological measures to the extent such circumvention | ||
189 | +is effected by exercising rights under this License with respect to | ||
190 | +the covered work, and you disclaim any intention to limit operation or | ||
191 | +modification of the work as a means of enforcing, against the work's | ||
192 | +users, your or third parties' legal rights to forbid circumvention of | ||
193 | +technological measures. | ||
194 | + | ||
195 | + 4. Conveying Verbatim Copies. | ||
196 | + | ||
197 | + You may convey verbatim copies of the Program's source code as you | ||
198 | +receive it, in any medium, provided that you conspicuously and | ||
199 | +appropriately publish on each copy an appropriate copyright notice; | ||
200 | +keep intact all notices stating that this License and any | ||
201 | +non-permissive terms added in accord with section 7 apply to the code; | ||
202 | +keep intact all notices of the absence of any warranty; and give all | ||
203 | +recipients a copy of this License along with the Program. | ||
204 | + | ||
205 | + You may charge any price or no price for each copy that you convey, | ||
206 | +and you may offer support or warranty protection for a fee. | ||
207 | + | ||
208 | + 5. Conveying Modified Source Versions. | ||
209 | + | ||
210 | + You may convey a work based on the Program, or the modifications to | ||
211 | +produce it from the Program, in the form of source code under the | ||
212 | +terms of section 4, provided that you also meet all of these conditions: | ||
213 | + | ||
214 | + a) The work must carry prominent notices stating that you modified | ||
215 | + it, and giving a relevant date. | ||
216 | + | ||
217 | + b) The work must carry prominent notices stating that it is | ||
218 | + released under this License and any conditions added under section | ||
219 | + 7. This requirement modifies the requirement in section 4 to | ||
220 | + "keep intact all notices". | ||
221 | + | ||
222 | + c) You must license the entire work, as a whole, under this | ||
223 | + License to anyone who comes into possession of a copy. This | ||
224 | + License will therefore apply, along with any applicable section 7 | ||
225 | + additional terms, to the whole of the work, and all its parts, | ||
226 | + regardless of how they are packaged. This License gives no | ||
227 | + permission to license the work in any other way, but it does not | ||
228 | + invalidate such permission if you have separately received it. | ||
229 | + | ||
230 | + d) If the work has interactive user interfaces, each must display | ||
231 | + Appropriate Legal Notices; however, if the Program has interactive | ||
232 | + interfaces that do not display Appropriate Legal Notices, your | ||
233 | + work need not make them do so. | ||
234 | + | ||
235 | + A compilation of a covered work with other separate and independent | ||
236 | +works, which are not by their nature extensions of the covered work, | ||
237 | +and which are not combined with it such as to form a larger program, | ||
238 | +in or on a volume of a storage or distribution medium, is called an | ||
239 | +"aggregate" if the compilation and its resulting copyright are not | ||
240 | +used to limit the access or legal rights of the compilation's users | ||
241 | +beyond what the individual works permit. Inclusion of a covered work | ||
242 | +in an aggregate does not cause this License to apply to the other | ||
243 | +parts of the aggregate. | ||
244 | + | ||
245 | + 6. Conveying Non-Source Forms. | ||
246 | + | ||
247 | + You may convey a covered work in object code form under the terms | ||
248 | +of sections 4 and 5, provided that you also convey the | ||
249 | +machine-readable Corresponding Source under the terms of this License, | ||
250 | +in one of these ways: | ||
251 | + | ||
252 | + a) Convey the object code in, or embodied in, a physical product | ||
253 | + (including a physical distribution medium), accompanied by the | ||
254 | + Corresponding Source fixed on a durable physical medium | ||
255 | + customarily used for software interchange. | ||
256 | + | ||
257 | + b) Convey the object code in, or embodied in, a physical product | ||
258 | + (including a physical distribution medium), accompanied by a | ||
259 | + written offer, valid for at least three years and valid for as | ||
260 | + long as you offer spare parts or customer support for that product | ||
261 | + model, to give anyone who possesses the object code either (1) a | ||
262 | + copy of the Corresponding Source for all the software in the | ||
263 | + product that is covered by this License, on a durable physical | ||
264 | + medium customarily used for software interchange, for a price no | ||
265 | + more than your reasonable cost of physically performing this | ||
266 | + conveying of source, or (2) access to copy the | ||
267 | + Corresponding Source from a network server at no charge. | ||
268 | + | ||
269 | + c) Convey individual copies of the object code with a copy of the | ||
270 | + written offer to provide the Corresponding Source. This | ||
271 | + alternative is allowed only occasionally and noncommercially, and | ||
272 | + only if you received the object code with such an offer, in accord | ||
273 | + with subsection 6b. | ||
274 | + | ||
275 | + d) Convey the object code by offering access from a designated | ||
276 | + place (gratis or for a charge), and offer equivalent access to the | ||
277 | + Corresponding Source in the same way through the same place at no | ||
278 | + further charge. You need not require recipients to copy the | ||
279 | + Corresponding Source along with the object code. If the place to | ||
280 | + copy the object code is a network server, the Corresponding Source | ||
281 | + may be on a different server (operated by you or a third party) | ||
282 | + that supports equivalent copying facilities, provided you maintain | ||
283 | + clear directions next to the object code saying where to find the | ||
284 | + Corresponding Source. Regardless of what server hosts the | ||
285 | + Corresponding Source, you remain obligated to ensure that it is | ||
286 | + available for as long as needed to satisfy these requirements. | ||
287 | + | ||
288 | + e) Convey the object code using peer-to-peer transmission, provided | ||
289 | + you inform other peers where the object code and Corresponding | ||
290 | + Source of the work are being offered to the general public at no | ||
291 | + charge under subsection 6d. | ||
292 | + | ||
293 | + A separable portion of the object code, whose source code is excluded | ||
294 | +from the Corresponding Source as a System Library, need not be | ||
295 | +included in conveying the object code work. | ||
296 | + | ||
297 | + A "User Product" is either (1) a "consumer product", which means any | ||
298 | +tangible personal property which is normally used for personal, family, | ||
299 | +or household purposes, or (2) anything designed or sold for incorporation | ||
300 | +into a dwelling. In determining whether a product is a consumer product, | ||
301 | +doubtful cases shall be resolved in favor of coverage. For a particular | ||
302 | +product received by a particular user, "normally used" refers to a | ||
303 | +typical or common use of that class of product, regardless of the status | ||
304 | +of the particular user or of the way in which the particular user | ||
305 | +actually uses, or expects or is expected to use, the product. A product | ||
306 | +is a consumer product regardless of whether the product has substantial | ||
307 | +commercial, industrial or non-consumer uses, unless such uses represent | ||
308 | +the only significant mode of use of the product. | ||
309 | + | ||
310 | + "Installation Information" for a User Product means any methods, | ||
311 | +procedures, authorization keys, or other information required to install | ||
312 | +and execute modified versions of a covered work in that User Product from | ||
313 | +a modified version of its Corresponding Source. The information must | ||
314 | +suffice to ensure that the continued functioning of the modified object | ||
315 | +code is in no case prevented or interfered with solely because | ||
316 | +modification has been made. | ||
317 | + | ||
318 | + If you convey an object code work under this section in, or with, or | ||
319 | +specifically for use in, a User Product, and the conveying occurs as | ||
320 | +part of a transaction in which the right of possession and use of the | ||
321 | +User Product is transferred to the recipient in perpetuity or for a | ||
322 | +fixed term (regardless of how the transaction is characterized), the | ||
323 | +Corresponding Source conveyed under this section must be accompanied | ||
324 | +by the Installation Information. But this requirement does not apply | ||
325 | +if neither you nor any third party retains the ability to install | ||
326 | +modified object code on the User Product (for example, the work has | ||
327 | +been installed in ROM). | ||
328 | + | ||
329 | + The requirement to provide Installation Information does not include a | ||
330 | +requirement to continue to provide support service, warranty, or updates | ||
331 | +for a work that has been modified or installed by the recipient, or for | ||
332 | +the User Product in which it has been modified or installed. Access to a | ||
333 | +network may be denied when the modification itself materially and | ||
334 | +adversely affects the operation of the network or violates the rules and | ||
335 | +protocols for communication across the network. | ||
336 | + | ||
337 | + Corresponding Source conveyed, and Installation Information provided, | ||
338 | +in accord with this section must be in a format that is publicly | ||
339 | +documented (and with an implementation available to the public in | ||
340 | +source code form), and must require no special password or key for | ||
341 | +unpacking, reading or copying. | ||
342 | + | ||
343 | + 7. Additional Terms. | ||
344 | + | ||
345 | + "Additional permissions" are terms that supplement the terms of this | ||
346 | +License by making exceptions from one or more of its conditions. | ||
347 | +Additional permissions that are applicable to the entire Program shall | ||
348 | +be treated as though they were included in this License, to the extent | ||
349 | +that they are valid under applicable law. If additional permissions | ||
350 | +apply only to part of the Program, that part may be used separately | ||
351 | +under those permissions, but the entire Program remains governed by | ||
352 | +this License without regard to the additional permissions. | ||
353 | + | ||
354 | + When you convey a copy of a covered work, you may at your option | ||
355 | +remove any additional permissions from that copy, or from any part of | ||
356 | +it. (Additional permissions may be written to require their own | ||
357 | +removal in certain cases when you modify the work.) You may place | ||
358 | +additional permissions on material, added by you to a covered work, | ||
359 | +for which you have or can give appropriate copyright permission. | ||
360 | + | ||
361 | + Notwithstanding any other provision of this License, for material you | ||
362 | +add to a covered work, you may (if authorized by the copyright holders of | ||
363 | +that material) supplement the terms of this License with terms: | ||
364 | + | ||
365 | + a) Disclaiming warranty or limiting liability differently from the | ||
366 | + terms of sections 15 and 16 of this License; or | ||
367 | + | ||
368 | + b) Requiring preservation of specified reasonable legal notices or | ||
369 | + author attributions in that material or in the Appropriate Legal | ||
370 | + Notices displayed by works containing it; or | ||
371 | + | ||
372 | + c) Prohibiting misrepresentation of the origin of that material, or | ||
373 | + requiring that modified versions of such material be marked in | ||
374 | + reasonable ways as different from the original version; or | ||
375 | + | ||
376 | + d) Limiting the use for publicity purposes of names of licensors or | ||
377 | + authors of the material; or | ||
378 | + | ||
379 | + e) Declining to grant rights under trademark law for use of some | ||
380 | + trade names, trademarks, or service marks; or | ||
381 | + | ||
382 | + f) Requiring indemnification of licensors and authors of that | ||
383 | + material by anyone who conveys the material (or modified versions of | ||
384 | + it) with contractual assumptions of liability to the recipient, for | ||
385 | + any liability that these contractual assumptions directly impose on | ||
386 | + those licensors and authors. | ||
387 | + | ||
388 | + All other non-permissive additional terms are considered "further | ||
389 | +restrictions" within the meaning of section 10. If the Program as you | ||
390 | +received it, or any part of it, contains a notice stating that it is | ||
391 | +governed by this License along with a term that is a further | ||
392 | +restriction, you may remove that term. If a license document contains | ||
393 | +a further restriction but permits relicensing or conveying under this | ||
394 | +License, you may add to a covered work material governed by the terms | ||
395 | +of that license document, provided that the further restriction does | ||
396 | +not survive such relicensing or conveying. | ||
397 | + | ||
398 | + If you add terms to a covered work in accord with this section, you | ||
399 | +must place, in the relevant source files, a statement of the | ||
400 | +additional terms that apply to those files, or a notice indicating | ||
401 | +where to find the applicable terms. | ||
402 | + | ||
403 | + Additional terms, permissive or non-permissive, may be stated in the | ||
404 | +form of a separately written license, or stated as exceptions; | ||
405 | +the above requirements apply either way. | ||
406 | + | ||
407 | + 8. Termination. | ||
408 | + | ||
409 | + You may not propagate or modify a covered work except as expressly | ||
410 | +provided under this License. Any attempt otherwise to propagate or | ||
411 | +modify it is void, and will automatically terminate your rights under | ||
412 | +this License (including any patent licenses granted under the third | ||
413 | +paragraph of section 11). | ||
414 | + | ||
415 | + However, if you cease all violation of this License, then your | ||
416 | +license from a particular copyright holder is reinstated (a) | ||
417 | +provisionally, unless and until the copyright holder explicitly and | ||
418 | +finally terminates your license, and (b) permanently, if the copyright | ||
419 | +holder fails to notify you of the violation by some reasonable means | ||
420 | +prior to 60 days after the cessation. | ||
421 | + | ||
422 | + Moreover, your license from a particular copyright holder is | ||
423 | +reinstated permanently if the copyright holder notifies you of the | ||
424 | +violation by some reasonable means, this is the first time you have | ||
425 | +received notice of violation of this License (for any work) from that | ||
426 | +copyright holder, and you cure the violation prior to 30 days after | ||
427 | +your receipt of the notice. | ||
428 | + | ||
429 | + Termination of your rights under this section does not terminate the | ||
430 | +licenses of parties who have received copies or rights from you under | ||
431 | +this License. If your rights have been terminated and not permanently | ||
432 | +reinstated, you do not qualify to receive new licenses for the same | ||
433 | +material under section 10. | ||
434 | + | ||
435 | + 9. Acceptance Not Required for Having Copies. | ||
436 | + | ||
437 | + You are not required to accept this License in order to receive or | ||
438 | +run a copy of the Program. Ancillary propagation of a covered work | ||
439 | +occurring solely as a consequence of using peer-to-peer transmission | ||
440 | +to receive a copy likewise does not require acceptance. However, | ||
441 | +nothing other than this License grants you permission to propagate or | ||
442 | +modify any covered work. These actions infringe copyright if you do | ||
443 | +not accept this License. Therefore, by modifying or propagating a | ||
444 | +covered work, you indicate your acceptance of this License to do so. | ||
445 | + | ||
446 | + 10. Automatic Licensing of Downstream Recipients. | ||
447 | + | ||
448 | + Each time you convey a covered work, the recipient automatically | ||
449 | +receives a license from the original licensors, to run, modify and | ||
450 | +propagate that work, subject to this License. You are not responsible | ||
451 | +for enforcing compliance by third parties with this License. | ||
452 | + | ||
453 | + An "entity transaction" is a transaction transferring control of an | ||
454 | +organization, or substantially all assets of one, or subdividing an | ||
455 | +organization, or merging organizations. If propagation of a covered | ||
456 | +work results from an entity transaction, each party to that | ||
457 | +transaction who receives a copy of the work also receives whatever | ||
458 | +licenses to the work the party's predecessor in interest had or could | ||
459 | +give under the previous paragraph, plus a right to possession of the | ||
460 | +Corresponding Source of the work from the predecessor in interest, if | ||
461 | +the predecessor has it or can get it with reasonable efforts. | ||
462 | + | ||
463 | + You may not impose any further restrictions on the exercise of the | ||
464 | +rights granted or affirmed under this License. For example, you may | ||
465 | +not impose a license fee, royalty, or other charge for exercise of | ||
466 | +rights granted under this License, and you may not initiate litigation | ||
467 | +(including a cross-claim or counterclaim in a lawsuit) alleging that | ||
468 | +any patent claim is infringed by making, using, selling, offering for | ||
469 | +sale, or importing the Program or any portion of it. | ||
470 | + | ||
471 | + 11. Patents. | ||
472 | + | ||
473 | + A "contributor" is a copyright holder who authorizes use under this | ||
474 | +License of the Program or a work on which the Program is based. The | ||
475 | +work thus licensed is called the contributor's "contributor version". | ||
476 | + | ||
477 | + A contributor's "essential patent claims" are all patent claims | ||
478 | +owned or controlled by the contributor, whether already acquired or | ||
479 | +hereafter acquired, that would be infringed by some manner, permitted | ||
480 | +by this License, of making, using, or selling its contributor version, | ||
481 | +but do not include claims that would be infringed only as a | ||
482 | +consequence of further modification of the contributor version. For | ||
483 | +purposes of this definition, "control" includes the right to grant | ||
484 | +patent sublicenses in a manner consistent with the requirements of | ||
485 | +this License. | ||
486 | + | ||
487 | + Each contributor grants you a non-exclusive, worldwide, royalty-free | ||
488 | +patent license under the contributor's essential patent claims, to | ||
489 | +make, use, sell, offer for sale, import and otherwise run, modify and | ||
490 | +propagate the contents of its contributor version. | ||
491 | + | ||
492 | + In the following three paragraphs, a "patent license" is any express | ||
493 | +agreement or commitment, however denominated, not to enforce a patent | ||
494 | +(such as an express permission to practice a patent or covenant not to | ||
495 | +sue for patent infringement). To "grant" such a patent license to a | ||
496 | +party means to make such an agreement or commitment not to enforce a | ||
497 | +patent against the party. | ||
498 | + | ||
499 | + If you convey a covered work, knowingly relying on a patent license, | ||
500 | +and the Corresponding Source of the work is not available for anyone | ||
501 | +to copy, free of charge and under the terms of this License, through a | ||
502 | +publicly available network server or other readily accessible means, | ||
503 | +then you must either (1) cause the Corresponding Source to be so | ||
504 | +available, or (2) arrange to deprive yourself of the benefit of the | ||
505 | +patent license for this particular work, or (3) arrange, in a manner | ||
506 | +consistent with the requirements of this License, to extend the patent | ||
507 | +license to downstream recipients. "Knowingly relying" means you have | ||
508 | +actual knowledge that, but for the patent license, your conveying the | ||
509 | +covered work in a country, or your recipient's use of the covered work | ||
510 | +in a country, would infringe one or more identifiable patents in that | ||
511 | +country that you have reason to believe are valid. | ||
512 | + | ||
513 | + If, pursuant to or in connection with a single transaction or | ||
514 | +arrangement, you convey, or propagate by procuring conveyance of, a | ||
515 | +covered work, and grant a patent license to some of the parties | ||
516 | +receiving the covered work authorizing them to use, propagate, modify | ||
517 | +or convey a specific copy of the covered work, then the patent license | ||
518 | +you grant is automatically extended to all recipients of the covered | ||
519 | +work and works based on it. | ||
520 | + | ||
521 | + A patent license is "discriminatory" if it does not include within | ||
522 | +the scope of its coverage, prohibits the exercise of, or is | ||
523 | +conditioned on the non-exercise of one or more of the rights that are | ||
524 | +specifically granted under this License. You may not convey a covered | ||
525 | +work if you are a party to an arrangement with a third party that is | ||
526 | +in the business of distributing software, under which you make payment | ||
527 | +to the third party based on the extent of your activity of conveying | ||
528 | +the work, and under which the third party grants, to any of the | ||
529 | +parties who would receive the covered work from you, a discriminatory | ||
530 | +patent license (a) in connection with copies of the covered work | ||
531 | +conveyed by you (or copies made from those copies), or (b) primarily | ||
532 | +for and in connection with specific products or compilations that | ||
533 | +contain the covered work, unless you entered into that arrangement, | ||
534 | +or that patent license was granted, prior to 28 March 2007. | ||
535 | + | ||
536 | + Nothing in this License shall be construed as excluding or limiting | ||
537 | +any implied license or other defenses to infringement that may | ||
538 | +otherwise be available to you under applicable patent law. | ||
539 | + | ||
540 | + 12. No Surrender of Others' Freedom. | ||
541 | + | ||
542 | + If conditions are imposed on you (whether by court order, agreement or | ||
543 | +otherwise) that contradict the conditions of this License, they do not | ||
544 | +excuse you from the conditions of this License. If you cannot convey a | ||
545 | +covered work so as to satisfy simultaneously your obligations under this | ||
546 | +License and any other pertinent obligations, then as a consequence you may | ||
547 | +not convey it at all. For example, if you agree to terms that obligate you | ||
548 | +to collect a royalty for further conveying from those to whom you convey | ||
549 | +the Program, the only way you could satisfy both those terms and this | ||
550 | +License would be to refrain entirely from conveying the Program. | ||
551 | + | ||
552 | + 13. Use with the GNU Affero General Public License. | ||
553 | + | ||
554 | + Notwithstanding any other provision of this License, you have | ||
555 | +permission to link or combine any covered work with a work licensed | ||
556 | +under version 3 of the GNU Affero General Public License into a single | ||
557 | +combined work, and to convey the resulting work. The terms of this | ||
558 | +License will continue to apply to the part which is the covered work, | ||
559 | +but the special requirements of the GNU Affero General Public License, | ||
560 | +section 13, concerning interaction through a network will apply to the | ||
561 | +combination as such. | ||
562 | + | ||
563 | + 14. Revised Versions of this License. | ||
564 | + | ||
565 | + The Free Software Foundation may publish revised and/or new versions of | ||
566 | +the GNU General Public License from time to time. Such new versions will | ||
567 | +be similar in spirit to the present version, but may differ in detail to | ||
568 | +address new problems or concerns. | ||
569 | + | ||
570 | + Each version is given a distinguishing version number. If the | ||
571 | +Program specifies that a certain numbered version of the GNU General | ||
572 | +Public License "or any later version" applies to it, you have the | ||
573 | +option of following the terms and conditions either of that numbered | ||
574 | +version or of any later version published by the Free Software | ||
575 | +Foundation. If the Program does not specify a version number of the | ||
576 | +GNU General Public License, you may choose any version ever published | ||
577 | +by the Free Software Foundation. | ||
578 | + | ||
579 | + If the Program specifies that a proxy can decide which future | ||
580 | +versions of the GNU General Public License can be used, that proxy's | ||
581 | +public statement of acceptance of a version permanently authorizes you | ||
582 | +to choose that version for the Program. | ||
583 | + | ||
584 | + Later license versions may give you additional or different | ||
585 | +permissions. However, no additional obligations are imposed on any | ||
586 | +author or copyright holder as a result of your choosing to follow a | ||
587 | +later version. | ||
588 | + | ||
589 | + 15. Disclaimer of Warranty. | ||
590 | + | ||
591 | + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | ||
592 | +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | ||
593 | +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | ||
594 | +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | ||
595 | +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||
596 | +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | ||
597 | +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | ||
598 | +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | ||
599 | + | ||
600 | + 16. Limitation of Liability. | ||
601 | + | ||
602 | + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | ||
603 | +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | ||
604 | +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | ||
605 | +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | ||
606 | +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | ||
607 | +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | ||
608 | +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | ||
609 | +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | ||
610 | +SUCH DAMAGES. | ||
611 | + | ||
612 | + 17. Interpretation of Sections 15 and 16. | ||
613 | + | ||
614 | + If the disclaimer of warranty and limitation of liability provided | ||
615 | +above cannot be given local legal effect according to their terms, | ||
616 | +reviewing courts shall apply local law that most closely approximates | ||
617 | +an absolute waiver of all civil liability in connection with the | ||
618 | +Program, unless a warranty or assumption of liability accompanies a | ||
619 | +copy of the Program in return for a fee. | ||
620 | + | ||
621 | + END OF TERMS AND CONDITIONS | ||
622 | + | ||
623 | + How to Apply These Terms to Your New Programs | ||
624 | + | ||
625 | + If you develop a new program, and you want it to be of the greatest | ||
626 | +possible use to the public, the best way to achieve this is to make it | ||
627 | +free software which everyone can redistribute and change under these terms. | ||
628 | + | ||
629 | + To do so, attach the following notices to the program. It is safest | ||
630 | +to attach them to the start of each source file to most effectively | ||
631 | +state the exclusion of warranty; and each file should have at least | ||
632 | +the "copyright" line and a pointer to where the full notice is found. | ||
633 | + | ||
634 | + <one line to give the program's name and a brief idea of what it does.> | ||
635 | + Copyright (C) <year> <name of author> | ||
636 | + | ||
637 | + This program is free software: you can redistribute it and/or modify | ||
638 | + it under the terms of the GNU General Public License as published by | ||
639 | + the Free Software Foundation, either version 3 of the License, or | ||
640 | + (at your option) any later version. | ||
641 | + | ||
642 | + This program is distributed in the hope that it will be useful, | ||
643 | + but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
644 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
645 | + GNU General Public License for more details. | ||
646 | + | ||
647 | + You should have received a copy of the GNU General Public License | ||
648 | + along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
649 | + | ||
650 | +Also add information on how to contact you by electronic and paper mail. | ||
651 | + | ||
652 | + If the program does terminal interaction, make it output a short | ||
653 | +notice like this when it starts in an interactive mode: | ||
654 | + | ||
655 | + <program> Copyright (C) <year> <name of author> | ||
656 | + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. | ||
657 | + This is free software, and you are welcome to redistribute it | ||
658 | + under certain conditions; type `show c' for details. | ||
659 | + | ||
660 | +The hypothetical commands `show w' and `show c' should show the appropriate | ||
661 | +parts of the General Public License. Of course, your program's commands | ||
662 | +might be different; for a GUI interface, you would use an "about box". | ||
663 | + | ||
664 | + You should also get your employer (if you work as a programmer) or school, | ||
665 | +if any, to sign a "copyright disclaimer" for the program, if necessary. | ||
666 | +For more information on this, and how to apply and follow the GNU GPL, see | ||
667 | +<http://www.gnu.org/licenses/>. | ||
668 | + | ||
669 | + The GNU General Public License does not permit incorporating your program | ||
670 | +into proprietary programs. If your program is a subroutine library, you | ||
671 | +may consider it more useful to permit linking proprietary applications with | ||
672 | +the library. If this is what you want to do, use the GNU Lesser General | ||
673 | +Public License instead of this License. But first, please read | ||
674 | +<http://www.gnu.org/philosophy/why-not-lgpl.html>. | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
YOLOv5/README.md
0 → 100644
1 | +<a align="left" href="https://apps.apple.com/app/id1452689527" target="_blank"> | ||
2 | +<img width="800" src="https://user-images.githubusercontent.com/26833433/98699617-a1595a00-2377-11eb-8145-fc674eb9b1a7.jpg"></a> | ||
3 | +  | ||
4 | + | ||
5 | +<a href="https://github.com/ultralytics/yolov5/actions"><img src="https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg" alt="CI CPU testing"></a> | ||
6 | + | ||
7 | +This repository represents Ultralytics open-source research into future object detection methods, and incorporates lessons learned and best practices evolved over thousands of hours of training and evolution on anonymized client datasets. **All code and models are under active development, and are subject to modification or deletion without notice.** Use at your own risk. | ||
8 | + | ||
9 | +<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/114313216-f0a5e100-9af5-11eb-8445-c682b60da2e3.png"></p> | ||
10 | +<details> | ||
11 | + <summary>YOLOv5-P5 640 Figure (click to expand)</summary> | ||
12 | + | ||
13 | +<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/114313219-f1d70e00-9af5-11eb-9973-52b1f98d321a.png"></p> | ||
14 | +</details> | ||
15 | +<details> | ||
16 | + <summary>Figure Notes (click to expand)</summary> | ||
17 | + | ||
18 | + * GPU Speed measures end-to-end time per image averaged over 5000 COCO val2017 images using a V100 GPU with batch size 32, and includes image preprocessing, PyTorch FP16 inference, postprocessing and NMS. | ||
19 | + * EfficientDet data from [google/automl](https://github.com/google/automl) at batch size 8. | ||
20 | + * **Reproduce** by `python test.py --task study --data coco.yaml --iou 0.7 --weights yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt` | ||
21 | +</details> | ||
22 | + | ||
23 | +- **April 11, 2021**: [v5.0 release](https://github.com/ultralytics/yolov5/releases/tag/v5.0): YOLOv5-P6 1280 models, [AWS](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart), [Supervise.ly](https://github.com/ultralytics/yolov5/issues/2518) and [YouTube](https://github.com/ultralytics/yolov5/pull/2752) integrations. | ||
24 | +- **January 5, 2021**: [v4.0 release](https://github.com/ultralytics/yolov5/releases/tag/v4.0): nn.SiLU() activations, [Weights & Biases](https://wandb.ai/site?utm_campaign=repo_yolo_readme) logging, [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/) integration. | ||
25 | +- **August 13, 2020**: [v3.0 release](https://github.com/ultralytics/yolov5/releases/tag/v3.0): nn.Hardswish() activations, data autodownload, native AMP. | ||
26 | +- **July 23, 2020**: [v2.0 release](https://github.com/ultralytics/yolov5/releases/tag/v2.0): improved model definition, training and mAP. | ||
27 | + | ||
28 | + | ||
29 | +## Pretrained Checkpoints | ||
30 | + | ||
31 | +[assets]: https://github.com/ultralytics/yolov5/releases | ||
32 | + | ||
33 | +Model |size<br><sup>(pixels) |mAP<sup>val<br>0.5:0.95 |mAP<sup>test<br>0.5:0.95 |mAP<sup>val<br>0.5 |Speed<br><sup>V100 (ms) | |params<br><sup>(M) |FLOPS<br><sup>640 (B) | ||
34 | +--- |--- |--- |--- |--- |--- |---|--- |--- | ||
35 | +[YOLOv5s][assets] |640 |36.7 |36.7 |55.4 |**2.0** | |7.3 |17.0 | ||
36 | +[YOLOv5m][assets] |640 |44.5 |44.5 |63.1 |2.7 | |21.4 |51.3 | ||
37 | +[YOLOv5l][assets] |640 |48.2 |48.2 |66.9 |3.8 | |47.0 |115.4 | ||
38 | +[YOLOv5x][assets] |640 |**50.4** |**50.4** |**68.8** |6.1 | |87.7 |218.8 | ||
39 | +| | | | | | || | | ||
40 | +[YOLOv5s6][assets] |1280 |43.3 |43.3 |61.9 |**4.3** | |12.7 |17.4 | ||
41 | +[YOLOv5m6][assets] |1280 |50.5 |50.5 |68.7 |8.4 | |35.9 |52.4 | ||
42 | +[YOLOv5l6][assets] |1280 |53.4 |53.4 |71.1 |12.3 | |77.2 |117.7 | ||
43 | +[YOLOv5x6][assets] |1280 |**54.4** |**54.4** |**72.0** |22.4 | |141.8 |222.9 | ||
44 | +| | | | | | || | | ||
45 | +[YOLOv5x6][assets] TTA |1280 |**55.0** |**55.0** |**72.0** |70.8 | |- |- | ||
46 | + | ||
47 | +<details> | ||
48 | + <summary>Table Notes (click to expand)</summary> | ||
49 | + | ||
50 | + * AP<sup>test</sup> denotes COCO [test-dev2017](http://cocodataset.org/#upload) server results, all other AP results denote val2017 accuracy. | ||
51 | + * AP values are for single-model single-scale unless otherwise noted. **Reproduce mAP** by `python test.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65` | ||
52 | + * Speed<sub>GPU</sub> averaged over 5000 COCO val2017 images using a GCP [n1-standard-16](https://cloud.google.com/compute/docs/machine-types#n1_standard_machine_types) V100 instance, and includes FP16 inference, postprocessing and NMS. **Reproduce speed** by `python test.py --data coco.yaml --img 640 --conf 0.25 --iou 0.45` | ||
53 | + * All checkpoints are trained to 300 epochs with default settings and hyperparameters (no autoaugmentation). | ||
54 | + * Test Time Augmentation ([TTA](https://github.com/ultralytics/yolov5/issues/303)) includes reflection and scale augmentation. **Reproduce TTA** by `python test.py --data coco.yaml --img 1536 --iou 0.7 --augment` | ||
55 | +</details> | ||
56 | + | ||
57 | + | ||
58 | +## Requirements | ||
59 | + | ||
60 | +Python 3.8 or later with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) dependencies installed, including `torch>=1.7`. To install run: | ||
61 | +<!-- $ sudo apt update && apt install -y libgl1-mesa-glx libsm6 libxext6 libxrender-dev --> | ||
62 | +```bash | ||
63 | +$ pip install -r requirements.txt | ||
64 | +``` | ||
65 | + | ||
66 | + | ||
67 | +## Tutorials | ||
68 | + | ||
69 | +* [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 🚀 RECOMMENDED | ||
70 | +* [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results) ☘️ RECOMMENDED | ||
71 | +* [Weights & Biases Logging](https://github.com/ultralytics/yolov5/issues/1289) 🌟 NEW | ||
72 | +* [Supervisely Ecosystem](https://github.com/ultralytics/yolov5/issues/2518) 🌟 NEW | ||
73 | +* [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475) | ||
74 | +* [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) ⭐ NEW | ||
75 | +* [TorchScript, ONNX, CoreML Export](https://github.com/ultralytics/yolov5/issues/251) 🚀 | ||
76 | +* [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303) | ||
77 | +* [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318) | ||
78 | +* [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304) | ||
79 | +* [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607) | ||
80 | +* [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314) ⭐ NEW | ||
81 | +* [TensorRT Deployment](https://github.com/wang-xinyu/tensorrtx) | ||
82 | + | ||
83 | + | ||
84 | +## Environments | ||
85 | + | ||
86 | +YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): | ||
87 | + | ||
88 | +- **Google Colab and Kaggle** notebooks with free GPU: <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> <a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a> | ||
89 | +- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) | ||
90 | +- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) | ||
91 | +- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) <a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a> | ||
92 | + | ||
93 | + | ||
94 | +## Inference | ||
95 | + | ||
96 | +`detect.py` runs inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`. | ||
97 | +```bash | ||
98 | +$ python detect.py --source 0 # webcam | ||
99 | + file.jpg # image | ||
100 | + file.mp4 # video | ||
101 | + path/ # directory | ||
102 | + path/*.jpg # glob | ||
103 | + 'https://youtu.be/NUsoVlDFqZg' # YouTube video | ||
104 | + 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream | ||
105 | +``` | ||
106 | + | ||
107 | +To run inference on example images in `data/images`: | ||
108 | +```bash | ||
109 | +$ python detect.py --source data/images --weights yolov5s.pt --conf 0.25 | ||
110 | + | ||
111 | +Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.25, device='', exist_ok=False, img_size=640, iou_thres=0.45, name='exp', project='runs/detect', save_conf=False, save_txt=False, source='data/images/', update=False, view_img=False, weights=['yolov5s.pt']) | ||
112 | +YOLOv5 v4.0-96-g83dc1b4 torch 1.7.0+cu101 CUDA:0 (Tesla V100-SXM2-16GB, 16160.5MB) | ||
113 | + | ||
114 | +Fusing layers... | ||
115 | +Model Summary: 224 layers, 7266973 parameters, 0 gradients, 17.0 GFLOPS | ||
116 | +image 1/2 /content/yolov5/data/images/bus.jpg: 640x480 4 persons, 1 bus, Done. (0.010s) | ||
117 | +image 2/2 /content/yolov5/data/images/zidane.jpg: 384x640 2 persons, 1 tie, Done. (0.011s) | ||
118 | +Results saved to runs/detect/exp2 | ||
119 | +Done. (0.103s) | ||
120 | +``` | ||
121 | +<img width="500" src="https://user-images.githubusercontent.com/26833433/97107365-685a8d80-16c7-11eb-8c2e-83aac701d8b9.jpeg"> | ||
122 | + | ||
123 | +### PyTorch Hub | ||
124 | + | ||
125 | +Inference with YOLOv5 and [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36): | ||
126 | +```python | ||
127 | +import torch | ||
128 | + | ||
129 | +# Model | ||
130 | +model = torch.hub.load('ultralytics/yolov5', 'yolov5s') | ||
131 | + | ||
132 | +# Image | ||
133 | +img = 'https://ultralytics.com/images/zidane.jpg' | ||
134 | + | ||
135 | +# Inference | ||
136 | +results = model(img) | ||
137 | +results.print() # or .show(), .save() | ||
138 | +``` | ||
139 | + | ||
140 | + | ||
141 | +## Training | ||
142 | + | ||
143 | +Run commands below to reproduce results on [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) dataset (dataset auto-downloads on first use). Training times for YOLOv5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). Use the largest `--batch-size` your GPU allows (batch sizes shown for 16 GB devices). | ||
144 | +```bash | ||
145 | +$ python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64 | ||
146 | + yolov5m 40 | ||
147 | + yolov5l 24 | ||
148 | + yolov5x 16 | ||
149 | +``` | ||
150 | +<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png"> | ||
151 | + | ||
152 | + | ||
153 | +## Citation | ||
154 | + | ||
155 | +[![DOI](https://zenodo.org/badge/264818686.svg)](https://zenodo.org/badge/latestdoi/264818686) | ||
156 | + | ||
157 | + | ||
158 | +## About Us | ||
159 | + | ||
160 | +Ultralytics is a U.S.-based particle physics and AI startup with over 6 years of expertise supporting government, academic and business clients. We offer a wide range of vision AI services, spanning from simple expert advice up to delivery of fully customized, end-to-end production solutions, including: | ||
161 | +- **Cloud-based AI** systems operating on **hundreds of HD video streams in realtime.** | ||
162 | +- **Edge AI** integrated into custom iOS and Android apps for realtime **30 FPS video inference.** | ||
163 | +- **Custom data training**, hyperparameter evolution, and model exportation to any destination. | ||
164 | + | ||
165 | +For business inquiries and professional support requests please visit us at https://ultralytics.com. | ||
166 | + | ||
167 | + | ||
168 | +## Contact | ||
169 | + | ||
170 | +**Issues should be raised directly in the repository.** For business inquiries or professional support requests please visit https://ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com. |
YOLOv5/__init__.py
0 → 100644
File mode changed
YOLOv5/detect.py
0 → 100644
1 | +import argparse | ||
2 | +import time | ||
3 | +from pathlib import Path | ||
4 | + | ||
5 | +import cv2 | ||
6 | +import torch | ||
7 | +import torch.backends.cudnn as cudnn | ||
8 | + | ||
9 | +from models.experimental import attempt_load | ||
10 | +from utils.datasets import LoadStreams, LoadImages | ||
11 | +from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \ | ||
12 | + scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box | ||
13 | +from utils.plots import colors, plot_one_box | ||
14 | +from utils.torch_utils import select_device, load_classifier, time_synchronized | ||
15 | + | ||
16 | + | ||
17 | +@torch.no_grad() | ||
18 | +def detect(opt): | ||
19 | + # source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size | ||
20 | + source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, True, opt.img_size | ||
21 | + save_img = not opt.nosave and not source.endswith('.txt') # save inference images | ||
22 | + webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( | ||
23 | + ('rtsp://', 'rtmp://', 'http://', 'https://')) | ||
24 | + | ||
25 | + # Directories | ||
26 | + save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run | ||
27 | + (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir | ||
28 | + | ||
29 | + # Initialize | ||
30 | + set_logging() | ||
31 | + device = select_device(opt.device) | ||
32 | + half = device.type != 'cpu' # half precision only supported on CUDA | ||
33 | + | ||
34 | + # Load model | ||
35 | + model = attempt_load(weights, map_location=device) # load FP32 model | ||
36 | + stride = int(model.stride.max()) # model stride | ||
37 | + imgsz = check_img_size(imgsz, s=stride) # check img_size | ||
38 | + names = model.module.names if hasattr(model, 'module') else model.names # get class names | ||
39 | + if half: | ||
40 | + model.half() # to FP16 | ||
41 | + | ||
42 | + # Second-stage classifier | ||
43 | + classify = False | ||
44 | + if classify: | ||
45 | + modelc = load_classifier(name='resnet101', n=2) # initialize | ||
46 | + modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval() | ||
47 | + | ||
48 | + # Set Dataloader | ||
49 | + vid_path, vid_writer = None, None | ||
50 | + if webcam: | ||
51 | + view_img = check_imshow() | ||
52 | + cudnn.benchmark = True # set True to speed up constant image size inference | ||
53 | + dataset = LoadStreams(source, img_size=imgsz, stride=stride) | ||
54 | + else: | ||
55 | + dataset = LoadImages(source, img_size=imgsz, stride=stride) | ||
56 | + | ||
57 | + # Run inference | ||
58 | + if device.type != 'cpu': | ||
59 | + model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once | ||
60 | + t0 = time.time() | ||
61 | + for path, img, im0s, vid_cap in dataset: | ||
62 | + img = torch.from_numpy(img).to(device) | ||
63 | + img = img.half() if half else img.float() # uint8 to fp16/32 | ||
64 | + img /= 255.0 # 0 - 255 to 0.0 - 1.0 | ||
65 | + if img.ndimension() == 3: | ||
66 | + img = img.unsqueeze(0) | ||
67 | + | ||
68 | + # Inference | ||
69 | + t1 = time_synchronized() | ||
70 | + pred = model(img, augment=opt.augment)[0] | ||
71 | + | ||
72 | + # Apply NMS | ||
73 | + pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, opt.classes, opt.agnostic_nms, | ||
74 | + max_det=opt.max_det) | ||
75 | + t2 = time_synchronized() | ||
76 | + | ||
77 | + # Apply Classifier | ||
78 | + if classify: | ||
79 | + pred = apply_classifier(pred, modelc, img, im0s) | ||
80 | + | ||
81 | + # Process detections | ||
82 | + for i, det in enumerate(pred): # detections per image | ||
83 | + if webcam: # batch_size >= 1 | ||
84 | + p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count | ||
85 | + else: | ||
86 | + p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) | ||
87 | + | ||
88 | + p = Path(p) # to Path | ||
89 | + save_path = str(save_dir / p.name) # img.jpg | ||
90 | + txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt | ||
91 | + s += '%gx%g ' % img.shape[2:] # print string | ||
92 | + gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh | ||
93 | + imc = im0.copy() if opt.save_crop else im0 # for opt.save_crop | ||
94 | + if len(det): | ||
95 | + # Rescale boxes from img_size to im0 size | ||
96 | + det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() | ||
97 | + | ||
98 | + # Print results | ||
99 | + for c in det[:, -1].unique(): | ||
100 | + n = (det[:, -1] == c).sum() # detections per class | ||
101 | + s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string | ||
102 | + | ||
103 | + # Write results | ||
104 | + for *xyxy, conf, cls in reversed(det): | ||
105 | + if save_txt: # Write to file | ||
106 | + | ||
107 | + # print("+++++++++++++++++++++++++++++++++") | ||
108 | + # print(torch.tensor(xyxy)) | ||
109 | + # print("+++++++++++++++++++++++++++++++++") | ||
110 | + | ||
111 | + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh | ||
112 | + | ||
113 | + # print("+++++++++++++++++++++++++++++++++") | ||
114 | + # print(xywh) | ||
115 | + # print("+++++++++++++++++++++++++++++++++") | ||
116 | + | ||
117 | + line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format | ||
118 | + with open(txt_path + '.txt', 'a') as f: | ||
119 | + f.write(('%g ' * len(line)).rstrip() % line + '\n') | ||
120 | + | ||
121 | + if save_img or opt.save_crop or view_img: # Add bbox to image | ||
122 | + c = int(cls) # integer class | ||
123 | + label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}') | ||
124 | + plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness) | ||
125 | + # if opt.save_crop: | ||
126 | + save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) | ||
127 | + | ||
128 | + # Print time (inference + NMS) | ||
129 | + print(f'{s}Done. ({t2 - t1:.3f}s)') | ||
130 | + | ||
131 | + # Stream results | ||
132 | + if view_img: | ||
133 | + cv2.imshow(str(p), im0) | ||
134 | + cv2.waitKey(1) # 1 millisecond | ||
135 | + | ||
136 | + # Save results (image with detections) | ||
137 | + if save_img: | ||
138 | + if dataset.mode == 'image': | ||
139 | + cv2.imwrite(save_path, im0) | ||
140 | + else: # 'video' or 'stream' | ||
141 | + if vid_path != save_path: # new video | ||
142 | + vid_path = save_path | ||
143 | + if isinstance(vid_writer, cv2.VideoWriter): | ||
144 | + vid_writer.release() # release previous video writer | ||
145 | + if vid_cap: # video | ||
146 | + fps = vid_cap.get(cv2.CAP_PROP_FPS) | ||
147 | + w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | ||
148 | + h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | ||
149 | + else: # stream | ||
150 | + fps, w, h = 30, im0.shape[1], im0.shape[0] | ||
151 | + save_path += '.mp4' | ||
152 | + vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) | ||
153 | + vid_writer.write(im0) | ||
154 | + | ||
155 | + if save_txt or save_img: | ||
156 | + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' | ||
157 | + print(f"Results saved to {save_dir}{s}") | ||
158 | + | ||
159 | + print(f'Done. ({time.time() - t0:.3f}s)') | ||
160 | + | ||
161 | + | ||
162 | +if __name__ == '__main__': | ||
163 | + parser = argparse.ArgumentParser() | ||
164 | + parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)') | ||
165 | + parser.add_argument('--source', type=str, default='data/images', help='source') # file/folder, 0 for webcam | ||
166 | + parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') | ||
167 | + parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold') | ||
168 | + parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS') | ||
169 | + parser.add_argument('--max-det', type=int, default=1000, help='maximum number of detections per image') | ||
170 | + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') | ||
171 | + parser.add_argument('--view-img', action='store_true', help='display results') | ||
172 | + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') | ||
173 | + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') | ||
174 | + parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') | ||
175 | + parser.add_argument('--nosave', action='store_true', help='do not save images/videos') | ||
176 | + parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') | ||
177 | + parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') | ||
178 | + parser.add_argument('--augment', action='store_true', help='augmented inference') | ||
179 | + parser.add_argument('--update', action='store_true', help='update all models') | ||
180 | + parser.add_argument('--project', default='runs/detect', help='save results to project/name') | ||
181 | + parser.add_argument('--name', default='exp', help='save results to project/name') | ||
182 | + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') | ||
183 | + parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') | ||
184 | + parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') | ||
185 | + parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') | ||
186 | + opt = parser.parse_args() | ||
187 | + print(opt) | ||
188 | + check_requirements(exclude=('tensorboard', 'pycocotools', 'thop')) | ||
189 | + | ||
190 | + if opt.update: # update all models (to fix SourceChangeWarning) | ||
191 | + for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']: | ||
192 | + detect(opt=opt) | ||
193 | + strip_optimizer(opt.weights) | ||
194 | + else: | ||
195 | + detect(opt=opt) |
YOLOv5/hubconf.py
0 → 100644
1 | +"""YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/ | ||
2 | + | ||
3 | +Usage: | ||
4 | + import torch | ||
5 | + model = torch.hub.load('ultralytics/yolov5', 'yolov5s') | ||
6 | +""" | ||
7 | + | ||
8 | +import torch | ||
9 | + | ||
10 | + | ||
11 | +def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
12 | + """Creates a specified YOLOv5 model | ||
13 | + | ||
14 | + Arguments: | ||
15 | + name (str): name of model, i.e. 'yolov5s' | ||
16 | + pretrained (bool): load pretrained weights into the model | ||
17 | + channels (int): number of input channels | ||
18 | + classes (int): number of model classes | ||
19 | + autoshape (bool): apply YOLOv5 .autoshape() wrapper to model | ||
20 | + verbose (bool): print all information to screen | ||
21 | + device (str, torch.device, None): device to use for model parameters | ||
22 | + | ||
23 | + Returns: | ||
24 | + YOLOv5 pytorch model | ||
25 | + """ | ||
26 | + from pathlib import Path | ||
27 | + | ||
28 | + from models.yolo import Model, attempt_load | ||
29 | + from utils.general import check_requirements, set_logging | ||
30 | + from utils.google_utils import attempt_download | ||
31 | + from utils.torch_utils import select_device | ||
32 | + | ||
33 | + check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('tensorboard', 'pycocotools', 'thop')) | ||
34 | + set_logging(verbose=verbose) | ||
35 | + | ||
36 | + fname = Path(name).with_suffix('.pt') # checkpoint filename | ||
37 | + try: | ||
38 | + if pretrained and channels == 3 and classes == 80: | ||
39 | + model = attempt_load(fname, map_location=torch.device('cpu')) # download/load FP32 model | ||
40 | + else: | ||
41 | + cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path | ||
42 | + model = Model(cfg, channels, classes) # create model | ||
43 | + if pretrained: | ||
44 | + ckpt = torch.load(attempt_download(fname), map_location=torch.device('cpu')) # load | ||
45 | + msd = model.state_dict() # model state_dict | ||
46 | + csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32 | ||
47 | + csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter | ||
48 | + model.load_state_dict(csd, strict=False) # load | ||
49 | + if len(ckpt['model'].names) == classes: | ||
50 | + model.names = ckpt['model'].names # set class names attribute | ||
51 | + if autoshape: | ||
52 | + model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS | ||
53 | + device = select_device('0' if torch.cuda.is_available() else 'cpu') if device is None else torch.device(device) | ||
54 | + return model.to(device) | ||
55 | + | ||
56 | + except Exception as e: | ||
57 | + help_url = 'https://github.com/ultralytics/yolov5/issues/36' | ||
58 | + s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url | ||
59 | + raise Exception(s) from e | ||
60 | + | ||
61 | + | ||
62 | +def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None): | ||
63 | + # YOLOv5 custom or local model | ||
64 | + return _create(path, autoshape=autoshape, verbose=verbose, device=device) | ||
65 | + | ||
66 | + | ||
67 | +def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
68 | + # YOLOv5-small model https://github.com/ultralytics/yolov5 | ||
69 | + return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device) | ||
70 | + | ||
71 | + | ||
72 | +def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
73 | + # YOLOv5-medium model https://github.com/ultralytics/yolov5 | ||
74 | + return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device) | ||
75 | + | ||
76 | + | ||
77 | +def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
78 | + # YOLOv5-large model https://github.com/ultralytics/yolov5 | ||
79 | + return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device) | ||
80 | + | ||
81 | + | ||
82 | +def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
83 | + # YOLOv5-xlarge model https://github.com/ultralytics/yolov5 | ||
84 | + return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device) | ||
85 | + | ||
86 | + | ||
87 | +def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
88 | + # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5 | ||
89 | + return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device) | ||
90 | + | ||
91 | + | ||
92 | +def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
93 | + # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5 | ||
94 | + return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device) | ||
95 | + | ||
96 | + | ||
97 | +def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
98 | + # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5 | ||
99 | + return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device) | ||
100 | + | ||
101 | + | ||
102 | +def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): | ||
103 | + # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5 | ||
104 | + return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device) | ||
105 | + | ||
106 | + | ||
107 | +if __name__ == '__main__': | ||
108 | + model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained | ||
109 | + # model = custom(path='path/to/model.pt') # custom | ||
110 | + | ||
111 | + # Verify inference | ||
112 | + import cv2 | ||
113 | + import numpy as np | ||
114 | + from PIL import Image | ||
115 | + | ||
116 | + imgs = ['data/images/zidane.jpg', # filename | ||
117 | + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI | ||
118 | + cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV | ||
119 | + Image.open('data/images/bus.jpg'), # PIL | ||
120 | + np.zeros((320, 640, 3))] # numpy | ||
121 | + | ||
122 | + results = model(imgs) # batched inference | ||
123 | + results.print() | ||
124 | + results.save() |
YOLOv5/models/__init__.py
0 → 100644
File mode changed
YOLOv5/models/common.py
0 → 100644
1 | +# YOLOv5 common modules | ||
2 | + | ||
3 | +import math | ||
4 | +from copy import copy | ||
5 | +from pathlib import Path | ||
6 | + | ||
7 | +import numpy as np | ||
8 | +import pandas as pd | ||
9 | +import requests | ||
10 | +import torch | ||
11 | +import torch.nn as nn | ||
12 | +from PIL import Image | ||
13 | +from torch.cuda import amp | ||
14 | + | ||
15 | +from utils.datasets import letterbox | ||
16 | +from utils.general import non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh, save_one_box | ||
17 | +from utils.plots import colors, plot_one_box | ||
18 | +from utils.torch_utils import time_synchronized | ||
19 | + | ||
20 | + | ||
21 | +def autopad(k, p=None): # kernel, padding | ||
22 | + # Pad to 'same' | ||
23 | + if p is None: | ||
24 | + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad | ||
25 | + return p | ||
26 | + | ||
27 | + | ||
28 | +def DWConv(c1, c2, k=1, s=1, act=True): | ||
29 | + # Depthwise convolution | ||
30 | + return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) | ||
31 | + | ||
32 | + | ||
33 | +class Conv(nn.Module): | ||
34 | + # Standard convolution | ||
35 | + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups | ||
36 | + super(Conv, self).__init__() | ||
37 | + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) | ||
38 | + self.bn = nn.BatchNorm2d(c2) | ||
39 | + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) | ||
40 | + | ||
41 | + def forward(self, x): | ||
42 | + return self.act(self.bn(self.conv(x))) | ||
43 | + | ||
44 | + def fuseforward(self, x): | ||
45 | + return self.act(self.conv(x)) | ||
46 | + | ||
47 | + | ||
48 | +class TransformerLayer(nn.Module): | ||
49 | + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) | ||
50 | + def __init__(self, c, num_heads): | ||
51 | + super().__init__() | ||
52 | + self.q = nn.Linear(c, c, bias=False) | ||
53 | + self.k = nn.Linear(c, c, bias=False) | ||
54 | + self.v = nn.Linear(c, c, bias=False) | ||
55 | + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) | ||
56 | + self.fc1 = nn.Linear(c, c, bias=False) | ||
57 | + self.fc2 = nn.Linear(c, c, bias=False) | ||
58 | + | ||
59 | + def forward(self, x): | ||
60 | + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x | ||
61 | + x = self.fc2(self.fc1(x)) + x | ||
62 | + return x | ||
63 | + | ||
64 | + | ||
65 | +class TransformerBlock(nn.Module): | ||
66 | + # Vision Transformer https://arxiv.org/abs/2010.11929 | ||
67 | + def __init__(self, c1, c2, num_heads, num_layers): | ||
68 | + super().__init__() | ||
69 | + self.conv = None | ||
70 | + if c1 != c2: | ||
71 | + self.conv = Conv(c1, c2) | ||
72 | + self.linear = nn.Linear(c2, c2) # learnable position embedding | ||
73 | + self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)]) | ||
74 | + self.c2 = c2 | ||
75 | + | ||
76 | + def forward(self, x): | ||
77 | + if self.conv is not None: | ||
78 | + x = self.conv(x) | ||
79 | + b, _, w, h = x.shape | ||
80 | + p = x.flatten(2) | ||
81 | + p = p.unsqueeze(0) | ||
82 | + p = p.transpose(0, 3) | ||
83 | + p = p.squeeze(3) | ||
84 | + e = self.linear(p) | ||
85 | + x = p + e | ||
86 | + | ||
87 | + x = self.tr(x) | ||
88 | + x = x.unsqueeze(3) | ||
89 | + x = x.transpose(0, 3) | ||
90 | + x = x.reshape(b, self.c2, w, h) | ||
91 | + return x | ||
92 | + | ||
93 | + | ||
94 | +class Bottleneck(nn.Module): | ||
95 | + # Standard bottleneck | ||
96 | + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion | ||
97 | + super(Bottleneck, self).__init__() | ||
98 | + c_ = int(c2 * e) # hidden channels | ||
99 | + self.cv1 = Conv(c1, c_, 1, 1) | ||
100 | + self.cv2 = Conv(c_, c2, 3, 1, g=g) | ||
101 | + self.add = shortcut and c1 == c2 | ||
102 | + | ||
103 | + def forward(self, x): | ||
104 | + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) | ||
105 | + | ||
106 | + | ||
107 | +class BottleneckCSP(nn.Module): | ||
108 | + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks | ||
109 | + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion | ||
110 | + super(BottleneckCSP, self).__init__() | ||
111 | + c_ = int(c2 * e) # hidden channels | ||
112 | + self.cv1 = Conv(c1, c_, 1, 1) | ||
113 | + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) | ||
114 | + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) | ||
115 | + self.cv4 = Conv(2 * c_, c2, 1, 1) | ||
116 | + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) | ||
117 | + self.act = nn.LeakyReLU(0.1, inplace=True) | ||
118 | + self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) | ||
119 | + | ||
120 | + def forward(self, x): | ||
121 | + y1 = self.cv3(self.m(self.cv1(x))) | ||
122 | + y2 = self.cv2(x) | ||
123 | + return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) | ||
124 | + | ||
125 | + | ||
126 | +class C3(nn.Module): | ||
127 | + # CSP Bottleneck with 3 convolutions | ||
128 | + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion | ||
129 | + super(C3, self).__init__() | ||
130 | + c_ = int(c2 * e) # hidden channels | ||
131 | + self.cv1 = Conv(c1, c_, 1, 1) | ||
132 | + self.cv2 = Conv(c1, c_, 1, 1) | ||
133 | + self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2) | ||
134 | + self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) | ||
135 | + # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)]) | ||
136 | + | ||
137 | + def forward(self, x): | ||
138 | + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)) | ||
139 | + | ||
140 | + | ||
141 | +class C3TR(C3): | ||
142 | + # C3 module with TransformerBlock() | ||
143 | + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): | ||
144 | + super().__init__(c1, c2, n, shortcut, g, e) | ||
145 | + c_ = int(c2 * e) | ||
146 | + self.m = TransformerBlock(c_, c_, 4, n) | ||
147 | + | ||
148 | + | ||
149 | +class SPP(nn.Module): | ||
150 | + # Spatial pyramid pooling layer used in YOLOv3-SPP | ||
151 | + def __init__(self, c1, c2, k=(5, 9, 13)): | ||
152 | + super(SPP, self).__init__() | ||
153 | + c_ = c1 // 2 # hidden channels | ||
154 | + self.cv1 = Conv(c1, c_, 1, 1) | ||
155 | + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) | ||
156 | + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) | ||
157 | + | ||
158 | + def forward(self, x): | ||
159 | + x = self.cv1(x) | ||
160 | + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) | ||
161 | + | ||
162 | + | ||
163 | +class Focus(nn.Module): | ||
164 | + # Focus wh information into c-space | ||
165 | + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups | ||
166 | + super(Focus, self).__init__() | ||
167 | + self.conv = Conv(c1 * 4, c2, k, s, p, g, act) | ||
168 | + # self.contract = Contract(gain=2) | ||
169 | + | ||
170 | + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) | ||
171 | + return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) | ||
172 | + # return self.conv(self.contract(x)) | ||
173 | + | ||
174 | + | ||
175 | +class Contract(nn.Module): | ||
176 | + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) | ||
177 | + def __init__(self, gain=2): | ||
178 | + super().__init__() | ||
179 | + self.gain = gain | ||
180 | + | ||
181 | + def forward(self, x): | ||
182 | + N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain' | ||
183 | + s = self.gain | ||
184 | + x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2) | ||
185 | + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) | ||
186 | + return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40) | ||
187 | + | ||
188 | + | ||
189 | +class Expand(nn.Module): | ||
190 | + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) | ||
191 | + def __init__(self, gain=2): | ||
192 | + super().__init__() | ||
193 | + self.gain = gain | ||
194 | + | ||
195 | + def forward(self, x): | ||
196 | + N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' | ||
197 | + s = self.gain | ||
198 | + x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80) | ||
199 | + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) | ||
200 | + return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160) | ||
201 | + | ||
202 | + | ||
203 | +class Concat(nn.Module): | ||
204 | + # Concatenate a list of tensors along dimension | ||
205 | + def __init__(self, dimension=1): | ||
206 | + super(Concat, self).__init__() | ||
207 | + self.d = dimension | ||
208 | + | ||
209 | + def forward(self, x): | ||
210 | + return torch.cat(x, self.d) | ||
211 | + | ||
212 | + | ||
213 | +class NMS(nn.Module): | ||
214 | + # Non-Maximum Suppression (NMS) module | ||
215 | + conf = 0.25 # confidence threshold | ||
216 | + iou = 0.45 # IoU threshold | ||
217 | + classes = None # (optional list) filter by class | ||
218 | + max_det = 1000 # maximum number of detections per image | ||
219 | + | ||
220 | + def __init__(self): | ||
221 | + super(NMS, self).__init__() | ||
222 | + | ||
223 | + def forward(self, x): | ||
224 | + return non_max_suppression(x[0], self.conf, iou_thres=self.iou, classes=self.classes, max_det=self.max_det) | ||
225 | + | ||
226 | + | ||
227 | +class AutoShape(nn.Module): | ||
228 | + # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS | ||
229 | + conf = 0.25 # NMS confidence threshold | ||
230 | + iou = 0.45 # NMS IoU threshold | ||
231 | + classes = None # (optional list) filter by class | ||
232 | + max_det = 1000 # maximum number of detections per image | ||
233 | + | ||
234 | + def __init__(self, model): | ||
235 | + super(AutoShape, self).__init__() | ||
236 | + self.model = model.eval() | ||
237 | + | ||
238 | + def autoshape(self): | ||
239 | + print('AutoShape already enabled, skipping... ') # model already converted to model.autoshape() | ||
240 | + return self | ||
241 | + | ||
242 | + @torch.no_grad() | ||
243 | + def forward(self, imgs, size=640, augment=False, profile=False): | ||
244 | + # Inference from various sources. For height=640, width=1280, RGB images example inputs are: | ||
245 | + # filename: imgs = 'data/images/zidane.jpg' | ||
246 | + # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg' | ||
247 | + # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3) | ||
248 | + # PIL: = Image.open('image.jpg') # HWC x(640,1280,3) | ||
249 | + # numpy: = np.zeros((640,1280,3)) # HWC | ||
250 | + # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values) | ||
251 | + # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images | ||
252 | + | ||
253 | + t = [time_synchronized()] | ||
254 | + p = next(self.model.parameters()) # for device and type | ||
255 | + if isinstance(imgs, torch.Tensor): # torch | ||
256 | + with amp.autocast(enabled=p.device.type != 'cpu'): | ||
257 | + return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference | ||
258 | + | ||
259 | + # Pre-process | ||
260 | + n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images | ||
261 | + shape0, shape1, files = [], [], [] # image and inference shapes, filenames | ||
262 | + for i, im in enumerate(imgs): | ||
263 | + f = f'image{i}' # filename | ||
264 | + if isinstance(im, str): # filename or uri | ||
265 | + im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)), im | ||
266 | + elif isinstance(im, Image.Image): # PIL Image | ||
267 | + im, f = np.asarray(im), getattr(im, 'filename', f) or f | ||
268 | + files.append(Path(f).with_suffix('.jpg').name) | ||
269 | + if im.shape[0] < 5: # image in CHW | ||
270 | + im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) | ||
271 | + im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input | ||
272 | + s = im.shape[:2] # HWC | ||
273 | + shape0.append(s) # image shape | ||
274 | + g = (size / max(s)) # gain | ||
275 | + shape1.append([y * g for y in s]) | ||
276 | + imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update | ||
277 | + shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape | ||
278 | + x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad | ||
279 | + x = np.stack(x, 0) if n > 1 else x[0][None] # stack | ||
280 | + x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW | ||
281 | + x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32 | ||
282 | + t.append(time_synchronized()) | ||
283 | + | ||
284 | + with amp.autocast(enabled=p.device.type != 'cpu'): | ||
285 | + # Inference | ||
286 | + y = self.model(x, augment, profile)[0] # forward | ||
287 | + t.append(time_synchronized()) | ||
288 | + | ||
289 | + # Post-process | ||
290 | + y = non_max_suppression(y, self.conf, iou_thres=self.iou, classes=self.classes, max_det=self.max_det) # NMS | ||
291 | + for i in range(n): | ||
292 | + scale_coords(shape1, y[i][:, :4], shape0[i]) | ||
293 | + | ||
294 | + t.append(time_synchronized()) | ||
295 | + return Detections(imgs, y, files, t, self.names, x.shape) | ||
296 | + | ||
297 | + | ||
298 | +class Detections: | ||
299 | + # detections class for YOLOv5 inference results | ||
300 | + def __init__(self, imgs, pred, files, times=None, names=None, shape=None): | ||
301 | + super(Detections, self).__init__() | ||
302 | + d = pred[0].device # device | ||
303 | + gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations | ||
304 | + self.imgs = imgs # list of images as numpy arrays | ||
305 | + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) | ||
306 | + self.names = names # class names | ||
307 | + self.files = files # image filenames | ||
308 | + self.xyxy = pred # xyxy pixels | ||
309 | + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels | ||
310 | + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized | ||
311 | + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized | ||
312 | + self.n = len(self.pred) # number of images (batch size) | ||
313 | + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms) | ||
314 | + self.s = shape # inference BCHW shape | ||
315 | + | ||
316 | + def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')): | ||
317 | + for i, (im, pred) in enumerate(zip(self.imgs, self.pred)): | ||
318 | + str = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' | ||
319 | + if pred is not None: | ||
320 | + for c in pred[:, -1].unique(): | ||
321 | + n = (pred[:, -1] == c).sum() # detections per class | ||
322 | + str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string | ||
323 | + if show or save or render or crop: | ||
324 | + for *box, conf, cls in pred: # xyxy, confidence, class | ||
325 | + label = f'{self.names[int(cls)]} {conf:.2f}' | ||
326 | + if crop: | ||
327 | + save_one_box(box, im, file=save_dir / 'crops' / self.names[int(cls)] / self.files[i]) | ||
328 | + else: # all others | ||
329 | + plot_one_box(box, im, label=label, color=colors(cls)) | ||
330 | + | ||
331 | + im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np | ||
332 | + if pprint: | ||
333 | + print(str.rstrip(', ')) | ||
334 | + if show: | ||
335 | + im.show(self.files[i]) # show | ||
336 | + if save: | ||
337 | + f = self.files[i] | ||
338 | + im.save(save_dir / f) # save | ||
339 | + print(f"{'Saved' * (i == 0)} {f}", end=',' if i < self.n - 1 else f' to {save_dir}\n') | ||
340 | + if render: | ||
341 | + self.imgs[i] = np.asarray(im) | ||
342 | + | ||
343 | + def print(self): | ||
344 | + self.display(pprint=True) # print results | ||
345 | + print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t) | ||
346 | + | ||
347 | + def show(self): | ||
348 | + self.display(show=True) # show results | ||
349 | + | ||
350 | + def save(self, save_dir='runs/hub/exp'): | ||
351 | + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp', mkdir=True) # increment save_dir | ||
352 | + self.display(save=True, save_dir=save_dir) # save results | ||
353 | + | ||
354 | + def crop(self, save_dir='runs/hub/exp'): | ||
355 | + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp', mkdir=True) # increment save_dir | ||
356 | + self.display(crop=True, save_dir=save_dir) # crop results | ||
357 | + print(f'Saved results to {save_dir}\n') | ||
358 | + | ||
359 | + def render(self): | ||
360 | + self.display(render=True) # render results | ||
361 | + return self.imgs | ||
362 | + | ||
363 | + def pandas(self): | ||
364 | + # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]) | ||
365 | + new = copy(self) # return copy | ||
366 | + ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns | ||
367 | + cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns | ||
368 | + for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]): | ||
369 | + a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update | ||
370 | + setattr(new, k, [pd.DataFrame(x, columns=c) for x in a]) | ||
371 | + return new | ||
372 | + | ||
373 | + def tolist(self): | ||
374 | + # return a list of Detections objects, i.e. 'for result in results.tolist():' | ||
375 | + x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)] | ||
376 | + for d in x: | ||
377 | + for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: | ||
378 | + setattr(d, k, getattr(d, k)[0]) # pop out of list | ||
379 | + return x | ||
380 | + | ||
381 | + def __len__(self): | ||
382 | + return self.n | ||
383 | + | ||
384 | + | ||
385 | +class Classify(nn.Module): | ||
386 | + # Classification head, i.e. x(b,c1,20,20) to x(b,c2) | ||
387 | + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups | ||
388 | + super(Classify, self).__init__() | ||
389 | + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) | ||
390 | + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) | ||
391 | + self.flat = nn.Flatten() | ||
392 | + | ||
393 | + def forward(self, x): | ||
394 | + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list | ||
395 | + return self.flat(self.conv(z)) # flatten to x(b,c2) |
YOLOv5/models/experimental.py
0 → 100644
1 | +# YOLOv5 experimental modules | ||
2 | + | ||
3 | +import numpy as np | ||
4 | +import torch | ||
5 | +import torch.nn as nn | ||
6 | + | ||
7 | +from models.common import Conv, DWConv | ||
8 | +from utils.google_utils import attempt_download | ||
9 | + | ||
10 | + | ||
11 | +class CrossConv(nn.Module): | ||
12 | + # Cross Convolution Downsample | ||
13 | + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): | ||
14 | + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut | ||
15 | + super(CrossConv, self).__init__() | ||
16 | + c_ = int(c2 * e) # hidden channels | ||
17 | + self.cv1 = Conv(c1, c_, (1, k), (1, s)) | ||
18 | + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) | ||
19 | + self.add = shortcut and c1 == c2 | ||
20 | + | ||
21 | + def forward(self, x): | ||
22 | + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) | ||
23 | + | ||
24 | + | ||
25 | +class Sum(nn.Module): | ||
26 | + # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 | ||
27 | + def __init__(self, n, weight=False): # n: number of inputs | ||
28 | + super(Sum, self).__init__() | ||
29 | + self.weight = weight # apply weights boolean | ||
30 | + self.iter = range(n - 1) # iter object | ||
31 | + if weight: | ||
32 | + self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights | ||
33 | + | ||
34 | + def forward(self, x): | ||
35 | + y = x[0] # no weight | ||
36 | + if self.weight: | ||
37 | + w = torch.sigmoid(self.w) * 2 | ||
38 | + for i in self.iter: | ||
39 | + y = y + x[i + 1] * w[i] | ||
40 | + else: | ||
41 | + for i in self.iter: | ||
42 | + y = y + x[i + 1] | ||
43 | + return y | ||
44 | + | ||
45 | + | ||
46 | +class GhostConv(nn.Module): | ||
47 | + # Ghost Convolution https://github.com/huawei-noah/ghostnet | ||
48 | + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups | ||
49 | + super(GhostConv, self).__init__() | ||
50 | + c_ = c2 // 2 # hidden channels | ||
51 | + self.cv1 = Conv(c1, c_, k, s, None, g, act) | ||
52 | + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) | ||
53 | + | ||
54 | + def forward(self, x): | ||
55 | + y = self.cv1(x) | ||
56 | + return torch.cat([y, self.cv2(y)], 1) | ||
57 | + | ||
58 | + | ||
59 | +class GhostBottleneck(nn.Module): | ||
60 | + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet | ||
61 | + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride | ||
62 | + super(GhostBottleneck, self).__init__() | ||
63 | + c_ = c2 // 2 | ||
64 | + self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw | ||
65 | + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw | ||
66 | + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear | ||
67 | + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), | ||
68 | + Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() | ||
69 | + | ||
70 | + def forward(self, x): | ||
71 | + return self.conv(x) + self.shortcut(x) | ||
72 | + | ||
73 | + | ||
74 | +class MixConv2d(nn.Module): | ||
75 | + # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 | ||
76 | + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): | ||
77 | + super(MixConv2d, self).__init__() | ||
78 | + groups = len(k) | ||
79 | + if equal_ch: # equal c_ per group | ||
80 | + i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices | ||
81 | + c_ = [(i == g).sum() for g in range(groups)] # intermediate channels | ||
82 | + else: # equal weight.numel() per group | ||
83 | + b = [c2] + [0] * groups | ||
84 | + a = np.eye(groups + 1, groups, k=-1) | ||
85 | + a -= np.roll(a, 1, axis=1) | ||
86 | + a *= np.array(k) ** 2 | ||
87 | + a[0] = 1 | ||
88 | + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b | ||
89 | + | ||
90 | + self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) | ||
91 | + self.bn = nn.BatchNorm2d(c2) | ||
92 | + self.act = nn.LeakyReLU(0.1, inplace=True) | ||
93 | + | ||
94 | + def forward(self, x): | ||
95 | + return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) | ||
96 | + | ||
97 | + | ||
98 | +class Ensemble(nn.ModuleList): | ||
99 | + # Ensemble of models | ||
100 | + def __init__(self): | ||
101 | + super(Ensemble, self).__init__() | ||
102 | + | ||
103 | + def forward(self, x, augment=False): | ||
104 | + y = [] | ||
105 | + for module in self: | ||
106 | + y.append(module(x, augment)[0]) | ||
107 | + # y = torch.stack(y).max(0)[0] # max ensemble | ||
108 | + # y = torch.stack(y).mean(0) # mean ensemble | ||
109 | + y = torch.cat(y, 1) # nms ensemble | ||
110 | + return y, None # inference, train output | ||
111 | + | ||
112 | + | ||
113 | +def attempt_load(weights, map_location=None, inplace=True): | ||
114 | + from models.yolo import Detect, Model | ||
115 | + | ||
116 | + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a | ||
117 | + model = Ensemble() | ||
118 | + for w in weights if isinstance(weights, list) else [weights]: | ||
119 | + ckpt = torch.load(attempt_download(w), map_location=map_location) # load | ||
120 | + model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model | ||
121 | + | ||
122 | + # Compatibility updates | ||
123 | + for m in model.modules(): | ||
124 | + if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]: | ||
125 | + m.inplace = inplace # pytorch 1.7.0 compatibility | ||
126 | + elif type(m) is Conv: | ||
127 | + m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility | ||
128 | + | ||
129 | + if len(model) == 1: | ||
130 | + return model[-1] # return model | ||
131 | + else: | ||
132 | + print(f'Ensemble created with {weights}\n') | ||
133 | + for k in ['names']: | ||
134 | + setattr(model, k, getattr(model[-1], k)) | ||
135 | + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride | ||
136 | + return model # return ensemble |
YOLOv5/models/export.py
0 → 100644
1 | +"""Exports a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats | ||
2 | + | ||
3 | +Usage: | ||
4 | + $ python path/to/models/export.py --weights yolov5s.pt --img 640 --batch 1 | ||
5 | +""" | ||
6 | + | ||
7 | +import argparse | ||
8 | +import sys | ||
9 | +import time | ||
10 | +from pathlib import Path | ||
11 | + | ||
12 | +sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories | ||
13 | + | ||
14 | +import torch | ||
15 | +import torch.nn as nn | ||
16 | +from torch.utils.mobile_optimizer import optimize_for_mobile | ||
17 | + | ||
18 | +import models | ||
19 | +from models.experimental import attempt_load | ||
20 | +from utils.activations import Hardswish, SiLU | ||
21 | +from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging | ||
22 | +from utils.torch_utils import select_device | ||
23 | + | ||
24 | +if __name__ == '__main__': | ||
25 | + parser = argparse.ArgumentParser() | ||
26 | + parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') | ||
27 | + parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width | ||
28 | + parser.add_argument('--batch-size', type=int, default=1, help='batch size') | ||
29 | + parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') | ||
30 | + parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats') | ||
31 | + parser.add_argument('--half', action='store_true', help='FP16 half-precision export') | ||
32 | + parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') | ||
33 | + parser.add_argument('--train', action='store_true', help='model.train() mode') | ||
34 | + parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only | ||
35 | + parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only | ||
36 | + parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only | ||
37 | + parser.add_argument('--opset-version', type=int, default=12, help='ONNX opset version') # ONNX-only | ||
38 | + opt = parser.parse_args() | ||
39 | + opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand | ||
40 | + opt.include = [x.lower() for x in opt.include] | ||
41 | + print(opt) | ||
42 | + set_logging() | ||
43 | + t = time.time() | ||
44 | + | ||
45 | + # Load PyTorch model | ||
46 | + device = select_device(opt.device) | ||
47 | + model = attempt_load(opt.weights, map_location=device) # load FP32 model | ||
48 | + labels = model.names | ||
49 | + | ||
50 | + # Checks | ||
51 | + gs = int(max(model.stride)) # grid size (max stride) | ||
52 | + opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples | ||
53 | + assert not (opt.device.lower() == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0' | ||
54 | + | ||
55 | + # Input | ||
56 | + img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection | ||
57 | + | ||
58 | + # Update model | ||
59 | + if opt.half: | ||
60 | + img, model = img.half(), model.half() # to FP16 | ||
61 | + if opt.train: | ||
62 | + model.train() # training mode (no grid construction in Detect layer) | ||
63 | + for k, m in model.named_modules(): | ||
64 | + m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility | ||
65 | + if isinstance(m, models.common.Conv): # assign export-friendly activations | ||
66 | + if isinstance(m.act, nn.Hardswish): | ||
67 | + m.act = Hardswish() | ||
68 | + elif isinstance(m.act, nn.SiLU): | ||
69 | + m.act = SiLU() | ||
70 | + elif isinstance(m, models.yolo.Detect): | ||
71 | + m.inplace = opt.inplace | ||
72 | + m.onnx_dynamic = opt.dynamic | ||
73 | + # m.forward = m.forward_export # assign forward (optional) | ||
74 | + | ||
75 | + for _ in range(2): | ||
76 | + y = model(img) # dry runs | ||
77 | + print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)") | ||
78 | + | ||
79 | + # TorchScript export ----------------------------------------------------------------------------------------------- | ||
80 | + if 'torchscript' in opt.include or 'coreml' in opt.include: | ||
81 | + prefix = colorstr('TorchScript:') | ||
82 | + try: | ||
83 | + print(f'\n{prefix} starting export with torch {torch.__version__}...') | ||
84 | + f = opt.weights.replace('.pt', '.torchscript.pt') # filename | ||
85 | + ts = torch.jit.trace(model, img, strict=False) | ||
86 | + (optimize_for_mobile(ts) if opt.optimize else ts).save(f) | ||
87 | + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') | ||
88 | + except Exception as e: | ||
89 | + print(f'{prefix} export failure: {e}') | ||
90 | + | ||
91 | + # ONNX export ------------------------------------------------------------------------------------------------------ | ||
92 | + if 'onnx' in opt.include: | ||
93 | + prefix = colorstr('ONNX:') | ||
94 | + try: | ||
95 | + import onnx | ||
96 | + | ||
97 | + print(f'{prefix} starting export with onnx {onnx.__version__}...') | ||
98 | + f = opt.weights.replace('.pt', '.onnx') # filename | ||
99 | + torch.onnx.export(model, img, f, verbose=False, opset_version=opt.opset_version, input_names=['images'], | ||
100 | + training=torch.onnx.TrainingMode.TRAINING if opt.train else torch.onnx.TrainingMode.EVAL, | ||
101 | + do_constant_folding=not opt.train, | ||
102 | + dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640) | ||
103 | + 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None) | ||
104 | + | ||
105 | + # Checks | ||
106 | + model_onnx = onnx.load(f) # load onnx model | ||
107 | + onnx.checker.check_model(model_onnx) # check onnx model | ||
108 | + # print(onnx.helper.printable_graph(model_onnx.graph)) # print | ||
109 | + | ||
110 | + # Simplify | ||
111 | + if opt.simplify: | ||
112 | + try: | ||
113 | + check_requirements(['onnx-simplifier']) | ||
114 | + import onnxsim | ||
115 | + | ||
116 | + print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') | ||
117 | + model_onnx, check = onnxsim.simplify( | ||
118 | + model_onnx, | ||
119 | + dynamic_input_shape=opt.dynamic, | ||
120 | + input_shapes={'images': list(img.shape)} if opt.dynamic else None) | ||
121 | + assert check, 'assert check failed' | ||
122 | + onnx.save(model_onnx, f) | ||
123 | + except Exception as e: | ||
124 | + print(f'{prefix} simplifier failure: {e}') | ||
125 | + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') | ||
126 | + except Exception as e: | ||
127 | + print(f'{prefix} export failure: {e}') | ||
128 | + | ||
129 | + # CoreML export ---------------------------------------------------------------------------------------------------- | ||
130 | + if 'coreml' in opt.include: | ||
131 | + prefix = colorstr('CoreML:') | ||
132 | + try: | ||
133 | + import coremltools as ct | ||
134 | + | ||
135 | + print(f'{prefix} starting export with coremltools {ct.__version__}...') | ||
136 | + assert opt.train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`' | ||
137 | + model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) | ||
138 | + f = opt.weights.replace('.pt', '.mlmodel') # filename | ||
139 | + model.save(f) | ||
140 | + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') | ||
141 | + except Exception as e: | ||
142 | + print(f'{prefix} export failure: {e}') | ||
143 | + | ||
144 | + # Finish | ||
145 | + print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.') |
YOLOv5/models/hub/anchors.yaml
0 → 100644
1 | +# Default YOLOv5 anchors for COCO data | ||
2 | + | ||
3 | + | ||
4 | +# P5 ------------------------------------------------------------------------------------------------------------------- | ||
5 | +# P5-640: | ||
6 | +anchors_p5_640: | ||
7 | + - [ 10,13, 16,30, 33,23 ] # P3/8 | ||
8 | + - [ 30,61, 62,45, 59,119 ] # P4/16 | ||
9 | + - [ 116,90, 156,198, 373,326 ] # P5/32 | ||
10 | + | ||
11 | + | ||
12 | +# P6 ------------------------------------------------------------------------------------------------------------------- | ||
13 | +# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 | ||
14 | +anchors_p6_640: | ||
15 | + - [ 9,11, 21,19, 17,41 ] # P3/8 | ||
16 | + - [ 43,32, 39,70, 86,64 ] # P4/16 | ||
17 | + - [ 65,131, 134,130, 120,265 ] # P5/32 | ||
18 | + - [ 282,180, 247,354, 512,387 ] # P6/64 | ||
19 | + | ||
20 | +# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 | ||
21 | +anchors_p6_1280: | ||
22 | + - [ 19,27, 44,40, 38,94 ] # P3/8 | ||
23 | + - [ 96,68, 86,152, 180,137 ] # P4/16 | ||
24 | + - [ 140,301, 303,264, 238,542 ] # P5/32 | ||
25 | + - [ 436,615, 739,380, 925,792 ] # P6/64 | ||
26 | + | ||
27 | +# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 | ||
28 | +anchors_p6_1920: | ||
29 | + - [ 28,41, 67,59, 57,141 ] # P3/8 | ||
30 | + - [ 144,103, 129,227, 270,205 ] # P4/16 | ||
31 | + - [ 209,452, 455,396, 358,812 ] # P5/32 | ||
32 | + - [ 653,922, 1109,570, 1387,1187 ] # P6/64 | ||
33 | + | ||
34 | + | ||
35 | +# P7 ------------------------------------------------------------------------------------------------------------------- | ||
36 | +# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 | ||
37 | +anchors_p7_640: | ||
38 | + - [ 11,11, 13,30, 29,20 ] # P3/8 | ||
39 | + - [ 30,46, 61,38, 39,92 ] # P4/16 | ||
40 | + - [ 78,80, 146,66, 79,163 ] # P5/32 | ||
41 | + - [ 149,150, 321,143, 157,303 ] # P6/64 | ||
42 | + - [ 257,402, 359,290, 524,372 ] # P7/128 | ||
43 | + | ||
44 | +# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 | ||
45 | +anchors_p7_1280: | ||
46 | + - [ 19,22, 54,36, 32,77 ] # P3/8 | ||
47 | + - [ 70,83, 138,71, 75,173 ] # P4/16 | ||
48 | + - [ 165,159, 148,334, 375,151 ] # P5/32 | ||
49 | + - [ 334,317, 251,626, 499,474 ] # P6/64 | ||
50 | + - [ 750,326, 534,814, 1079,818 ] # P7/128 | ||
51 | + | ||
52 | +# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 | ||
53 | +anchors_p7_1920: | ||
54 | + - [ 29,34, 81,55, 47,115 ] # P3/8 | ||
55 | + - [ 105,124, 207,107, 113,259 ] # P4/16 | ||
56 | + - [ 247,238, 222,500, 563,227 ] # P5/32 | ||
57 | + - [ 501,476, 376,939, 749,711 ] # P6/64 | ||
58 | + - [ 1126,489, 801,1222, 1618,1227 ] # P7/128 |
YOLOv5/models/hub/yolov3-spp.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# darknet53 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Conv, [32, 3, 1]], # 0 | ||
16 | + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 | ||
17 | + [-1, 1, Bottleneck, [64]], | ||
18 | + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 | ||
19 | + [-1, 2, Bottleneck, [128]], | ||
20 | + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 | ||
21 | + [-1, 8, Bottleneck, [256]], | ||
22 | + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 | ||
23 | + [-1, 8, Bottleneck, [512]], | ||
24 | + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 | ||
25 | + [-1, 4, Bottleneck, [1024]], # 10 | ||
26 | + ] | ||
27 | + | ||
28 | +# YOLOv3-SPP head | ||
29 | +head: | ||
30 | + [[-1, 1, Bottleneck, [1024, False]], | ||
31 | + [-1, 1, SPP, [512, [5, 9, 13]]], | ||
32 | + [-1, 1, Conv, [1024, 3, 1]], | ||
33 | + [-1, 1, Conv, [512, 1, 1]], | ||
34 | + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) | ||
35 | + | ||
36 | + [-2, 1, Conv, [256, 1, 1]], | ||
37 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
38 | + [[-1, 8], 1, Concat, [1]], # cat backbone P4 | ||
39 | + [-1, 1, Bottleneck, [512, False]], | ||
40 | + [-1, 1, Bottleneck, [512, False]], | ||
41 | + [-1, 1, Conv, [256, 1, 1]], | ||
42 | + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) | ||
43 | + | ||
44 | + [-2, 1, Conv, [128, 1, 1]], | ||
45 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
46 | + [[-1, 6], 1, Concat, [1]], # cat backbone P3 | ||
47 | + [-1, 1, Bottleneck, [256, False]], | ||
48 | + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) | ||
49 | + | ||
50 | + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
51 | + ] |
YOLOv5/models/hub/yolov3-tiny.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,14, 23,27, 37,58] # P4/16 | ||
9 | + - [81,82, 135,169, 344,319] # P5/32 | ||
10 | + | ||
11 | +# YOLOv3-tiny backbone | ||
12 | +backbone: | ||
13 | + # [from, number, module, args] | ||
14 | + [[-1, 1, Conv, [16, 3, 1]], # 0 | ||
15 | + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2 | ||
16 | + [-1, 1, Conv, [32, 3, 1]], | ||
17 | + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4 | ||
18 | + [-1, 1, Conv, [64, 3, 1]], | ||
19 | + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8 | ||
20 | + [-1, 1, Conv, [128, 3, 1]], | ||
21 | + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16 | ||
22 | + [-1, 1, Conv, [256, 3, 1]], | ||
23 | + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32 | ||
24 | + [-1, 1, Conv, [512, 3, 1]], | ||
25 | + [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11 | ||
26 | + [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12 | ||
27 | + ] | ||
28 | + | ||
29 | +# YOLOv3-tiny head | ||
30 | +head: | ||
31 | + [[-1, 1, Conv, [1024, 3, 1]], | ||
32 | + [-1, 1, Conv, [256, 1, 1]], | ||
33 | + [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large) | ||
34 | + | ||
35 | + [-2, 1, Conv, [128, 1, 1]], | ||
36 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
37 | + [[-1, 8], 1, Concat, [1]], # cat backbone P4 | ||
38 | + [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium) | ||
39 | + | ||
40 | + [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5) | ||
41 | + ] |
YOLOv5/models/hub/yolov3.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# darknet53 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Conv, [32, 3, 1]], # 0 | ||
16 | + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 | ||
17 | + [-1, 1, Bottleneck, [64]], | ||
18 | + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 | ||
19 | + [-1, 2, Bottleneck, [128]], | ||
20 | + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 | ||
21 | + [-1, 8, Bottleneck, [256]], | ||
22 | + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 | ||
23 | + [-1, 8, Bottleneck, [512]], | ||
24 | + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 | ||
25 | + [-1, 4, Bottleneck, [1024]], # 10 | ||
26 | + ] | ||
27 | + | ||
28 | +# YOLOv3 head | ||
29 | +head: | ||
30 | + [[-1, 1, Bottleneck, [1024, False]], | ||
31 | + [-1, 1, Conv, [512, [1, 1]]], | ||
32 | + [-1, 1, Conv, [1024, 3, 1]], | ||
33 | + [-1, 1, Conv, [512, 1, 1]], | ||
34 | + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) | ||
35 | + | ||
36 | + [-2, 1, Conv, [256, 1, 1]], | ||
37 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
38 | + [[-1, 8], 1, Concat, [1]], # cat backbone P4 | ||
39 | + [-1, 1, Bottleneck, [512, False]], | ||
40 | + [-1, 1, Bottleneck, [512, False]], | ||
41 | + [-1, 1, Conv, [256, 1, 1]], | ||
42 | + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) | ||
43 | + | ||
44 | + [-2, 1, Conv, [128, 1, 1]], | ||
45 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
46 | + [[-1, 6], 1, Concat, [1]], # cat backbone P3 | ||
47 | + [-1, 1, Bottleneck, [256, False]], | ||
48 | + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) | ||
49 | + | ||
50 | + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
51 | + ] |
YOLOv5/models/hub/yolov5-fpn.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, Bottleneck, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, BottleneckCSP, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, BottleneckCSP, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 6, BottleneckCSP, [1024]], # 9 | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 FPN head | ||
28 | +head: | ||
29 | + [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large) | ||
30 | + | ||
31 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
32 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
33 | + [-1, 1, Conv, [512, 1, 1]], | ||
34 | + [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium) | ||
35 | + | ||
36 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
37 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
38 | + [-1, 1, Conv, [256, 1, 1]], | ||
39 | + [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small) | ||
40 | + | ||
41 | + [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
42 | + ] |
YOLOv5/models/hub/yolov5-p2.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: 3 | ||
8 | + | ||
9 | +# YOLOv5 backbone | ||
10 | +backbone: | ||
11 | + # [from, number, module, args] | ||
12 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
13 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
14 | + [ -1, 3, C3, [ 128 ] ], | ||
15 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
16 | + [ -1, 9, C3, [ 256 ] ], | ||
17 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
18 | + [ -1, 9, C3, [ 512 ] ], | ||
19 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 | ||
20 | + [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ], | ||
21 | + [ -1, 3, C3, [ 1024, False ] ], # 9 | ||
22 | + ] | ||
23 | + | ||
24 | +# YOLOv5 head | ||
25 | +head: | ||
26 | + [ [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
27 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
28 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
29 | + [ -1, 3, C3, [ 512, False ] ], # 13 | ||
30 | + | ||
31 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
32 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
33 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
34 | + [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) | ||
35 | + | ||
36 | + [ -1, 1, Conv, [ 128, 1, 1 ] ], | ||
37 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
38 | + [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2 | ||
39 | + [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall) | ||
40 | + | ||
41 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], | ||
42 | + [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3 | ||
43 | + [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small) | ||
44 | + | ||
45 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
46 | + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
47 | + [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium) | ||
48 | + | ||
49 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
50 | + [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
51 | + [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large) | ||
52 | + | ||
53 | + [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5) | ||
54 | + ] |
YOLOv5/models/hub/yolov5-p6.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: 3 | ||
8 | + | ||
9 | +# YOLOv5 backbone | ||
10 | +backbone: | ||
11 | + # [from, number, module, args] | ||
12 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
13 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
14 | + [ -1, 3, C3, [ 128 ] ], | ||
15 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
16 | + [ -1, 9, C3, [ 256 ] ], | ||
17 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
18 | + [ -1, 9, C3, [ 512 ] ], | ||
19 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 | ||
20 | + [ -1, 3, C3, [ 768 ] ], | ||
21 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 | ||
22 | + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], | ||
23 | + [ -1, 3, C3, [ 1024, False ] ], # 11 | ||
24 | + ] | ||
25 | + | ||
26 | +# YOLOv5 head | ||
27 | +head: | ||
28 | + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], | ||
29 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
30 | + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 | ||
31 | + [ -1, 3, C3, [ 768, False ] ], # 15 | ||
32 | + | ||
33 | + [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
34 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
35 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
36 | + [ -1, 3, C3, [ 512, False ] ], # 19 | ||
37 | + | ||
38 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
39 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
40 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
41 | + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) | ||
42 | + | ||
43 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
44 | + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
45 | + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) | ||
46 | + | ||
47 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
48 | + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
49 | + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) | ||
50 | + | ||
51 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], | ||
52 | + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 | ||
53 | + [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge) | ||
54 | + | ||
55 | + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) | ||
56 | + ] |
YOLOv5/models/hub/yolov5-p7.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: 3 | ||
8 | + | ||
9 | +# YOLOv5 backbone | ||
10 | +backbone: | ||
11 | + # [from, number, module, args] | ||
12 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
13 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
14 | + [ -1, 3, C3, [ 128 ] ], | ||
15 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
16 | + [ -1, 9, C3, [ 256 ] ], | ||
17 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
18 | + [ -1, 9, C3, [ 512 ] ], | ||
19 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 | ||
20 | + [ -1, 3, C3, [ 768 ] ], | ||
21 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 | ||
22 | + [ -1, 3, C3, [ 1024 ] ], | ||
23 | + [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128 | ||
24 | + [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ], | ||
25 | + [ -1, 3, C3, [ 1280, False ] ], # 13 | ||
26 | + ] | ||
27 | + | ||
28 | +# YOLOv5 head | ||
29 | +head: | ||
30 | + [ [ -1, 1, Conv, [ 1024, 1, 1 ] ], | ||
31 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
32 | + [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6 | ||
33 | + [ -1, 3, C3, [ 1024, False ] ], # 17 | ||
34 | + | ||
35 | + [ -1, 1, Conv, [ 768, 1, 1 ] ], | ||
36 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
37 | + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 | ||
38 | + [ -1, 3, C3, [ 768, False ] ], # 21 | ||
39 | + | ||
40 | + [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
41 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
42 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
43 | + [ -1, 3, C3, [ 512, False ] ], # 25 | ||
44 | + | ||
45 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
46 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
47 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
48 | + [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small) | ||
49 | + | ||
50 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
51 | + [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
52 | + [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium) | ||
53 | + | ||
54 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
55 | + [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
56 | + [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large) | ||
57 | + | ||
58 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], | ||
59 | + [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6 | ||
60 | + [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge) | ||
61 | + | ||
62 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], | ||
63 | + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7 | ||
64 | + [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge) | ||
65 | + | ||
66 | + [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7) | ||
67 | + ] |
YOLOv5/models/hub/yolov5-panet.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, BottleneckCSP, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, BottleneckCSP, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, BottleneckCSP, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 3, BottleneckCSP, [1024, False]], # 9 | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 PANet head | ||
28 | +head: | ||
29 | + [[-1, 1, Conv, [512, 1, 1]], | ||
30 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
31 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
32 | + [-1, 3, BottleneckCSP, [512, False]], # 13 | ||
33 | + | ||
34 | + [-1, 1, Conv, [256, 1, 1]], | ||
35 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
36 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
37 | + [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small) | ||
38 | + | ||
39 | + [-1, 1, Conv, [256, 3, 2]], | ||
40 | + [[-1, 14], 1, Concat, [1]], # cat head P4 | ||
41 | + [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium) | ||
42 | + | ||
43 | + [-1, 1, Conv, [512, 3, 2]], | ||
44 | + [[-1, 10], 1, Concat, [1]], # cat head P5 | ||
45 | + [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large) | ||
46 | + | ||
47 | + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
48 | + ] |
YOLOv5/models/hub/yolov5l6.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [ 19,27, 44,40, 38,94 ] # P3/8 | ||
9 | + - [ 96,68, 86,152, 180,137 ] # P4/16 | ||
10 | + - [ 140,301, 303,264, 238,542 ] # P5/32 | ||
11 | + - [ 436,615, 739,380, 925,792 ] # P6/64 | ||
12 | + | ||
13 | +# YOLOv5 backbone | ||
14 | +backbone: | ||
15 | + # [from, number, module, args] | ||
16 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
17 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
18 | + [ -1, 3, C3, [ 128 ] ], | ||
19 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
20 | + [ -1, 9, C3, [ 256 ] ], | ||
21 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
22 | + [ -1, 9, C3, [ 512 ] ], | ||
23 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 | ||
24 | + [ -1, 3, C3, [ 768 ] ], | ||
25 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 | ||
26 | + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], | ||
27 | + [ -1, 3, C3, [ 1024, False ] ], # 11 | ||
28 | + ] | ||
29 | + | ||
30 | +# YOLOv5 head | ||
31 | +head: | ||
32 | + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], | ||
33 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
34 | + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 | ||
35 | + [ -1, 3, C3, [ 768, False ] ], # 15 | ||
36 | + | ||
37 | + [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
38 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
39 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
40 | + [ -1, 3, C3, [ 512, False ] ], # 19 | ||
41 | + | ||
42 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
43 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
44 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
45 | + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) | ||
46 | + | ||
47 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
48 | + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
49 | + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) | ||
50 | + | ||
51 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
52 | + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
53 | + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) | ||
54 | + | ||
55 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], | ||
56 | + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 | ||
57 | + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) | ||
58 | + | ||
59 | + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) | ||
60 | + ] |
YOLOv5/models/hub/yolov5m6.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 0.67 # model depth multiple | ||
4 | +width_multiple: 0.75 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [ 19,27, 44,40, 38,94 ] # P3/8 | ||
9 | + - [ 96,68, 86,152, 180,137 ] # P4/16 | ||
10 | + - [ 140,301, 303,264, 238,542 ] # P5/32 | ||
11 | + - [ 436,615, 739,380, 925,792 ] # P6/64 | ||
12 | + | ||
13 | +# YOLOv5 backbone | ||
14 | +backbone: | ||
15 | + # [from, number, module, args] | ||
16 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
17 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
18 | + [ -1, 3, C3, [ 128 ] ], | ||
19 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
20 | + [ -1, 9, C3, [ 256 ] ], | ||
21 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
22 | + [ -1, 9, C3, [ 512 ] ], | ||
23 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 | ||
24 | + [ -1, 3, C3, [ 768 ] ], | ||
25 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 | ||
26 | + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], | ||
27 | + [ -1, 3, C3, [ 1024, False ] ], # 11 | ||
28 | + ] | ||
29 | + | ||
30 | +# YOLOv5 head | ||
31 | +head: | ||
32 | + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], | ||
33 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
34 | + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 | ||
35 | + [ -1, 3, C3, [ 768, False ] ], # 15 | ||
36 | + | ||
37 | + [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
38 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
39 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
40 | + [ -1, 3, C3, [ 512, False ] ], # 19 | ||
41 | + | ||
42 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
43 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
44 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
45 | + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) | ||
46 | + | ||
47 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
48 | + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
49 | + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) | ||
50 | + | ||
51 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
52 | + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
53 | + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) | ||
54 | + | ||
55 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], | ||
56 | + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 | ||
57 | + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) | ||
58 | + | ||
59 | + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) | ||
60 | + ] |
YOLOv5/models/hub/yolov5s-transformer.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 0.33 # model depth multiple | ||
4 | +width_multiple: 0.50 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, C3, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, C3, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, C3, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 head | ||
28 | +head: | ||
29 | + [[-1, 1, Conv, [512, 1, 1]], | ||
30 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
31 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
32 | + [-1, 3, C3, [512, False]], # 13 | ||
33 | + | ||
34 | + [-1, 1, Conv, [256, 1, 1]], | ||
35 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
36 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
37 | + [-1, 3, C3, [256, False]], # 17 (P3/8-small) | ||
38 | + | ||
39 | + [-1, 1, Conv, [256, 3, 2]], | ||
40 | + [[-1, 14], 1, Concat, [1]], # cat head P4 | ||
41 | + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) | ||
42 | + | ||
43 | + [-1, 1, Conv, [512, 3, 2]], | ||
44 | + [[-1, 10], 1, Concat, [1]], # cat head P5 | ||
45 | + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) | ||
46 | + | ||
47 | + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
48 | + ] |
YOLOv5/models/hub/yolov5s6.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 0.33 # model depth multiple | ||
4 | +width_multiple: 0.50 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [ 19,27, 44,40, 38,94 ] # P3/8 | ||
9 | + - [ 96,68, 86,152, 180,137 ] # P4/16 | ||
10 | + - [ 140,301, 303,264, 238,542 ] # P5/32 | ||
11 | + - [ 436,615, 739,380, 925,792 ] # P6/64 | ||
12 | + | ||
13 | +# YOLOv5 backbone | ||
14 | +backbone: | ||
15 | + # [from, number, module, args] | ||
16 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
17 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
18 | + [ -1, 3, C3, [ 128 ] ], | ||
19 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
20 | + [ -1, 9, C3, [ 256 ] ], | ||
21 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
22 | + [ -1, 9, C3, [ 512 ] ], | ||
23 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 | ||
24 | + [ -1, 3, C3, [ 768 ] ], | ||
25 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 | ||
26 | + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], | ||
27 | + [ -1, 3, C3, [ 1024, False ] ], # 11 | ||
28 | + ] | ||
29 | + | ||
30 | +# YOLOv5 head | ||
31 | +head: | ||
32 | + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], | ||
33 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
34 | + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 | ||
35 | + [ -1, 3, C3, [ 768, False ] ], # 15 | ||
36 | + | ||
37 | + [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
38 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
39 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
40 | + [ -1, 3, C3, [ 512, False ] ], # 19 | ||
41 | + | ||
42 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
43 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
44 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
45 | + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) | ||
46 | + | ||
47 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
48 | + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
49 | + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) | ||
50 | + | ||
51 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
52 | + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
53 | + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) | ||
54 | + | ||
55 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], | ||
56 | + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 | ||
57 | + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) | ||
58 | + | ||
59 | + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) | ||
60 | + ] |
YOLOv5/models/hub/yolov5x6.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.33 # model depth multiple | ||
4 | +width_multiple: 1.25 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [ 19,27, 44,40, 38,94 ] # P3/8 | ||
9 | + - [ 96,68, 86,152, 180,137 ] # P4/16 | ||
10 | + - [ 140,301, 303,264, 238,542 ] # P5/32 | ||
11 | + - [ 436,615, 739,380, 925,792 ] # P6/64 | ||
12 | + | ||
13 | +# YOLOv5 backbone | ||
14 | +backbone: | ||
15 | + # [from, number, module, args] | ||
16 | + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 | ||
17 | + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 | ||
18 | + [ -1, 3, C3, [ 128 ] ], | ||
19 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 | ||
20 | + [ -1, 9, C3, [ 256 ] ], | ||
21 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 | ||
22 | + [ -1, 9, C3, [ 512 ] ], | ||
23 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 | ||
24 | + [ -1, 3, C3, [ 768 ] ], | ||
25 | + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 | ||
26 | + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], | ||
27 | + [ -1, 3, C3, [ 1024, False ] ], # 11 | ||
28 | + ] | ||
29 | + | ||
30 | +# YOLOv5 head | ||
31 | +head: | ||
32 | + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], | ||
33 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
34 | + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 | ||
35 | + [ -1, 3, C3, [ 768, False ] ], # 15 | ||
36 | + | ||
37 | + [ -1, 1, Conv, [ 512, 1, 1 ] ], | ||
38 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
39 | + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 | ||
40 | + [ -1, 3, C3, [ 512, False ] ], # 19 | ||
41 | + | ||
42 | + [ -1, 1, Conv, [ 256, 1, 1 ] ], | ||
43 | + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], | ||
44 | + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 | ||
45 | + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) | ||
46 | + | ||
47 | + [ -1, 1, Conv, [ 256, 3, 2 ] ], | ||
48 | + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 | ||
49 | + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) | ||
50 | + | ||
51 | + [ -1, 1, Conv, [ 512, 3, 2 ] ], | ||
52 | + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 | ||
53 | + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) | ||
54 | + | ||
55 | + [ -1, 1, Conv, [ 768, 3, 2 ] ], | ||
56 | + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 | ||
57 | + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) | ||
58 | + | ||
59 | + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) | ||
60 | + ] |
YOLOv5/models/yolo.py
0 → 100644
1 | +"""YOLOv5-specific modules | ||
2 | + | ||
3 | +Usage: | ||
4 | + $ python path/to/models/yolo.py --cfg yolov5s.yaml | ||
5 | +""" | ||
6 | + | ||
7 | +import argparse | ||
8 | +import logging | ||
9 | +import sys | ||
10 | +from copy import deepcopy | ||
11 | +from pathlib import Path | ||
12 | + | ||
13 | +sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories | ||
14 | +logger = logging.getLogger(__name__) | ||
15 | + | ||
16 | +from models.common import * | ||
17 | +from models.experimental import * | ||
18 | +from utils.autoanchor import check_anchor_order | ||
19 | +from utils.general import make_divisible, check_file, set_logging | ||
20 | +from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \ | ||
21 | + select_device, copy_attr | ||
22 | + | ||
23 | +try: | ||
24 | + import thop # for FLOPS computation | ||
25 | +except ImportError: | ||
26 | + thop = None | ||
27 | + | ||
28 | + | ||
29 | +class Detect(nn.Module): | ||
30 | + stride = None # strides computed during build | ||
31 | + onnx_dynamic = False # ONNX export parameter | ||
32 | + | ||
33 | + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer | ||
34 | + super(Detect, self).__init__() | ||
35 | + self.nc = nc # number of classes | ||
36 | + self.no = nc + 5 # number of outputs per anchor | ||
37 | + self.nl = len(anchors) # number of detection layers | ||
38 | + self.na = len(anchors[0]) // 2 # number of anchors | ||
39 | + self.grid = [torch.zeros(1)] * self.nl # init grid | ||
40 | + a = torch.tensor(anchors).float().view(self.nl, -1, 2) | ||
41 | + self.register_buffer('anchors', a) # shape(nl,na,2) | ||
42 | + self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) | ||
43 | + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv | ||
44 | + self.inplace = inplace # use in-place ops (e.g. slice assignment) | ||
45 | + | ||
46 | + def forward(self, x): | ||
47 | + # x = x.copy() # for profiling | ||
48 | + z = [] # inference output | ||
49 | + for i in range(self.nl): | ||
50 | + x[i] = self.m[i](x[i]) # conv | ||
51 | + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) | ||
52 | + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() | ||
53 | + | ||
54 | + if not self.training: # inference | ||
55 | + if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic: | ||
56 | + self.grid[i] = self._make_grid(nx, ny).to(x[i].device) | ||
57 | + | ||
58 | + y = x[i].sigmoid() | ||
59 | + if self.inplace: | ||
60 | + y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy | ||
61 | + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh | ||
62 | + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 | ||
63 | + xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy | ||
64 | + wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh | ||
65 | + y = torch.cat((xy, wh, y[..., 4:]), -1) | ||
66 | + z.append(y.view(bs, -1, self.no)) | ||
67 | + | ||
68 | + return x if self.training else (torch.cat(z, 1), x) | ||
69 | + | ||
70 | + @staticmethod | ||
71 | + def _make_grid(nx=20, ny=20): | ||
72 | + yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) | ||
73 | + return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() | ||
74 | + | ||
75 | + | ||
76 | +class Model(nn.Module): | ||
77 | + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes | ||
78 | + super(Model, self).__init__() | ||
79 | + if isinstance(cfg, dict): | ||
80 | + self.yaml = cfg # model dict | ||
81 | + else: # is *.yaml | ||
82 | + import yaml # for torch hub | ||
83 | + self.yaml_file = Path(cfg).name | ||
84 | + with open(cfg) as f: | ||
85 | + self.yaml = yaml.safe_load(f) # model dict | ||
86 | + | ||
87 | + # Define model | ||
88 | + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels | ||
89 | + if nc and nc != self.yaml['nc']: | ||
90 | + logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") | ||
91 | + self.yaml['nc'] = nc # override yaml value | ||
92 | + if anchors: | ||
93 | + logger.info(f'Overriding model.yaml anchors with anchors={anchors}') | ||
94 | + self.yaml['anchors'] = round(anchors) # override yaml value | ||
95 | + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist | ||
96 | + self.names = [str(i) for i in range(self.yaml['nc'])] # default names | ||
97 | + self.inplace = self.yaml.get('inplace', True) | ||
98 | + # logger.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) | ||
99 | + | ||
100 | + # Build strides, anchors | ||
101 | + m = self.model[-1] # Detect() | ||
102 | + if isinstance(m, Detect): | ||
103 | + s = 256 # 2x min stride | ||
104 | + m.inplace = self.inplace | ||
105 | + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward | ||
106 | + m.anchors /= m.stride.view(-1, 1, 1) | ||
107 | + check_anchor_order(m) | ||
108 | + self.stride = m.stride | ||
109 | + self._initialize_biases() # only run once | ||
110 | + # logger.info('Strides: %s' % m.stride.tolist()) | ||
111 | + | ||
112 | + # Init weights, biases | ||
113 | + initialize_weights(self) | ||
114 | + self.info() | ||
115 | + logger.info('') | ||
116 | + | ||
117 | + def forward(self, x, augment=False, profile=False): | ||
118 | + if augment: | ||
119 | + return self.forward_augment(x) # augmented inference, None | ||
120 | + else: | ||
121 | + return self.forward_once(x, profile) # single-scale inference, train | ||
122 | + | ||
123 | + def forward_augment(self, x): | ||
124 | + img_size = x.shape[-2:] # height, width | ||
125 | + s = [1, 0.83, 0.67] # scales | ||
126 | + f = [None, 3, None] # flips (2-ud, 3-lr) | ||
127 | + y = [] # outputs | ||
128 | + for si, fi in zip(s, f): | ||
129 | + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) | ||
130 | + yi = self.forward_once(xi)[0] # forward | ||
131 | + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save | ||
132 | + yi = self._descale_pred(yi, fi, si, img_size) | ||
133 | + y.append(yi) | ||
134 | + return torch.cat(y, 1), None # augmented inference, train | ||
135 | + | ||
136 | + def forward_once(self, x, profile=False): | ||
137 | + y, dt = [], [] # outputs | ||
138 | + for m in self.model: | ||
139 | + if m.f != -1: # if not from previous layer | ||
140 | + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers | ||
141 | + | ||
142 | + if profile: | ||
143 | + o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS | ||
144 | + t = time_synchronized() | ||
145 | + for _ in range(10): | ||
146 | + _ = m(x) | ||
147 | + dt.append((time_synchronized() - t) * 100) | ||
148 | + if m == self.model[0]: | ||
149 | + logger.info(f"{'time (ms)':>10s} {'GFLOPS':>10s} {'params':>10s} {'module'}") | ||
150 | + logger.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') | ||
151 | + | ||
152 | + x = m(x) # run | ||
153 | + y.append(x if m.i in self.save else None) # save output | ||
154 | + | ||
155 | + if profile: | ||
156 | + logger.info('%.1fms total' % sum(dt)) | ||
157 | + return x | ||
158 | + | ||
159 | + def _descale_pred(self, p, flips, scale, img_size): | ||
160 | + # de-scale predictions following augmented inference (inverse operation) | ||
161 | + if self.inplace: | ||
162 | + p[..., :4] /= scale # de-scale | ||
163 | + if flips == 2: | ||
164 | + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud | ||
165 | + elif flips == 3: | ||
166 | + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr | ||
167 | + else: | ||
168 | + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale | ||
169 | + if flips == 2: | ||
170 | + y = img_size[0] - y # de-flip ud | ||
171 | + elif flips == 3: | ||
172 | + x = img_size[1] - x # de-flip lr | ||
173 | + p = torch.cat((x, y, wh, p[..., 4:]), -1) | ||
174 | + return p | ||
175 | + | ||
176 | + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency | ||
177 | + # https://arxiv.org/abs/1708.02002 section 3.3 | ||
178 | + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. | ||
179 | + m = self.model[-1] # Detect() module | ||
180 | + for mi, s in zip(m.m, m.stride): # from | ||
181 | + b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) | ||
182 | + b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) | ||
183 | + b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls | ||
184 | + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) | ||
185 | + | ||
186 | + def _print_biases(self): | ||
187 | + m = self.model[-1] # Detect() module | ||
188 | + for mi in m.m: # from | ||
189 | + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) | ||
190 | + logger.info( | ||
191 | + ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) | ||
192 | + | ||
193 | + # def _print_weights(self): | ||
194 | + # for m in self.model.modules(): | ||
195 | + # if type(m) is Bottleneck: | ||
196 | + # logger.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights | ||
197 | + | ||
198 | + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers | ||
199 | + logger.info('Fusing layers... ') | ||
200 | + for m in self.model.modules(): | ||
201 | + if type(m) is Conv and hasattr(m, 'bn'): | ||
202 | + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv | ||
203 | + delattr(m, 'bn') # remove batchnorm | ||
204 | + m.forward = m.fuseforward # update forward | ||
205 | + self.info() | ||
206 | + return self | ||
207 | + | ||
208 | + def nms(self, mode=True): # add or remove NMS module | ||
209 | + present = type(self.model[-1]) is NMS # last layer is NMS | ||
210 | + if mode and not present: | ||
211 | + logger.info('Adding NMS... ') | ||
212 | + m = NMS() # module | ||
213 | + m.f = -1 # from | ||
214 | + m.i = self.model[-1].i + 1 # index | ||
215 | + self.model.add_module(name='%s' % m.i, module=m) # add | ||
216 | + self.eval() | ||
217 | + elif not mode and present: | ||
218 | + logger.info('Removing NMS... ') | ||
219 | + self.model = self.model[:-1] # remove | ||
220 | + return self | ||
221 | + | ||
222 | + def autoshape(self): # add AutoShape module | ||
223 | + logger.info('Adding AutoShape... ') | ||
224 | + m = AutoShape(self) # wrap model | ||
225 | + copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes | ||
226 | + return m | ||
227 | + | ||
228 | + def info(self, verbose=False, img_size=640): # print model information | ||
229 | + model_info(self, verbose, img_size) | ||
230 | + | ||
231 | + | ||
232 | +def parse_model(d, ch): # model_dict, input_channels(3) | ||
233 | + logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) | ||
234 | + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] | ||
235 | + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors | ||
236 | + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) | ||
237 | + | ||
238 | + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out | ||
239 | + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args | ||
240 | + m = eval(m) if isinstance(m, str) else m # eval strings | ||
241 | + for j, a in enumerate(args): | ||
242 | + try: | ||
243 | + args[j] = eval(a) if isinstance(a, str) else a # eval strings | ||
244 | + except: | ||
245 | + pass | ||
246 | + | ||
247 | + n = max(round(n * gd), 1) if n > 1 else n # depth gain | ||
248 | + if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, | ||
249 | + C3, C3TR]: | ||
250 | + c1, c2 = ch[f], args[0] | ||
251 | + if c2 != no: # if not output | ||
252 | + c2 = make_divisible(c2 * gw, 8) | ||
253 | + | ||
254 | + args = [c1, c2, *args[1:]] | ||
255 | + if m in [BottleneckCSP, C3, C3TR]: | ||
256 | + args.insert(2, n) # number of repeats | ||
257 | + n = 1 | ||
258 | + elif m is nn.BatchNorm2d: | ||
259 | + args = [ch[f]] | ||
260 | + elif m is Concat: | ||
261 | + c2 = sum([ch[x] for x in f]) | ||
262 | + elif m is Detect: | ||
263 | + args.append([ch[x] for x in f]) | ||
264 | + if isinstance(args[1], int): # number of anchors | ||
265 | + args[1] = [list(range(args[1] * 2))] * len(f) | ||
266 | + elif m is Contract: | ||
267 | + c2 = ch[f] * args[0] ** 2 | ||
268 | + elif m is Expand: | ||
269 | + c2 = ch[f] // args[0] ** 2 | ||
270 | + else: | ||
271 | + c2 = ch[f] | ||
272 | + | ||
273 | + m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module | ||
274 | + t = str(m)[8:-2].replace('__main__.', '') # module type | ||
275 | + np = sum([x.numel() for x in m_.parameters()]) # number params | ||
276 | + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params | ||
277 | + logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print | ||
278 | + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist | ||
279 | + layers.append(m_) | ||
280 | + if i == 0: | ||
281 | + ch = [] | ||
282 | + ch.append(c2) | ||
283 | + return nn.Sequential(*layers), sorted(save) | ||
284 | + | ||
285 | + | ||
286 | +if __name__ == '__main__': | ||
287 | + parser = argparse.ArgumentParser() | ||
288 | + parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') | ||
289 | + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') | ||
290 | + opt = parser.parse_args() | ||
291 | + opt.cfg = check_file(opt.cfg) # check file | ||
292 | + set_logging() | ||
293 | + device = select_device(opt.device) | ||
294 | + | ||
295 | + # Create model | ||
296 | + model = Model(opt.cfg).to(device) | ||
297 | + model.train() | ||
298 | + | ||
299 | + # Profile | ||
300 | + # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 320, 320).to(device) | ||
301 | + # y = model(img, profile=True) | ||
302 | + | ||
303 | + # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898) | ||
304 | + # from torch.utils.tensorboard import SummaryWriter | ||
305 | + # tb_writer = SummaryWriter('.') | ||
306 | + # logger.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/") | ||
307 | + # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph | ||
308 | + # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard |
YOLOv5/models/yolov5l.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.0 # model depth multiple | ||
4 | +width_multiple: 1.0 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, C3, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, C3, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, C3, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 3, C3, [1024, False]], # 9 | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 head | ||
28 | +head: | ||
29 | + [[-1, 1, Conv, [512, 1, 1]], | ||
30 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
31 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
32 | + [-1, 3, C3, [512, False]], # 13 | ||
33 | + | ||
34 | + [-1, 1, Conv, [256, 1, 1]], | ||
35 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
36 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
37 | + [-1, 3, C3, [256, False]], # 17 (P3/8-small) | ||
38 | + | ||
39 | + [-1, 1, Conv, [256, 3, 2]], | ||
40 | + [[-1, 14], 1, Concat, [1]], # cat head P4 | ||
41 | + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) | ||
42 | + | ||
43 | + [-1, 1, Conv, [512, 3, 2]], | ||
44 | + [[-1, 10], 1, Concat, [1]], # cat head P5 | ||
45 | + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) | ||
46 | + | ||
47 | + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
48 | + ] |
YOLOv5/models/yolov5m.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 0.67 # model depth multiple | ||
4 | +width_multiple: 0.75 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, C3, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, C3, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, C3, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 3, C3, [1024, False]], # 9 | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 head | ||
28 | +head: | ||
29 | + [[-1, 1, Conv, [512, 1, 1]], | ||
30 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
31 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
32 | + [-1, 3, C3, [512, False]], # 13 | ||
33 | + | ||
34 | + [-1, 1, Conv, [256, 1, 1]], | ||
35 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
36 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
37 | + [-1, 3, C3, [256, False]], # 17 (P3/8-small) | ||
38 | + | ||
39 | + [-1, 1, Conv, [256, 3, 2]], | ||
40 | + [[-1, 14], 1, Concat, [1]], # cat head P4 | ||
41 | + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) | ||
42 | + | ||
43 | + [-1, 1, Conv, [512, 3, 2]], | ||
44 | + [[-1, 10], 1, Concat, [1]], # cat head P5 | ||
45 | + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) | ||
46 | + | ||
47 | + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
48 | + ] |
YOLOv5/models/yolov5s.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 1 # number of classes | ||
3 | +depth_multiple: 0.33 # model depth multiple | ||
4 | +width_multiple: 0.50 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, C3, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, C3, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, C3, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 3, C3, [1024, False]], # 9 | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 head | ||
28 | +head: | ||
29 | + [[-1, 1, Conv, [512, 1, 1]], | ||
30 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
31 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
32 | + [-1, 3, C3, [512, False]], # 13 | ||
33 | + | ||
34 | + [-1, 1, Conv, [256, 1, 1]], | ||
35 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
36 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
37 | + [-1, 3, C3, [256, False]], # 17 (P3/8-small) | ||
38 | + | ||
39 | + [-1, 1, Conv, [256, 3, 2]], | ||
40 | + [[-1, 14], 1, Concat, [1]], # cat head P4 | ||
41 | + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) | ||
42 | + | ||
43 | + [-1, 1, Conv, [512, 3, 2]], | ||
44 | + [[-1, 10], 1, Concat, [1]], # cat head P5 | ||
45 | + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) | ||
46 | + | ||
47 | + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
48 | + ] |
YOLOv5/models/yolov5x.yaml
0 → 100644
1 | +# parameters | ||
2 | +nc: 80 # number of classes | ||
3 | +depth_multiple: 1.33 # model depth multiple | ||
4 | +width_multiple: 1.25 # layer channel multiple | ||
5 | + | ||
6 | +# anchors | ||
7 | +anchors: | ||
8 | + - [10,13, 16,30, 33,23] # P3/8 | ||
9 | + - [30,61, 62,45, 59,119] # P4/16 | ||
10 | + - [116,90, 156,198, 373,326] # P5/32 | ||
11 | + | ||
12 | +# YOLOv5 backbone | ||
13 | +backbone: | ||
14 | + # [from, number, module, args] | ||
15 | + [[-1, 1, Focus, [64, 3]], # 0-P1/2 | ||
16 | + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 | ||
17 | + [-1, 3, C3, [128]], | ||
18 | + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 | ||
19 | + [-1, 9, C3, [256]], | ||
20 | + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 | ||
21 | + [-1, 9, C3, [512]], | ||
22 | + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 | ||
23 | + [-1, 1, SPP, [1024, [5, 9, 13]]], | ||
24 | + [-1, 3, C3, [1024, False]], # 9 | ||
25 | + ] | ||
26 | + | ||
27 | +# YOLOv5 head | ||
28 | +head: | ||
29 | + [[-1, 1, Conv, [512, 1, 1]], | ||
30 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
31 | + [[-1, 6], 1, Concat, [1]], # cat backbone P4 | ||
32 | + [-1, 3, C3, [512, False]], # 13 | ||
33 | + | ||
34 | + [-1, 1, Conv, [256, 1, 1]], | ||
35 | + [-1, 1, nn.Upsample, [None, 2, 'nearest']], | ||
36 | + [[-1, 4], 1, Concat, [1]], # cat backbone P3 | ||
37 | + [-1, 3, C3, [256, False]], # 17 (P3/8-small) | ||
38 | + | ||
39 | + [-1, 1, Conv, [256, 3, 2]], | ||
40 | + [[-1, 14], 1, Concat, [1]], # cat head P4 | ||
41 | + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) | ||
42 | + | ||
43 | + [-1, 1, Conv, [512, 3, 2]], | ||
44 | + [[-1, 10], 1, Concat, [1]], # cat head P5 | ||
45 | + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) | ||
46 | + | ||
47 | + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) | ||
48 | + ] |
YOLOv5/requirements.txt
0 → 100644
1 | +# pip install -r requirements.txt | ||
2 | + | ||
3 | +# base ---------------------------------------- | ||
4 | +matplotlib>=3.2.2 | ||
5 | +numpy>=1.18.5 | ||
6 | +opencv-python>=4.1.2 | ||
7 | +Pillow | ||
8 | +PyYAML>=5.3.1 | ||
9 | +scipy>=1.4.1 | ||
10 | +torch>=1.7.0 | ||
11 | +torchvision>=0.8.1 | ||
12 | +tqdm>=4.41.0 | ||
13 | + | ||
14 | +# logging ------------------------------------- | ||
15 | +tensorboard>=2.4.1 | ||
16 | +# wandb | ||
17 | + | ||
18 | +# plotting ------------------------------------ | ||
19 | +seaborn>=0.11.0 | ||
20 | +pandas | ||
21 | + | ||
22 | +# export -------------------------------------- | ||
23 | +# coremltools>=4.1 | ||
24 | +# onnx>=1.9.0 | ||
25 | +# scikit-learn==0.19.2 # for coreml quantization | ||
26 | + | ||
27 | +# extras -------------------------------------- | ||
28 | +# Cython # for pycocotools https://github.com/cocodataset/cocoapi/issues/172 | ||
29 | +pycocotools>=2.0 # COCO mAP | ||
30 | +thop # FLOPS computation |
YOLOv5/test.py
0 → 100644
1 | +import argparse | ||
2 | +import json | ||
3 | +import os | ||
4 | +from pathlib import Path | ||
5 | +from threading import Thread | ||
6 | + | ||
7 | +import numpy as np | ||
8 | +import torch | ||
9 | +import yaml | ||
10 | +from tqdm import tqdm | ||
11 | + | ||
12 | +from models.experimental import attempt_load | ||
13 | +from utils.datasets import create_dataloader | ||
14 | +from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \ | ||
15 | + box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr | ||
16 | +from utils.metrics import ap_per_class, ConfusionMatrix | ||
17 | +from utils.plots import plot_images, output_to_target, plot_study_txt | ||
18 | +from utils.torch_utils import select_device, time_synchronized | ||
19 | + | ||
20 | + | ||
21 | +@torch.no_grad() | ||
22 | +def test(data, | ||
23 | + weights=None, | ||
24 | + batch_size=32, | ||
25 | + imgsz=1920, # default 640 | ||
26 | + conf_thres=0.1, ########## CHANGE HIGH # default 0.001 | ||
27 | + iou_thres=0.05, # for NMS ########### CHANGE REDUCE # defaul 0.6 | ||
28 | + save_json=False, | ||
29 | + single_cls=False, | ||
30 | + augment=False, # CHANGE TRUE # default False | ||
31 | + verbose=False, | ||
32 | + model=None, | ||
33 | + dataloader=None, | ||
34 | + save_dir=Path(''), # for saving images | ||
35 | + save_txt=False, # for auto-labelling | ||
36 | + save_hybrid=False, # for hybrid auto-labelling | ||
37 | + save_conf=False, # save auto-label confidences | ||
38 | + plots=True, | ||
39 | + wandb_logger=None, | ||
40 | + compute_loss=None, | ||
41 | + half_precision=True, | ||
42 | + is_coco=False, | ||
43 | + opt=None): | ||
44 | + # Initialize/load model and set device | ||
45 | + training = model is not None | ||
46 | + if training: # called by train.py | ||
47 | + device = next(model.parameters()).device # get model device | ||
48 | + | ||
49 | + else: # called directly | ||
50 | + set_logging() | ||
51 | + device = select_device(opt.device, batch_size=batch_size) | ||
52 | + | ||
53 | + # Directories | ||
54 | + save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run | ||
55 | + (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir | ||
56 | + | ||
57 | + # Load model | ||
58 | + model = attempt_load(weights, map_location=device) # load FP32 model | ||
59 | + gs = max(int(model.stride.max()), 32) # grid size (max stride) | ||
60 | + imgsz = check_img_size(imgsz, s=gs) # check img_size | ||
61 | + | ||
62 | + # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99 | ||
63 | + # if device.type != 'cpu' and torch.cuda.device_count() > 1: | ||
64 | + # model = nn.DataParallel(model) | ||
65 | + | ||
66 | + # Half | ||
67 | + half = device.type != 'cpu' and half_precision # half precision only supported on CUDA | ||
68 | + if half: | ||
69 | + model.half() | ||
70 | + | ||
71 | + # Configure | ||
72 | + model.eval() | ||
73 | + if isinstance(data, str): | ||
74 | + is_coco = data.endswith('coco.yaml') | ||
75 | + with open(data) as f: | ||
76 | + data = yaml.safe_load(f) | ||
77 | + check_dataset(data) # check | ||
78 | + nc = 1 if single_cls else int(data['nc']) # number of classes | ||
79 | + iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95 | ||
80 | + niou = iouv.numel() | ||
81 | + | ||
82 | + # Logging | ||
83 | + log_imgs = 0 | ||
84 | + if wandb_logger and wandb_logger.wandb: | ||
85 | + log_imgs = min(wandb_logger.log_imgs, 100) | ||
86 | + # Dataloader | ||
87 | + if not training: | ||
88 | + if device.type != 'cpu': | ||
89 | + model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once | ||
90 | + task = opt.task if opt.task in ('train', 'val', 'test') else 'val' # path to train/val/test images | ||
91 | + dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True, | ||
92 | + prefix=colorstr(f'{task}: '))[0] | ||
93 | + | ||
94 | + seen = 0 | ||
95 | + confusion_matrix = ConfusionMatrix(nc=nc) | ||
96 | + names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)} | ||
97 | + coco91class = coco80_to_coco91_class() | ||
98 | + s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95') | ||
99 | + p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0. | ||
100 | + loss = torch.zeros(3, device=device) | ||
101 | + jdict, stats, ap, ap_class, wandb_images = [], [], [], [], [] | ||
102 | + for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)): | ||
103 | + img = img.to(device, non_blocking=True) | ||
104 | + img = img.half() if half else img.float() # uint8 to fp16/32 | ||
105 | + img /= 255.0 # 0 - 255 to 0.0 - 1.0 | ||
106 | + targets = targets.to(device) | ||
107 | + nb, _, height, width = img.shape # batch size, channels, height, width | ||
108 | + | ||
109 | + # Run model | ||
110 | + t = time_synchronized() | ||
111 | + out, train_out = model(img, augment=augment) # inference and training outputs | ||
112 | + t0 += time_synchronized() - t | ||
113 | + | ||
114 | + # Compute loss | ||
115 | + if compute_loss: | ||
116 | + loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls | ||
117 | + | ||
118 | + # Run NMS | ||
119 | + targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels | ||
120 | + lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling | ||
121 | + t = time_synchronized() | ||
122 | + out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls) | ||
123 | + t1 += time_synchronized() - t | ||
124 | + | ||
125 | + # Statistics per image | ||
126 | + for si, pred in enumerate(out): | ||
127 | + labels = targets[targets[:, 0] == si, 1:] | ||
128 | + nl = len(labels) | ||
129 | + tcls = labels[:, 0].tolist() if nl else [] # target class | ||
130 | + path = Path(paths[si]) | ||
131 | + seen += 1 | ||
132 | + | ||
133 | + if len(pred) == 0: | ||
134 | + if nl: | ||
135 | + stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls)) | ||
136 | + continue | ||
137 | + | ||
138 | + # Predictions | ||
139 | + if single_cls: | ||
140 | + pred[:, 5] = 0 | ||
141 | + predn = pred.clone() | ||
142 | + scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred | ||
143 | + | ||
144 | + # Append to text file | ||
145 | + if save_txt: | ||
146 | + gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh | ||
147 | + for *xyxy, conf, cls in predn.tolist(): | ||
148 | + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh | ||
149 | + line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format | ||
150 | + with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f: | ||
151 | + f.write(('%g ' * len(line)).rstrip() % line + '\n') | ||
152 | + | ||
153 | + # W&B logging - Media Panel Plots | ||
154 | + if len(wandb_images) < log_imgs and wandb_logger.current_epoch > 0: # Check for test operation | ||
155 | + if wandb_logger.current_epoch % wandb_logger.bbox_interval == 0: | ||
156 | + box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, | ||
157 | + "class_id": int(cls), | ||
158 | + "box_caption": "%s %.3f" % (names[cls], conf), | ||
159 | + "scores": {"class_score": conf}, | ||
160 | + "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()] | ||
161 | + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space | ||
162 | + wandb_images.append(wandb_logger.wandb.Image(img[si], boxes=boxes, caption=path.name)) | ||
163 | + wandb_logger.log_training_progress(predn, path, names) if wandb_logger and wandb_logger.wandb_run else None | ||
164 | + | ||
165 | + # Append to pycocotools JSON dictionary | ||
166 | + if save_json: | ||
167 | + # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ... | ||
168 | + image_id = int(path.stem) if path.stem.isnumeric() else path.stem | ||
169 | + box = xyxy2xywh(predn[:, :4]) # xywh | ||
170 | + | ||
171 | + | ||
172 | + print("+++++++++++++++++++++++++++++++++++") | ||
173 | + print(box) | ||
174 | + print("+++++++++++++++++++++++++++++++++++") | ||
175 | + | ||
176 | + | ||
177 | + box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner | ||
178 | + for p, b in zip(pred.tolist(), box.tolist()): | ||
179 | + jdict.append({'image_id': image_id, | ||
180 | + 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]), | ||
181 | + 'bbox': [round(x, 3) for x in b], | ||
182 | + 'score': round(p[4], 5)}) | ||
183 | + | ||
184 | + print("++++++++++++++++++++++++++++++++++++++") | ||
185 | + print(jdict) | ||
186 | + print("++++++++++++++++++++++++++++++++++++++") | ||
187 | + | ||
188 | + # Assign all predictions as incorrect | ||
189 | + correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device) | ||
190 | + if nl: | ||
191 | + detected = [] # target indices | ||
192 | + tcls_tensor = labels[:, 0] | ||
193 | + | ||
194 | + # target boxes | ||
195 | + tbox = xywh2xyxy(labels[:, 1:5]) | ||
196 | + scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels | ||
197 | + if plots: | ||
198 | + confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1)) | ||
199 | + | ||
200 | + # Per target class | ||
201 | + for cls in torch.unique(tcls_tensor): | ||
202 | + ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # target indices | ||
203 | + pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # prediction indices | ||
204 | + | ||
205 | + # Search for detections | ||
206 | + if pi.shape[0]: | ||
207 | + # Prediction to target ious | ||
208 | + ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices | ||
209 | + | ||
210 | + # Append detections | ||
211 | + detected_set = set() | ||
212 | + for j in (ious > iouv[0]).nonzero(as_tuple=False): | ||
213 | + d = ti[i[j]] # detected target | ||
214 | + if d.item() not in detected_set: | ||
215 | + detected_set.add(d.item()) | ||
216 | + detected.append(d) | ||
217 | + correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn | ||
218 | + if len(detected) == nl: # all targets already located in image | ||
219 | + break | ||
220 | + | ||
221 | + | ||
222 | + print("++++++++++++++++++++++++++++++++++++++++++++++++++++++") | ||
223 | + print(detected_set) | ||
224 | + print("++++++++++++++++++++++++++++++++++++++++++++++++++++++") | ||
225 | + | ||
226 | + | ||
227 | + # Append statistics (correct, conf, pcls, tcls) | ||
228 | + stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) | ||
229 | + | ||
230 | + # Plot images | ||
231 | + if plots and batch_i < 3: | ||
232 | + f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels | ||
233 | + Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start() | ||
234 | + f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions | ||
235 | + Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start() | ||
236 | + | ||
237 | + # Compute statistics | ||
238 | + stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy | ||
239 | + if len(stats) and stats[0].any(): | ||
240 | + p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names) | ||
241 | + ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95 | ||
242 | + mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() | ||
243 | + nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class | ||
244 | + else: | ||
245 | + nt = torch.zeros(1) | ||
246 | + | ||
247 | + # Print results | ||
248 | + pf = '%20s' + '%12i' * 2 + '%12.3g' * 4 # print format | ||
249 | + print(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) | ||
250 | + | ||
251 | + # Print results per class | ||
252 | + if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats): | ||
253 | + for i, c in enumerate(ap_class): | ||
254 | + print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) | ||
255 | + | ||
256 | + # Print speeds | ||
257 | + t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple | ||
258 | + if not training: | ||
259 | + print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t) | ||
260 | + | ||
261 | + # Plots | ||
262 | + if plots: | ||
263 | + confusion_matrix.plot(save_dir=save_dir, names=list(names.values())) | ||
264 | + if wandb_logger and wandb_logger.wandb: | ||
265 | + val_batches = [wandb_logger.wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))] | ||
266 | + wandb_logger.log({"Validation": val_batches}) | ||
267 | + if wandb_images: | ||
268 | + wandb_logger.log({"Bounding Box Debugger/Images": wandb_images}) | ||
269 | + | ||
270 | + # Save JSON | ||
271 | + if save_json and len(jdict): | ||
272 | + w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights | ||
273 | + anno_json = '../coco/annotations/instances_val2017.json' # annotations json | ||
274 | + pred_json = str(save_dir / f"{w}_predictions.json") # predictions json | ||
275 | + print('\nEvaluating pycocotools mAP... saving %s...' % pred_json) | ||
276 | + with open(pred_json, 'w') as f: | ||
277 | + json.dump(jdict, f) | ||
278 | + | ||
279 | + try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb | ||
280 | + from pycocotools.coco import COCO | ||
281 | + from pycocotools.cocoeval import COCOeval | ||
282 | + | ||
283 | + anno = COCO(anno_json) # init annotations api | ||
284 | + pred = anno.loadRes(pred_json) # init predictions api | ||
285 | + eval = COCOeval(anno, pred, 'bbox') | ||
286 | + if is_coco: | ||
287 | + eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate | ||
288 | + eval.evaluate() | ||
289 | + eval.accumulate() | ||
290 | + eval.summarize() | ||
291 | + map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5) | ||
292 | + except Exception as e: | ||
293 | + print(f'pycocotools unable to run: {e}') | ||
294 | + | ||
295 | + # Return results | ||
296 | + model.float() # for training | ||
297 | + if not training: | ||
298 | + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' | ||
299 | + print(f"Results saved to {save_dir}{s}") | ||
300 | + maps = np.zeros(nc) + map | ||
301 | + for i, c in enumerate(ap_class): | ||
302 | + maps[c] = ap[i] | ||
303 | + return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t | ||
304 | + | ||
305 | + | ||
306 | +if __name__ == '__main__': | ||
307 | + parser = argparse.ArgumentParser(prog='test.py') | ||
308 | + parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)') | ||
309 | + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path') | ||
310 | + parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch') | ||
311 | + parser.add_argument('--img-size', type=int, default=1920, help='inference size (pixels)') #default 640 | ||
312 | + parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold') | ||
313 | + parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS') | ||
314 | + parser.add_argument('--task', default='val', help='train, val, test, speed or study') | ||
315 | + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') | ||
316 | + parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') | ||
317 | + parser.add_argument('--augment', action='store_true', help='augmented inference') | ||
318 | + parser.add_argument('--verbose', action='store_true', help='report mAP by class') | ||
319 | + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') | ||
320 | + parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt') | ||
321 | + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') | ||
322 | + parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file') | ||
323 | + parser.add_argument('--project', default='runs/test', help='save to project/name') | ||
324 | + parser.add_argument('--name', default='exp', help='save to project/name') | ||
325 | + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') | ||
326 | + opt = parser.parse_args() | ||
327 | + opt.save_json |= opt.data.endswith('coco.yaml') | ||
328 | + opt.data = check_file(opt.data) # check file | ||
329 | + print(opt) | ||
330 | + check_requirements(exclude=('tensorboard', 'pycocotools', 'thop')) | ||
331 | + | ||
332 | + if opt.task in ('train', 'val', 'test'): # run normally | ||
333 | + test(opt.data, | ||
334 | + opt.weights, | ||
335 | + opt.batch_size, | ||
336 | + opt.img_size, | ||
337 | + opt.conf_thres, | ||
338 | + opt.iou_thres, | ||
339 | + opt.save_json, | ||
340 | + opt.single_cls, | ||
341 | + opt.augment, | ||
342 | + opt.verbose, | ||
343 | + save_txt=opt.save_txt | opt.save_hybrid, | ||
344 | + save_hybrid=opt.save_hybrid, | ||
345 | + save_conf=opt.save_conf, | ||
346 | + opt=opt | ||
347 | + ) | ||
348 | + | ||
349 | + elif opt.task == 'speed': # speed benchmarks | ||
350 | + for w in opt.weights: | ||
351 | + test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False, opt=opt) | ||
352 | + | ||
353 | + elif opt.task == 'study': # run over a range of settings and save/plot | ||
354 | + # python test.py --task study --data coco.yaml --iou 0.7 --weights yolov5s.pt yolov5m.pt yolov5l.pt yolov5x.pt | ||
355 | + x = list(range(256, 1536 + 128, 128)) # x axis (image sizes) | ||
356 | + for w in opt.weights: | ||
357 | + f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to | ||
358 | + y = [] # y axis | ||
359 | + for i in x: # img-size | ||
360 | + print(f'\nRunning {f} point {i}...') | ||
361 | + r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json, | ||
362 | + plots=False, opt=opt) | ||
363 | + y.append(r + t) # results and times | ||
364 | + np.savetxt(f, y, fmt='%10.4g') # save | ||
365 | + os.system('zip -r study.zip study_*.txt') | ||
366 | + plot_study_txt(x=x) # plot |
YOLOv5/train.py
0 → 100644
1 | +import argparse | ||
2 | +import logging | ||
3 | +import math | ||
4 | +import os | ||
5 | +import random | ||
6 | +import time | ||
7 | +from copy import deepcopy | ||
8 | +from pathlib import Path | ||
9 | +from threading import Thread | ||
10 | + | ||
11 | +import numpy as np | ||
12 | +import torch.distributed as dist | ||
13 | +import torch.nn as nn | ||
14 | +import torch.nn.functional as F | ||
15 | +import torch.optim as optim | ||
16 | +import torch.optim.lr_scheduler as lr_scheduler | ||
17 | +import torch.utils.data | ||
18 | +import yaml | ||
19 | +from torch.cuda import amp | ||
20 | +from torch.nn.parallel import DistributedDataParallel as DDP | ||
21 | +from torch.utils.tensorboard import SummaryWriter | ||
22 | +from tqdm import tqdm | ||
23 | + | ||
24 | +import test # import test.py to get mAP after each epoch | ||
25 | +from models.experimental import attempt_load | ||
26 | +from models.yolo import Model | ||
27 | +from utils.autoanchor import check_anchors | ||
28 | +from utils.datasets import create_dataloader | ||
29 | +from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \ | ||
30 | + fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \ | ||
31 | + check_requirements, print_mutation, set_logging, one_cycle, colorstr | ||
32 | +from utils.google_utils import attempt_download | ||
33 | +from utils.loss import ComputeLoss | ||
34 | +from utils.plots import plot_images, plot_labels, plot_results, plot_evolution | ||
35 | +from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, de_parallel | ||
36 | +from utils.wandb_logging.wandb_utils import WandbLogger, check_wandb_resume | ||
37 | + | ||
38 | +logger = logging.getLogger(__name__) | ||
39 | + | ||
40 | + | ||
41 | +def train(hyp, opt, device, tb_writer=None): | ||
42 | + logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) | ||
43 | + save_dir, epochs, batch_size, total_batch_size, weights, rank = \ | ||
44 | + Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank | ||
45 | + | ||
46 | + # Directories | ||
47 | + wdir = save_dir / 'weights' | ||
48 | + wdir.mkdir(parents=True, exist_ok=True) # make dir | ||
49 | + last = wdir / 'last.pt' | ||
50 | + best = wdir / 'best.pt' | ||
51 | + results_file = save_dir / 'results.txt' | ||
52 | + | ||
53 | + # Save run settings | ||
54 | + with open(save_dir / 'hyp.yaml', 'w') as f: | ||
55 | + yaml.safe_dump(hyp, f, sort_keys=False) | ||
56 | + with open(save_dir / 'opt.yaml', 'w') as f: | ||
57 | + yaml.safe_dump(vars(opt), f, sort_keys=False) | ||
58 | + | ||
59 | + # Configure | ||
60 | + plots = not opt.evolve # create plots | ||
61 | + cuda = device.type != 'cpu' | ||
62 | + init_seeds(2 + rank) | ||
63 | + with open(opt.data) as f: | ||
64 | + data_dict = yaml.safe_load(f) # data dict | ||
65 | + | ||
66 | + # Logging- Doing this before checking the dataset. Might update data_dict | ||
67 | + loggers = {'wandb': None} # loggers dict | ||
68 | + if rank in [-1, 0]: | ||
69 | + opt.hyp = hyp # add hyperparameters | ||
70 | + run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None | ||
71 | + wandb_logger = WandbLogger(opt, save_dir.stem, run_id, data_dict) | ||
72 | + loggers['wandb'] = wandb_logger.wandb | ||
73 | + data_dict = wandb_logger.data_dict | ||
74 | + if wandb_logger.wandb: | ||
75 | + weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming | ||
76 | + | ||
77 | + nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes | ||
78 | + names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names | ||
79 | + assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check | ||
80 | + is_coco = opt.data.endswith('coco.yaml') and nc == 80 # COCO dataset | ||
81 | + | ||
82 | + # Model | ||
83 | + pretrained = weights.endswith('.pt') | ||
84 | + if pretrained: | ||
85 | + with torch_distributed_zero_first(rank): | ||
86 | + weights = attempt_download(weights) # download if not found locally | ||
87 | + ckpt = torch.load(weights, map_location=device) # load checkpoint | ||
88 | + model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create | ||
89 | + exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys | ||
90 | + state_dict = ckpt['model'].float().state_dict() # to FP32 | ||
91 | + state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect | ||
92 | + model.load_state_dict(state_dict, strict=False) # load | ||
93 | + logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report | ||
94 | + else: | ||
95 | + model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create | ||
96 | + with torch_distributed_zero_first(rank): | ||
97 | + check_dataset(data_dict) # check | ||
98 | + train_path = data_dict['train'] | ||
99 | + test_path = data_dict['val'] | ||
100 | + | ||
101 | + # Freeze | ||
102 | + freeze = [] # parameter names to freeze (full or partial) | ||
103 | + for k, v in model.named_parameters(): | ||
104 | + v.requires_grad = True # train all layers | ||
105 | + if any(x in k for x in freeze): | ||
106 | + print('freezing %s' % k) | ||
107 | + v.requires_grad = False | ||
108 | + | ||
109 | + # Optimizer | ||
110 | + nbs = 64 # nominal batch size | ||
111 | + accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing | ||
112 | + hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay | ||
113 | + logger.info(f"Scaled weight_decay = {hyp['weight_decay']}") | ||
114 | + | ||
115 | + pg0, pg1, pg2 = [], [], [] # optimizer parameter groups | ||
116 | + for k, v in model.named_modules(): | ||
117 | + if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): | ||
118 | + pg2.append(v.bias) # biases | ||
119 | + if isinstance(v, nn.BatchNorm2d): | ||
120 | + pg0.append(v.weight) # no decay | ||
121 | + elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): | ||
122 | + pg1.append(v.weight) # apply decay | ||
123 | + | ||
124 | + if opt.adam: | ||
125 | + optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum | ||
126 | + else: | ||
127 | + optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) | ||
128 | + | ||
129 | + optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay | ||
130 | + optimizer.add_param_group({'params': pg2}) # add pg2 (biases) | ||
131 | + logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0))) | ||
132 | + del pg0, pg1, pg2 | ||
133 | + | ||
134 | + # Scheduler https://arxiv.org/pdf/1812.01187.pdf | ||
135 | + # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR | ||
136 | + if opt.linear_lr: | ||
137 | + lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear | ||
138 | + else: | ||
139 | + lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf'] | ||
140 | + scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) | ||
141 | + # plot_lr_scheduler(optimizer, scheduler, epochs) | ||
142 | + | ||
143 | + # EMA | ||
144 | + ema = ModelEMA(model) if rank in [-1, 0] else None | ||
145 | + | ||
146 | + # Resume | ||
147 | + start_epoch, best_fitness = 0, 0.0 | ||
148 | + if pretrained: | ||
149 | + # Optimizer | ||
150 | + if ckpt['optimizer'] is not None: | ||
151 | + optimizer.load_state_dict(ckpt['optimizer']) | ||
152 | + best_fitness = ckpt['best_fitness'] | ||
153 | + | ||
154 | + # EMA | ||
155 | + if ema and ckpt.get('ema'): | ||
156 | + ema.ema.load_state_dict(ckpt['ema'].float().state_dict()) | ||
157 | + ema.updates = ckpt['updates'] | ||
158 | + | ||
159 | + # Results | ||
160 | + if ckpt.get('training_results') is not None: | ||
161 | + results_file.write_text(ckpt['training_results']) # write results.txt | ||
162 | + | ||
163 | + # Epochs | ||
164 | + start_epoch = ckpt['epoch'] + 1 | ||
165 | + if opt.resume: | ||
166 | + assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs) | ||
167 | + if epochs < start_epoch: | ||
168 | + logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' % | ||
169 | + (weights, ckpt['epoch'], epochs)) | ||
170 | + epochs += ckpt['epoch'] # finetune additional epochs | ||
171 | + | ||
172 | + del ckpt, state_dict | ||
173 | + | ||
174 | + # Image sizes | ||
175 | + gs = max(int(model.stride.max()), 32) # grid size (max stride) | ||
176 | + nl = model.model[-1].nl # number of detection layers (used for scaling hyp['obj']) | ||
177 | + imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples | ||
178 | + | ||
179 | + # DP mode | ||
180 | + if cuda and rank == -1 and torch.cuda.device_count() > 1: | ||
181 | + model = torch.nn.DataParallel(model) | ||
182 | + | ||
183 | + # SyncBatchNorm | ||
184 | + if opt.sync_bn and cuda and rank != -1: | ||
185 | + model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device) | ||
186 | + logger.info('Using SyncBatchNorm()') | ||
187 | + | ||
188 | + # Trainloader | ||
189 | + dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, | ||
190 | + hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank, | ||
191 | + world_size=opt.world_size, workers=opt.workers, | ||
192 | + image_weights=opt.image_weights, quad=opt.quad, prefix=colorstr('train: ')) | ||
193 | + mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class | ||
194 | + nb = len(dataloader) # number of batches | ||
195 | + assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1) | ||
196 | + | ||
197 | + # Process 0 | ||
198 | + if rank in [-1, 0]: | ||
199 | + testloader = create_dataloader(test_path, imgsz_test, batch_size * 2, gs, opt, # testloader | ||
200 | + hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True, rank=-1, | ||
201 | + world_size=opt.world_size, workers=opt.workers, | ||
202 | + pad=0.5, prefix=colorstr('val: '))[0] | ||
203 | + | ||
204 | + if not opt.resume: | ||
205 | + labels = np.concatenate(dataset.labels, 0) | ||
206 | + c = torch.tensor(labels[:, 0]) # classes | ||
207 | + # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency | ||
208 | + # model._initialize_biases(cf.to(device)) | ||
209 | + if plots: | ||
210 | + plot_labels(labels, names, save_dir, loggers) | ||
211 | + if tb_writer: | ||
212 | + tb_writer.add_histogram('classes', c, 0) | ||
213 | + | ||
214 | + # Anchors | ||
215 | + if not opt.noautoanchor: | ||
216 | + check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) | ||
217 | + model.half().float() # pre-reduce anchor precision | ||
218 | + | ||
219 | + # DDP mode | ||
220 | + if cuda and rank != -1: | ||
221 | + model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank, | ||
222 | + # nn.MultiheadAttention incompatibility with DDP https://github.com/pytorch/pytorch/issues/26698 | ||
223 | + find_unused_parameters=any(isinstance(layer, nn.MultiheadAttention) for layer in model.modules())) | ||
224 | + | ||
225 | + # Model parameters | ||
226 | + hyp['box'] *= 3. / nl # scale to layers | ||
227 | + hyp['cls'] *= nc / 80. * 3. / nl # scale to classes and layers | ||
228 | + hyp['obj'] *= (imgsz / 640) ** 2 * 3. / nl # scale to image size and layers | ||
229 | + hyp['label_smoothing'] = opt.label_smoothing | ||
230 | + model.nc = nc # attach number of classes to model | ||
231 | + model.hyp = hyp # attach hyperparameters to model | ||
232 | + model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou) | ||
233 | + model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights | ||
234 | + model.names = names | ||
235 | + | ||
236 | + # Start training | ||
237 | + t0 = time.time() | ||
238 | + nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations) | ||
239 | + # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training | ||
240 | + maps = np.zeros(nc) # mAP per class | ||
241 | + results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls) | ||
242 | + scheduler.last_epoch = start_epoch - 1 # do not move | ||
243 | + scaler = amp.GradScaler(enabled=cuda) | ||
244 | + compute_loss = ComputeLoss(model) # init loss class | ||
245 | + logger.info(f'Image sizes {imgsz} train, {imgsz_test} test\n' | ||
246 | + f'Using {dataloader.num_workers} dataloader workers\n' | ||
247 | + f'Logging results to {save_dir}\n' | ||
248 | + f'Starting training for {epochs} epochs...') | ||
249 | + for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ | ||
250 | + model.train() | ||
251 | + | ||
252 | + # Update image weights (optional) | ||
253 | + if opt.image_weights: | ||
254 | + # Generate indices | ||
255 | + if rank in [-1, 0]: | ||
256 | + cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights | ||
257 | + iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights | ||
258 | + dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx | ||
259 | + # Broadcast if DDP | ||
260 | + if rank != -1: | ||
261 | + indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int() | ||
262 | + dist.broadcast(indices, 0) | ||
263 | + if rank != 0: | ||
264 | + dataset.indices = indices.cpu().numpy() | ||
265 | + | ||
266 | + # Update mosaic border | ||
267 | + # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs) | ||
268 | + # dataset.mosaic_border = [b - imgsz, -b] # height, width borders | ||
269 | + | ||
270 | + mloss = torch.zeros(4, device=device) # mean losses | ||
271 | + if rank != -1: | ||
272 | + dataloader.sampler.set_epoch(epoch) | ||
273 | + pbar = enumerate(dataloader) | ||
274 | + logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'labels', 'img_size')) | ||
275 | + if rank in [-1, 0]: | ||
276 | + pbar = tqdm(pbar, total=nb) # progress bar | ||
277 | + optimizer.zero_grad() | ||
278 | + for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- | ||
279 | + ni = i + nb * epoch # number integrated batches (since train start) | ||
280 | + imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0 | ||
281 | + | ||
282 | + # Warmup | ||
283 | + if ni <= nw: | ||
284 | + xi = [0, nw] # x interp | ||
285 | + # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou) | ||
286 | + accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round()) | ||
287 | + for j, x in enumerate(optimizer.param_groups): | ||
288 | + # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 | ||
289 | + x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) | ||
290 | + if 'momentum' in x: | ||
291 | + x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']]) | ||
292 | + | ||
293 | + # Multi-scale | ||
294 | + if opt.multi_scale: | ||
295 | + sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size | ||
296 | + sf = sz / max(imgs.shape[2:]) # scale factor | ||
297 | + if sf != 1: | ||
298 | + ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) | ||
299 | + imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) | ||
300 | + | ||
301 | + # Forward | ||
302 | + with amp.autocast(enabled=cuda): | ||
303 | + pred = model(imgs) # forward | ||
304 | + loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size | ||
305 | + if rank != -1: | ||
306 | + loss *= opt.world_size # gradient averaged between devices in DDP mode | ||
307 | + if opt.quad: | ||
308 | + loss *= 4. | ||
309 | + | ||
310 | + # Backward | ||
311 | + scaler.scale(loss).backward() | ||
312 | + | ||
313 | + # Optimize | ||
314 | + if ni % accumulate == 0: | ||
315 | + scaler.step(optimizer) # optimizer.step | ||
316 | + scaler.update() | ||
317 | + optimizer.zero_grad() | ||
318 | + if ema: | ||
319 | + ema.update(model) | ||
320 | + | ||
321 | |||
322 | + if rank in [-1, 0]: | ||
323 | + mloss = (mloss * i + loss_items) / (i + 1) # update mean losses | ||
324 | + mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB) | ||
325 | + s = ('%10s' * 2 + '%10.4g' * 6) % ( | ||
326 | + '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1]) | ||
327 | + pbar.set_description(s) | ||
328 | + | ||
329 | + # Plot | ||
330 | + if plots and ni < 3: | ||
331 | + f = save_dir / f'train_batch{ni}.jpg' # filename | ||
332 | + Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() | ||
333 | + if tb_writer: | ||
334 | + tb_writer.add_graph(torch.jit.trace(de_parallel(model), imgs, strict=False), []) # model graph | ||
335 | + # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch) | ||
336 | + elif plots and ni == 10 and wandb_logger.wandb: | ||
337 | + wandb_logger.log({"Mosaics": [wandb_logger.wandb.Image(str(x), caption=x.name) for x in | ||
338 | + save_dir.glob('train*.jpg') if x.exists()]}) | ||
339 | + | ||
340 | + # end batch ------------------------------------------------------------------------------------------------ | ||
341 | + # end epoch ---------------------------------------------------------------------------------------------------- | ||
342 | + | ||
343 | + # Scheduler | ||
344 | + lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard | ||
345 | + scheduler.step() | ||
346 | + | ||
347 | + # DDP process 0 or single-GPU | ||
348 | + if rank in [-1, 0]: | ||
349 | + # mAP | ||
350 | + ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride', 'class_weights']) | ||
351 | + final_epoch = epoch + 1 == epochs | ||
352 | + if not opt.notest or final_epoch: # Calculate mAP | ||
353 | + wandb_logger.current_epoch = epoch + 1 | ||
354 | + results, maps, times = test.test(data_dict, | ||
355 | + batch_size=batch_size * 2, | ||
356 | + imgsz=imgsz_test, | ||
357 | + model=ema.ema, | ||
358 | + single_cls=opt.single_cls, | ||
359 | + dataloader=testloader, | ||
360 | + save_dir=save_dir, | ||
361 | + save_json=is_coco and final_epoch, | ||
362 | + verbose=nc < 50 and final_epoch, | ||
363 | + plots=plots and final_epoch, | ||
364 | + wandb_logger=wandb_logger, | ||
365 | + compute_loss=compute_loss, | ||
366 | + is_coco=is_coco) | ||
367 | + | ||
368 | + # Write | ||
369 | + with open(results_file, 'a') as f: | ||
370 | + f.write(s + '%10.4g' * 7 % results + '\n') # append metrics, val_loss | ||
371 | + | ||
372 | + # Log | ||
373 | + tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss | ||
374 | + 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', | ||
375 | + 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss | ||
376 | + 'x/lr0', 'x/lr1', 'x/lr2'] # params | ||
377 | + for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags): | ||
378 | + if tb_writer: | ||
379 | + tb_writer.add_scalar(tag, x, epoch) # tensorboard | ||
380 | + if wandb_logger.wandb: | ||
381 | + wandb_logger.log({tag: x}) # W&B | ||
382 | + | ||
383 | + # Update best mAP | ||
384 | + fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95] | ||
385 | + if fi > best_fitness: | ||
386 | + best_fitness = fi | ||
387 | + wandb_logger.end_epoch(best_result=best_fitness == fi) | ||
388 | + | ||
389 | + # Save model | ||
390 | + if (not opt.nosave) or (final_epoch and not opt.evolve): # if save | ||
391 | + ckpt = {'epoch': epoch, | ||
392 | + 'best_fitness': best_fitness, | ||
393 | + 'training_results': results_file.read_text(), | ||
394 | + 'model': deepcopy(de_parallel(model)).half(), | ||
395 | + 'ema': deepcopy(ema.ema).half(), | ||
396 | + 'updates': ema.updates, | ||
397 | + 'optimizer': optimizer.state_dict(), | ||
398 | + 'wandb_id': wandb_logger.wandb_run.id if wandb_logger.wandb else None} | ||
399 | + | ||
400 | + # Save last, best and delete | ||
401 | + torch.save(ckpt, last) | ||
402 | + if best_fitness == fi: | ||
403 | + torch.save(ckpt, best) | ||
404 | + if wandb_logger.wandb: | ||
405 | + if ((epoch + 1) % opt.save_period == 0 and not final_epoch) and opt.save_period != -1: | ||
406 | + wandb_logger.log_model( | ||
407 | + last.parent, opt, epoch, fi, best_model=best_fitness == fi) | ||
408 | + del ckpt | ||
409 | + | ||
410 | + # end epoch ---------------------------------------------------------------------------------------------------- | ||
411 | + # end training | ||
412 | + if rank in [-1, 0]: | ||
413 | + logger.info(f'{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.\n') | ||
414 | + if plots: | ||
415 | + plot_results(save_dir=save_dir) # save as results.png | ||
416 | + if wandb_logger.wandb: | ||
417 | + files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]] | ||
418 | + wandb_logger.log({"Results": [wandb_logger.wandb.Image(str(save_dir / f), caption=f) for f in files | ||
419 | + if (save_dir / f).exists()]}) | ||
420 | + | ||
421 | + if not opt.evolve: | ||
422 | + if is_coco: # COCO dataset | ||
423 | + for m in [last, best] if best.exists() else [last]: # speed, mAP tests | ||
424 | + results, _, _ = test.test(opt.data, | ||
425 | + batch_size=batch_size * 2, | ||
426 | + imgsz=imgsz_test, | ||
427 | + conf_thres=0.001, | ||
428 | + iou_thres=0.7, | ||
429 | + model=attempt_load(m, device).half(), | ||
430 | + single_cls=opt.single_cls, | ||
431 | + dataloader=testloader, | ||
432 | + save_dir=save_dir, | ||
433 | + save_json=True, | ||
434 | + plots=False, | ||
435 | + is_coco=is_coco) | ||
436 | + | ||
437 | + # Strip optimizers | ||
438 | + for f in last, best: | ||
439 | + if f.exists(): | ||
440 | + strip_optimizer(f) # strip optimizers | ||
441 | + if wandb_logger.wandb: # Log the stripped model | ||
442 | + wandb_logger.wandb.log_artifact(str(best if best.exists() else last), type='model', | ||
443 | + name='run_' + wandb_logger.wandb_run.id + '_model', | ||
444 | + aliases=['latest', 'best', 'stripped']) | ||
445 | + wandb_logger.finish_run() | ||
446 | + else: | ||
447 | + dist.destroy_process_group() | ||
448 | + torch.cuda.empty_cache() | ||
449 | + return results | ||
450 | + | ||
451 | + | ||
452 | +if __name__ == '__main__': | ||
453 | + parser = argparse.ArgumentParser() | ||
454 | + parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path') | ||
455 | + parser.add_argument('--cfg', type=str, default='', help='model.yaml path') | ||
456 | + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') | ||
457 | + parser.add_argument('--hyp', type=str, default='data/hyp.scratch.yaml', help='hyperparameters path') | ||
458 | + parser.add_argument('--epochs', type=int, default=300) | ||
459 | + parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs') | ||
460 | + parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes') | ||
461 | + parser.add_argument('--rect', action='store_true', help='rectangular training') | ||
462 | + parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') | ||
463 | + parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') | ||
464 | + parser.add_argument('--notest', action='store_true', help='only test final epoch') | ||
465 | + parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check') | ||
466 | + parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters') | ||
467 | + parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') | ||
468 | + parser.add_argument('--cache-images', action='store_true', help='cache images for faster training') | ||
469 | + parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training') | ||
470 | + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') | ||
471 | + parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%') | ||
472 | + parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class') | ||
473 | + parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer') | ||
474 | + parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode') | ||
475 | + parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify') | ||
476 | + parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers') | ||
477 | + parser.add_argument('--project', default='runs/train', help='save to project/name') | ||
478 | + parser.add_argument('--entity', default=None, help='W&B entity') | ||
479 | + parser.add_argument('--name', default='exp', help='save to project/name') | ||
480 | + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') | ||
481 | + parser.add_argument('--quad', action='store_true', help='quad dataloader') | ||
482 | + parser.add_argument('--linear-lr', action='store_true', help='linear LR') | ||
483 | + parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon') | ||
484 | + parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table') | ||
485 | + parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B') | ||
486 | + parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch') | ||
487 | + parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used') | ||
488 | + opt = parser.parse_args() | ||
489 | + | ||
490 | + # Set DDP variables | ||
491 | + opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 | ||
492 | + opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1 | ||
493 | + set_logging(opt.global_rank) | ||
494 | + if opt.global_rank in [-1, 0]: | ||
495 | + check_git_status() | ||
496 | + check_requirements(exclude=('pycocotools', 'thop')) | ||
497 | + | ||
498 | + # Resume | ||
499 | + wandb_run = check_wandb_resume(opt) | ||
500 | + if opt.resume and not wandb_run: # resume an interrupted run | ||
501 | + ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path | ||
502 | + assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist' | ||
503 | + apriori = opt.global_rank, opt.local_rank | ||
504 | + with open(Path(ckpt).parent.parent / 'opt.yaml') as f: | ||
505 | + opt = argparse.Namespace(**yaml.safe_load(f)) # replace | ||
506 | + opt.cfg, opt.weights, opt.resume, opt.batch_size, opt.global_rank, opt.local_rank = \ | ||
507 | + '', ckpt, True, opt.total_batch_size, *apriori # reinstate | ||
508 | + logger.info('Resuming training from %s' % ckpt) | ||
509 | + else: | ||
510 | + # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml') | ||
511 | + opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files | ||
512 | + assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified' | ||
513 | + opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test) | ||
514 | + opt.name = 'evolve' if opt.evolve else opt.name | ||
515 | + opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve)) | ||
516 | + | ||
517 | + # DDP mode | ||
518 | + opt.total_batch_size = opt.batch_size | ||
519 | + device = select_device(opt.device, batch_size=opt.batch_size) | ||
520 | + if opt.local_rank != -1: | ||
521 | + assert torch.cuda.device_count() > opt.local_rank | ||
522 | + torch.cuda.set_device(opt.local_rank) | ||
523 | + device = torch.device('cuda', opt.local_rank) | ||
524 | + dist.init_process_group(backend='nccl', init_method='env://') # distributed backend | ||
525 | + assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count' | ||
526 | + assert not opt.image_weights, '--image-weights argument is not compatible with DDP training' | ||
527 | + opt.batch_size = opt.total_batch_size // opt.world_size | ||
528 | + | ||
529 | + # Hyperparameters | ||
530 | + with open(opt.hyp) as f: | ||
531 | + hyp = yaml.safe_load(f) # load hyps | ||
532 | + | ||
533 | + # Train | ||
534 | + logger.info(opt) | ||
535 | + if not opt.evolve: | ||
536 | + tb_writer = None # init loggers | ||
537 | + if opt.global_rank in [-1, 0]: | ||
538 | + prefix = colorstr('tensorboard: ') | ||
539 | + logger.info(f"{prefix}Start with 'tensorboard --logdir {opt.project}', view at http://localhost:6006/") | ||
540 | + tb_writer = SummaryWriter(opt.save_dir) # Tensorboard | ||
541 | + train(hyp, opt, device, tb_writer) | ||
542 | + | ||
543 | + # Evolve hyperparameters (optional) | ||
544 | + else: | ||
545 | + # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit) | ||
546 | + meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3) | ||
547 | + 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) | ||
548 | + 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1 | ||
549 | + 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay | ||
550 | + 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok) | ||
551 | + 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum | ||
552 | + 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr | ||
553 | + 'box': (1, 0.02, 0.2), # box loss gain | ||
554 | + 'cls': (1, 0.2, 4.0), # cls loss gain | ||
555 | + 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight | ||
556 | + 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels) | ||
557 | + 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight | ||
558 | + 'iou_t': (0, 0.1, 0.7), # IoU training threshold | ||
559 | + 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold | ||
560 | + 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore) | ||
561 | + 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5) | ||
562 | + 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction) | ||
563 | + 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction) | ||
564 | + 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction) | ||
565 | + 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg) | ||
566 | + 'translate': (1, 0.0, 0.9), # image translation (+/- fraction) | ||
567 | + 'scale': (1, 0.0, 0.9), # image scale (+/- gain) | ||
568 | + 'shear': (1, 0.0, 10.0), # image shear (+/- deg) | ||
569 | + 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 | ||
570 | + 'flipud': (1, 0.0, 1.0), # image flip up-down (probability) | ||
571 | + 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability) | ||
572 | + 'mosaic': (1, 0.0, 1.0), # image mixup (probability) | ||
573 | + 'mixup': (1, 0.0, 1.0)} # image mixup (probability) | ||
574 | + | ||
575 | + assert opt.local_rank == -1, 'DDP mode not implemented for --evolve' | ||
576 | + opt.notest, opt.nosave = True, True # only test/save final epoch | ||
577 | + # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices | ||
578 | + yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here | ||
579 | + if opt.bucket: | ||
580 | + os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists | ||
581 | + | ||
582 | + for _ in range(300): # generations to evolve | ||
583 | + if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate | ||
584 | + # Select parent(s) | ||
585 | + parent = 'single' # parent selection method: 'single' or 'weighted' | ||
586 | + x = np.loadtxt('evolve.txt', ndmin=2) | ||
587 | + n = min(5, len(x)) # number of previous results to consider | ||
588 | + x = x[np.argsort(-fitness(x))][:n] # top n mutations | ||
589 | + w = fitness(x) - fitness(x).min() # weights | ||
590 | + if parent == 'single' or len(x) == 1: | ||
591 | + # x = x[random.randint(0, n - 1)] # random selection | ||
592 | + x = x[random.choices(range(n), weights=w)[0]] # weighted selection | ||
593 | + elif parent == 'weighted': | ||
594 | + x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination | ||
595 | + | ||
596 | + # Mutate | ||
597 | + mp, s = 0.8, 0.2 # mutation probability, sigma | ||
598 | + npr = np.random | ||
599 | + npr.seed(int(time.time())) | ||
600 | + g = np.array([x[0] for x in meta.values()]) # gains 0-1 | ||
601 | + ng = len(meta) | ||
602 | + v = np.ones(ng) | ||
603 | + while all(v == 1): # mutate until a change occurs (prevent duplicates) | ||
604 | + v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) | ||
605 | + for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) | ||
606 | + hyp[k] = float(x[i + 7] * v[i]) # mutate | ||
607 | + | ||
608 | + # Constrain to limits | ||
609 | + for k, v in meta.items(): | ||
610 | + hyp[k] = max(hyp[k], v[1]) # lower limit | ||
611 | + hyp[k] = min(hyp[k], v[2]) # upper limit | ||
612 | + hyp[k] = round(hyp[k], 5) # significant digits | ||
613 | + | ||
614 | + # Train mutation | ||
615 | + results = train(hyp.copy(), opt, device) | ||
616 | + | ||
617 | + # Write mutation results | ||
618 | + print_mutation(hyp.copy(), results, yaml_file, opt.bucket) | ||
619 | + | ||
620 | + # Plot results | ||
621 | + plot_evolution(yaml_file) | ||
622 | + print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n' | ||
623 | + f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}') |
YOLOv5/tutorial.ipynb
0 → 100644
This diff could not be displayed because it is too large.
YOLOv5/utils/__init__.py
0 → 100644
File mode changed
YOLOv5/utils/activations.py
0 → 100644
1 | +# Activation functions | ||
2 | + | ||
3 | +import torch | ||
4 | +import torch.nn as nn | ||
5 | +import torch.nn.functional as F | ||
6 | + | ||
7 | + | ||
8 | +# SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- | ||
9 | +class SiLU(nn.Module): # export-friendly version of nn.SiLU() | ||
10 | + @staticmethod | ||
11 | + def forward(x): | ||
12 | + return x * torch.sigmoid(x) | ||
13 | + | ||
14 | + | ||
15 | +class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() | ||
16 | + @staticmethod | ||
17 | + def forward(x): | ||
18 | + # return x * F.hardsigmoid(x) # for torchscript and CoreML | ||
19 | + return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX | ||
20 | + | ||
21 | + | ||
22 | +# Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- | ||
23 | +class Mish(nn.Module): | ||
24 | + @staticmethod | ||
25 | + def forward(x): | ||
26 | + return x * F.softplus(x).tanh() | ||
27 | + | ||
28 | + | ||
29 | +class MemoryEfficientMish(nn.Module): | ||
30 | + class F(torch.autograd.Function): | ||
31 | + @staticmethod | ||
32 | + def forward(ctx, x): | ||
33 | + ctx.save_for_backward(x) | ||
34 | + return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) | ||
35 | + | ||
36 | + @staticmethod | ||
37 | + def backward(ctx, grad_output): | ||
38 | + x = ctx.saved_tensors[0] | ||
39 | + sx = torch.sigmoid(x) | ||
40 | + fx = F.softplus(x).tanh() | ||
41 | + return grad_output * (fx + x * sx * (1 - fx * fx)) | ||
42 | + | ||
43 | + def forward(self, x): | ||
44 | + return self.F.apply(x) | ||
45 | + | ||
46 | + | ||
47 | +# FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- | ||
48 | +class FReLU(nn.Module): | ||
49 | + def __init__(self, c1, k=3): # ch_in, kernel | ||
50 | + super().__init__() | ||
51 | + self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) | ||
52 | + self.bn = nn.BatchNorm2d(c1) | ||
53 | + | ||
54 | + def forward(self, x): | ||
55 | + return torch.max(x, self.bn(self.conv(x))) | ||
56 | + | ||
57 | + | ||
58 | +# ACON https://arxiv.org/pdf/2009.04759.pdf ---------------------------------------------------------------------------- | ||
59 | +class AconC(nn.Module): | ||
60 | + r""" ACON activation (activate or not). | ||
61 | + AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter | ||
62 | + according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>. | ||
63 | + """ | ||
64 | + | ||
65 | + def __init__(self, c1): | ||
66 | + super().__init__() | ||
67 | + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) | ||
68 | + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) | ||
69 | + self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) | ||
70 | + | ||
71 | + def forward(self, x): | ||
72 | + dpx = (self.p1 - self.p2) * x | ||
73 | + return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x | ||
74 | + | ||
75 | + | ||
76 | +class MetaAconC(nn.Module): | ||
77 | + r""" ACON activation (activate or not). | ||
78 | + MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network | ||
79 | + according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>. | ||
80 | + """ | ||
81 | + | ||
82 | + def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r | ||
83 | + super().__init__() | ||
84 | + c2 = max(r, c1 // r) | ||
85 | + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) | ||
86 | + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) | ||
87 | + self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) | ||
88 | + self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) | ||
89 | + # self.bn1 = nn.BatchNorm2d(c2) | ||
90 | + # self.bn2 = nn.BatchNorm2d(c1) | ||
91 | + | ||
92 | + def forward(self, x): | ||
93 | + y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) | ||
94 | + # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 | ||
95 | + # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable | ||
96 | + beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed | ||
97 | + dpx = (self.p1 - self.p2) * x | ||
98 | + return dpx * torch.sigmoid(beta * dpx) + self.p2 * x |
YOLOv5/utils/autoanchor.py
0 → 100644
1 | +# Auto-anchor utils | ||
2 | + | ||
3 | +import numpy as np | ||
4 | +import torch | ||
5 | +import yaml | ||
6 | +from tqdm import tqdm | ||
7 | + | ||
8 | +from utils.general import colorstr | ||
9 | + | ||
10 | + | ||
11 | +def check_anchor_order(m): | ||
12 | + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary | ||
13 | + a = m.anchor_grid.prod(-1).view(-1) # anchor area | ||
14 | + da = a[-1] - a[0] # delta a | ||
15 | + ds = m.stride[-1] - m.stride[0] # delta s | ||
16 | + if da.sign() != ds.sign(): # same order | ||
17 | + print('Reversing anchor order') | ||
18 | + m.anchors[:] = m.anchors.flip(0) | ||
19 | + m.anchor_grid[:] = m.anchor_grid.flip(0) | ||
20 | + | ||
21 | + | ||
22 | +def check_anchors(dataset, model, thr=4.0, imgsz=640): | ||
23 | + # Check anchor fit to data, recompute if necessary | ||
24 | + prefix = colorstr('autoanchor: ') | ||
25 | + print(f'\n{prefix}Analyzing anchors... ', end='') | ||
26 | + m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() | ||
27 | + shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) | ||
28 | + scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale | ||
29 | + wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh | ||
30 | + | ||
31 | + def metric(k): # compute metric | ||
32 | + r = wh[:, None] / k[None] | ||
33 | + x = torch.min(r, 1. / r).min(2)[0] # ratio metric | ||
34 | + best = x.max(1)[0] # best_x | ||
35 | + aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold | ||
36 | + bpr = (best > 1. / thr).float().mean() # best possible recall | ||
37 | + return bpr, aat | ||
38 | + | ||
39 | + anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors | ||
40 | + bpr, aat = metric(anchors) | ||
41 | + print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') | ||
42 | + if bpr < 0.98: # threshold to recompute | ||
43 | + print('. Attempting to improve anchors, please wait...') | ||
44 | + na = m.anchor_grid.numel() // 2 # number of anchors | ||
45 | + try: | ||
46 | + anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) | ||
47 | + except Exception as e: | ||
48 | + print(f'{prefix}ERROR: {e}') | ||
49 | + new_bpr = metric(anchors)[0] | ||
50 | + if new_bpr > bpr: # replace anchors | ||
51 | + anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) | ||
52 | + m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference | ||
53 | + m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss | ||
54 | + check_anchor_order(m) | ||
55 | + print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') | ||
56 | + else: | ||
57 | + print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') | ||
58 | + print('') # newline | ||
59 | + | ||
60 | + | ||
61 | +def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): | ||
62 | + """ Creates kmeans-evolved anchors from training dataset | ||
63 | + | ||
64 | + Arguments: | ||
65 | + path: path to dataset *.yaml, or a loaded dataset | ||
66 | + n: number of anchors | ||
67 | + img_size: image size used for training | ||
68 | + thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 | ||
69 | + gen: generations to evolve anchors using genetic algorithm | ||
70 | + verbose: print all results | ||
71 | + | ||
72 | + Return: | ||
73 | + k: kmeans evolved anchors | ||
74 | + | ||
75 | + Usage: | ||
76 | + from utils.autoanchor import *; _ = kmean_anchors() | ||
77 | + """ | ||
78 | + from scipy.cluster.vq import kmeans | ||
79 | + | ||
80 | + thr = 1. / thr | ||
81 | + prefix = colorstr('autoanchor: ') | ||
82 | + | ||
83 | + def metric(k, wh): # compute metrics | ||
84 | + r = wh[:, None] / k[None] | ||
85 | + x = torch.min(r, 1. / r).min(2)[0] # ratio metric | ||
86 | + # x = wh_iou(wh, torch.tensor(k)) # iou metric | ||
87 | + return x, x.max(1)[0] # x, best_x | ||
88 | + | ||
89 | + def anchor_fitness(k): # mutation fitness | ||
90 | + _, best = metric(torch.tensor(k, dtype=torch.float32), wh) | ||
91 | + return (best * (best > thr).float()).mean() # fitness | ||
92 | + | ||
93 | + def print_results(k): | ||
94 | + k = k[np.argsort(k.prod(1))] # sort small to large | ||
95 | + x, best = metric(k, wh0) | ||
96 | + bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr | ||
97 | + print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') | ||
98 | + print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' | ||
99 | + f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') | ||
100 | + for i, x in enumerate(k): | ||
101 | + print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg | ||
102 | + return k | ||
103 | + | ||
104 | + if isinstance(path, str): # *.yaml file | ||
105 | + with open(path) as f: | ||
106 | + data_dict = yaml.safe_load(f) # model dict | ||
107 | + from utils.datasets import LoadImagesAndLabels | ||
108 | + dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) | ||
109 | + else: | ||
110 | + dataset = path # dataset | ||
111 | + | ||
112 | + # Get label wh | ||
113 | + shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) | ||
114 | + wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh | ||
115 | + | ||
116 | + # Filter | ||
117 | + i = (wh0 < 3.0).any(1).sum() | ||
118 | + if i: | ||
119 | + print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') | ||
120 | + wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels | ||
121 | + # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 | ||
122 | + | ||
123 | + # Kmeans calculation | ||
124 | + print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') | ||
125 | + s = wh.std(0) # sigmas for whitening | ||
126 | + k, dist = kmeans(wh / s, n, iter=30) # points, mean distance | ||
127 | + assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}') | ||
128 | + k *= s | ||
129 | + wh = torch.tensor(wh, dtype=torch.float32) # filtered | ||
130 | + wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered | ||
131 | + k = print_results(k) | ||
132 | + | ||
133 | + # Plot | ||
134 | + # k, d = [None] * 20, [None] * 20 | ||
135 | + # for i in tqdm(range(1, 21)): | ||
136 | + # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance | ||
137 | + # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) | ||
138 | + # ax = ax.ravel() | ||
139 | + # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') | ||
140 | + # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh | ||
141 | + # ax[0].hist(wh[wh[:, 0]<100, 0],400) | ||
142 | + # ax[1].hist(wh[wh[:, 1]<100, 1],400) | ||
143 | + # fig.savefig('wh.png', dpi=200) | ||
144 | + | ||
145 | + # Evolve | ||
146 | + npr = np.random | ||
147 | + f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma | ||
148 | + pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar | ||
149 | + for _ in pbar: | ||
150 | + v = np.ones(sh) | ||
151 | + while (v == 1).all(): # mutate until a change occurs (prevent duplicates) | ||
152 | + v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) | ||
153 | + kg = (k.copy() * v).clip(min=2.0) | ||
154 | + fg = anchor_fitness(kg) | ||
155 | + if fg > f: | ||
156 | + f, k = fg, kg.copy() | ||
157 | + pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' | ||
158 | + if verbose: | ||
159 | + print_results(k) | ||
160 | + | ||
161 | + return print_results(k) |
YOLOv5/utils/aws/__init__.py
0 → 100644
File mode changed
YOLOv5/utils/aws/mime.sh
0 → 100644
1 | +# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ | ||
2 | +# This script will run on every instance restart, not only on first start | ||
3 | +# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- | ||
4 | + | ||
5 | +Content-Type: multipart/mixed; boundary="//" | ||
6 | +MIME-Version: 1.0 | ||
7 | + | ||
8 | +--// | ||
9 | +Content-Type: text/cloud-config; charset="us-ascii" | ||
10 | +MIME-Version: 1.0 | ||
11 | +Content-Transfer-Encoding: 7bit | ||
12 | +Content-Disposition: attachment; filename="cloud-config.txt" | ||
13 | + | ||
14 | +#cloud-config | ||
15 | +cloud_final_modules: | ||
16 | +- [scripts-user, always] | ||
17 | + | ||
18 | +--// | ||
19 | +Content-Type: text/x-shellscript; charset="us-ascii" | ||
20 | +MIME-Version: 1.0 | ||
21 | +Content-Transfer-Encoding: 7bit | ||
22 | +Content-Disposition: attachment; filename="userdata.txt" | ||
23 | + | ||
24 | +#!/bin/bash | ||
25 | +# --- paste contents of userdata.sh here --- | ||
26 | +--// |
YOLOv5/utils/aws/resume.py
0 → 100644
1 | +# Resume all interrupted trainings in yolov5/ dir including DDP trainings | ||
2 | +# Usage: $ python utils/aws/resume.py | ||
3 | + | ||
4 | +import os | ||
5 | +import sys | ||
6 | +from pathlib import Path | ||
7 | + | ||
8 | +import torch | ||
9 | +import yaml | ||
10 | + | ||
11 | +sys.path.append('./') # to run '$ python *.py' files in subdirectories | ||
12 | + | ||
13 | +port = 0 # --master_port | ||
14 | +path = Path('').resolve() | ||
15 | +for last in path.rglob('*/**/last.pt'): | ||
16 | + ckpt = torch.load(last) | ||
17 | + if ckpt['optimizer'] is None: | ||
18 | + continue | ||
19 | + | ||
20 | + # Load opt.yaml | ||
21 | + with open(last.parent.parent / 'opt.yaml') as f: | ||
22 | + opt = yaml.safe_load(f) | ||
23 | + | ||
24 | + # Get device count | ||
25 | + d = opt['device'].split(',') # devices | ||
26 | + nd = len(d) # number of devices | ||
27 | + ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel | ||
28 | + | ||
29 | + if ddp: # multi-GPU | ||
30 | + port += 1 | ||
31 | + cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}' | ||
32 | + else: # single-GPU | ||
33 | + cmd = f'python train.py --resume {last}' | ||
34 | + | ||
35 | + cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread | ||
36 | + print(cmd) | ||
37 | + os.system(cmd) |
YOLOv5/utils/aws/userdata.sh
0 → 100644
1 | +#!/bin/bash | ||
2 | +# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html | ||
3 | +# This script will run only once on first instance start (for a re-start script see mime.sh) | ||
4 | +# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir | ||
5 | +# Use >300 GB SSD | ||
6 | + | ||
7 | +cd home/ubuntu | ||
8 | +if [ ! -d yolov5 ]; then | ||
9 | + echo "Running first-time script." # install dependencies, download COCO, pull Docker | ||
10 | + git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5 | ||
11 | + cd yolov5 | ||
12 | + bash data/scripts/get_coco.sh && echo "Data done." & | ||
13 | + sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & | ||
14 | + python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & | ||
15 | + wait && echo "All tasks done." # finish background tasks | ||
16 | +else | ||
17 | + echo "Running re-start script." # resume interrupted runs | ||
18 | + i=0 | ||
19 | + list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' | ||
20 | + while IFS= read -r id; do | ||
21 | + ((i++)) | ||
22 | + echo "restarting container $i: $id" | ||
23 | + sudo docker start $id | ||
24 | + # sudo docker exec -it $id python train.py --resume # single-GPU | ||
25 | + sudo docker exec -d $id python utils/aws/resume.py # multi-scenario | ||
26 | + done <<<"$list" | ||
27 | +fi |
YOLOv5/utils/datasets.py
0 → 100644
1 | +# Dataset utils and dataloaders | ||
2 | + | ||
3 | +import glob | ||
4 | +import hashlib | ||
5 | +import logging | ||
6 | +import math | ||
7 | +import os | ||
8 | +import random | ||
9 | +import shutil | ||
10 | +import time | ||
11 | +from itertools import repeat | ||
12 | +from multiprocessing.pool import ThreadPool | ||
13 | +from pathlib import Path | ||
14 | +from threading import Thread | ||
15 | + | ||
16 | +import cv2 | ||
17 | +import numpy as np | ||
18 | +import torch | ||
19 | +import torch.nn.functional as F | ||
20 | +from PIL import Image, ExifTags | ||
21 | +from torch.utils.data import Dataset | ||
22 | +from tqdm import tqdm | ||
23 | + | ||
24 | +from utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \ | ||
25 | + resample_segments, clean_str | ||
26 | +from utils.torch_utils import torch_distributed_zero_first | ||
27 | + | ||
28 | +# Parameters | ||
29 | +help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' | ||
30 | +img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes | ||
31 | +vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes | ||
32 | +logger = logging.getLogger(__name__) | ||
33 | + | ||
34 | +# Get orientation exif tag | ||
35 | +for orientation in ExifTags.TAGS.keys(): | ||
36 | + if ExifTags.TAGS[orientation] == 'Orientation': | ||
37 | + break | ||
38 | + | ||
39 | + | ||
40 | +def get_hash(paths): | ||
41 | + # Returns a single hash value of a list of paths (files or dirs) | ||
42 | + size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes | ||
43 | + h = hashlib.md5(str(size).encode()) # hash sizes | ||
44 | + h.update(''.join(paths).encode()) # hash paths | ||
45 | + return h.hexdigest() # return hash | ||
46 | + | ||
47 | + | ||
48 | +def exif_size(img): | ||
49 | + # Returns exif-corrected PIL size | ||
50 | + s = img.size # (width, height) | ||
51 | + try: | ||
52 | + rotation = dict(img._getexif().items())[orientation] | ||
53 | + if rotation == 6: # rotation 270 | ||
54 | + s = (s[1], s[0]) | ||
55 | + elif rotation == 8: # rotation 90 | ||
56 | + s = (s[1], s[0]) | ||
57 | + except: | ||
58 | + pass | ||
59 | + | ||
60 | + return s | ||
61 | + | ||
62 | + | ||
63 | +def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False, | ||
64 | + rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''): | ||
65 | + # Make sure only the first process in DDP process the dataset first, and the following others can use the cache | ||
66 | + with torch_distributed_zero_first(rank): | ||
67 | + dataset = LoadImagesAndLabels(path, imgsz, batch_size, | ||
68 | + augment=augment, # augment images | ||
69 | + hyp=hyp, # augmentation hyperparameters | ||
70 | + rect=rect, # rectangular training | ||
71 | + cache_images=cache, | ||
72 | + single_cls=opt.single_cls, | ||
73 | + stride=int(stride), | ||
74 | + pad=pad, | ||
75 | + image_weights=image_weights, | ||
76 | + prefix=prefix) | ||
77 | + | ||
78 | + batch_size = min(batch_size, len(dataset)) | ||
79 | + nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers | ||
80 | + sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None | ||
81 | + loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader | ||
82 | + # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader() | ||
83 | + dataloader = loader(dataset, | ||
84 | + batch_size=batch_size, | ||
85 | + num_workers=nw, | ||
86 | + sampler=sampler, | ||
87 | + pin_memory=True, | ||
88 | + collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn) | ||
89 | + return dataloader, dataset | ||
90 | + | ||
91 | + | ||
92 | +class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader): | ||
93 | + """ Dataloader that reuses workers | ||
94 | + | ||
95 | + Uses same syntax as vanilla DataLoader | ||
96 | + """ | ||
97 | + | ||
98 | + def __init__(self, *args, **kwargs): | ||
99 | + super().__init__(*args, **kwargs) | ||
100 | + object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) | ||
101 | + self.iterator = super().__iter__() | ||
102 | + | ||
103 | + def __len__(self): | ||
104 | + return len(self.batch_sampler.sampler) | ||
105 | + | ||
106 | + def __iter__(self): | ||
107 | + for i in range(len(self)): | ||
108 | + yield next(self.iterator) | ||
109 | + | ||
110 | + | ||
111 | +class _RepeatSampler(object): | ||
112 | + """ Sampler that repeats forever | ||
113 | + | ||
114 | + Args: | ||
115 | + sampler (Sampler) | ||
116 | + """ | ||
117 | + | ||
118 | + def __init__(self, sampler): | ||
119 | + self.sampler = sampler | ||
120 | + | ||
121 | + def __iter__(self): | ||
122 | + while True: | ||
123 | + yield from iter(self.sampler) | ||
124 | + | ||
125 | + | ||
126 | +class LoadImages: # for inference | ||
127 | + def __init__(self, path, img_size=640, stride=32): | ||
128 | + p = str(Path(path).absolute()) # os-agnostic absolute path | ||
129 | + if '*' in p: | ||
130 | + files = sorted(glob.glob(p, recursive=True)) # glob | ||
131 | + elif os.path.isdir(p): | ||
132 | + files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir | ||
133 | + elif os.path.isfile(p): | ||
134 | + files = [p] # files | ||
135 | + else: | ||
136 | + raise Exception(f'ERROR: {p} does not exist') | ||
137 | + | ||
138 | + images = [x for x in files if x.split('.')[-1].lower() in img_formats] | ||
139 | + videos = [x for x in files if x.split('.')[-1].lower() in vid_formats] | ||
140 | + ni, nv = len(images), len(videos) | ||
141 | + | ||
142 | + self.img_size = img_size | ||
143 | + self.stride = stride | ||
144 | + self.files = images + videos | ||
145 | + self.nf = ni + nv # number of files | ||
146 | + self.video_flag = [False] * ni + [True] * nv | ||
147 | + self.mode = 'image' | ||
148 | + if any(videos): | ||
149 | + self.new_video(videos[0]) # new video | ||
150 | + else: | ||
151 | + self.cap = None | ||
152 | + assert self.nf > 0, f'No images or videos found in {p}. ' \ | ||
153 | + f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}' | ||
154 | + | ||
155 | + def __iter__(self): | ||
156 | + self.count = 0 | ||
157 | + return self | ||
158 | + | ||
159 | + def __next__(self): | ||
160 | + if self.count == self.nf: | ||
161 | + raise StopIteration | ||
162 | + path = self.files[self.count] | ||
163 | + | ||
164 | + if self.video_flag[self.count]: | ||
165 | + # Read video | ||
166 | + self.mode = 'video' | ||
167 | + ret_val, img0 = self.cap.read() | ||
168 | + if not ret_val: | ||
169 | + self.count += 1 | ||
170 | + self.cap.release() | ||
171 | + if self.count == self.nf: # last video | ||
172 | + raise StopIteration | ||
173 | + else: | ||
174 | + path = self.files[self.count] | ||
175 | + self.new_video(path) | ||
176 | + ret_val, img0 = self.cap.read() | ||
177 | + | ||
178 | + self.frame += 1 | ||
179 | + print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='') | ||
180 | + | ||
181 | + else: | ||
182 | + # Read image | ||
183 | + self.count += 1 | ||
184 | + img0 = cv2.imread(path) # BGR | ||
185 | + assert img0 is not None, 'Image Not Found ' + path | ||
186 | + print(f'image {self.count}/{self.nf} {path}: ', end='') | ||
187 | + | ||
188 | + # Padded resize | ||
189 | + img = letterbox(img0, self.img_size, stride=self.stride)[0] | ||
190 | + | ||
191 | + # Convert | ||
192 | + img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 | ||
193 | + img = np.ascontiguousarray(img) | ||
194 | + | ||
195 | + return path, img, img0, self.cap | ||
196 | + | ||
197 | + def new_video(self, path): | ||
198 | + self.frame = 0 | ||
199 | + self.cap = cv2.VideoCapture(path) | ||
200 | + self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) | ||
201 | + | ||
202 | + def __len__(self): | ||
203 | + return self.nf # number of files | ||
204 | + | ||
205 | + | ||
206 | +class LoadWebcam: # for inference | ||
207 | + def __init__(self, pipe='0', img_size=640, stride=32): | ||
208 | + self.img_size = img_size | ||
209 | + self.stride = stride | ||
210 | + | ||
211 | + if pipe.isnumeric(): | ||
212 | + pipe = eval(pipe) # local camera | ||
213 | + # pipe = 'rtsp://192.168.1.64/1' # IP camera | ||
214 | + # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login | ||
215 | + # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera | ||
216 | + | ||
217 | + self.pipe = pipe | ||
218 | + self.cap = cv2.VideoCapture(pipe) # video capture object | ||
219 | + self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size | ||
220 | + | ||
221 | + def __iter__(self): | ||
222 | + self.count = -1 | ||
223 | + return self | ||
224 | + | ||
225 | + def __next__(self): | ||
226 | + self.count += 1 | ||
227 | + if cv2.waitKey(1) == ord('q'): # q to quit | ||
228 | + self.cap.release() | ||
229 | + cv2.destroyAllWindows() | ||
230 | + raise StopIteration | ||
231 | + | ||
232 | + # Read frame | ||
233 | + if self.pipe == 0: # local camera | ||
234 | + ret_val, img0 = self.cap.read() | ||
235 | + img0 = cv2.flip(img0, 1) # flip left-right | ||
236 | + else: # IP camera | ||
237 | + n = 0 | ||
238 | + while True: | ||
239 | + n += 1 | ||
240 | + self.cap.grab() | ||
241 | + if n % 30 == 0: # skip frames | ||
242 | + ret_val, img0 = self.cap.retrieve() | ||
243 | + if ret_val: | ||
244 | + break | ||
245 | + | ||
246 | |||
247 | + assert ret_val, f'Camera Error {self.pipe}' | ||
248 | + img_path = 'webcam.jpg' | ||
249 | + print(f'webcam {self.count}: ', end='') | ||
250 | + | ||
251 | + # Padded resize | ||
252 | + img = letterbox(img0, self.img_size, stride=self.stride)[0] | ||
253 | + | ||
254 | + # Convert | ||
255 | + img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 | ||
256 | + img = np.ascontiguousarray(img) | ||
257 | + | ||
258 | + return img_path, img, img0, None | ||
259 | + | ||
260 | + def __len__(self): | ||
261 | + return 0 | ||
262 | + | ||
263 | + | ||
264 | +class LoadStreams: # multiple IP or RTSP cameras | ||
265 | + def __init__(self, sources='streams.txt', img_size=640, stride=32): | ||
266 | + self.mode = 'stream' | ||
267 | + self.img_size = img_size | ||
268 | + self.stride = stride | ||
269 | + | ||
270 | + if os.path.isfile(sources): | ||
271 | + with open(sources, 'r') as f: | ||
272 | + sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] | ||
273 | + else: | ||
274 | + sources = [sources] | ||
275 | + | ||
276 | + n = len(sources) | ||
277 | + self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n | ||
278 | + self.sources = [clean_str(x) for x in sources] # clean source names for later | ||
279 | + for i, s in enumerate(sources): # index, source | ||
280 | + # Start thread to read frames from video stream | ||
281 | + print(f'{i + 1}/{n}: {s}... ', end='') | ||
282 | + if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video | ||
283 | + check_requirements(('pafy', 'youtube_dl')) | ||
284 | + import pafy | ||
285 | + s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL | ||
286 | + s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam | ||
287 | + cap = cv2.VideoCapture(s) | ||
288 | + assert cap.isOpened(), f'Failed to open {s}' | ||
289 | + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | ||
290 | + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | ||
291 | + self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback | ||
292 | + self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback | ||
293 | + | ||
294 | + _, self.imgs[i] = cap.read() # guarantee first frame | ||
295 | + self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True) | ||
296 | + print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") | ||
297 | + self.threads[i].start() | ||
298 | + print('') # newline | ||
299 | + | ||
300 | + # check for common shapes | ||
301 | + s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes | ||
302 | + self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal | ||
303 | + if not self.rect: | ||
304 | + print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.') | ||
305 | + | ||
306 | + def update(self, i, cap): | ||
307 | + # Read stream `i` frames in daemon thread | ||
308 | + n, f = 0, self.frames[i] | ||
309 | + while cap.isOpened() and n < f: | ||
310 | + n += 1 | ||
311 | + # _, self.imgs[index] = cap.read() | ||
312 | + cap.grab() | ||
313 | + if n % 4: # read every 4th frame | ||
314 | + success, im = cap.retrieve() | ||
315 | + self.imgs[i] = im if success else self.imgs[i] * 0 | ||
316 | + time.sleep(1 / self.fps[i]) # wait time | ||
317 | + | ||
318 | + def __iter__(self): | ||
319 | + self.count = -1 | ||
320 | + return self | ||
321 | + | ||
322 | + def __next__(self): | ||
323 | + self.count += 1 | ||
324 | + if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit | ||
325 | + cv2.destroyAllWindows() | ||
326 | + raise StopIteration | ||
327 | + | ||
328 | + # Letterbox | ||
329 | + img0 = self.imgs.copy() | ||
330 | + img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0] | ||
331 | + | ||
332 | + # Stack | ||
333 | + img = np.stack(img, 0) | ||
334 | + | ||
335 | + # Convert | ||
336 | + img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416 | ||
337 | + img = np.ascontiguousarray(img) | ||
338 | + | ||
339 | + return self.sources, img, img0, None | ||
340 | + | ||
341 | + def __len__(self): | ||
342 | + return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years | ||
343 | + | ||
344 | + | ||
345 | +def img2label_paths(img_paths): | ||
346 | + # Define label paths as a function of image paths | ||
347 | + sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings | ||
348 | + return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths] | ||
349 | + | ||
350 | + | ||
351 | +class LoadImagesAndLabels(Dataset): # for training/testing | ||
352 | + def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, | ||
353 | + cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''): | ||
354 | + self.img_size = img_size | ||
355 | + self.augment = augment | ||
356 | + self.hyp = hyp | ||
357 | + self.image_weights = image_weights | ||
358 | + self.rect = False if image_weights else rect | ||
359 | + self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) | ||
360 | + self.mosaic_border = [-img_size // 2, -img_size // 2] | ||
361 | + self.stride = stride | ||
362 | + self.path = path | ||
363 | + | ||
364 | + try: | ||
365 | + f = [] # image files | ||
366 | + for p in path if isinstance(path, list) else [path]: | ||
367 | + p = Path(p) # os-agnostic | ||
368 | + if p.is_dir(): # dir | ||
369 | + f += glob.glob(str(p / '**' / '*.*'), recursive=True) | ||
370 | + # f = list(p.rglob('**/*.*')) # pathlib | ||
371 | + elif p.is_file(): # file | ||
372 | + with open(p, 'r') as t: | ||
373 | + t = t.read().strip().splitlines() | ||
374 | + parent = str(p.parent) + os.sep | ||
375 | + f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path | ||
376 | + # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) | ||
377 | + else: | ||
378 | + raise Exception(f'{prefix}{p} does not exist') | ||
379 | + self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats]) | ||
380 | + # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib | ||
381 | + assert self.img_files, f'{prefix}No images found' | ||
382 | + except Exception as e: | ||
383 | + raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}') | ||
384 | + | ||
385 | + # Check cache | ||
386 | + self.label_files = img2label_paths(self.img_files) # labels | ||
387 | + cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels | ||
388 | + if cache_path.is_file(): | ||
389 | + cache, exists = torch.load(cache_path), True # load | ||
390 | + if cache['hash'] != get_hash(self.label_files + self.img_files): # changed | ||
391 | + cache, exists = self.cache_labels(cache_path, prefix), False # re-cache | ||
392 | + else: | ||
393 | + cache, exists = self.cache_labels(cache_path, prefix), False # cache | ||
394 | + | ||
395 | + # Display cache | ||
396 | + nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total | ||
397 | + if exists: | ||
398 | + d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" | ||
399 | + tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results | ||
400 | + assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}' | ||
401 | + | ||
402 | + # Read cache | ||
403 | + cache.pop('hash') # remove hash | ||
404 | + cache.pop('version') # remove version | ||
405 | + labels, shapes, self.segments = zip(*cache.values()) | ||
406 | + self.labels = list(labels) | ||
407 | + self.shapes = np.array(shapes, dtype=np.float64) | ||
408 | + self.img_files = list(cache.keys()) # update | ||
409 | + self.label_files = img2label_paths(cache.keys()) # update | ||
410 | + if single_cls: | ||
411 | + for x in self.labels: | ||
412 | + x[:, 0] = 0 | ||
413 | + | ||
414 | + n = len(shapes) # number of images | ||
415 | + bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index | ||
416 | + nb = bi[-1] + 1 # number of batches | ||
417 | + self.batch = bi # batch index of image | ||
418 | + self.n = n | ||
419 | + self.indices = range(n) | ||
420 | + | ||
421 | + # Rectangular Training | ||
422 | + if self.rect: | ||
423 | + # Sort by aspect ratio | ||
424 | + s = self.shapes # wh | ||
425 | + ar = s[:, 1] / s[:, 0] # aspect ratio | ||
426 | + irect = ar.argsort() | ||
427 | + self.img_files = [self.img_files[i] for i in irect] | ||
428 | + self.label_files = [self.label_files[i] for i in irect] | ||
429 | + self.labels = [self.labels[i] for i in irect] | ||
430 | + self.shapes = s[irect] # wh | ||
431 | + ar = ar[irect] | ||
432 | + | ||
433 | + # Set training image shapes | ||
434 | + shapes = [[1, 1]] * nb | ||
435 | + for i in range(nb): | ||
436 | + ari = ar[bi == i] | ||
437 | + mini, maxi = ari.min(), ari.max() | ||
438 | + if maxi < 1: | ||
439 | + shapes[i] = [maxi, 1] | ||
440 | + elif mini > 1: | ||
441 | + shapes[i] = [1, 1 / mini] | ||
442 | + | ||
443 | + self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride | ||
444 | + | ||
445 | + # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) | ||
446 | + self.imgs = [None] * n | ||
447 | + if cache_images: | ||
448 | + gb = 0 # Gigabytes of cached images | ||
449 | + self.img_hw0, self.img_hw = [None] * n, [None] * n | ||
450 | + results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) # 8 threads | ||
451 | + pbar = tqdm(enumerate(results), total=n) | ||
452 | + for i, x in pbar: | ||
453 | + self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i) | ||
454 | + gb += self.imgs[i].nbytes | ||
455 | + pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)' | ||
456 | + pbar.close() | ||
457 | + | ||
458 | + def cache_labels(self, path=Path('./labels.cache'), prefix=''): | ||
459 | + # Cache dataset labels, check images and read shapes | ||
460 | + x = {} # dict | ||
461 | + nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate | ||
462 | + pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files)) | ||
463 | + for i, (im_file, lb_file) in enumerate(pbar): | ||
464 | + try: | ||
465 | + # verify images | ||
466 | + im = Image.open(im_file) | ||
467 | + im.verify() # PIL verify | ||
468 | + shape = exif_size(im) # image size | ||
469 | + segments = [] # instance segments | ||
470 | + assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' | ||
471 | + assert im.format.lower() in img_formats, f'invalid image format {im.format}' | ||
472 | + | ||
473 | + # verify labels | ||
474 | + if os.path.isfile(lb_file): | ||
475 | + nf += 1 # label found | ||
476 | + with open(lb_file, 'r') as f: | ||
477 | + l = [x.split() for x in f.read().strip().splitlines() if len(x)] | ||
478 | + if any([len(x) > 8 for x in l]): # is segment | ||
479 | + classes = np.array([x[0] for x in l], dtype=np.float32) | ||
480 | + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...) | ||
481 | + l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) | ||
482 | + l = np.array(l, dtype=np.float32) | ||
483 | + if len(l): | ||
484 | + assert l.shape[1] == 5, 'labels require 5 columns each' | ||
485 | + assert (l >= 0).all(), 'negative labels' | ||
486 | + assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels' | ||
487 | + assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels' | ||
488 | + else: | ||
489 | + ne += 1 # label empty | ||
490 | + l = np.zeros((0, 5), dtype=np.float32) | ||
491 | + else: | ||
492 | + nm += 1 # label missing | ||
493 | + l = np.zeros((0, 5), dtype=np.float32) | ||
494 | + x[im_file] = [l, shape, segments] | ||
495 | + except Exception as e: | ||
496 | + nc += 1 | ||
497 | + logging.info(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}') | ||
498 | + | ||
499 | + pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \ | ||
500 | + f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted" | ||
501 | + pbar.close() | ||
502 | + | ||
503 | + if nf == 0: | ||
504 | + logging.info(f'{prefix}WARNING: No labels found in {path}. See {help_url}') | ||
505 | + | ||
506 | + x['hash'] = get_hash(self.label_files + self.img_files) | ||
507 | + x['results'] = nf, nm, ne, nc, i + 1 | ||
508 | + x['version'] = 0.2 # cache version | ||
509 | + try: | ||
510 | + torch.save(x, path) # save cache for next time | ||
511 | + logging.info(f'{prefix}New cache created: {path}') | ||
512 | + except Exception as e: | ||
513 | + logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable | ||
514 | + return x | ||
515 | + | ||
516 | + def __len__(self): | ||
517 | + return len(self.img_files) | ||
518 | + | ||
519 | + # def __iter__(self): | ||
520 | + # self.count = -1 | ||
521 | + # print('ran dataset iter') | ||
522 | + # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) | ||
523 | + # return self | ||
524 | + | ||
525 | + def __getitem__(self, index): | ||
526 | + index = self.indices[index] # linear, shuffled, or image_weights | ||
527 | + | ||
528 | + hyp = self.hyp | ||
529 | + mosaic = self.mosaic and random.random() < hyp['mosaic'] | ||
530 | + if mosaic: | ||
531 | + # Load mosaic | ||
532 | + img, labels = load_mosaic(self, index) | ||
533 | + shapes = None | ||
534 | + | ||
535 | + # MixUp https://arxiv.org/pdf/1710.09412.pdf | ||
536 | + if random.random() < hyp['mixup']: | ||
537 | + img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1)) | ||
538 | + r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0 | ||
539 | + img = (img * r + img2 * (1 - r)).astype(np.uint8) | ||
540 | + labels = np.concatenate((labels, labels2), 0) | ||
541 | + | ||
542 | + else: | ||
543 | + # Load image | ||
544 | + img, (h0, w0), (h, w) = load_image(self, index) | ||
545 | + | ||
546 | + # Letterbox | ||
547 | + shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape | ||
548 | + img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) | ||
549 | + shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling | ||
550 | + | ||
551 | + labels = self.labels[index].copy() | ||
552 | + if labels.size: # normalized xywh to pixel xyxy format | ||
553 | + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) | ||
554 | + | ||
555 | + if self.augment: | ||
556 | + # Augment imagespace | ||
557 | + if not mosaic: | ||
558 | + img, labels = random_perspective(img, labels, | ||
559 | + degrees=hyp['degrees'], | ||
560 | + translate=hyp['translate'], | ||
561 | + scale=hyp['scale'], | ||
562 | + shear=hyp['shear'], | ||
563 | + perspective=hyp['perspective']) | ||
564 | + | ||
565 | + # Augment colorspace | ||
566 | + augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) | ||
567 | + | ||
568 | + # Apply cutouts | ||
569 | + # if random.random() < 0.9: | ||
570 | + # labels = cutout(img, labels) | ||
571 | + | ||
572 | + nL = len(labels) # number of labels | ||
573 | + if nL: | ||
574 | + labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh | ||
575 | + labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1 | ||
576 | + labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1 | ||
577 | + | ||
578 | + if self.augment: | ||
579 | + # flip up-down | ||
580 | + if random.random() < hyp['flipud']: | ||
581 | + img = np.flipud(img) | ||
582 | + if nL: | ||
583 | + labels[:, 2] = 1 - labels[:, 2] | ||
584 | + | ||
585 | + # flip left-right | ||
586 | + if random.random() < hyp['fliplr']: | ||
587 | + img = np.fliplr(img) | ||
588 | + if nL: | ||
589 | + labels[:, 1] = 1 - labels[:, 1] | ||
590 | + | ||
591 | + labels_out = torch.zeros((nL, 6)) | ||
592 | + if nL: | ||
593 | + labels_out[:, 1:] = torch.from_numpy(labels) | ||
594 | + | ||
595 | + # Convert | ||
596 | + img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 | ||
597 | + img = np.ascontiguousarray(img) | ||
598 | + | ||
599 | + return torch.from_numpy(img), labels_out, self.img_files[index], shapes | ||
600 | + | ||
601 | + @staticmethod | ||
602 | + def collate_fn(batch): | ||
603 | + img, label, path, shapes = zip(*batch) # transposed | ||
604 | + for i, l in enumerate(label): | ||
605 | + l[:, 0] = i # add target image index for build_targets() | ||
606 | + return torch.stack(img, 0), torch.cat(label, 0), path, shapes | ||
607 | + | ||
608 | + @staticmethod | ||
609 | + def collate_fn4(batch): | ||
610 | + img, label, path, shapes = zip(*batch) # transposed | ||
611 | + n = len(shapes) // 4 | ||
612 | + img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] | ||
613 | + | ||
614 | + ho = torch.tensor([[0., 0, 0, 1, 0, 0]]) | ||
615 | + wo = torch.tensor([[0., 0, 1, 0, 0, 0]]) | ||
616 | + s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale | ||
617 | + for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW | ||
618 | + i *= 4 | ||
619 | + if random.random() < 0.5: | ||
620 | + im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[ | ||
621 | + 0].type(img[i].type()) | ||
622 | + l = label[i] | ||
623 | + else: | ||
624 | + im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) | ||
625 | + l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s | ||
626 | + img4.append(im) | ||
627 | + label4.append(l) | ||
628 | + | ||
629 | + for i, l in enumerate(label4): | ||
630 | + l[:, 0] = i # add target image index for build_targets() | ||
631 | + | ||
632 | + return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4 | ||
633 | + | ||
634 | + | ||
635 | +# Ancillary functions -------------------------------------------------------------------------------------------------- | ||
636 | +def load_image(self, index): | ||
637 | + # loads 1 image from dataset, returns img, original hw, resized hw | ||
638 | + img = self.imgs[index] | ||
639 | + if img is None: # not cached | ||
640 | + path = self.img_files[index] | ||
641 | + img = cv2.imread(path) # BGR | ||
642 | + assert img is not None, 'Image Not Found ' + path | ||
643 | + h0, w0 = img.shape[:2] # orig hw | ||
644 | + r = self.img_size / max(h0, w0) # ratio | ||
645 | + if r != 1: # if sizes are not equal | ||
646 | + img = cv2.resize(img, (int(w0 * r), int(h0 * r)), | ||
647 | + interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR) | ||
648 | + return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized | ||
649 | + else: | ||
650 | + return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized | ||
651 | + | ||
652 | + | ||
653 | +def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5): | ||
654 | + r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains | ||
655 | + hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV)) | ||
656 | + dtype = img.dtype # uint8 | ||
657 | + | ||
658 | + x = np.arange(0, 256, dtype=np.int16) | ||
659 | + lut_hue = ((x * r[0]) % 180).astype(dtype) | ||
660 | + lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) | ||
661 | + lut_val = np.clip(x * r[2], 0, 255).astype(dtype) | ||
662 | + | ||
663 | + img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype) | ||
664 | + cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed | ||
665 | + | ||
666 | + | ||
667 | +def hist_equalize(img, clahe=True, bgr=False): | ||
668 | + # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255 | ||
669 | + yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) | ||
670 | + if clahe: | ||
671 | + c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) | ||
672 | + yuv[:, :, 0] = c.apply(yuv[:, :, 0]) | ||
673 | + else: | ||
674 | + yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram | ||
675 | + return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB | ||
676 | + | ||
677 | + | ||
678 | +def load_mosaic(self, index): | ||
679 | + # loads images in a 4-mosaic | ||
680 | + | ||
681 | + labels4, segments4 = [], [] | ||
682 | + s = self.img_size | ||
683 | + yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y | ||
684 | + indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices | ||
685 | + for i, index in enumerate(indices): | ||
686 | + # Load image | ||
687 | + img, _, (h, w) = load_image(self, index) | ||
688 | + | ||
689 | + # place img in img4 | ||
690 | + if i == 0: # top left | ||
691 | + img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles | ||
692 | + x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) | ||
693 | + x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) | ||
694 | + elif i == 1: # top right | ||
695 | + x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc | ||
696 | + x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h | ||
697 | + elif i == 2: # bottom left | ||
698 | + x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) | ||
699 | + x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) | ||
700 | + elif i == 3: # bottom right | ||
701 | + x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) | ||
702 | + x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) | ||
703 | + | ||
704 | + img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] | ||
705 | + padw = x1a - x1b | ||
706 | + padh = y1a - y1b | ||
707 | + | ||
708 | + # Labels | ||
709 | + labels, segments = self.labels[index].copy(), self.segments[index].copy() | ||
710 | + if labels.size: | ||
711 | + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format | ||
712 | + segments = [xyn2xy(x, w, h, padw, padh) for x in segments] | ||
713 | + labels4.append(labels) | ||
714 | + segments4.extend(segments) | ||
715 | + | ||
716 | + # Concat/clip labels | ||
717 | + labels4 = np.concatenate(labels4, 0) | ||
718 | + for x in (labels4[:, 1:], *segments4): | ||
719 | + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() | ||
720 | + # img4, labels4 = replicate(img4, labels4) # replicate | ||
721 | + | ||
722 | + # Augment | ||
723 | + img4, labels4 = random_perspective(img4, labels4, segments4, | ||
724 | + degrees=self.hyp['degrees'], | ||
725 | + translate=self.hyp['translate'], | ||
726 | + scale=self.hyp['scale'], | ||
727 | + shear=self.hyp['shear'], | ||
728 | + perspective=self.hyp['perspective'], | ||
729 | + border=self.mosaic_border) # border to remove | ||
730 | + | ||
731 | + return img4, labels4 | ||
732 | + | ||
733 | + | ||
734 | +def load_mosaic9(self, index): | ||
735 | + # loads images in a 9-mosaic | ||
736 | + | ||
737 | + labels9, segments9 = [], [] | ||
738 | + s = self.img_size | ||
739 | + indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices | ||
740 | + for i, index in enumerate(indices): | ||
741 | + # Load image | ||
742 | + img, _, (h, w) = load_image(self, index) | ||
743 | + | ||
744 | + # place img in img9 | ||
745 | + if i == 0: # center | ||
746 | + img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles | ||
747 | + h0, w0 = h, w | ||
748 | + c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates | ||
749 | + elif i == 1: # top | ||
750 | + c = s, s - h, s + w, s | ||
751 | + elif i == 2: # top right | ||
752 | + c = s + wp, s - h, s + wp + w, s | ||
753 | + elif i == 3: # right | ||
754 | + c = s + w0, s, s + w0 + w, s + h | ||
755 | + elif i == 4: # bottom right | ||
756 | + c = s + w0, s + hp, s + w0 + w, s + hp + h | ||
757 | + elif i == 5: # bottom | ||
758 | + c = s + w0 - w, s + h0, s + w0, s + h0 + h | ||
759 | + elif i == 6: # bottom left | ||
760 | + c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h | ||
761 | + elif i == 7: # left | ||
762 | + c = s - w, s + h0 - h, s, s + h0 | ||
763 | + elif i == 8: # top left | ||
764 | + c = s - w, s + h0 - hp - h, s, s + h0 - hp | ||
765 | + | ||
766 | + padx, pady = c[:2] | ||
767 | + x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords | ||
768 | + | ||
769 | + # Labels | ||
770 | + labels, segments = self.labels[index].copy(), self.segments[index].copy() | ||
771 | + if labels.size: | ||
772 | + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format | ||
773 | + segments = [xyn2xy(x, w, h, padx, pady) for x in segments] | ||
774 | + labels9.append(labels) | ||
775 | + segments9.extend(segments) | ||
776 | + | ||
777 | + # Image | ||
778 | + img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] | ||
779 | + hp, wp = h, w # height, width previous | ||
780 | + | ||
781 | + # Offset | ||
782 | + yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y | ||
783 | + img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] | ||
784 | + | ||
785 | + # Concat/clip labels | ||
786 | + labels9 = np.concatenate(labels9, 0) | ||
787 | + labels9[:, [1, 3]] -= xc | ||
788 | + labels9[:, [2, 4]] -= yc | ||
789 | + c = np.array([xc, yc]) # centers | ||
790 | + segments9 = [x - c for x in segments9] | ||
791 | + | ||
792 | + for x in (labels9[:, 1:], *segments9): | ||
793 | + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() | ||
794 | + # img9, labels9 = replicate(img9, labels9) # replicate | ||
795 | + | ||
796 | + # Augment | ||
797 | + img9, labels9 = random_perspective(img9, labels9, segments9, | ||
798 | + degrees=self.hyp['degrees'], | ||
799 | + translate=self.hyp['translate'], | ||
800 | + scale=self.hyp['scale'], | ||
801 | + shear=self.hyp['shear'], | ||
802 | + perspective=self.hyp['perspective'], | ||
803 | + border=self.mosaic_border) # border to remove | ||
804 | + | ||
805 | + return img9, labels9 | ||
806 | + | ||
807 | + | ||
808 | +def replicate(img, labels): | ||
809 | + # Replicate labels | ||
810 | + h, w = img.shape[:2] | ||
811 | + boxes = labels[:, 1:].astype(int) | ||
812 | + x1, y1, x2, y2 = boxes.T | ||
813 | + s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) | ||
814 | + for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices | ||
815 | + x1b, y1b, x2b, y2b = boxes[i] | ||
816 | + bh, bw = y2b - y1b, x2b - x1b | ||
817 | + yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y | ||
818 | + x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] | ||
819 | + img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] | ||
820 | + labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) | ||
821 | + | ||
822 | + return img, labels | ||
823 | + | ||
824 | + | ||
825 | +def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): | ||
826 | + # Resize and pad image while meeting stride-multiple constraints | ||
827 | + shape = img.shape[:2] # current shape [height, width] | ||
828 | + if isinstance(new_shape, int): | ||
829 | + new_shape = (new_shape, new_shape) | ||
830 | + | ||
831 | + # Scale ratio (new / old) | ||
832 | + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) | ||
833 | + if not scaleup: # only scale down, do not scale up (for better test mAP) | ||
834 | + r = min(r, 1.0) | ||
835 | + | ||
836 | + # Compute padding | ||
837 | + ratio = r, r # width, height ratios | ||
838 | + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) | ||
839 | + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding | ||
840 | + if auto: # minimum rectangle | ||
841 | + dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding | ||
842 | + elif scaleFill: # stretch | ||
843 | + dw, dh = 0.0, 0.0 | ||
844 | + new_unpad = (new_shape[1], new_shape[0]) | ||
845 | + ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios | ||
846 | + | ||
847 | + dw /= 2 # divide padding into 2 sides | ||
848 | + dh /= 2 | ||
849 | + | ||
850 | + if shape[::-1] != new_unpad: # resize | ||
851 | + img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR) | ||
852 | + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) | ||
853 | + left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) | ||
854 | + img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border | ||
855 | + return img, ratio, (dw, dh) | ||
856 | + | ||
857 | + | ||
858 | +def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, | ||
859 | + border=(0, 0)): | ||
860 | + # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10)) | ||
861 | + # targets = [cls, xyxy] | ||
862 | + | ||
863 | + height = img.shape[0] + border[0] * 2 # shape(h,w,c) | ||
864 | + width = img.shape[1] + border[1] * 2 | ||
865 | + | ||
866 | + # Center | ||
867 | + C = np.eye(3) | ||
868 | + C[0, 2] = -img.shape[1] / 2 # x translation (pixels) | ||
869 | + C[1, 2] = -img.shape[0] / 2 # y translation (pixels) | ||
870 | + | ||
871 | + # Perspective | ||
872 | + P = np.eye(3) | ||
873 | + P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) | ||
874 | + P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) | ||
875 | + | ||
876 | + # Rotation and Scale | ||
877 | + R = np.eye(3) | ||
878 | + a = random.uniform(-degrees, degrees) | ||
879 | + # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations | ||
880 | + s = random.uniform(1 - scale, 1 + scale) | ||
881 | + # s = 2 ** random.uniform(-scale, scale) | ||
882 | + R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) | ||
883 | + | ||
884 | + # Shear | ||
885 | + S = np.eye(3) | ||
886 | + S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) | ||
887 | + S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) | ||
888 | + | ||
889 | + # Translation | ||
890 | + T = np.eye(3) | ||
891 | + T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) | ||
892 | + T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) | ||
893 | + | ||
894 | + # Combined rotation matrix | ||
895 | + M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT | ||
896 | + if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed | ||
897 | + if perspective: | ||
898 | + img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114)) | ||
899 | + else: # affine | ||
900 | + img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) | ||
901 | + | ||
902 | + # Visualize | ||
903 | + # import matplotlib.pyplot as plt | ||
904 | + # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() | ||
905 | + # ax[0].imshow(img[:, :, ::-1]) # base | ||
906 | + # ax[1].imshow(img2[:, :, ::-1]) # warped | ||
907 | + | ||
908 | + # Transform label coordinates | ||
909 | + n = len(targets) | ||
910 | + if n: | ||
911 | + use_segments = any(x.any() for x in segments) | ||
912 | + new = np.zeros((n, 4)) | ||
913 | + if use_segments: # warp segments | ||
914 | + segments = resample_segments(segments) # upsample | ||
915 | + for i, segment in enumerate(segments): | ||
916 | + xy = np.ones((len(segment), 3)) | ||
917 | + xy[:, :2] = segment | ||
918 | + xy = xy @ M.T # transform | ||
919 | + xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine | ||
920 | + | ||
921 | + # clip | ||
922 | + new[i] = segment2box(xy, width, height) | ||
923 | + | ||
924 | + else: # warp boxes | ||
925 | + xy = np.ones((n * 4, 3)) | ||
926 | + xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 | ||
927 | + xy = xy @ M.T # transform | ||
928 | + xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine | ||
929 | + | ||
930 | + # create new boxes | ||
931 | + x = xy[:, [0, 2, 4, 6]] | ||
932 | + y = xy[:, [1, 3, 5, 7]] | ||
933 | + new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T | ||
934 | + | ||
935 | + # clip | ||
936 | + new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) | ||
937 | + new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) | ||
938 | + | ||
939 | + # filter candidates | ||
940 | + i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) | ||
941 | + targets = targets[i] | ||
942 | + targets[:, 1:5] = new[i] | ||
943 | + | ||
944 | + return img, targets | ||
945 | + | ||
946 | + | ||
947 | +def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) | ||
948 | + # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio | ||
949 | + w1, h1 = box1[2] - box1[0], box1[3] - box1[1] | ||
950 | + w2, h2 = box2[2] - box2[0], box2[3] - box2[1] | ||
951 | + ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio | ||
952 | + return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates | ||
953 | + | ||
954 | + | ||
955 | +def cutout(image, labels): | ||
956 | + # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 | ||
957 | + h, w = image.shape[:2] | ||
958 | + | ||
959 | + def bbox_ioa(box1, box2): | ||
960 | + # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2 | ||
961 | + box2 = box2.transpose() | ||
962 | + | ||
963 | + # Get the coordinates of bounding boxes | ||
964 | + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] | ||
965 | + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] | ||
966 | + | ||
967 | + # Intersection area | ||
968 | + inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ | ||
969 | + (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) | ||
970 | + | ||
971 | + # box2 area | ||
972 | + box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16 | ||
973 | + | ||
974 | + # Intersection over box2 area | ||
975 | + return inter_area / box2_area | ||
976 | + | ||
977 | + # create random masks | ||
978 | + scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction | ||
979 | + for s in scales: | ||
980 | + mask_h = random.randint(1, int(h * s)) | ||
981 | + mask_w = random.randint(1, int(w * s)) | ||
982 | + | ||
983 | + # box | ||
984 | + xmin = max(0, random.randint(0, w) - mask_w // 2) | ||
985 | + ymin = max(0, random.randint(0, h) - mask_h // 2) | ||
986 | + xmax = min(w, xmin + mask_w) | ||
987 | + ymax = min(h, ymin + mask_h) | ||
988 | + | ||
989 | + # apply random color mask | ||
990 | + image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] | ||
991 | + | ||
992 | + # return unobscured labels | ||
993 | + if len(labels) and s > 0.03: | ||
994 | + box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) | ||
995 | + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area | ||
996 | + labels = labels[ioa < 0.60] # remove >60% obscured labels | ||
997 | + | ||
998 | + return labels | ||
999 | + | ||
1000 | + | ||
1001 | +def create_folder(path='./new'): | ||
1002 | + # Create folder | ||
1003 | + if os.path.exists(path): | ||
1004 | + shutil.rmtree(path) # delete output folder | ||
1005 | + os.makedirs(path) # make new output folder | ||
1006 | + | ||
1007 | + | ||
1008 | +def flatten_recursive(path='../coco128'): | ||
1009 | + # Flatten a recursive directory by bringing all files to top level | ||
1010 | + new_path = Path(path + '_flat') | ||
1011 | + create_folder(new_path) | ||
1012 | + for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): | ||
1013 | + shutil.copyfile(file, new_path / Path(file).name) | ||
1014 | + | ||
1015 | + | ||
1016 | +def extract_boxes(path='../coco128/'): # from utils.datasets import *; extract_boxes('../coco128') | ||
1017 | + # Convert detection dataset into classification dataset, with one directory per class | ||
1018 | + | ||
1019 | + path = Path(path) # images dir | ||
1020 | + shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing | ||
1021 | + files = list(path.rglob('*.*')) | ||
1022 | + n = len(files) # number of files | ||
1023 | + for im_file in tqdm(files, total=n): | ||
1024 | + if im_file.suffix[1:] in img_formats: | ||
1025 | + # image | ||
1026 | + im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB | ||
1027 | + h, w = im.shape[:2] | ||
1028 | + | ||
1029 | + # labels | ||
1030 | + lb_file = Path(img2label_paths([str(im_file)])[0]) | ||
1031 | + if Path(lb_file).exists(): | ||
1032 | + with open(lb_file, 'r') as f: | ||
1033 | + lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels | ||
1034 | + | ||
1035 | + for j, x in enumerate(lb): | ||
1036 | + c = int(x[0]) # class | ||
1037 | + f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename | ||
1038 | + if not f.parent.is_dir(): | ||
1039 | + f.parent.mkdir(parents=True) | ||
1040 | + | ||
1041 | + b = x[1:] * [w, h, w, h] # box | ||
1042 | + # b[2:] = b[2:].max() # rectangle to square | ||
1043 | + b[2:] = b[2:] * 1.2 + 3 # pad | ||
1044 | + b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) | ||
1045 | + | ||
1046 | + b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image | ||
1047 | + b[[1, 3]] = np.clip(b[[1, 3]], 0, h) | ||
1048 | + assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' | ||
1049 | + | ||
1050 | + | ||
1051 | +def autosplit(path='../coco128', weights=(0.9, 0.1, 0.0), annotated_only=False): | ||
1052 | + """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files | ||
1053 | + Usage: from utils.datasets import *; autosplit('../coco128') | ||
1054 | + Arguments | ||
1055 | + path: Path to images directory | ||
1056 | + weights: Train, val, test weights (list) | ||
1057 | + annotated_only: Only use images with an annotated txt file | ||
1058 | + """ | ||
1059 | + path = Path(path) # images dir | ||
1060 | + files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only | ||
1061 | + n = len(files) # number of files | ||
1062 | + indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split | ||
1063 | + | ||
1064 | + txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files | ||
1065 | + [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing | ||
1066 | + | ||
1067 | + print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) | ||
1068 | + for i, img in tqdm(zip(indices, files), total=n): | ||
1069 | + if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label | ||
1070 | + with open(path / txt[i], 'a') as f: | ||
1071 | + f.write(str(img) + '\n') # add image to txt file |
YOLOv5/utils/flask_rest_api/README.md
0 → 100644
1 | +# Flask REST API | ||
2 | +[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). | ||
3 | + | ||
4 | +## Requirements | ||
5 | + | ||
6 | +[Flask](https://palletsprojects.com/p/flask/) is required. Install with: | ||
7 | +```shell | ||
8 | +$ pip install Flask | ||
9 | +``` | ||
10 | + | ||
11 | +## Run | ||
12 | + | ||
13 | +After Flask installation run: | ||
14 | + | ||
15 | +```shell | ||
16 | +$ python3 restapi.py --port 5000 | ||
17 | +``` | ||
18 | + | ||
19 | +Then use [curl](https://curl.se/) to perform a request: | ||
20 | + | ||
21 | +```shell | ||
22 | +$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'` | ||
23 | +``` | ||
24 | + | ||
25 | +The model inference results are returned as a JSON response: | ||
26 | + | ||
27 | +```json | ||
28 | +[ | ||
29 | + { | ||
30 | + "class": 0, | ||
31 | + "confidence": 0.8900438547, | ||
32 | + "height": 0.9318675399, | ||
33 | + "name": "person", | ||
34 | + "width": 0.3264600933, | ||
35 | + "xcenter": 0.7438579798, | ||
36 | + "ycenter": 0.5207948685 | ||
37 | + }, | ||
38 | + { | ||
39 | + "class": 0, | ||
40 | + "confidence": 0.8440024257, | ||
41 | + "height": 0.7155083418, | ||
42 | + "name": "person", | ||
43 | + "width": 0.6546785235, | ||
44 | + "xcenter": 0.427829951, | ||
45 | + "ycenter": 0.6334488392 | ||
46 | + }, | ||
47 | + { | ||
48 | + "class": 27, | ||
49 | + "confidence": 0.3771208823, | ||
50 | + "height": 0.3902671337, | ||
51 | + "name": "tie", | ||
52 | + "width": 0.0696444362, | ||
53 | + "xcenter": 0.3675483763, | ||
54 | + "ycenter": 0.7991207838 | ||
55 | + }, | ||
56 | + { | ||
57 | + "class": 27, | ||
58 | + "confidence": 0.3527112305, | ||
59 | + "height": 0.1540903747, | ||
60 | + "name": "tie", | ||
61 | + "width": 0.0336618312, | ||
62 | + "xcenter": 0.7814827561, | ||
63 | + "ycenter": 0.5065554976 | ||
64 | + } | ||
65 | +] | ||
66 | +``` | ||
67 | + | ||
68 | +An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given in `example_request.py` |
1 | +"""Perform test request""" | ||
2 | +import pprint | ||
3 | + | ||
4 | +import requests | ||
5 | + | ||
6 | +DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" | ||
7 | +TEST_IMAGE = "zidane.jpg" | ||
8 | + | ||
9 | +image_data = open(TEST_IMAGE, "rb").read() | ||
10 | + | ||
11 | +response = requests.post(DETECTION_URL, files={"image": image_data}).json() | ||
12 | + | ||
13 | +pprint.pprint(response) |
YOLOv5/utils/flask_rest_api/restapi.py
0 → 100644
1 | +""" | ||
2 | +Run a rest API exposing the yolov5s object detection model | ||
3 | +""" | ||
4 | +import argparse | ||
5 | +import io | ||
6 | + | ||
7 | +import torch | ||
8 | +from PIL import Image | ||
9 | +from flask import Flask, request | ||
10 | + | ||
11 | +app = Flask(__name__) | ||
12 | + | ||
13 | +DETECTION_URL = "/v1/object-detection/yolov5s" | ||
14 | + | ||
15 | + | ||
16 | +@app.route(DETECTION_URL, methods=["POST"]) | ||
17 | +def predict(): | ||
18 | + if not request.method == "POST": | ||
19 | + return | ||
20 | + | ||
21 | + if request.files.get("image"): | ||
22 | + image_file = request.files["image"] | ||
23 | + image_bytes = image_file.read() | ||
24 | + | ||
25 | + img = Image.open(io.BytesIO(image_bytes)) | ||
26 | + | ||
27 | + results = model(img, size=640) # reduce size=320 for faster inference | ||
28 | + return results.pandas().xyxy[0].to_json(orient="records") | ||
29 | + | ||
30 | + | ||
31 | +if __name__ == "__main__": | ||
32 | + parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") | ||
33 | + parser.add_argument("--port", default=5000, type=int, help="port number") | ||
34 | + args = parser.parse_args() | ||
35 | + | ||
36 | + model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache | ||
37 | + app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat |
YOLOv5/utils/general.py
0 → 100644
1 | +# YOLOv5 general utils | ||
2 | + | ||
3 | +import glob | ||
4 | +import logging | ||
5 | +import math | ||
6 | +import os | ||
7 | +import platform | ||
8 | +import random | ||
9 | +import re | ||
10 | +import subprocess | ||
11 | +import time | ||
12 | +from itertools import repeat | ||
13 | +from multiprocessing.pool import ThreadPool | ||
14 | +from pathlib import Path | ||
15 | + | ||
16 | +import cv2 | ||
17 | +import numpy as np | ||
18 | +import pandas as pd | ||
19 | +import pkg_resources as pkg | ||
20 | +import torch | ||
21 | +import torchvision | ||
22 | +import yaml | ||
23 | + | ||
24 | +from utils.google_utils import gsutil_getsize | ||
25 | +from utils.metrics import fitness | ||
26 | +from utils.torch_utils import init_torch_seeds | ||
27 | + | ||
28 | +# Settings | ||
29 | +torch.set_printoptions(linewidth=320, precision=5, profile='long') | ||
30 | +np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5 | ||
31 | +pd.options.display.max_columns = 10 | ||
32 | +cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) | ||
33 | +os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads | ||
34 | + | ||
35 | + | ||
36 | +def set_logging(rank=-1, verbose=True): | ||
37 | + logging.basicConfig( | ||
38 | + format="%(message)s", | ||
39 | + level=logging.INFO if (verbose and rank in [-1, 0]) else logging.WARN) | ||
40 | + | ||
41 | + | ||
42 | +def init_seeds(seed=0): | ||
43 | + # Initialize random number generator (RNG) seeds | ||
44 | + random.seed(seed) | ||
45 | + np.random.seed(seed) | ||
46 | + init_torch_seeds(seed) | ||
47 | + | ||
48 | + | ||
49 | +def get_latest_run(search_dir='.'): | ||
50 | + # Return path to most recent 'last.pt' in /runs (i.e. to --resume from) | ||
51 | + last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True) | ||
52 | + return max(last_list, key=os.path.getctime) if last_list else '' | ||
53 | + | ||
54 | + | ||
55 | +def is_docker(): | ||
56 | + # Is environment a Docker container? | ||
57 | + return Path('/workspace').exists() # or Path('/.dockerenv').exists() | ||
58 | + | ||
59 | + | ||
60 | +def is_colab(): | ||
61 | + # Is environment a Google Colab instance? | ||
62 | + try: | ||
63 | + import google.colab | ||
64 | + return True | ||
65 | + except Exception as e: | ||
66 | + return False | ||
67 | + | ||
68 | + | ||
69 | +def is_pip(): | ||
70 | + # Is file in a pip package? | ||
71 | + return 'site-packages' in Path(__file__).absolute().parts | ||
72 | + | ||
73 | + | ||
74 | +def emojis(str=''): | ||
75 | + # Return platform-dependent emoji-safe version of string | ||
76 | + return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str | ||
77 | + | ||
78 | + | ||
79 | +def file_size(file): | ||
80 | + # Return file size in MB | ||
81 | + return Path(file).stat().st_size / 1e6 | ||
82 | + | ||
83 | + | ||
84 | +def check_online(): | ||
85 | + # Check internet connectivity | ||
86 | + import socket | ||
87 | + try: | ||
88 | + socket.create_connection(("1.1.1.1", 443), 5) # check host accesability | ||
89 | + return True | ||
90 | + except OSError: | ||
91 | + return False | ||
92 | + | ||
93 | + | ||
94 | +def check_git_status(): | ||
95 | + # Recommend 'git pull' if code is out of date | ||
96 | + print(colorstr('github: '), end='') | ||
97 | + try: | ||
98 | + assert Path('.git').exists(), 'skipping check (not a git repository)' | ||
99 | + assert not is_docker(), 'skipping check (Docker image)' | ||
100 | + assert check_online(), 'skipping check (offline)' | ||
101 | + | ||
102 | + cmd = 'git fetch && git config --get remote.origin.url' | ||
103 | + url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url | ||
104 | + branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out | ||
105 | + n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind | ||
106 | + if n > 0: | ||
107 | + s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \ | ||
108 | + f"Use 'git pull' to update or 'git clone {url}' to download latest." | ||
109 | + else: | ||
110 | + s = f'up to date with {url} ✅' | ||
111 | + print(emojis(s)) # emoji-safe | ||
112 | + except Exception as e: | ||
113 | + print(e) | ||
114 | + | ||
115 | + | ||
116 | +def check_python(minimum='3.7.0', required=True): | ||
117 | + # Check current python version vs. required python version | ||
118 | + current = platform.python_version() | ||
119 | + result = pkg.parse_version(current) >= pkg.parse_version(minimum) | ||
120 | + if required: | ||
121 | + assert result, f'Python {minimum} required by YOLOv5, but Python {current} is currently installed' | ||
122 | + return result | ||
123 | + | ||
124 | + | ||
125 | +def check_requirements(requirements='requirements.txt', exclude=()): | ||
126 | + # Check installed dependencies meet requirements (pass *.txt file or list of packages) | ||
127 | + prefix = colorstr('red', 'bold', 'requirements:') | ||
128 | + check_python() # check python version | ||
129 | + if isinstance(requirements, (str, Path)): # requirements.txt file | ||
130 | + file = Path(requirements) | ||
131 | + if not file.exists(): | ||
132 | + print(f"{prefix} {file.resolve()} not found, check failed.") | ||
133 | + return | ||
134 | + requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(file.open()) if x.name not in exclude] | ||
135 | + else: # list or tuple of packages | ||
136 | + requirements = [x for x in requirements if x not in exclude] | ||
137 | + | ||
138 | + n = 0 # number of packages updates | ||
139 | + for r in requirements: | ||
140 | + try: | ||
141 | + pkg.require(r) | ||
142 | + except Exception as e: # DistributionNotFound or VersionConflict if requirements not met | ||
143 | + n += 1 | ||
144 | + print(f"{prefix} {r} not found and is required by YOLOv5, attempting auto-update...") | ||
145 | + try: | ||
146 | + print(subprocess.check_output(f"pip install '{r}'", shell=True).decode()) | ||
147 | + except Exception as e: | ||
148 | + print(f'{prefix} {e}') | ||
149 | + | ||
150 | + if n: # if packages updated | ||
151 | + source = file.resolve() if 'file' in locals() else requirements | ||
152 | + s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \ | ||
153 | + f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n" | ||
154 | + print(emojis(s)) # emoji-safe | ||
155 | + | ||
156 | + | ||
157 | +def check_img_size(img_size, s=32): | ||
158 | + # Verify img_size is a multiple of stride s | ||
159 | + new_size = make_divisible(img_size, int(s)) # ceil gs-multiple | ||
160 | + if new_size != img_size: | ||
161 | + print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size)) | ||
162 | + return new_size | ||
163 | + | ||
164 | + | ||
165 | +def check_imshow(): | ||
166 | + # Check if environment supports image displays | ||
167 | + try: | ||
168 | + assert not is_docker(), 'cv2.imshow() is disabled in Docker environments' | ||
169 | + assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments' | ||
170 | + cv2.imshow('test', np.zeros((1, 1, 3))) | ||
171 | + cv2.waitKey(1) | ||
172 | + cv2.destroyAllWindows() | ||
173 | + cv2.waitKey(1) | ||
174 | + return True | ||
175 | + except Exception as e: | ||
176 | + print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}') | ||
177 | + return False | ||
178 | + | ||
179 | + | ||
180 | +def check_file(file): | ||
181 | + # Search/download file (if necessary) and return path | ||
182 | + file = str(file) # convert to str() | ||
183 | + if Path(file).is_file() or file == '': # exists | ||
184 | + return file | ||
185 | + elif file.startswith(('http://', 'https://')): # download | ||
186 | + url, file = file, Path(file).name | ||
187 | + print(f'Downloading {url} to {file}...') | ||
188 | + torch.hub.download_url_to_file(url, file) | ||
189 | + assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check | ||
190 | + return file | ||
191 | + else: # search | ||
192 | + files = glob.glob('./**/' + file, recursive=True) # find file | ||
193 | + assert len(files), f'File not found: {file}' # assert file was found | ||
194 | + assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique | ||
195 | + return files[0] # return file | ||
196 | + | ||
197 | + | ||
198 | +def check_dataset(dict): | ||
199 | + # Download dataset if not found locally | ||
200 | + val, s = dict.get('val'), dict.get('download') | ||
201 | + if val and len(val): | ||
202 | + val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path | ||
203 | + if not all(x.exists() for x in val): | ||
204 | + print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()]) | ||
205 | + if s and len(s): # download script | ||
206 | + if s.startswith('http') and s.endswith('.zip'): # URL | ||
207 | + f = Path(s).name # filename | ||
208 | + print(f'Downloading {s} ...') | ||
209 | + torch.hub.download_url_to_file(s, f) | ||
210 | + r = os.system(f'unzip -q {f} -d ../ && rm {f}') # unzip | ||
211 | + elif s.startswith('bash '): # bash script | ||
212 | + print(f'Running {s} ...') | ||
213 | + r = os.system(s) | ||
214 | + else: # python script | ||
215 | + r = exec(s) # return None | ||
216 | + print('Dataset autodownload %s\n' % ('success' if r in (0, None) else 'failure')) # print result | ||
217 | + else: | ||
218 | + raise Exception('Dataset not found.') | ||
219 | + | ||
220 | + | ||
221 | +def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1): | ||
222 | + # Multi-threaded file download and unzip function | ||
223 | + def download_one(url, dir): | ||
224 | + # Download 1 file | ||
225 | + f = dir / Path(url).name # filename | ||
226 | + if not f.exists(): | ||
227 | + print(f'Downloading {url} to {f}...') | ||
228 | + if curl: | ||
229 | + os.system(f"curl -L '{url}' -o '{f}' --retry 9 -C -") # curl download, retry and resume on fail | ||
230 | + else: | ||
231 | + torch.hub.download_url_to_file(url, f, progress=True) # torch download | ||
232 | + if unzip and f.suffix in ('.zip', '.gz'): | ||
233 | + print(f'Unzipping {f}...') | ||
234 | + if f.suffix == '.zip': | ||
235 | + s = f'unzip -qo {f} -d {dir} && rm {f}' # unzip -quiet -overwrite | ||
236 | + elif f.suffix == '.gz': | ||
237 | + s = f'tar xfz {f} --directory {f.parent}' # unzip | ||
238 | + if delete: # delete zip file after unzip | ||
239 | + s += f' && rm {f}' | ||
240 | + os.system(s) | ||
241 | + | ||
242 | + dir = Path(dir) | ||
243 | + dir.mkdir(parents=True, exist_ok=True) # make directory | ||
244 | + if threads > 1: | ||
245 | + pool = ThreadPool(threads) | ||
246 | + pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded | ||
247 | + pool.close() | ||
248 | + pool.join() | ||
249 | + else: | ||
250 | + for u in tuple(url) if isinstance(url, str) else url: | ||
251 | + download_one(u, dir) | ||
252 | + | ||
253 | + | ||
254 | +def make_divisible(x, divisor): | ||
255 | + # Returns x evenly divisible by divisor | ||
256 | + return math.ceil(x / divisor) * divisor | ||
257 | + | ||
258 | + | ||
259 | +def clean_str(s): | ||
260 | + # Cleans a string by replacing special characters with underscore _ | ||
261 | + return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s) | ||
262 | + | ||
263 | + | ||
264 | +def one_cycle(y1=0.0, y2=1.0, steps=100): | ||
265 | + # lambda function for sinusoidal ramp from y1 to y2 | ||
266 | + return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 | ||
267 | + | ||
268 | + | ||
269 | +def colorstr(*input): | ||
270 | + # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world') | ||
271 | + *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string | ||
272 | + colors = {'black': '\033[30m', # basic colors | ||
273 | + 'red': '\033[31m', | ||
274 | + 'green': '\033[32m', | ||
275 | + 'yellow': '\033[33m', | ||
276 | + 'blue': '\033[34m', | ||
277 | + 'magenta': '\033[35m', | ||
278 | + 'cyan': '\033[36m', | ||
279 | + 'white': '\033[37m', | ||
280 | + 'bright_black': '\033[90m', # bright colors | ||
281 | + 'bright_red': '\033[91m', | ||
282 | + 'bright_green': '\033[92m', | ||
283 | + 'bright_yellow': '\033[93m', | ||
284 | + 'bright_blue': '\033[94m', | ||
285 | + 'bright_magenta': '\033[95m', | ||
286 | + 'bright_cyan': '\033[96m', | ||
287 | + 'bright_white': '\033[97m', | ||
288 | + 'end': '\033[0m', # misc | ||
289 | + 'bold': '\033[1m', | ||
290 | + 'underline': '\033[4m'} | ||
291 | + return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] | ||
292 | + | ||
293 | + | ||
294 | +def labels_to_class_weights(labels, nc=80): | ||
295 | + # Get class weights (inverse frequency) from training labels | ||
296 | + if labels[0] is None: # no labels loaded | ||
297 | + return torch.Tensor() | ||
298 | + | ||
299 | + labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO | ||
300 | + classes = labels[:, 0].astype(np.int) # labels = [class xywh] | ||
301 | + weights = np.bincount(classes, minlength=nc) # occurrences per class | ||
302 | + | ||
303 | + # Prepend gridpoint count (for uCE training) | ||
304 | + # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image | ||
305 | + # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start | ||
306 | + | ||
307 | + weights[weights == 0] = 1 # replace empty bins with 1 | ||
308 | + weights = 1 / weights # number of targets per class | ||
309 | + weights /= weights.sum() # normalize | ||
310 | + return torch.from_numpy(weights) | ||
311 | + | ||
312 | + | ||
313 | +def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): | ||
314 | + # Produces image weights based on class_weights and image contents | ||
315 | + class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels]) | ||
316 | + image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1) | ||
317 | + # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample | ||
318 | + return image_weights | ||
319 | + | ||
320 | + | ||
321 | +def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) | ||
322 | + # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/ | ||
323 | + # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n') | ||
324 | + # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n') | ||
325 | + # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco | ||
326 | + # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet | ||
327 | + x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, | ||
328 | + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, | ||
329 | + 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] | ||
330 | + return x | ||
331 | + | ||
332 | + | ||
333 | +def xyxy2xywh(x): | ||
334 | + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right | ||
335 | + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) | ||
336 | + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center | ||
337 | + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center | ||
338 | + y[:, 2] = x[:, 2] - x[:, 0] # width | ||
339 | + y[:, 3] = x[:, 3] - x[:, 1] # height | ||
340 | + return y | ||
341 | + | ||
342 | + | ||
343 | +def xywh2xyxy(x): | ||
344 | + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right | ||
345 | + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) | ||
346 | + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x | ||
347 | + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y | ||
348 | + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x | ||
349 | + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y | ||
350 | + return y | ||
351 | + | ||
352 | + | ||
353 | +def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): | ||
354 | + # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right | ||
355 | + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) | ||
356 | + y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x | ||
357 | + y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y | ||
358 | + y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x | ||
359 | + y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y | ||
360 | + return y | ||
361 | + | ||
362 | + | ||
363 | +def xyn2xy(x, w=640, h=640, padw=0, padh=0): | ||
364 | + # Convert normalized segments into pixel segments, shape (n,2) | ||
365 | + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) | ||
366 | + y[:, 0] = w * x[:, 0] + padw # top left x | ||
367 | + y[:, 1] = h * x[:, 1] + padh # top left y | ||
368 | + return y | ||
369 | + | ||
370 | + | ||
371 | +def segment2box(segment, width=640, height=640): | ||
372 | + # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy) | ||
373 | + x, y = segment.T # segment xy | ||
374 | + inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height) | ||
375 | + x, y, = x[inside], y[inside] | ||
376 | + return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy | ||
377 | + | ||
378 | + | ||
379 | +def segments2boxes(segments): | ||
380 | + # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh) | ||
381 | + boxes = [] | ||
382 | + for s in segments: | ||
383 | + x, y = s.T # segment xy | ||
384 | + boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy | ||
385 | + return xyxy2xywh(np.array(boxes)) # cls, xywh | ||
386 | + | ||
387 | + | ||
388 | +def resample_segments(segments, n=1000): | ||
389 | + # Up-sample an (n,2) segment | ||
390 | + for i, s in enumerate(segments): | ||
391 | + x = np.linspace(0, len(s) - 1, n) | ||
392 | + xp = np.arange(len(s)) | ||
393 | + segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy | ||
394 | + return segments | ||
395 | + | ||
396 | + | ||
397 | +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): | ||
398 | + # Rescale coords (xyxy) from img1_shape to img0_shape | ||
399 | + if ratio_pad is None: # calculate from img0_shape | ||
400 | + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new | ||
401 | + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding | ||
402 | + else: | ||
403 | + gain = ratio_pad[0][0] | ||
404 | + pad = ratio_pad[1] | ||
405 | + | ||
406 | + coords[:, [0, 2]] -= pad[0] # x padding | ||
407 | + coords[:, [1, 3]] -= pad[1] # y padding | ||
408 | + coords[:, :4] /= gain | ||
409 | + clip_coords(coords, img0_shape) | ||
410 | + return coords | ||
411 | + | ||
412 | + | ||
413 | +def clip_coords(boxes, img_shape): | ||
414 | + # Clip bounding xyxy bounding boxes to image shape (height, width) | ||
415 | + boxes[:, 0].clamp_(0, img_shape[1]) # x1 | ||
416 | + boxes[:, 1].clamp_(0, img_shape[0]) # y1 | ||
417 | + boxes[:, 2].clamp_(0, img_shape[1]) # x2 | ||
418 | + boxes[:, 3].clamp_(0, img_shape[0]) # y2 | ||
419 | + | ||
420 | + | ||
421 | +def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): | ||
422 | + # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 | ||
423 | + box2 = box2.T | ||
424 | + | ||
425 | + # Get the coordinates of bounding boxes | ||
426 | + if x1y1x2y2: # x1, y1, x2, y2 = box1 | ||
427 | + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] | ||
428 | + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] | ||
429 | + else: # transform from xywh to xyxy | ||
430 | + b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 | ||
431 | + b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 | ||
432 | + b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 | ||
433 | + b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 | ||
434 | + | ||
435 | + # Intersection area | ||
436 | + inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ | ||
437 | + (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) | ||
438 | + | ||
439 | + # Union Area | ||
440 | + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps | ||
441 | + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps | ||
442 | + union = w1 * h1 + w2 * h2 - inter + eps | ||
443 | + | ||
444 | + iou = inter / union | ||
445 | + if GIoU or DIoU or CIoU: | ||
446 | + cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width | ||
447 | + ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height | ||
448 | + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 | ||
449 | + c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared | ||
450 | + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + | ||
451 | + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared | ||
452 | + if DIoU: | ||
453 | + return iou - rho2 / c2 # DIoU | ||
454 | + elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 | ||
455 | + v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) | ||
456 | + with torch.no_grad(): | ||
457 | + alpha = v / (v - iou + (1 + eps)) | ||
458 | + return iou - (rho2 / c2 + v * alpha) # CIoU | ||
459 | + else: # GIoU https://arxiv.org/pdf/1902.09630.pdf | ||
460 | + c_area = cw * ch + eps # convex area | ||
461 | + return iou - (c_area - union) / c_area # GIoU | ||
462 | + else: | ||
463 | + return iou # IoU | ||
464 | + | ||
465 | + | ||
466 | +def box_iou(box1, box2): | ||
467 | + # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py | ||
468 | + """ | ||
469 | + Return intersection-over-union (Jaccard index) of boxes. | ||
470 | + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. | ||
471 | + Arguments: | ||
472 | + box1 (Tensor[N, 4]) | ||
473 | + box2 (Tensor[M, 4]) | ||
474 | + Returns: | ||
475 | + iou (Tensor[N, M]): the NxM matrix containing the pairwise | ||
476 | + IoU values for every element in boxes1 and boxes2 | ||
477 | + """ | ||
478 | + | ||
479 | + def box_area(box): | ||
480 | + # box = 4xn | ||
481 | + return (box[2] - box[0]) * (box[3] - box[1]) | ||
482 | + | ||
483 | + area1 = box_area(box1.T) | ||
484 | + area2 = box_area(box2.T) | ||
485 | + | ||
486 | + # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) | ||
487 | + inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) | ||
488 | + return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter) | ||
489 | + | ||
490 | + | ||
491 | +def wh_iou(wh1, wh2): | ||
492 | + # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 | ||
493 | + wh1 = wh1[:, None] # [N,1,2] | ||
494 | + wh2 = wh2[None] # [1,M,2] | ||
495 | + inter = torch.min(wh1, wh2).prod(2) # [N,M] | ||
496 | + return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) | ||
497 | + | ||
498 | + | ||
499 | +def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, | ||
500 | + labels=(), max_det=300): | ||
501 | + """Runs Non-Maximum Suppression (NMS) on inference results | ||
502 | + | ||
503 | + Returns: | ||
504 | + list of detections, on (n,6) tensor per image [xyxy, conf, cls] | ||
505 | + """ | ||
506 | + | ||
507 | + nc = prediction.shape[2] - 5 # number of classes | ||
508 | + xc = prediction[..., 4] > conf_thres # candidates | ||
509 | + | ||
510 | + # Checks | ||
511 | + assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0' | ||
512 | + assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0' | ||
513 | + | ||
514 | + # Settings | ||
515 | + min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height | ||
516 | + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() | ||
517 | + time_limit = 10.0 # seconds to quit after | ||
518 | + redundant = True # require redundant detections | ||
519 | + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) | ||
520 | + merge = False # use merge-NMS | ||
521 | + | ||
522 | + t = time.time() | ||
523 | + output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] | ||
524 | + for xi, x in enumerate(prediction): # image index, image inference | ||
525 | + # Apply constraints | ||
526 | + # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height | ||
527 | + x = x[xc[xi]] # confidence | ||
528 | + | ||
529 | + # Cat apriori labels if autolabelling | ||
530 | + if labels and len(labels[xi]): | ||
531 | + l = labels[xi] | ||
532 | + v = torch.zeros((len(l), nc + 5), device=x.device) | ||
533 | + v[:, :4] = l[:, 1:5] # box | ||
534 | + v[:, 4] = 1.0 # conf | ||
535 | + v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls | ||
536 | + x = torch.cat((x, v), 0) | ||
537 | + | ||
538 | + # If none remain process next image | ||
539 | + if not x.shape[0]: | ||
540 | + continue | ||
541 | + | ||
542 | + # Compute conf | ||
543 | + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf | ||
544 | + | ||
545 | + # Box (center x, center y, width, height) to (x1, y1, x2, y2) | ||
546 | + box = xywh2xyxy(x[:, :4]) | ||
547 | + | ||
548 | + # Detections matrix nx6 (xyxy, conf, cls) | ||
549 | + if multi_label: | ||
550 | + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T | ||
551 | + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) | ||
552 | + else: # best class only | ||
553 | + conf, j = x[:, 5:].max(1, keepdim=True) | ||
554 | + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] | ||
555 | + | ||
556 | + # Filter by class | ||
557 | + if classes is not None: | ||
558 | + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] | ||
559 | + | ||
560 | + # Apply finite constraint | ||
561 | + # if not torch.isfinite(x).all(): | ||
562 | + # x = x[torch.isfinite(x).all(1)] | ||
563 | + | ||
564 | + # Check shape | ||
565 | + n = x.shape[0] # number of boxes | ||
566 | + if not n: # no boxes | ||
567 | + continue | ||
568 | + elif n > max_nms: # excess boxes | ||
569 | + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence | ||
570 | + | ||
571 | + # Batched NMS | ||
572 | + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes | ||
573 | + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores | ||
574 | + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS | ||
575 | + if i.shape[0] > max_det: # limit detections | ||
576 | + i = i[:max_det] | ||
577 | + if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) | ||
578 | + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) | ||
579 | + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix | ||
580 | + weights = iou * scores[None] # box weights | ||
581 | + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes | ||
582 | + if redundant: | ||
583 | + i = i[iou.sum(1) > 1] # require redundancy | ||
584 | + | ||
585 | + output[xi] = x[i] | ||
586 | + if (time.time() - t) > time_limit: | ||
587 | + print(f'WARNING: NMS time limit {time_limit}s exceeded') | ||
588 | + break # time limit exceeded | ||
589 | + | ||
590 | + return output | ||
591 | + | ||
592 | + | ||
593 | +def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer() | ||
594 | + # Strip optimizer from 'f' to finalize training, optionally save as 's' | ||
595 | + x = torch.load(f, map_location=torch.device('cpu')) | ||
596 | + if x.get('ema'): | ||
597 | + x['model'] = x['ema'] # replace model with ema | ||
598 | + for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys | ||
599 | + x[k] = None | ||
600 | + x['epoch'] = -1 | ||
601 | + x['model'].half() # to FP16 | ||
602 | + for p in x['model'].parameters(): | ||
603 | + p.requires_grad = False | ||
604 | + torch.save(x, s or f) | ||
605 | + mb = os.path.getsize(s or f) / 1E6 # filesize | ||
606 | + print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB") | ||
607 | + | ||
608 | + | ||
609 | +def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''): | ||
610 | + # Print mutation results to evolve.txt (for use with train.py --evolve) | ||
611 | + a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys | ||
612 | + b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values | ||
613 | + c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) | ||
614 | + print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c)) | ||
615 | + | ||
616 | + if bucket: | ||
617 | + url = 'gs://%s/evolve.txt' % bucket | ||
618 | + if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0): | ||
619 | + os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local | ||
620 | + | ||
621 | + with open('evolve.txt', 'a') as f: # append result | ||
622 | + f.write(c + b + '\n') | ||
623 | + x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows | ||
624 | + x = x[np.argsort(-fitness(x))] # sort | ||
625 | + np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness | ||
626 | + | ||
627 | + # Save yaml | ||
628 | + for i, k in enumerate(hyp.keys()): | ||
629 | + hyp[k] = float(x[0, i + 7]) | ||
630 | + with open(yaml_file, 'w') as f: | ||
631 | + results = tuple(x[0, :7]) | ||
632 | + c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) | ||
633 | + f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n') | ||
634 | + yaml.safe_dump(hyp, f, sort_keys=False) | ||
635 | + | ||
636 | + if bucket: | ||
637 | + os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload | ||
638 | + | ||
639 | + | ||
640 | +def apply_classifier(x, model, img, im0): | ||
641 | + # Apply a second stage classifier to yolo outputs | ||
642 | + im0 = [im0] if isinstance(im0, np.ndarray) else im0 | ||
643 | + for i, d in enumerate(x): # per image | ||
644 | + if d is not None and len(d): | ||
645 | + d = d.clone() | ||
646 | + | ||
647 | + # Reshape and pad cutouts | ||
648 | + b = xyxy2xywh(d[:, :4]) # boxes | ||
649 | + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square | ||
650 | + b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad | ||
651 | + d[:, :4] = xywh2xyxy(b).long() | ||
652 | + | ||
653 | + # Rescale boxes from img_size to im0 size | ||
654 | + scale_coords(img.shape[2:], d[:, :4], im0[i].shape) | ||
655 | + | ||
656 | + # Classes | ||
657 | + pred_cls1 = d[:, 5].long() | ||
658 | + ims = [] | ||
659 | + for j, a in enumerate(d): # per item | ||
660 | + cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])] | ||
661 | + im = cv2.resize(cutout, (224, 224)) # BGR | ||
662 | + # cv2.imwrite('test%i.jpg' % j, cutout) | ||
663 | + | ||
664 | + im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 | ||
665 | + im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32 | ||
666 | + im /= 255.0 # 0 - 255 to 0.0 - 1.0 | ||
667 | + ims.append(im) | ||
668 | + | ||
669 | + pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction | ||
670 | + x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections | ||
671 | + | ||
672 | + return x | ||
673 | + | ||
674 | + | ||
675 | +def save_one_box(xyxy, im, file='image.jpg', gain=1.02, pad=10, square=False, BGR=False, save=True): | ||
676 | + # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop | ||
677 | + xyxy = torch.tensor(xyxy).view(-1, 4) | ||
678 | + b = xyxy2xywh(xyxy) # boxes | ||
679 | + if square: | ||
680 | + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square | ||
681 | + b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad | ||
682 | + xyxy = xywh2xyxy(b).long() | ||
683 | + clip_coords(xyxy, im.shape) | ||
684 | + crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)] | ||
685 | + if save: | ||
686 | + cv2.imwrite(str(increment_path(file, mkdir=True).with_suffix('.jpg')), crop) | ||
687 | + return crop | ||
688 | + | ||
689 | + | ||
690 | +def increment_path(path, exist_ok=False, sep='', mkdir=False): | ||
691 | + # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. | ||
692 | + path = Path(path) # os-agnostic | ||
693 | + if path.exists() and not exist_ok: | ||
694 | + suffix = path.suffix | ||
695 | + path = path.with_suffix('') | ||
696 | + dirs = glob.glob(f"{path}{sep}*") # similar paths | ||
697 | + matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] | ||
698 | + i = [int(m.groups()[0]) for m in matches if m] # indices | ||
699 | + n = max(i) + 1 if i else 2 # increment number | ||
700 | + path = Path(f"{path}{sep}{n}{suffix}") # update path | ||
701 | + dir = path if path.suffix == '' else path.parent # directory | ||
702 | + if not dir.exists() and mkdir: | ||
703 | + dir.mkdir(parents=True, exist_ok=True) # make directory | ||
704 | + return path |
YOLOv5/utils/google_app_engine/Dockerfile
0 → 100644
1 | +FROM gcr.io/google-appengine/python | ||
2 | + | ||
3 | +# Create a virtualenv for dependencies. This isolates these packages from | ||
4 | +# system-level packages. | ||
5 | +# Use -p python3 or -p python3.7 to select python version. Default is version 2. | ||
6 | +RUN virtualenv /env -p python3 | ||
7 | + | ||
8 | +# Setting these environment variables are the same as running | ||
9 | +# source /env/bin/activate. | ||
10 | +ENV VIRTUAL_ENV /env | ||
11 | +ENV PATH /env/bin:$PATH | ||
12 | + | ||
13 | +RUN apt-get update && apt-get install -y python-opencv | ||
14 | + | ||
15 | +# Copy the application's requirements.txt and run pip to install all | ||
16 | +# dependencies into the virtualenv. | ||
17 | +ADD requirements.txt /app/requirements.txt | ||
18 | +RUN pip install -r /app/requirements.txt | ||
19 | + | ||
20 | +# Add the application source code. | ||
21 | +ADD . /app | ||
22 | + | ||
23 | +# Run a WSGI server to serve the application. gunicorn must be declared as | ||
24 | +# a dependency in requirements.txt. | ||
25 | +CMD gunicorn -b :$PORT main:app |
YOLOv5/utils/google_app_engine/app.yaml
0 → 100644
YOLOv5/utils/google_utils.py
0 → 100644
1 | +# Google utils: https://cloud.google.com/storage/docs/reference/libraries | ||
2 | + | ||
3 | +import os | ||
4 | +import platform | ||
5 | +import subprocess | ||
6 | +import time | ||
7 | +from pathlib import Path | ||
8 | + | ||
9 | +import requests | ||
10 | +import torch | ||
11 | + | ||
12 | + | ||
13 | +def gsutil_getsize(url=''): | ||
14 | + # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du | ||
15 | + s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') | ||
16 | + return eval(s.split(' ')[0]) if len(s) else 0 # bytes | ||
17 | + | ||
18 | + | ||
19 | +def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): | ||
20 | + # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes | ||
21 | + file = Path(file) | ||
22 | + try: # GitHub | ||
23 | + print(f'Downloading {url} to {file}...') | ||
24 | + torch.hub.download_url_to_file(url, str(file)) | ||
25 | + assert file.exists() and file.stat().st_size > min_bytes # check | ||
26 | + except Exception as e: # GCP | ||
27 | + file.unlink(missing_ok=True) # remove partial downloads | ||
28 | + print(f'Download error: {e}\nRe-attempting {url2 or url} to {file}...') | ||
29 | + os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail | ||
30 | + finally: | ||
31 | + if not file.exists() or file.stat().st_size < min_bytes: # check | ||
32 | + file.unlink(missing_ok=True) # remove partial downloads | ||
33 | + print(f'ERROR: Download failure: {error_msg or url}') | ||
34 | + print('') | ||
35 | + | ||
36 | + | ||
37 | +def attempt_download(file, repo='ultralytics/yolov5'): | ||
38 | + # Attempt file download if does not exist | ||
39 | + file = Path(str(file).strip().replace("'", '')) | ||
40 | + | ||
41 | + if not file.exists(): | ||
42 | + # URL specified | ||
43 | + name = file.name | ||
44 | + if str(file).startswith(('http:/', 'https:/')): # download | ||
45 | + url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ | ||
46 | + safe_download(file=name, url=url, min_bytes=1E5) | ||
47 | + return name | ||
48 | + | ||
49 | + # GitHub assets | ||
50 | + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) | ||
51 | + try: | ||
52 | + response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api | ||
53 | + assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] | ||
54 | + tag = response['tag_name'] # i.e. 'v1.0' | ||
55 | + except: # fallback plan | ||
56 | + assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', | ||
57 | + 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] | ||
58 | + try: | ||
59 | + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] | ||
60 | + except: | ||
61 | + tag = 'v5.0' # current release | ||
62 | + | ||
63 | + if name in assets: | ||
64 | + safe_download(file, | ||
65 | + url=f'https://github.com/{repo}/releases/download/{tag}/{name}', | ||
66 | + # url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional) | ||
67 | + min_bytes=1E5, | ||
68 | + error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/') | ||
69 | + | ||
70 | + return str(file) | ||
71 | + | ||
72 | + | ||
73 | +def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): | ||
74 | + # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download() | ||
75 | + t = time.time() | ||
76 | + file = Path(file) | ||
77 | + cookie = Path('cookie') # gdrive cookie | ||
78 | + print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') | ||
79 | + file.unlink(missing_ok=True) # remove existing file | ||
80 | + cookie.unlink(missing_ok=True) # remove existing cookie | ||
81 | + | ||
82 | + # Attempt file download | ||
83 | + out = "NUL" if platform.system() == "Windows" else "/dev/null" | ||
84 | + os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') | ||
85 | + if os.path.exists('cookie'): # large file | ||
86 | + s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' | ||
87 | + else: # small file | ||
88 | + s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' | ||
89 | + r = os.system(s) # execute, capture return | ||
90 | + cookie.unlink(missing_ok=True) # remove existing cookie | ||
91 | + | ||
92 | + # Error check | ||
93 | + if r != 0: | ||
94 | + file.unlink(missing_ok=True) # remove partial | ||
95 | + print('Download error ') # raise Exception('Download error') | ||
96 | + return r | ||
97 | + | ||
98 | + # Unzip if archive | ||
99 | + if file.suffix == '.zip': | ||
100 | + print('unzipping... ', end='') | ||
101 | + os.system(f'unzip -q {file}') # unzip | ||
102 | + file.unlink() # remove zip to free space | ||
103 | + | ||
104 | + print(f'Done ({time.time() - t:.1f}s)') | ||
105 | + return r | ||
106 | + | ||
107 | + | ||
108 | +def get_token(cookie="./cookie"): | ||
109 | + with open(cookie) as f: | ||
110 | + for line in f: | ||
111 | + if "download" in line: | ||
112 | + return line.split()[-1] | ||
113 | + return "" | ||
114 | + | ||
115 | +# def upload_blob(bucket_name, source_file_name, destination_blob_name): | ||
116 | +# # Uploads a file to a bucket | ||
117 | +# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python | ||
118 | +# | ||
119 | +# storage_client = storage.Client() | ||
120 | +# bucket = storage_client.get_bucket(bucket_name) | ||
121 | +# blob = bucket.blob(destination_blob_name) | ||
122 | +# | ||
123 | +# blob.upload_from_filename(source_file_name) | ||
124 | +# | ||
125 | +# print('File {} uploaded to {}.'.format( | ||
126 | +# source_file_name, | ||
127 | +# destination_blob_name)) | ||
128 | +# | ||
129 | +# | ||
130 | +# def download_blob(bucket_name, source_blob_name, destination_file_name): | ||
131 | +# # Uploads a blob from a bucket | ||
132 | +# storage_client = storage.Client() | ||
133 | +# bucket = storage_client.get_bucket(bucket_name) | ||
134 | +# blob = bucket.blob(source_blob_name) | ||
135 | +# | ||
136 | +# blob.download_to_filename(destination_file_name) | ||
137 | +# | ||
138 | +# print('Blob {} downloaded to {}.'.format( | ||
139 | +# source_blob_name, | ||
140 | +# destination_file_name)) |
YOLOv5/utils/loss.py
0 → 100644
1 | +# Loss functions | ||
2 | + | ||
3 | +import torch | ||
4 | +import torch.nn as nn | ||
5 | + | ||
6 | +from utils.general import bbox_iou | ||
7 | +from utils.torch_utils import is_parallel | ||
8 | + | ||
9 | + | ||
10 | +def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 | ||
11 | + # return positive, negative label smoothing BCE targets | ||
12 | + return 1.0 - 0.5 * eps, 0.5 * eps | ||
13 | + | ||
14 | + | ||
15 | +class BCEBlurWithLogitsLoss(nn.Module): | ||
16 | + # BCEwithLogitLoss() with reduced missing label effects. | ||
17 | + def __init__(self, alpha=0.05): | ||
18 | + super(BCEBlurWithLogitsLoss, self).__init__() | ||
19 | + self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() | ||
20 | + self.alpha = alpha | ||
21 | + | ||
22 | + def forward(self, pred, true): | ||
23 | + loss = self.loss_fcn(pred, true) | ||
24 | + pred = torch.sigmoid(pred) # prob from logits | ||
25 | + dx = pred - true # reduce only missing label effects | ||
26 | + # dx = (pred - true).abs() # reduce missing label and false label effects | ||
27 | + alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) | ||
28 | + loss *= alpha_factor | ||
29 | + return loss.mean() | ||
30 | + | ||
31 | + | ||
32 | +class FocalLoss(nn.Module): | ||
33 | + # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) | ||
34 | + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): | ||
35 | + super(FocalLoss, self).__init__() | ||
36 | + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() | ||
37 | + self.gamma = gamma | ||
38 | + self.alpha = alpha | ||
39 | + self.reduction = loss_fcn.reduction | ||
40 | + self.loss_fcn.reduction = 'none' # required to apply FL to each element | ||
41 | + | ||
42 | + def forward(self, pred, true): | ||
43 | + loss = self.loss_fcn(pred, true) | ||
44 | + # p_t = torch.exp(-loss) | ||
45 | + # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability | ||
46 | + | ||
47 | + # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py | ||
48 | + pred_prob = torch.sigmoid(pred) # prob from logits | ||
49 | + p_t = true * pred_prob + (1 - true) * (1 - pred_prob) | ||
50 | + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) | ||
51 | + modulating_factor = (1.0 - p_t) ** self.gamma | ||
52 | + loss *= alpha_factor * modulating_factor | ||
53 | + | ||
54 | + if self.reduction == 'mean': | ||
55 | + return loss.mean() | ||
56 | + elif self.reduction == 'sum': | ||
57 | + return loss.sum() | ||
58 | + else: # 'none' | ||
59 | + return loss | ||
60 | + | ||
61 | + | ||
62 | +class QFocalLoss(nn.Module): | ||
63 | + # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) | ||
64 | + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): | ||
65 | + super(QFocalLoss, self).__init__() | ||
66 | + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() | ||
67 | + self.gamma = gamma | ||
68 | + self.alpha = alpha | ||
69 | + self.reduction = loss_fcn.reduction | ||
70 | + self.loss_fcn.reduction = 'none' # required to apply FL to each element | ||
71 | + | ||
72 | + def forward(self, pred, true): | ||
73 | + loss = self.loss_fcn(pred, true) | ||
74 | + | ||
75 | + pred_prob = torch.sigmoid(pred) # prob from logits | ||
76 | + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) | ||
77 | + modulating_factor = torch.abs(true - pred_prob) ** self.gamma | ||
78 | + loss *= alpha_factor * modulating_factor | ||
79 | + | ||
80 | + if self.reduction == 'mean': | ||
81 | + return loss.mean() | ||
82 | + elif self.reduction == 'sum': | ||
83 | + return loss.sum() | ||
84 | + else: # 'none' | ||
85 | + return loss | ||
86 | + | ||
87 | + | ||
88 | +class ComputeLoss: | ||
89 | + # Compute losses | ||
90 | + def __init__(self, model, autobalance=False): | ||
91 | + super(ComputeLoss, self).__init__() | ||
92 | + device = next(model.parameters()).device # get model device | ||
93 | + h = model.hyp # hyperparameters | ||
94 | + | ||
95 | + # Define criteria | ||
96 | + BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) | ||
97 | + BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) | ||
98 | + | ||
99 | + # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 | ||
100 | + self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets | ||
101 | + | ||
102 | + # Focal loss | ||
103 | + g = h['fl_gamma'] # focal loss gamma | ||
104 | + if g > 0: | ||
105 | + BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) | ||
106 | + | ||
107 | + det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module | ||
108 | + self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7 | ||
109 | + self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index | ||
110 | + self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance | ||
111 | + for k in 'na', 'nc', 'nl', 'anchors': | ||
112 | + setattr(self, k, getattr(det, k)) | ||
113 | + | ||
114 | + def __call__(self, p, targets): # predictions, targets, model | ||
115 | + device = targets.device | ||
116 | + lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) | ||
117 | + tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets | ||
118 | + | ||
119 | + # Losses | ||
120 | + for i, pi in enumerate(p): # layer index, layer predictions | ||
121 | + b, a, gj, gi = indices[i] # image, anchor, gridy, gridx | ||
122 | + tobj = torch.zeros_like(pi[..., 0], device=device) # target obj | ||
123 | + | ||
124 | + n = b.shape[0] # number of targets | ||
125 | + if n: | ||
126 | + ps = pi[b, a, gj, gi] # prediction subset corresponding to targets | ||
127 | + | ||
128 | + # Regression | ||
129 | + pxy = ps[:, :2].sigmoid() * 2. - 0.5 | ||
130 | + pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] | ||
131 | + pbox = torch.cat((pxy, pwh), 1) # predicted box | ||
132 | + iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) | ||
133 | + lbox += (1.0 - iou).mean() # iou loss | ||
134 | + | ||
135 | + # Objectness | ||
136 | + tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio | ||
137 | + | ||
138 | + # Classification | ||
139 | + if self.nc > 1: # cls loss (only if multiple classes) | ||
140 | + t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets | ||
141 | + t[range(n), tcls[i]] = self.cp | ||
142 | + lcls += self.BCEcls(ps[:, 5:], t) # BCE | ||
143 | + | ||
144 | + # Append targets to text file | ||
145 | + # with open('targets.txt', 'a') as file: | ||
146 | + # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] | ||
147 | + | ||
148 | + obji = self.BCEobj(pi[..., 4], tobj) | ||
149 | + lobj += obji * self.balance[i] # obj loss | ||
150 | + if self.autobalance: | ||
151 | + self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() | ||
152 | + | ||
153 | + if self.autobalance: | ||
154 | + self.balance = [x / self.balance[self.ssi] for x in self.balance] | ||
155 | + lbox *= self.hyp['box'] | ||
156 | + lobj *= self.hyp['obj'] | ||
157 | + lcls *= self.hyp['cls'] | ||
158 | + bs = tobj.shape[0] # batch size | ||
159 | + | ||
160 | + loss = lbox + lobj + lcls | ||
161 | + return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach() | ||
162 | + | ||
163 | + def build_targets(self, p, targets): | ||
164 | + # Build targets for compute_loss(), input targets(image,class,x,y,w,h) | ||
165 | + na, nt = self.na, targets.shape[0] # number of anchors, targets | ||
166 | + tcls, tbox, indices, anch = [], [], [], [] | ||
167 | + gain = torch.ones(7, device=targets.device) # normalized to gridspace gain | ||
168 | + ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) | ||
169 | + targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices | ||
170 | + | ||
171 | + g = 0.5 # bias | ||
172 | + off = torch.tensor([[0, 0], | ||
173 | + [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m | ||
174 | + # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm | ||
175 | + ], device=targets.device).float() * g # offsets | ||
176 | + | ||
177 | + for i in range(self.nl): | ||
178 | + anchors = self.anchors[i] | ||
179 | + gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain | ||
180 | + | ||
181 | + # Match targets to anchors | ||
182 | + t = targets * gain | ||
183 | + if nt: | ||
184 | + # Matches | ||
185 | + r = t[:, :, 4:6] / anchors[:, None] # wh ratio | ||
186 | + j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare | ||
187 | + # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) | ||
188 | + t = t[j] # filter | ||
189 | + | ||
190 | + # Offsets | ||
191 | + gxy = t[:, 2:4] # grid xy | ||
192 | + gxi = gain[[2, 3]] - gxy # inverse | ||
193 | + j, k = ((gxy % 1. < g) & (gxy > 1.)).T | ||
194 | + l, m = ((gxi % 1. < g) & (gxi > 1.)).T | ||
195 | + j = torch.stack((torch.ones_like(j), j, k, l, m)) | ||
196 | + t = t.repeat((5, 1, 1))[j] | ||
197 | + offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] | ||
198 | + else: | ||
199 | + t = targets[0] | ||
200 | + offsets = 0 | ||
201 | + | ||
202 | + # Define | ||
203 | + b, c = t[:, :2].long().T # image, class | ||
204 | + gxy = t[:, 2:4] # grid xy | ||
205 | + gwh = t[:, 4:6] # grid wh | ||
206 | + gij = (gxy - offsets).long() | ||
207 | + gi, gj = gij.T # grid xy indices | ||
208 | + | ||
209 | + # Append | ||
210 | + a = t[:, 6].long() # anchor indices | ||
211 | + indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices | ||
212 | + tbox.append(torch.cat((gxy - gij, gwh), 1)) # box | ||
213 | + anch.append(anchors[a]) # anchors | ||
214 | + tcls.append(c) # class | ||
215 | + | ||
216 | + return tcls, tbox, indices, anch |
YOLOv5/utils/metrics.py
0 → 100644
1 | +# Model validation metrics | ||
2 | + | ||
3 | +from pathlib import Path | ||
4 | + | ||
5 | +import matplotlib.pyplot as plt | ||
6 | +import numpy as np | ||
7 | +import torch | ||
8 | + | ||
9 | +from . import general | ||
10 | + | ||
11 | + | ||
12 | +def fitness(x): | ||
13 | + # Model fitness as a weighted combination of metrics | ||
14 | + w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] | ||
15 | + return (x[:, :4] * w).sum(1) | ||
16 | + | ||
17 | + | ||
18 | +def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()): | ||
19 | + """ Compute the average precision, given the recall and precision curves. | ||
20 | + Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. | ||
21 | + # Arguments | ||
22 | + tp: True positives (nparray, nx1 or nx10). | ||
23 | + conf: Objectness value from 0-1 (nparray). | ||
24 | + pred_cls: Predicted object classes (nparray). | ||
25 | + target_cls: True object classes (nparray). | ||
26 | + plot: Plot precision-recall curve at mAP@0.5 | ||
27 | + save_dir: Plot save directory | ||
28 | + # Returns | ||
29 | + The average precision as computed in py-faster-rcnn. | ||
30 | + """ | ||
31 | + | ||
32 | + # Sort by objectness | ||
33 | + i = np.argsort(-conf) | ||
34 | + tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] | ||
35 | + | ||
36 | + # Find unique classes | ||
37 | + unique_classes = np.unique(target_cls) | ||
38 | + nc = unique_classes.shape[0] # number of classes, number of detections | ||
39 | + | ||
40 | + # Create Precision-Recall curve and compute AP for each class | ||
41 | + px, py = np.linspace(0, 1, 1000), [] # for plotting | ||
42 | + ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) | ||
43 | + for ci, c in enumerate(unique_classes): | ||
44 | + i = pred_cls == c | ||
45 | + n_l = (target_cls == c).sum() # number of labels | ||
46 | + n_p = i.sum() # number of predictions | ||
47 | + | ||
48 | + if n_p == 0 or n_l == 0: | ||
49 | + continue | ||
50 | + else: | ||
51 | + # Accumulate FPs and TPs | ||
52 | + fpc = (1 - tp[i]).cumsum(0) | ||
53 | + tpc = tp[i].cumsum(0) | ||
54 | + | ||
55 | + # Recall | ||
56 | + recall = tpc / (n_l + 1e-16) # recall curve | ||
57 | + r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases | ||
58 | + | ||
59 | + # Precision | ||
60 | + precision = tpc / (tpc + fpc) # precision curve | ||
61 | + p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score | ||
62 | + | ||
63 | + # AP from recall-precision curve | ||
64 | + for j in range(tp.shape[1]): | ||
65 | + ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) | ||
66 | + if plot and j == 0: | ||
67 | + py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 | ||
68 | + | ||
69 | + # Compute F1 (harmonic mean of precision and recall) | ||
70 | + f1 = 2 * p * r / (p + r + 1e-16) | ||
71 | + if plot: | ||
72 | + plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) | ||
73 | + plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') | ||
74 | + plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') | ||
75 | + plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') | ||
76 | + | ||
77 | + i = f1.mean(0).argmax() # max F1 index | ||
78 | + return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32') | ||
79 | + | ||
80 | + | ||
81 | +def compute_ap(recall, precision): | ||
82 | + """ Compute the average precision, given the recall and precision curves | ||
83 | + # Arguments | ||
84 | + recall: The recall curve (list) | ||
85 | + precision: The precision curve (list) | ||
86 | + # Returns | ||
87 | + Average precision, precision curve, recall curve | ||
88 | + """ | ||
89 | + | ||
90 | + # Append sentinel values to beginning and end | ||
91 | + mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) | ||
92 | + mpre = np.concatenate(([1.], precision, [0.])) | ||
93 | + | ||
94 | + # Compute the precision envelope | ||
95 | + mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) | ||
96 | + | ||
97 | + # Integrate area under curve | ||
98 | + method = 'interp' # methods: 'continuous', 'interp' | ||
99 | + if method == 'interp': | ||
100 | + x = np.linspace(0, 1, 101) # 101-point interp (COCO) | ||
101 | + ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate | ||
102 | + else: # 'continuous' | ||
103 | + i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes | ||
104 | + ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve | ||
105 | + | ||
106 | + return ap, mpre, mrec | ||
107 | + | ||
108 | + | ||
109 | +class ConfusionMatrix: | ||
110 | + # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix | ||
111 | + def __init__(self, nc, conf=0.25, iou_thres=0.45): | ||
112 | + self.matrix = np.zeros((nc + 1, nc + 1)) | ||
113 | + self.nc = nc # number of classes | ||
114 | + self.conf = conf | ||
115 | + self.iou_thres = iou_thres | ||
116 | + | ||
117 | + def process_batch(self, detections, labels): | ||
118 | + """ | ||
119 | + Return intersection-over-union (Jaccard index) of boxes. | ||
120 | + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. | ||
121 | + Arguments: | ||
122 | + detections (Array[N, 6]), x1, y1, x2, y2, conf, class | ||
123 | + labels (Array[M, 5]), class, x1, y1, x2, y2 | ||
124 | + Returns: | ||
125 | + None, updates confusion matrix accordingly | ||
126 | + """ | ||
127 | + detections = detections[detections[:, 4] > self.conf] | ||
128 | + gt_classes = labels[:, 0].int() | ||
129 | + detection_classes = detections[:, 5].int() | ||
130 | + iou = general.box_iou(labels[:, 1:], detections[:, :4]) | ||
131 | + | ||
132 | + x = torch.where(iou > self.iou_thres) | ||
133 | + if x[0].shape[0]: | ||
134 | + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() | ||
135 | + if x[0].shape[0] > 1: | ||
136 | + matches = matches[matches[:, 2].argsort()[::-1]] | ||
137 | + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] | ||
138 | + matches = matches[matches[:, 2].argsort()[::-1]] | ||
139 | + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] | ||
140 | + else: | ||
141 | + matches = np.zeros((0, 3)) | ||
142 | + | ||
143 | + n = matches.shape[0] > 0 | ||
144 | + m0, m1, _ = matches.transpose().astype(np.int16) | ||
145 | + for i, gc in enumerate(gt_classes): | ||
146 | + j = m0 == i | ||
147 | + if n and sum(j) == 1: | ||
148 | + self.matrix[detection_classes[m1[j]], gc] += 1 # correct | ||
149 | + else: | ||
150 | + self.matrix[self.nc, gc] += 1 # background FP | ||
151 | + | ||
152 | + if n: | ||
153 | + for i, dc in enumerate(detection_classes): | ||
154 | + if not any(m1 == i): | ||
155 | + self.matrix[dc, self.nc] += 1 # background FN | ||
156 | + | ||
157 | + def matrix(self): | ||
158 | + return self.matrix | ||
159 | + | ||
160 | + def plot(self, save_dir='', names=()): | ||
161 | + try: | ||
162 | + import seaborn as sn | ||
163 | + | ||
164 | + array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize | ||
165 | + array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) | ||
166 | + | ||
167 | + fig = plt.figure(figsize=(12, 9), tight_layout=True) | ||
168 | + sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size | ||
169 | + labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels | ||
170 | + sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, | ||
171 | + xticklabels=names + ['background FP'] if labels else "auto", | ||
172 | + yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) | ||
173 | + fig.axes[0].set_xlabel('True') | ||
174 | + fig.axes[0].set_ylabel('Predicted') | ||
175 | + fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) | ||
176 | + except Exception as e: | ||
177 | + pass | ||
178 | + | ||
179 | + def print(self): | ||
180 | + for i in range(self.nc + 1): | ||
181 | + print(' '.join(map(str, self.matrix[i]))) | ||
182 | + | ||
183 | + | ||
184 | +# Plots ---------------------------------------------------------------------------------------------------------------- | ||
185 | + | ||
186 | +def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): | ||
187 | + # Precision-recall curve | ||
188 | + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) | ||
189 | + py = np.stack(py, axis=1) | ||
190 | + | ||
191 | + if 0 < len(names) < 21: # display per-class legend if < 21 classes | ||
192 | + for i, y in enumerate(py.T): | ||
193 | + ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) | ||
194 | + else: | ||
195 | + ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) | ||
196 | + | ||
197 | + ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) | ||
198 | + ax.set_xlabel('Recall') | ||
199 | + ax.set_ylabel('Precision') | ||
200 | + ax.set_xlim(0, 1) | ||
201 | + ax.set_ylim(0, 1) | ||
202 | + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") | ||
203 | + fig.savefig(Path(save_dir), dpi=250) | ||
204 | + | ||
205 | + | ||
206 | +def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): | ||
207 | + # Metric-confidence curve | ||
208 | + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) | ||
209 | + | ||
210 | + if 0 < len(names) < 21: # display per-class legend if < 21 classes | ||
211 | + for i, y in enumerate(py): | ||
212 | + ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) | ||
213 | + else: | ||
214 | + ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) | ||
215 | + | ||
216 | + y = py.mean(0) | ||
217 | + ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') | ||
218 | + ax.set_xlabel(xlabel) | ||
219 | + ax.set_ylabel(ylabel) | ||
220 | + ax.set_xlim(0, 1) | ||
221 | + ax.set_ylim(0, 1) | ||
222 | + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") | ||
223 | + fig.savefig(Path(save_dir), dpi=250) |
YOLOv5/utils/plots.py
0 → 100644
1 | +# Plotting utils | ||
2 | + | ||
3 | +import glob | ||
4 | +import math | ||
5 | +import os | ||
6 | +import random | ||
7 | +from copy import copy | ||
8 | +from pathlib import Path | ||
9 | + | ||
10 | +import cv2 | ||
11 | +import matplotlib | ||
12 | +import matplotlib.pyplot as plt | ||
13 | +import numpy as np | ||
14 | +import pandas as pd | ||
15 | +import seaborn as sns | ||
16 | +import torch | ||
17 | +import yaml | ||
18 | +from PIL import Image, ImageDraw, ImageFont | ||
19 | + | ||
20 | +from utils.general import xywh2xyxy, xyxy2xywh | ||
21 | +from utils.metrics import fitness | ||
22 | + | ||
23 | +# Settings | ||
24 | +matplotlib.rc('font', **{'size': 11}) | ||
25 | +matplotlib.use('Agg') # for writing to files only | ||
26 | + | ||
27 | + | ||
28 | +class Colors: | ||
29 | + # Ultralytics color palette https://ultralytics.com/ | ||
30 | + def __init__(self): | ||
31 | + # hex = matplotlib.colors.TABLEAU_COLORS.values() | ||
32 | + hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB', | ||
33 | + '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7') | ||
34 | + self.palette = [self.hex2rgb('#' + c) for c in hex] | ||
35 | + self.n = len(self.palette) | ||
36 | + | ||
37 | + def __call__(self, i, bgr=False): | ||
38 | + c = self.palette[int(i) % self.n] | ||
39 | + return (c[2], c[1], c[0]) if bgr else c | ||
40 | + | ||
41 | + @staticmethod | ||
42 | + def hex2rgb(h): # rgb order (PIL) | ||
43 | + return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) | ||
44 | + | ||
45 | + | ||
46 | +colors = Colors() # create instance for 'from utils.plots import colors' | ||
47 | + | ||
48 | + | ||
49 | +def hist2d(x, y, n=100): | ||
50 | + # 2d histogram used in labels.png and evolve.png | ||
51 | + xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n) | ||
52 | + hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges)) | ||
53 | + xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1) | ||
54 | + yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1) | ||
55 | + return np.log(hist[xidx, yidx]) | ||
56 | + | ||
57 | + | ||
58 | +def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): | ||
59 | + from scipy.signal import butter, filtfilt | ||
60 | + | ||
61 | + # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy | ||
62 | + def butter_lowpass(cutoff, fs, order): | ||
63 | + nyq = 0.5 * fs | ||
64 | + normal_cutoff = cutoff / nyq | ||
65 | + return butter(order, normal_cutoff, btype='low', analog=False) | ||
66 | + | ||
67 | + b, a = butter_lowpass(cutoff, fs, order=order) | ||
68 | + return filtfilt(b, a, data) # forward-backward filter | ||
69 | + | ||
70 | + | ||
71 | +def plot_one_box(x, im, color=(128, 128, 128), label=None, line_thickness=3): | ||
72 | + # Plots one bounding box on image 'im' using OpenCV | ||
73 | + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.' | ||
74 | + tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness | ||
75 | + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) | ||
76 | + cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) | ||
77 | + if label: | ||
78 | + tf = max(tl - 1, 1) # font thickness | ||
79 | + t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] | ||
80 | + c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 | ||
81 | + cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled | ||
82 | + cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) | ||
83 | + | ||
84 | + | ||
85 | +def plot_one_box_PIL(box, im, color=(128, 128, 128), label=None, line_thickness=None): | ||
86 | + # Plots one bounding box on image 'im' using PIL | ||
87 | + im = Image.fromarray(im) | ||
88 | + draw = ImageDraw.Draw(im) | ||
89 | + line_thickness = line_thickness or max(int(min(im.size) / 200), 2) | ||
90 | + draw.rectangle(box, width=line_thickness, outline=color) # plot | ||
91 | + if label: | ||
92 | + font = ImageFont.truetype("Arial.ttf", size=max(round(max(im.size) / 40), 12)) | ||
93 | + txt_width, txt_height = font.getsize(label) | ||
94 | + draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=color) | ||
95 | + draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font) | ||
96 | + return np.asarray(im) | ||
97 | + | ||
98 | + | ||
99 | +def plot_wh_methods(): # from utils.plots import *; plot_wh_methods() | ||
100 | + # Compares the two methods for width-height anchor multiplication | ||
101 | + # https://github.com/ultralytics/yolov3/issues/168 | ||
102 | + x = np.arange(-4.0, 4.0, .1) | ||
103 | + ya = np.exp(x) | ||
104 | + yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2 | ||
105 | + | ||
106 | + fig = plt.figure(figsize=(6, 3), tight_layout=True) | ||
107 | + plt.plot(x, ya, '.-', label='YOLOv3') | ||
108 | + plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2') | ||
109 | + plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6') | ||
110 | + plt.xlim(left=-4, right=4) | ||
111 | + plt.ylim(bottom=0, top=6) | ||
112 | + plt.xlabel('input') | ||
113 | + plt.ylabel('output') | ||
114 | + plt.grid() | ||
115 | + plt.legend() | ||
116 | + fig.savefig('comparison.png', dpi=200) | ||
117 | + | ||
118 | + | ||
119 | +def output_to_target(output): | ||
120 | + # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] | ||
121 | + targets = [] | ||
122 | + for i, o in enumerate(output): | ||
123 | + for *box, conf, cls in o.cpu().numpy(): | ||
124 | + targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf]) | ||
125 | + return np.array(targets) | ||
126 | + | ||
127 | + | ||
128 | +def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16): | ||
129 | + # Plot image grid with labels | ||
130 | + | ||
131 | + if isinstance(images, torch.Tensor): | ||
132 | + images = images.cpu().float().numpy() | ||
133 | + if isinstance(targets, torch.Tensor): | ||
134 | + targets = targets.cpu().numpy() | ||
135 | + | ||
136 | + # un-normalise | ||
137 | + if np.max(images[0]) <= 1: | ||
138 | + images *= 255 | ||
139 | + | ||
140 | + tl = 3 # line thickness | ||
141 | + tf = max(tl - 1, 1) # font thickness | ||
142 | + bs, _, h, w = images.shape # batch size, _, height, width | ||
143 | + bs = min(bs, max_subplots) # limit plot images | ||
144 | + ns = np.ceil(bs ** 0.5) # number of subplots (square) | ||
145 | + | ||
146 | + # Check if we should resize | ||
147 | + scale_factor = max_size / max(h, w) | ||
148 | + if scale_factor < 1: | ||
149 | + h = math.ceil(scale_factor * h) | ||
150 | + w = math.ceil(scale_factor * w) | ||
151 | + | ||
152 | + mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init | ||
153 | + for i, img in enumerate(images): | ||
154 | + if i == max_subplots: # if last batch has fewer images than we expect | ||
155 | + break | ||
156 | + | ||
157 | + block_x = int(w * (i // ns)) | ||
158 | + block_y = int(h * (i % ns)) | ||
159 | + | ||
160 | + img = img.transpose(1, 2, 0) | ||
161 | + if scale_factor < 1: | ||
162 | + img = cv2.resize(img, (w, h)) | ||
163 | + | ||
164 | + mosaic[block_y:block_y + h, block_x:block_x + w, :] = img | ||
165 | + if len(targets) > 0: | ||
166 | + image_targets = targets[targets[:, 0] == i] | ||
167 | + boxes = xywh2xyxy(image_targets[:, 2:6]).T | ||
168 | + classes = image_targets[:, 1].astype('int') | ||
169 | + labels = image_targets.shape[1] == 6 # labels if no conf column | ||
170 | + conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred) | ||
171 | + | ||
172 | + if boxes.shape[1]: | ||
173 | + if boxes.max() <= 1.01: # if normalized with tolerance 0.01 | ||
174 | + boxes[[0, 2]] *= w # scale to pixels | ||
175 | + boxes[[1, 3]] *= h | ||
176 | + elif scale_factor < 1: # absolute coords need scale if image scales | ||
177 | + boxes *= scale_factor | ||
178 | + boxes[[0, 2]] += block_x | ||
179 | + boxes[[1, 3]] += block_y | ||
180 | + for j, box in enumerate(boxes.T): | ||
181 | + cls = int(classes[j]) | ||
182 | + color = colors(cls) | ||
183 | + cls = names[cls] if names else cls | ||
184 | + if labels or conf[j] > 0.25: # 0.25 conf thresh | ||
185 | + label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j]) | ||
186 | + plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl) | ||
187 | + | ||
188 | + # Draw image filename labels | ||
189 | + if paths: | ||
190 | + label = Path(paths[i]).name[:40] # trim to 40 char | ||
191 | + t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] | ||
192 | + cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf, | ||
193 | + lineType=cv2.LINE_AA) | ||
194 | + | ||
195 | + # Image border | ||
196 | + cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3) | ||
197 | + | ||
198 | + if fname: | ||
199 | + r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size | ||
200 | + mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA) | ||
201 | + # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save | ||
202 | + Image.fromarray(mosaic).save(fname) # PIL save | ||
203 | + return mosaic | ||
204 | + | ||
205 | + | ||
206 | +def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): | ||
207 | + # Plot LR simulating training for full epochs | ||
208 | + optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals | ||
209 | + y = [] | ||
210 | + for _ in range(epochs): | ||
211 | + scheduler.step() | ||
212 | + y.append(optimizer.param_groups[0]['lr']) | ||
213 | + plt.plot(y, '.-', label='LR') | ||
214 | + plt.xlabel('epoch') | ||
215 | + plt.ylabel('LR') | ||
216 | + plt.grid() | ||
217 | + plt.xlim(0, epochs) | ||
218 | + plt.ylim(0) | ||
219 | + plt.savefig(Path(save_dir) / 'LR.png', dpi=200) | ||
220 | + plt.close() | ||
221 | + | ||
222 | + | ||
223 | +def plot_test_txt(): # from utils.plots import *; plot_test() | ||
224 | + # Plot test.txt histograms | ||
225 | + x = np.loadtxt('test.txt', dtype=np.float32) | ||
226 | + box = xyxy2xywh(x[:, :4]) | ||
227 | + cx, cy = box[:, 0], box[:, 1] | ||
228 | + | ||
229 | + fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True) | ||
230 | + ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0) | ||
231 | + ax.set_aspect('equal') | ||
232 | + plt.savefig('hist2d.png', dpi=300) | ||
233 | + | ||
234 | + fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True) | ||
235 | + ax[0].hist(cx, bins=600) | ||
236 | + ax[1].hist(cy, bins=600) | ||
237 | + plt.savefig('hist1d.png', dpi=200) | ||
238 | + | ||
239 | + | ||
240 | +def plot_targets_txt(): # from utils.plots import *; plot_targets_txt() | ||
241 | + # Plot targets.txt histograms | ||
242 | + x = np.loadtxt('targets.txt', dtype=np.float32).T | ||
243 | + s = ['x targets', 'y targets', 'width targets', 'height targets'] | ||
244 | + fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True) | ||
245 | + ax = ax.ravel() | ||
246 | + for i in range(4): | ||
247 | + ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std())) | ||
248 | + ax[i].legend() | ||
249 | + ax[i].set_title(s[i]) | ||
250 | + plt.savefig('targets.jpg', dpi=200) | ||
251 | + | ||
252 | + | ||
253 | +def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt() | ||
254 | + # Plot study.txt generated by test.py | ||
255 | + fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True) | ||
256 | + # ax = ax.ravel() | ||
257 | + | ||
258 | + fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True) | ||
259 | + # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]: | ||
260 | + for f in sorted(Path(path).glob('study*.txt')): | ||
261 | + y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T | ||
262 | + x = np.arange(y.shape[1]) if x is None else np.array(x) | ||
263 | + s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)'] | ||
264 | + # for i in range(7): | ||
265 | + # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) | ||
266 | + # ax[i].set_title(s[i]) | ||
267 | + | ||
268 | + j = y[3].argmax() + 1 | ||
269 | + ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8, | ||
270 | + label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO')) | ||
271 | + | ||
272 | + ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5], | ||
273 | + 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet') | ||
274 | + | ||
275 | + ax2.grid(alpha=0.2) | ||
276 | + ax2.set_yticks(np.arange(20, 60, 5)) | ||
277 | + ax2.set_xlim(0, 57) | ||
278 | + ax2.set_ylim(30, 55) | ||
279 | + ax2.set_xlabel('GPU Speed (ms/img)') | ||
280 | + ax2.set_ylabel('COCO AP val') | ||
281 | + ax2.legend(loc='lower right') | ||
282 | + plt.savefig(str(Path(path).name) + '.png', dpi=300) | ||
283 | + | ||
284 | + | ||
285 | +def plot_labels(labels, names=(), save_dir=Path(''), loggers=None): | ||
286 | + # plot dataset labels | ||
287 | + print('Plotting labels... ') | ||
288 | + c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes | ||
289 | + nc = int(c.max() + 1) # number of classes | ||
290 | + x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height']) | ||
291 | + | ||
292 | + # seaborn correlogram | ||
293 | + sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) | ||
294 | + plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200) | ||
295 | + plt.close() | ||
296 | + | ||
297 | + # matplotlib labels | ||
298 | + matplotlib.use('svg') # faster | ||
299 | + ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() | ||
300 | + y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) | ||
301 | + # [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195 | ||
302 | + ax[0].set_ylabel('instances') | ||
303 | + if 0 < len(names) < 30: | ||
304 | + ax[0].set_xticks(range(len(names))) | ||
305 | + ax[0].set_xticklabels(names, rotation=90, fontsize=10) | ||
306 | + else: | ||
307 | + ax[0].set_xlabel('classes') | ||
308 | + sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) | ||
309 | + sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) | ||
310 | + | ||
311 | + # rectangles | ||
312 | + labels[:, 1:3] = 0.5 # center | ||
313 | + labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000 | ||
314 | + img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255) | ||
315 | + for cls, *box in labels[:1000]: | ||
316 | + ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot | ||
317 | + ax[1].imshow(img) | ||
318 | + ax[1].axis('off') | ||
319 | + | ||
320 | + for a in [0, 1, 2, 3]: | ||
321 | + for s in ['top', 'right', 'left', 'bottom']: | ||
322 | + ax[a].spines[s].set_visible(False) | ||
323 | + | ||
324 | + plt.savefig(save_dir / 'labels.jpg', dpi=200) | ||
325 | + matplotlib.use('Agg') | ||
326 | + plt.close() | ||
327 | + | ||
328 | + # loggers | ||
329 | + for k, v in loggers.items() or {}: | ||
330 | + if k == 'wandb' and v: | ||
331 | + v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False) | ||
332 | + | ||
333 | + | ||
334 | +def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution() | ||
335 | + # Plot hyperparameter evolution results in evolve.txt | ||
336 | + with open(yaml_file) as f: | ||
337 | + hyp = yaml.safe_load(f) | ||
338 | + x = np.loadtxt('evolve.txt', ndmin=2) | ||
339 | + f = fitness(x) | ||
340 | + # weights = (f - f.min()) ** 2 # for weighted results | ||
341 | + plt.figure(figsize=(10, 12), tight_layout=True) | ||
342 | + matplotlib.rc('font', **{'size': 8}) | ||
343 | + for i, (k, v) in enumerate(hyp.items()): | ||
344 | + y = x[:, i + 7] | ||
345 | + # mu = (y * weights).sum() / weights.sum() # best weighted result | ||
346 | + mu = y[f.argmax()] # best single result | ||
347 | + plt.subplot(6, 5, i + 1) | ||
348 | + plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none') | ||
349 | + plt.plot(mu, f.max(), 'k+', markersize=15) | ||
350 | + plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters | ||
351 | + if i % 5 != 0: | ||
352 | + plt.yticks([]) | ||
353 | + print('%15s: %.3g' % (k, mu)) | ||
354 | + plt.savefig('evolve.png', dpi=200) | ||
355 | + print('\nPlot saved as evolve.png') | ||
356 | + | ||
357 | + | ||
358 | +def profile_idetection(start=0, stop=0, labels=(), save_dir=''): | ||
359 | + # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection() | ||
360 | + ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel() | ||
361 | + s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS'] | ||
362 | + files = list(Path(save_dir).glob('frames*.txt')) | ||
363 | + for fi, f in enumerate(files): | ||
364 | + try: | ||
365 | + results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows | ||
366 | + n = results.shape[1] # number of rows | ||
367 | + x = np.arange(start, min(stop, n) if stop else n) | ||
368 | + results = results[:, x] | ||
369 | + t = (results[0] - results[0].min()) # set t0=0s | ||
370 | + results[0] = x | ||
371 | + for i, a in enumerate(ax): | ||
372 | + if i < len(results): | ||
373 | + label = labels[fi] if len(labels) else f.stem.replace('frames_', '') | ||
374 | + a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5) | ||
375 | + a.set_title(s[i]) | ||
376 | + a.set_xlabel('time (s)') | ||
377 | + # if fi == len(files) - 1: | ||
378 | + # a.set_ylim(bottom=0) | ||
379 | + for side in ['top', 'right']: | ||
380 | + a.spines[side].set_visible(False) | ||
381 | + else: | ||
382 | + a.remove() | ||
383 | + except Exception as e: | ||
384 | + print('Warning: Plotting error for %s; %s' % (f, e)) | ||
385 | + | ||
386 | + ax[1].legend() | ||
387 | + plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200) | ||
388 | + | ||
389 | + | ||
390 | +def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay() | ||
391 | + # Plot training 'results*.txt', overlaying train and val losses | ||
392 | + s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends | ||
393 | + t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles | ||
394 | + for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')): | ||
395 | + results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T | ||
396 | + n = results.shape[1] # number of rows | ||
397 | + x = range(start, min(stop, n) if stop else n) | ||
398 | + fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True) | ||
399 | + ax = ax.ravel() | ||
400 | + for i in range(5): | ||
401 | + for j in [i, i + 5]: | ||
402 | + y = results[j, x] | ||
403 | + ax[i].plot(x, y, marker='.', label=s[j]) | ||
404 | + # y_smooth = butter_lowpass_filtfilt(y) | ||
405 | + # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j]) | ||
406 | + | ||
407 | + ax[i].set_title(t[i]) | ||
408 | + ax[i].legend() | ||
409 | + ax[i].set_ylabel(f) if i == 0 else None # add filename | ||
410 | + fig.savefig(f.replace('.txt', '.png'), dpi=200) | ||
411 | + | ||
412 | + | ||
413 | +def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''): | ||
414 | + # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp') | ||
415 | + fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) | ||
416 | + ax = ax.ravel() | ||
417 | + s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall', | ||
418 | + 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95'] | ||
419 | + if bucket: | ||
420 | + # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id] | ||
421 | + files = ['results%g.txt' % x for x in id] | ||
422 | + c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id) | ||
423 | + os.system(c) | ||
424 | + else: | ||
425 | + files = list(Path(save_dir).glob('results*.txt')) | ||
426 | + assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir) | ||
427 | + for fi, f in enumerate(files): | ||
428 | + try: | ||
429 | + results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T | ||
430 | + n = results.shape[1] # number of rows | ||
431 | + x = range(start, min(stop, n) if stop else n) | ||
432 | + for i in range(10): | ||
433 | + y = results[i, x] | ||
434 | + if i in [0, 1, 2, 5, 6, 7]: | ||
435 | + y[y == 0] = np.nan # don't show zero loss values | ||
436 | + # y /= y[0] # normalize | ||
437 | + label = labels[fi] if len(labels) else f.stem | ||
438 | + ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8) | ||
439 | + ax[i].set_title(s[i]) | ||
440 | + # if i in [5, 6, 7]: # share train and val loss y axes | ||
441 | + # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) | ||
442 | + except Exception as e: | ||
443 | + print('Warning: Plotting error for %s; %s' % (f, e)) | ||
444 | + | ||
445 | + ax[1].legend() | ||
446 | + fig.savefig(Path(save_dir) / 'results.png', dpi=200) |
YOLOv5/utils/torch_utils.py
0 → 100644
1 | +# YOLOv5 PyTorch utils | ||
2 | + | ||
3 | +import datetime | ||
4 | +import logging | ||
5 | +import math | ||
6 | +import os | ||
7 | +import platform | ||
8 | +import subprocess | ||
9 | +import time | ||
10 | +from contextlib import contextmanager | ||
11 | +from copy import deepcopy | ||
12 | +from pathlib import Path | ||
13 | + | ||
14 | +import torch | ||
15 | +import torch.backends.cudnn as cudnn | ||
16 | +import torch.nn as nn | ||
17 | +import torch.nn.functional as F | ||
18 | +import torchvision | ||
19 | + | ||
20 | +try: | ||
21 | + import thop # for FLOPS computation | ||
22 | +except ImportError: | ||
23 | + thop = None | ||
24 | +logger = logging.getLogger(__name__) | ||
25 | + | ||
26 | + | ||
27 | +@contextmanager | ||
28 | +def torch_distributed_zero_first(local_rank: int): | ||
29 | + """ | ||
30 | + Decorator to make all processes in distributed training wait for each local_master to do something. | ||
31 | + """ | ||
32 | + if local_rank not in [-1, 0]: | ||
33 | + torch.distributed.barrier() | ||
34 | + yield | ||
35 | + if local_rank == 0: | ||
36 | + torch.distributed.barrier() | ||
37 | + | ||
38 | + | ||
39 | +def init_torch_seeds(seed=0): | ||
40 | + # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html | ||
41 | + torch.manual_seed(seed) | ||
42 | + if seed == 0: # slower, more reproducible | ||
43 | + cudnn.benchmark, cudnn.deterministic = False, True | ||
44 | + else: # faster, less reproducible | ||
45 | + cudnn.benchmark, cudnn.deterministic = True, False | ||
46 | + | ||
47 | + | ||
48 | +def date_modified(path=__file__): | ||
49 | + # return human-readable file modification date, i.e. '2021-3-26' | ||
50 | + t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime) | ||
51 | + return f'{t.year}-{t.month}-{t.day}' | ||
52 | + | ||
53 | + | ||
54 | +def git_describe(path=Path(__file__).parent): # path must be a directory | ||
55 | + # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe | ||
56 | + s = f'git -C {path} describe --tags --long --always' | ||
57 | + try: | ||
58 | + return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1] | ||
59 | + except subprocess.CalledProcessError as e: | ||
60 | + return '' # not a git repository | ||
61 | + | ||
62 | + | ||
63 | +def select_device(device='', batch_size=None): | ||
64 | + # device = 'cpu' or '0' or '0,1,2,3' | ||
65 | + s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string | ||
66 | + cpu = device.lower() == 'cpu' | ||
67 | + if cpu: | ||
68 | + os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False | ||
69 | + elif device: # non-cpu device requested | ||
70 | + os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable | ||
71 | + assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability | ||
72 | + | ||
73 | + cuda = not cpu and torch.cuda.is_available() | ||
74 | + if cuda: | ||
75 | + devices = device.split(',') if device else range(torch.cuda.device_count()) # i.e. 0,1,6,7 | ||
76 | + n = len(devices) # device count | ||
77 | + if n > 1 and batch_size: # check batch_size is divisible by device_count | ||
78 | + assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' | ||
79 | + space = ' ' * len(s) | ||
80 | + for i, d in enumerate(devices): | ||
81 | + p = torch.cuda.get_device_properties(i) | ||
82 | + s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB | ||
83 | + else: | ||
84 | + s += 'CPU\n' | ||
85 | + | ||
86 | + logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe | ||
87 | + return torch.device('cuda:0' if cuda else 'cpu') | ||
88 | + | ||
89 | + | ||
90 | +def time_synchronized(): | ||
91 | + # pytorch-accurate time | ||
92 | + if torch.cuda.is_available(): | ||
93 | + torch.cuda.synchronize() | ||
94 | + return time.time() | ||
95 | + | ||
96 | + | ||
97 | +def profile(x, ops, n=100, device=None): | ||
98 | + # profile a pytorch module or list of modules. Example usage: | ||
99 | + # x = torch.randn(16, 3, 640, 640) # input | ||
100 | + # m1 = lambda x: x * torch.sigmoid(x) | ||
101 | + # m2 = nn.SiLU() | ||
102 | + # profile(x, [m1, m2], n=100) # profile speed over 100 iterations | ||
103 | + | ||
104 | + device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') | ||
105 | + x = x.to(device) | ||
106 | + x.requires_grad = True | ||
107 | + print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') | ||
108 | + print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") | ||
109 | + for m in ops if isinstance(ops, list) else [ops]: | ||
110 | + m = m.to(device) if hasattr(m, 'to') else m # device | ||
111 | + m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type | ||
112 | + dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward | ||
113 | + try: | ||
114 | + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS | ||
115 | + except: | ||
116 | + flops = 0 | ||
117 | + | ||
118 | + for _ in range(n): | ||
119 | + t[0] = time_synchronized() | ||
120 | + y = m(x) | ||
121 | + t[1] = time_synchronized() | ||
122 | + try: | ||
123 | + _ = y.sum().backward() | ||
124 | + t[2] = time_synchronized() | ||
125 | + except: # no backward method | ||
126 | + t[2] = float('nan') | ||
127 | + dtf += (t[1] - t[0]) * 1000 / n # ms per op forward | ||
128 | + dtb += (t[2] - t[1]) * 1000 / n # ms per op backward | ||
129 | + | ||
130 | + s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' | ||
131 | + s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' | ||
132 | + p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters | ||
133 | + print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') | ||
134 | + | ||
135 | + | ||
136 | +def is_parallel(model): | ||
137 | + # Returns True if model is of type DP or DDP | ||
138 | + return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) | ||
139 | + | ||
140 | + | ||
141 | +def de_parallel(model): | ||
142 | + # De-parallelize a model: returns single-GPU model if model is of type DP or DDP | ||
143 | + return model.module if is_parallel(model) else model | ||
144 | + | ||
145 | + | ||
146 | +def intersect_dicts(da, db, exclude=()): | ||
147 | + # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values | ||
148 | + return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} | ||
149 | + | ||
150 | + | ||
151 | +def initialize_weights(model): | ||
152 | + for m in model.modules(): | ||
153 | + t = type(m) | ||
154 | + if t is nn.Conv2d: | ||
155 | + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') | ||
156 | + elif t is nn.BatchNorm2d: | ||
157 | + m.eps = 1e-3 | ||
158 | + m.momentum = 0.03 | ||
159 | + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: | ||
160 | + m.inplace = True | ||
161 | + | ||
162 | + | ||
163 | +def find_modules(model, mclass=nn.Conv2d): | ||
164 | + # Finds layer indices matching module class 'mclass' | ||
165 | + return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] | ||
166 | + | ||
167 | + | ||
168 | +def sparsity(model): | ||
169 | + # Return global model sparsity | ||
170 | + a, b = 0., 0. | ||
171 | + for p in model.parameters(): | ||
172 | + a += p.numel() | ||
173 | + b += (p == 0).sum() | ||
174 | + return b / a | ||
175 | + | ||
176 | + | ||
177 | +def prune(model, amount=0.3): | ||
178 | + # Prune model to requested global sparsity | ||
179 | + import torch.nn.utils.prune as prune | ||
180 | + print('Pruning model... ', end='') | ||
181 | + for name, m in model.named_modules(): | ||
182 | + if isinstance(m, nn.Conv2d): | ||
183 | + prune.l1_unstructured(m, name='weight', amount=amount) # prune | ||
184 | + prune.remove(m, 'weight') # make permanent | ||
185 | + print(' %.3g global sparsity' % sparsity(model)) | ||
186 | + | ||
187 | + | ||
188 | +def fuse_conv_and_bn(conv, bn): | ||
189 | + # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ | ||
190 | + fusedconv = nn.Conv2d(conv.in_channels, | ||
191 | + conv.out_channels, | ||
192 | + kernel_size=conv.kernel_size, | ||
193 | + stride=conv.stride, | ||
194 | + padding=conv.padding, | ||
195 | + groups=conv.groups, | ||
196 | + bias=True).requires_grad_(False).to(conv.weight.device) | ||
197 | + | ||
198 | + # prepare filters | ||
199 | + w_conv = conv.weight.clone().view(conv.out_channels, -1) | ||
200 | + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) | ||
201 | + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) | ||
202 | + | ||
203 | + # prepare spatial bias | ||
204 | + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias | ||
205 | + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) | ||
206 | + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) | ||
207 | + | ||
208 | + return fusedconv | ||
209 | + | ||
210 | + | ||
211 | +def model_info(model, verbose=False, img_size=640): | ||
212 | + # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] | ||
213 | + n_p = sum(x.numel() for x in model.parameters()) # number parameters | ||
214 | + n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients | ||
215 | + if verbose: | ||
216 | + print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) | ||
217 | + for i, (name, p) in enumerate(model.named_parameters()): | ||
218 | + name = name.replace('module_list.', '') | ||
219 | + print('%5g %40s %9s %12g %20s %10.3g %10.3g' % | ||
220 | + (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) | ||
221 | + | ||
222 | + try: # FLOPS | ||
223 | + from thop import profile | ||
224 | + stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 | ||
225 | + img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input | ||
226 | + flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS | ||
227 | + img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float | ||
228 | + fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS | ||
229 | + except (ImportError, Exception): | ||
230 | + fs = '' | ||
231 | + | ||
232 | + logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") | ||
233 | + | ||
234 | + | ||
235 | +def load_classifier(name='resnet101', n=2): | ||
236 | + # Loads a pretrained model reshaped to n-class output | ||
237 | + model = torchvision.models.__dict__[name](pretrained=True) | ||
238 | + | ||
239 | + # ResNet model properties | ||
240 | + # input_size = [3, 224, 224] | ||
241 | + # input_space = 'RGB' | ||
242 | + # input_range = [0, 1] | ||
243 | + # mean = [0.485, 0.456, 0.406] | ||
244 | + # std = [0.229, 0.224, 0.225] | ||
245 | + | ||
246 | + # Reshape output to n classes | ||
247 | + filters = model.fc.weight.shape[1] | ||
248 | + model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) | ||
249 | + model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) | ||
250 | + model.fc.out_features = n | ||
251 | + return model | ||
252 | + | ||
253 | + | ||
254 | +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) | ||
255 | + # scales img(bs,3,y,x) by ratio constrained to gs-multiple | ||
256 | + if ratio == 1.0: | ||
257 | + return img | ||
258 | + else: | ||
259 | + h, w = img.shape[2:] | ||
260 | + s = (int(h * ratio), int(w * ratio)) # new size | ||
261 | + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize | ||
262 | + if not same_shape: # pad/crop img | ||
263 | + h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] | ||
264 | + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean | ||
265 | + | ||
266 | + | ||
267 | +def copy_attr(a, b, include=(), exclude=()): | ||
268 | + # Copy attributes from b to a, options to only include [...] and to exclude [...] | ||
269 | + for k, v in b.__dict__.items(): | ||
270 | + if (len(include) and k not in include) or k.startswith('_') or k in exclude: | ||
271 | + continue | ||
272 | + else: | ||
273 | + setattr(a, k, v) | ||
274 | + | ||
275 | + | ||
276 | +class ModelEMA: | ||
277 | + """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models | ||
278 | + Keep a moving average of everything in the model state_dict (parameters and buffers). | ||
279 | + This is intended to allow functionality like | ||
280 | + https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage | ||
281 | + A smoothed version of the weights is necessary for some training schemes to perform well. | ||
282 | + This class is sensitive where it is initialized in the sequence of model init, | ||
283 | + GPU assignment and distributed training wrappers. | ||
284 | + """ | ||
285 | + | ||
286 | + def __init__(self, model, decay=0.9999, updates=0): | ||
287 | + # Create EMA | ||
288 | + self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA | ||
289 | + # if next(model.parameters()).device.type != 'cpu': | ||
290 | + # self.ema.half() # FP16 EMA | ||
291 | + self.updates = updates # number of EMA updates | ||
292 | + self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) | ||
293 | + for p in self.ema.parameters(): | ||
294 | + p.requires_grad_(False) | ||
295 | + | ||
296 | + def update(self, model): | ||
297 | + # Update EMA parameters | ||
298 | + with torch.no_grad(): | ||
299 | + self.updates += 1 | ||
300 | + d = self.decay(self.updates) | ||
301 | + | ||
302 | + msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict | ||
303 | + for k, v in self.ema.state_dict().items(): | ||
304 | + if v.dtype.is_floating_point: | ||
305 | + v *= d | ||
306 | + v += (1. - d) * msd[k].detach() | ||
307 | + | ||
308 | + def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): | ||
309 | + # Update EMA attributes | ||
310 | + copy_attr(self.ema, model, include, exclude) |
YOLOv5/utils/wandb_logging/__init__.py
0 → 100644
File mode changed
YOLOv5/utils/wandb_logging/log_dataset.py
0 → 100644
1 | +import argparse | ||
2 | + | ||
3 | +import yaml | ||
4 | + | ||
5 | +from wandb_utils import WandbLogger | ||
6 | + | ||
7 | +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' | ||
8 | + | ||
9 | + | ||
10 | +def create_dataset_artifact(opt): | ||
11 | + with open(opt.data) as f: | ||
12 | + data = yaml.safe_load(f) # data dict | ||
13 | + logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation') | ||
14 | + | ||
15 | + | ||
16 | +if __name__ == '__main__': | ||
17 | + parser = argparse.ArgumentParser() | ||
18 | + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') | ||
19 | + parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') | ||
20 | + parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') | ||
21 | + opt = parser.parse_args() | ||
22 | + opt.resume = False # Explicitly disallow resume check for dataset upload job | ||
23 | + | ||
24 | + create_dataset_artifact(opt) |
YOLOv5/utils/wandb_logging/wandb_utils.py
0 → 100644
1 | +"""Utilities and tools for tracking runs with Weights & Biases.""" | ||
2 | +import json | ||
3 | +import sys | ||
4 | +from pathlib import Path | ||
5 | + | ||
6 | +import torch | ||
7 | +import yaml | ||
8 | +from tqdm import tqdm | ||
9 | + | ||
10 | +sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path | ||
11 | +from utils.datasets import LoadImagesAndLabels | ||
12 | +from utils.datasets import img2label_paths | ||
13 | +from utils.general import colorstr, xywh2xyxy, check_dataset, check_file | ||
14 | + | ||
15 | +try: | ||
16 | + import wandb | ||
17 | + from wandb import init, finish | ||
18 | +except ImportError: | ||
19 | + wandb = None | ||
20 | + | ||
21 | +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' | ||
22 | + | ||
23 | + | ||
24 | +def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX): | ||
25 | + return from_string[len(prefix):] | ||
26 | + | ||
27 | + | ||
28 | +def check_wandb_config_file(data_config_file): | ||
29 | + wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path | ||
30 | + if Path(wandb_config).is_file(): | ||
31 | + return wandb_config | ||
32 | + return data_config_file | ||
33 | + | ||
34 | + | ||
35 | +def get_run_info(run_path): | ||
36 | + run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX)) | ||
37 | + run_id = run_path.stem | ||
38 | + project = run_path.parent.stem | ||
39 | + entity = run_path.parent.parent.stem | ||
40 | + model_artifact_name = 'run_' + run_id + '_model' | ||
41 | + return entity, project, run_id, model_artifact_name | ||
42 | + | ||
43 | + | ||
44 | +def check_wandb_resume(opt): | ||
45 | + process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None | ||
46 | + if isinstance(opt.resume, str): | ||
47 | + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): | ||
48 | + if opt.global_rank not in [-1, 0]: # For resuming DDP runs | ||
49 | + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) | ||
50 | + api = wandb.Api() | ||
51 | + artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest') | ||
52 | + modeldir = artifact.download() | ||
53 | + opt.weights = str(Path(modeldir) / "last.pt") | ||
54 | + return True | ||
55 | + return None | ||
56 | + | ||
57 | + | ||
58 | +def process_wandb_config_ddp_mode(opt): | ||
59 | + with open(check_file(opt.data)) as f: | ||
60 | + data_dict = yaml.safe_load(f) # data dict | ||
61 | + train_dir, val_dir = None, None | ||
62 | + if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX): | ||
63 | + api = wandb.Api() | ||
64 | + train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias) | ||
65 | + train_dir = train_artifact.download() | ||
66 | + train_path = Path(train_dir) / 'data/images/' | ||
67 | + data_dict['train'] = str(train_path) | ||
68 | + | ||
69 | + if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX): | ||
70 | + api = wandb.Api() | ||
71 | + val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias) | ||
72 | + val_dir = val_artifact.download() | ||
73 | + val_path = Path(val_dir) / 'data/images/' | ||
74 | + data_dict['val'] = str(val_path) | ||
75 | + if train_dir or val_dir: | ||
76 | + ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml') | ||
77 | + with open(ddp_data_path, 'w') as f: | ||
78 | + yaml.safe_dump(data_dict, f) | ||
79 | + opt.data = ddp_data_path | ||
80 | + | ||
81 | + | ||
82 | +class WandbLogger(): | ||
83 | + """Log training runs, datasets, models, and predictions to Weights & Biases. | ||
84 | + | ||
85 | + This logger sends information to W&B at wandb.ai. By default, this information | ||
86 | + includes hyperparameters, system configuration and metrics, model metrics, | ||
87 | + and basic data metrics and analyses. | ||
88 | + | ||
89 | + By providing additional command line arguments to train.py, datasets, | ||
90 | + models and predictions can also be logged. | ||
91 | + | ||
92 | + For more on how this logger is used, see the Weights & Biases documentation: | ||
93 | + https://docs.wandb.com/guides/integrations/yolov5 | ||
94 | + """ | ||
95 | + def __init__(self, opt, name, run_id, data_dict, job_type='Training'): | ||
96 | + # Pre-training routine -- | ||
97 | + self.job_type = job_type | ||
98 | + self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict | ||
99 | + # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call | ||
100 | + if isinstance(opt.resume, str): # checks resume from artifact | ||
101 | + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): | ||
102 | + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) | ||
103 | + model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name | ||
104 | + assert wandb, 'install wandb to resume wandb runs' | ||
105 | + # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config | ||
106 | + self.wandb_run = wandb.init(id=run_id, project=project, entity=entity, resume='allow') | ||
107 | + opt.resume = model_artifact_name | ||
108 | + elif self.wandb: | ||
109 | + self.wandb_run = wandb.init(config=opt, | ||
110 | + resume="allow", | ||
111 | + project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, | ||
112 | + entity=opt.entity, | ||
113 | + name=name, | ||
114 | + job_type=job_type, | ||
115 | + id=run_id) if not wandb.run else wandb.run | ||
116 | + if self.wandb_run: | ||
117 | + if self.job_type == 'Training': | ||
118 | + if not opt.resume: | ||
119 | + wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict | ||
120 | + # Info useful for resuming from artifacts | ||
121 | + self.wandb_run.config.opt = vars(opt) | ||
122 | + self.wandb_run.config.data_dict = wandb_data_dict | ||
123 | + self.data_dict = self.setup_training(opt, data_dict) | ||
124 | + if self.job_type == 'Dataset Creation': | ||
125 | + self.data_dict = self.check_and_upload_dataset(opt) | ||
126 | + else: | ||
127 | + prefix = colorstr('wandb: ') | ||
128 | + print(f"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)") | ||
129 | + | ||
130 | + def check_and_upload_dataset(self, opt): | ||
131 | + assert wandb, 'Install wandb to upload dataset' | ||
132 | + check_dataset(self.data_dict) | ||
133 | + config_path = self.log_dataset_artifact(check_file(opt.data), | ||
134 | + opt.single_cls, | ||
135 | + 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem) | ||
136 | + print("Created dataset config file ", config_path) | ||
137 | + with open(config_path) as f: | ||
138 | + wandb_data_dict = yaml.safe_load(f) | ||
139 | + return wandb_data_dict | ||
140 | + | ||
141 | + def setup_training(self, opt, data_dict): | ||
142 | + self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants | ||
143 | + self.bbox_interval = opt.bbox_interval | ||
144 | + if isinstance(opt.resume, str): | ||
145 | + modeldir, _ = self.download_model_artifact(opt) | ||
146 | + if modeldir: | ||
147 | + self.weights = Path(modeldir) / "last.pt" | ||
148 | + config = self.wandb_run.config | ||
149 | + opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str( | ||
150 | + self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \ | ||
151 | + config.opt['hyp'] | ||
152 | + data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume | ||
153 | + if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download | ||
154 | + self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'), | ||
155 | + opt.artifact_alias) | ||
156 | + self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'), | ||
157 | + opt.artifact_alias) | ||
158 | + self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None | ||
159 | + if self.train_artifact_path is not None: | ||
160 | + train_path = Path(self.train_artifact_path) / 'data/images/' | ||
161 | + data_dict['train'] = str(train_path) | ||
162 | + if self.val_artifact_path is not None: | ||
163 | + val_path = Path(self.val_artifact_path) / 'data/images/' | ||
164 | + data_dict['val'] = str(val_path) | ||
165 | + self.val_table = self.val_artifact.get("val") | ||
166 | + self.map_val_table_path() | ||
167 | + if self.val_artifact is not None: | ||
168 | + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") | ||
169 | + self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"]) | ||
170 | + if opt.bbox_interval == -1: | ||
171 | + self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1 | ||
172 | + return data_dict | ||
173 | + | ||
174 | + def download_dataset_artifact(self, path, alias): | ||
175 | + if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX): | ||
176 | + artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) | ||
177 | + dataset_artifact = wandb.use_artifact(artifact_path.as_posix()) | ||
178 | + assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" | ||
179 | + datadir = dataset_artifact.download() | ||
180 | + return datadir, dataset_artifact | ||
181 | + return None, None | ||
182 | + | ||
183 | + def download_model_artifact(self, opt): | ||
184 | + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): | ||
185 | + model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest") | ||
186 | + assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' | ||
187 | + modeldir = model_artifact.download() | ||
188 | + epochs_trained = model_artifact.metadata.get('epochs_trained') | ||
189 | + total_epochs = model_artifact.metadata.get('total_epochs') | ||
190 | + is_finished = total_epochs is None | ||
191 | + assert not is_finished, 'training is finished, can only resume incomplete runs.' | ||
192 | + return modeldir, model_artifact | ||
193 | + return None, None | ||
194 | + | ||
195 | + def log_model(self, path, opt, epoch, fitness_score, best_model=False): | ||
196 | + model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={ | ||
197 | + 'original_url': str(path), | ||
198 | + 'epochs_trained': epoch + 1, | ||
199 | + 'save period': opt.save_period, | ||
200 | + 'project': opt.project, | ||
201 | + 'total_epochs': opt.epochs, | ||
202 | + 'fitness_score': fitness_score | ||
203 | + }) | ||
204 | + model_artifact.add_file(str(path / 'last.pt'), name='last.pt') | ||
205 | + wandb.log_artifact(model_artifact, | ||
206 | + aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else '']) | ||
207 | + print("Saving model artifact on epoch ", epoch + 1) | ||
208 | + | ||
209 | + def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False): | ||
210 | + with open(data_file) as f: | ||
211 | + data = yaml.safe_load(f) # data dict | ||
212 | + nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names']) | ||
213 | + names = {k: v for k, v in enumerate(names)} # to index dictionary | ||
214 | + self.train_artifact = self.create_dataset_table(LoadImagesAndLabels( | ||
215 | + data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None | ||
216 | + self.val_artifact = self.create_dataset_table(LoadImagesAndLabels( | ||
217 | + data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None | ||
218 | + if data.get('train'): | ||
219 | + data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train') | ||
220 | + if data.get('val'): | ||
221 | + data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val') | ||
222 | + path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path | ||
223 | + data.pop('download', None) | ||
224 | + with open(path, 'w') as f: | ||
225 | + yaml.safe_dump(data, f) | ||
226 | + | ||
227 | + if self.job_type == 'Training': # builds correct artifact pipeline graph | ||
228 | + self.wandb_run.use_artifact(self.val_artifact) | ||
229 | + self.wandb_run.use_artifact(self.train_artifact) | ||
230 | + self.val_artifact.wait() | ||
231 | + self.val_table = self.val_artifact.get('val') | ||
232 | + self.map_val_table_path() | ||
233 | + else: | ||
234 | + self.wandb_run.log_artifact(self.train_artifact) | ||
235 | + self.wandb_run.log_artifact(self.val_artifact) | ||
236 | + return path | ||
237 | + | ||
238 | + def map_val_table_path(self): | ||
239 | + self.val_table_map = {} | ||
240 | + print("Mapping dataset") | ||
241 | + for i, data in enumerate(tqdm(self.val_table.data)): | ||
242 | + self.val_table_map[data[3]] = data[0] | ||
243 | + | ||
244 | + def create_dataset_table(self, dataset, class_to_id, name='dataset'): | ||
245 | + # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging | ||
246 | + artifact = wandb.Artifact(name=name, type="dataset") | ||
247 | + img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None | ||
248 | + img_files = tqdm(dataset.img_files) if not img_files else img_files | ||
249 | + for img_file in img_files: | ||
250 | + if Path(img_file).is_dir(): | ||
251 | + artifact.add_dir(img_file, name='data/images') | ||
252 | + labels_path = 'labels'.join(dataset.path.rsplit('images', 1)) | ||
253 | + artifact.add_dir(labels_path, name='data/labels') | ||
254 | + else: | ||
255 | + artifact.add_file(img_file, name='data/images/' + Path(img_file).name) | ||
256 | + label_file = Path(img2label_paths([img_file])[0]) | ||
257 | + artifact.add_file(str(label_file), | ||
258 | + name='data/labels/' + label_file.name) if label_file.exists() else None | ||
259 | + table = wandb.Table(columns=["id", "train_image", "Classes", "name"]) | ||
260 | + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) | ||
261 | + for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)): | ||
262 | + box_data, img_classes = [], {} | ||
263 | + for cls, *xywh in labels[:, 1:].tolist(): | ||
264 | + cls = int(cls) | ||
265 | + box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]}, | ||
266 | + "class_id": cls, | ||
267 | + "box_caption": "%s" % (class_to_id[cls])}) | ||
268 | + img_classes[cls] = class_to_id[cls] | ||
269 | + boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space | ||
270 | + table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes), | ||
271 | + Path(paths).name) | ||
272 | + artifact.add(table, name) | ||
273 | + return artifact | ||
274 | + | ||
275 | + def log_training_progress(self, predn, path, names): | ||
276 | + if self.val_table and self.result_table: | ||
277 | + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()]) | ||
278 | + box_data = [] | ||
279 | + total_conf = 0 | ||
280 | + for *xyxy, conf, cls in predn.tolist(): | ||
281 | + if conf >= 0.25: | ||
282 | + box_data.append( | ||
283 | + {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, | ||
284 | + "class_id": int(cls), | ||
285 | + "box_caption": "%s %.3f" % (names[cls], conf), | ||
286 | + "scores": {"class_score": conf}, | ||
287 | + "domain": "pixel"}) | ||
288 | + total_conf = total_conf + conf | ||
289 | + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space | ||
290 | + id = self.val_table_map[Path(path).name] | ||
291 | + self.result_table.add_data(self.current_epoch, | ||
292 | + id, | ||
293 | + wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set), | ||
294 | + total_conf / max(1, len(box_data)) | ||
295 | + ) | ||
296 | + | ||
297 | + def log(self, log_dict): | ||
298 | + if self.wandb_run: | ||
299 | + for key, value in log_dict.items(): | ||
300 | + self.log_dict[key] = value | ||
301 | + | ||
302 | + def end_epoch(self, best_result=False): | ||
303 | + if self.wandb_run: | ||
304 | + wandb.log(self.log_dict) | ||
305 | + self.log_dict = {} | ||
306 | + if self.result_artifact: | ||
307 | + train_results = wandb.JoinedTable(self.val_table, self.result_table, "id") | ||
308 | + self.result_artifact.add(train_results, 'result') | ||
309 | + wandb.log_artifact(self.result_artifact, aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), | ||
310 | + ('best' if best_result else '')]) | ||
311 | + self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"]) | ||
312 | + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") | ||
313 | + | ||
314 | + def finish_run(self): | ||
315 | + if self.wandb_run: | ||
316 | + if self.log_dict: | ||
317 | + wandb.log(self.log_dict) | ||
318 | + wandb.run.finish() |
YOLOv5/weights/download_weights.sh
0 → 100644
1 | +#!/bin/bash | ||
2 | +# Download latest models from https://github.com/ultralytics/yolov5/releases | ||
3 | +# Usage: | ||
4 | +# $ bash weights/download_weights.sh | ||
5 | + | ||
6 | +python - <<EOF | ||
7 | +from utils.google_utils import attempt_download | ||
8 | + | ||
9 | +for x in ['s', 'm', 'l', 'x']: | ||
10 | + attempt_download(f'yolov5{x}.pt') | ||
11 | + | ||
12 | +EOF |
-
Please register or login to post a comment