Spaces:
Runtime error
Runtime error
mnauf
commited on
Commit
Β·
79dbd5a
1
Parent(s):
9570612
first commit
Browse filesThis view is limited to 50 files because it contains too many changes. Β
See raw diff
- .dockerignore +222 -0
- .gitignore +256 -0
- .pre-commit-config.yaml +64 -0
- CONTRIBUTING.md +93 -0
- LICENSE +674 -0
- README.md +0 -13
- app.py +32 -0
- benchmarks.py +169 -0
- classify/predict.py +223 -0
- classify/train.py +331 -0
- classify/val.py +169 -0
- data/Argoverse.yaml +74 -0
- data/GlobalWheat2020.yaml +54 -0
- data/ImageNet.yaml +1022 -0
- data/Objects365.yaml +438 -0
- data/SKU-110K.yaml +53 -0
- data/VOC.yaml +100 -0
- data/VisDrone.yaml +70 -0
- data/coco.yaml +116 -0
- data/coco128-seg.yaml +101 -0
- data/coco128.yaml +7 -0
- data/custom_data.yaml +7 -0
- data/hyps/hyp.Objects365.yaml +34 -0
- data/hyps/hyp.VOC.yaml +40 -0
- data/hyps/hyp.scratch-high.yaml +34 -0
- data/hyps/hyp.scratch-low.yaml +34 -0
- data/hyps/hyp.scratch-med.yaml +34 -0
- data/scripts/download_weights.sh +21 -0
- data/scripts/get_coco.sh +56 -0
- data/scripts/get_coco128.sh +17 -0
- data/scripts/get_imagenet.sh +51 -0
- data/xView.yaml +153 -0
- export.py +617 -0
- hubconf.py +169 -0
- models/__init__.py +0 -0
- models/common.py +851 -0
- models/experimental.py +111 -0
- models/hub/anchors.yaml +59 -0
- models/hub/yolov3-spp.yaml +51 -0
- models/hub/yolov3-tiny.yaml +41 -0
- models/hub/yolov3.yaml +51 -0
- models/hub/yolov5-bifpn.yaml +48 -0
- models/hub/yolov5-fpn.yaml +42 -0
- models/hub/yolov5-p2.yaml +54 -0
- models/hub/yolov5-p34.yaml +41 -0
- models/hub/yolov5-p6.yaml +56 -0
- models/hub/yolov5-p7.yaml +67 -0
- models/hub/yolov5-panet.yaml +48 -0
- models/hub/yolov5l6.yaml +60 -0
- models/hub/yolov5m6.yaml +60 -0
.dockerignore
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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*.csv
|
12 |
+
*.jpg
|
13 |
+
|
14 |
+
# Neural Network weights -----------------------------------------------------------------------------------------------
|
15 |
+
**/*.pt
|
16 |
+
**/*.pth
|
17 |
+
**/*.onnx
|
18 |
+
**/*.engine
|
19 |
+
**/*.mlmodel
|
20 |
+
**/*.torchscript
|
21 |
+
**/*.torchscript.pt
|
22 |
+
**/*.tflite
|
23 |
+
**/*.h5
|
24 |
+
**/*.pb
|
25 |
+
*_saved_model/
|
26 |
+
*_web_model/
|
27 |
+
*_openvino_model/
|
28 |
+
|
29 |
+
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
30 |
+
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
31 |
+
|
32 |
+
|
33 |
+
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
34 |
+
# Byte-compiled / optimized / DLL files
|
35 |
+
__pycache__/
|
36 |
+
*.py[cod]
|
37 |
+
*$py.class
|
38 |
+
|
39 |
+
# C extensions
|
40 |
+
*.so
|
41 |
+
|
42 |
+
# Distribution / packaging
|
43 |
+
.Python
|
44 |
+
env/
|
45 |
+
build/
|
46 |
+
develop-eggs/
|
47 |
+
dist/
|
48 |
+
downloads/
|
49 |
+
eggs/
|
50 |
+
.eggs/
|
51 |
+
lib/
|
52 |
+
lib64/
|
53 |
+
parts/
|
54 |
+
sdist/
|
55 |
+
var/
|
56 |
+
wheels/
|
57 |
+
*.egg-info/
|
58 |
+
wandb/
|
59 |
+
.installed.cfg
|
60 |
+
*.egg
|
61 |
+
|
62 |
+
# PyInstaller
|
63 |
+
# Usually these files are written by a python script from a template
|
64 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
65 |
+
*.manifest
|
66 |
+
*.spec
|
67 |
+
|
68 |
+
# Installer logs
|
69 |
+
pip-log.txt
|
70 |
+
pip-delete-this-directory.txt
|
71 |
+
|
72 |
+
# Unit test / coverage reports
|
73 |
+
htmlcov/
|
74 |
+
.tox/
|
75 |
+
.coverage
|
76 |
+
.coverage.*
|
77 |
+
.cache
|
78 |
+
nosetests.xml
|
79 |
+
coverage.xml
|
80 |
+
*.cover
|
81 |
+
.hypothesis/
|
82 |
+
|
83 |
+
# Translations
|
84 |
+
*.mo
|
85 |
+
*.pot
|
86 |
+
|
87 |
+
# Django stuff:
|
88 |
+
*.log
|
89 |
+
local_settings.py
|
90 |
+
|
91 |
+
# Flask stuff:
|
92 |
+
instance/
|
93 |
+
.webassets-cache
|
94 |
+
|
95 |
+
# Scrapy stuff:
|
96 |
+
.scrapy
|
97 |
+
|
98 |
+
# Sphinx documentation
|
99 |
+
docs/_build/
|
100 |
+
|
101 |
+
# PyBuilder
|
102 |
+
target/
|
103 |
+
|
104 |
+
# Jupyter Notebook
|
105 |
+
.ipynb_checkpoints
|
106 |
+
|
107 |
+
# pyenv
|
108 |
+
.python-version
|
109 |
+
|
110 |
+
# celery beat schedule file
|
111 |
+
celerybeat-schedule
|
112 |
+
|
113 |
+
# SageMath parsed files
|
114 |
+
*.sage.py
|
115 |
+
|
116 |
+
# dotenv
|
117 |
+
.env
|
118 |
+
|
119 |
+
# virtualenv
|
120 |
+
.venv*
|
121 |
+
venv*/
|
122 |
+
ENV*/
|
123 |
+
|
124 |
+
# Spyder project settings
|
125 |
+
.spyderproject
|
126 |
+
.spyproject
|
127 |
+
|
128 |
+
# Rope project settings
|
129 |
+
.ropeproject
|
130 |
+
|
131 |
+
# mkdocs documentation
|
132 |
+
/site
|
133 |
+
|
134 |
+
# mypy
|
135 |
+
.mypy_cache/
|
136 |
+
|
137 |
+
|
138 |
+
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
139 |
+
|
140 |
+
# General
|
141 |
+
.DS_Store
|
142 |
+
.AppleDouble
|
143 |
+
.LSOverride
|
144 |
+
|
145 |
+
# Icon must end with two \r
|
146 |
+
Icon
|
147 |
+
Icon?
|
148 |
+
|
149 |
+
# Thumbnails
|
150 |
+
._*
|
151 |
+
|
152 |
+
# Files that might appear in the root of a volume
|
153 |
+
.DocumentRevisions-V100
|
154 |
+
.fseventsd
|
155 |
+
.Spotlight-V100
|
156 |
+
.TemporaryItems
|
157 |
+
.Trashes
|
158 |
+
.VolumeIcon.icns
|
159 |
+
.com.apple.timemachine.donotpresent
|
160 |
+
|
161 |
+
# Directories potentially created on remote AFP share
|
162 |
+
.AppleDB
|
163 |
+
.AppleDesktop
|
164 |
+
Network Trash Folder
|
165 |
+
Temporary Items
|
166 |
+
.apdisk
|
167 |
+
|
168 |
+
|
169 |
+
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
170 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
171 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
172 |
+
|
173 |
+
# User-specific stuff:
|
174 |
+
.idea/*
|
175 |
+
.idea/**/workspace.xml
|
176 |
+
.idea/**/tasks.xml
|
177 |
+
.idea/dictionaries
|
178 |
+
.html # Bokeh Plots
|
179 |
+
.pg # TensorFlow Frozen Graphs
|
180 |
+
.avi # videos
|
181 |
+
|
182 |
+
# Sensitive or high-churn files:
|
183 |
+
.idea/**/dataSources/
|
184 |
+
.idea/**/dataSources.ids
|
185 |
+
.idea/**/dataSources.local.xml
|
186 |
+
.idea/**/sqlDataSources.xml
|
187 |
+
.idea/**/dynamic.xml
|
188 |
+
.idea/**/uiDesigner.xml
|
189 |
+
|
190 |
+
# Gradle:
|
191 |
+
.idea/**/gradle.xml
|
192 |
+
.idea/**/libraries
|
193 |
+
|
194 |
+
# CMake
|
195 |
+
cmake-build-debug/
|
196 |
+
cmake-build-release/
|
197 |
+
|
198 |
+
# Mongo Explorer plugin:
|
199 |
+
.idea/**/mongoSettings.xml
|
200 |
+
|
201 |
+
## File-based project format:
|
202 |
+
*.iws
|
203 |
+
|
204 |
+
## Plugin-specific files:
|
205 |
+
|
206 |
+
# IntelliJ
|
207 |
+
out/
|
208 |
+
|
209 |
+
# mpeltonen/sbt-idea plugin
|
210 |
+
.idea_modules/
|
211 |
+
|
212 |
+
# JIRA plugin
|
213 |
+
atlassian-ide-plugin.xml
|
214 |
+
|
215 |
+
# Cursive Clojure plugin
|
216 |
+
.idea/replstate.xml
|
217 |
+
|
218 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
219 |
+
com_crashlytics_export_strings.xml
|
220 |
+
crashlytics.properties
|
221 |
+
crashlytics-build.properties
|
222 |
+
fabric.properties
|
.gitignore
ADDED
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
*.cfg
|
23 |
+
!setup.cfg
|
24 |
+
!cfg/yolov3*.cfg
|
25 |
+
|
26 |
+
storage.googleapis.com
|
27 |
+
runs/*
|
28 |
+
data/*
|
29 |
+
data/images/*
|
30 |
+
!data/*.yaml
|
31 |
+
!data/hyps
|
32 |
+
!data/scripts
|
33 |
+
!data/images
|
34 |
+
!data/images/zidane.jpg
|
35 |
+
!data/images/bus.jpg
|
36 |
+
!data/*.sh
|
37 |
+
|
38 |
+
results*.csv
|
39 |
+
|
40 |
+
# Datasets -------------------------------------------------------------------------------------------------------------
|
41 |
+
coco/
|
42 |
+
coco128/
|
43 |
+
VOC/
|
44 |
+
|
45 |
+
# MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
|
46 |
+
*.m~
|
47 |
+
*.mat
|
48 |
+
!targets*.mat
|
49 |
+
|
50 |
+
# Neural Network weights -----------------------------------------------------------------------------------------------
|
51 |
+
*.weights
|
52 |
+
*.pt
|
53 |
+
*.pb
|
54 |
+
*.onnx
|
55 |
+
*.engine
|
56 |
+
*.mlmodel
|
57 |
+
*.torchscript
|
58 |
+
*.tflite
|
59 |
+
*.h5
|
60 |
+
*_saved_model/
|
61 |
+
*_web_model/
|
62 |
+
*_openvino_model/
|
63 |
+
darknet53.conv.74
|
64 |
+
yolov3-tiny.conv.15
|
65 |
+
|
66 |
+
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
67 |
+
# Byte-compiled / optimized / DLL files
|
68 |
+
__pycache__/
|
69 |
+
*.py[cod]
|
70 |
+
*$py.class
|
71 |
+
|
72 |
+
# C extensions
|
73 |
+
*.so
|
74 |
+
|
75 |
+
# Distribution / packaging
|
76 |
+
.Python
|
77 |
+
env/
|
78 |
+
build/
|
79 |
+
develop-eggs/
|
80 |
+
dist/
|
81 |
+
downloads/
|
82 |
+
eggs/
|
83 |
+
.eggs/
|
84 |
+
lib/
|
85 |
+
lib64/
|
86 |
+
parts/
|
87 |
+
sdist/
|
88 |
+
var/
|
89 |
+
wheels/
|
90 |
+
*.egg-info/
|
91 |
+
/wandb/
|
92 |
+
.installed.cfg
|
93 |
+
*.egg
|
94 |
+
|
95 |
+
|
96 |
+
# PyInstaller
|
97 |
+
# Usually these files are written by a python script from a template
|
98 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
99 |
+
*.manifest
|
100 |
+
*.spec
|
101 |
+
|
102 |
+
# Installer logs
|
103 |
+
pip-log.txt
|
104 |
+
pip-delete-this-directory.txt
|
105 |
+
|
106 |
+
# Unit test / coverage reports
|
107 |
+
htmlcov/
|
108 |
+
.tox/
|
109 |
+
.coverage
|
110 |
+
.coverage.*
|
111 |
+
.cache
|
112 |
+
nosetests.xml
|
113 |
+
coverage.xml
|
114 |
+
*.cover
|
115 |
+
.hypothesis/
|
116 |
+
|
117 |
+
# Translations
|
118 |
+
*.mo
|
119 |
+
*.pot
|
120 |
+
|
121 |
+
# Django stuff:
|
122 |
+
*.log
|
123 |
+
local_settings.py
|
124 |
+
|
125 |
+
# Flask stuff:
|
126 |
+
instance/
|
127 |
+
.webassets-cache
|
128 |
+
|
129 |
+
# Scrapy stuff:
|
130 |
+
.scrapy
|
131 |
+
|
132 |
+
# Sphinx documentation
|
133 |
+
docs/_build/
|
134 |
+
|
135 |
+
# PyBuilder
|
136 |
+
target/
|
137 |
+
|
138 |
+
# Jupyter Notebook
|
139 |
+
.ipynb_checkpoints
|
140 |
+
|
141 |
+
# pyenv
|
142 |
+
.python-version
|
143 |
+
|
144 |
+
# celery beat schedule file
|
145 |
+
celerybeat-schedule
|
146 |
+
|
147 |
+
# SageMath parsed files
|
148 |
+
*.sage.py
|
149 |
+
|
150 |
+
# dotenv
|
151 |
+
.env
|
152 |
+
|
153 |
+
# virtualenv
|
154 |
+
.venv*
|
155 |
+
venv*/
|
156 |
+
ENV*/
|
157 |
+
|
158 |
+
# Spyder project settings
|
159 |
+
.spyderproject
|
160 |
+
.spyproject
|
161 |
+
|
162 |
+
# Rope project settings
|
163 |
+
.ropeproject
|
164 |
+
|
165 |
+
# mkdocs documentation
|
166 |
+
/site
|
167 |
+
|
168 |
+
# mypy
|
169 |
+
.mypy_cache/
|
170 |
+
|
171 |
+
|
172 |
+
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
173 |
+
|
174 |
+
# General
|
175 |
+
.DS_Store
|
176 |
+
.AppleDouble
|
177 |
+
.LSOverride
|
178 |
+
|
179 |
+
# Icon must end with two \r
|
180 |
+
Icon
|
181 |
+
Icon?
|
182 |
+
|
183 |
+
# Thumbnails
|
184 |
+
._*
|
185 |
+
|
186 |
+
# Files that might appear in the root of a volume
|
187 |
+
.DocumentRevisions-V100
|
188 |
+
.fseventsd
|
189 |
+
.Spotlight-V100
|
190 |
+
.TemporaryItems
|
191 |
+
.Trashes
|
192 |
+
.VolumeIcon.icns
|
193 |
+
.com.apple.timemachine.donotpresent
|
194 |
+
|
195 |
+
# Directories potentially created on remote AFP share
|
196 |
+
.AppleDB
|
197 |
+
.AppleDesktop
|
198 |
+
Network Trash Folder
|
199 |
+
Temporary Items
|
200 |
+
.apdisk
|
201 |
+
|
202 |
+
|
203 |
+
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
204 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
205 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
206 |
+
|
207 |
+
# User-specific stuff:
|
208 |
+
.idea/*
|
209 |
+
.idea/**/workspace.xml
|
210 |
+
.idea/**/tasks.xml
|
211 |
+
.idea/dictionaries
|
212 |
+
.html # Bokeh Plots
|
213 |
+
.pg # TensorFlow Frozen Graphs
|
214 |
+
.avi # videos
|
215 |
+
|
216 |
+
# Sensitive or high-churn files:
|
217 |
+
.idea/**/dataSources/
|
218 |
+
.idea/**/dataSources.ids
|
219 |
+
.idea/**/dataSources.local.xml
|
220 |
+
.idea/**/sqlDataSources.xml
|
221 |
+
.idea/**/dynamic.xml
|
222 |
+
.idea/**/uiDesigner.xml
|
223 |
+
|
224 |
+
# Gradle:
|
225 |
+
.idea/**/gradle.xml
|
226 |
+
.idea/**/libraries
|
227 |
+
|
228 |
+
# CMake
|
229 |
+
cmake-build-debug/
|
230 |
+
cmake-build-release/
|
231 |
+
|
232 |
+
# Mongo Explorer plugin:
|
233 |
+
.idea/**/mongoSettings.xml
|
234 |
+
|
235 |
+
## File-based project format:
|
236 |
+
*.iws
|
237 |
+
|
238 |
+
## Plugin-specific files:
|
239 |
+
|
240 |
+
# IntelliJ
|
241 |
+
out/
|
242 |
+
|
243 |
+
# mpeltonen/sbt-idea plugin
|
244 |
+
.idea_modules/
|
245 |
+
|
246 |
+
# JIRA plugin
|
247 |
+
atlassian-ide-plugin.xml
|
248 |
+
|
249 |
+
# Cursive Clojure plugin
|
250 |
+
.idea/replstate.xml
|
251 |
+
|
252 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
253 |
+
com_crashlytics_export_strings.xml
|
254 |
+
crashlytics.properties
|
255 |
+
crashlytics-build.properties
|
256 |
+
fabric.properties
|
.pre-commit-config.yaml
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Define hooks for code formations
|
2 |
+
# Will be applied on any updated commit files if a user has installed and linked commit hook
|
3 |
+
|
4 |
+
default_language_version:
|
5 |
+
python: python3.8
|
6 |
+
|
7 |
+
# Define bot property if installed via https://github.com/marketplace/pre-commit-ci
|
8 |
+
ci:
|
9 |
+
autofix_prs: true
|
10 |
+
autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
|
11 |
+
autoupdate_schedule: monthly
|
12 |
+
# submodules: true
|
13 |
+
|
14 |
+
repos:
|
15 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
16 |
+
rev: v4.3.0
|
17 |
+
hooks:
|
18 |
+
# - id: end-of-file-fixer
|
19 |
+
- id: trailing-whitespace
|
20 |
+
- id: check-case-conflict
|
21 |
+
- id: check-yaml
|
22 |
+
- id: check-toml
|
23 |
+
- id: pretty-format-json
|
24 |
+
- id: check-docstring-first
|
25 |
+
|
26 |
+
- repo: https://github.com/asottile/pyupgrade
|
27 |
+
rev: v2.38.2
|
28 |
+
hooks:
|
29 |
+
- id: pyupgrade
|
30 |
+
name: Upgrade code
|
31 |
+
args: [ --py37-plus ]
|
32 |
+
|
33 |
+
- repo: https://github.com/PyCQA/isort
|
34 |
+
rev: 5.10.1
|
35 |
+
hooks:
|
36 |
+
- id: isort
|
37 |
+
name: Sort imports
|
38 |
+
|
39 |
+
- repo: https://github.com/pre-commit/mirrors-yapf
|
40 |
+
rev: v0.32.0
|
41 |
+
hooks:
|
42 |
+
- id: yapf
|
43 |
+
name: YAPF formatting
|
44 |
+
|
45 |
+
- repo: https://github.com/executablebooks/mdformat
|
46 |
+
rev: 0.7.16
|
47 |
+
hooks:
|
48 |
+
- id: mdformat
|
49 |
+
name: MD formatting
|
50 |
+
additional_dependencies:
|
51 |
+
- mdformat-gfm
|
52 |
+
- mdformat-black
|
53 |
+
exclude: "README.md|README_cn.md"
|
54 |
+
|
55 |
+
- repo: https://github.com/asottile/yesqa
|
56 |
+
rev: v1.4.0
|
57 |
+
hooks:
|
58 |
+
- id: yesqa
|
59 |
+
|
60 |
+
- repo: https://github.com/PyCQA/flake8
|
61 |
+
rev: 5.0.4
|
62 |
+
hooks:
|
63 |
+
- id: flake8
|
64 |
+
name: PEP8
|
CONTRIBUTING.md
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Contributing to YOLOv5 π
|
2 |
+
|
3 |
+
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
|
4 |
+
|
5 |
+
- Reporting a bug
|
6 |
+
- Discussing the current state of the code
|
7 |
+
- Submitting a fix
|
8 |
+
- Proposing a new feature
|
9 |
+
- Becoming a maintainer
|
10 |
+
|
11 |
+
YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
|
12 |
+
helping push the frontiers of what's possible in AI π!
|
13 |
+
|
14 |
+
## Submitting a Pull Request (PR) π οΈ
|
15 |
+
|
16 |
+
Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
|
17 |
+
|
18 |
+
### 1. Select File to Update
|
19 |
+
|
20 |
+
Select `requirements.txt` to update by clicking on it in GitHub.
|
21 |
+
|
22 |
+
<p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
|
23 |
+
|
24 |
+
### 2. Click 'Edit this file'
|
25 |
+
|
26 |
+
Button is in top-right corner.
|
27 |
+
|
28 |
+
<p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
|
29 |
+
|
30 |
+
### 3. Make Changes
|
31 |
+
|
32 |
+
Change `matplotlib` version from `3.2.2` to `3.3`.
|
33 |
+
|
34 |
+
<p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
|
35 |
+
|
36 |
+
### 4. Preview Changes and Submit PR
|
37 |
+
|
38 |
+
Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
|
39 |
+
for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
|
40 |
+
changes** button. All done, your PR is now submitted to YOLOv5 for review and approval π!
|
41 |
+
|
42 |
+
<p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
|
43 |
+
|
44 |
+
### PR recommendations
|
45 |
+
|
46 |
+
To allow your work to be integrated as seamlessly as possible, we advise you to:
|
47 |
+
|
48 |
+
- β
Verify your PR is **up-to-date** with `ultralytics/yolov5` `master` branch. If your PR is behind you can update
|
49 |
+
your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
|
50 |
+
|
51 |
+
<p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 15" src="https://user-images.githubusercontent.com/26833433/187295893-50ed9f44-b2c9-4138-a614-de69bd1753d7.png"></p>
|
52 |
+
|
53 |
+
- β
Verify all YOLOv5 Continuous Integration (CI) **checks are passing**.
|
54 |
+
|
55 |
+
<p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 03" src="https://user-images.githubusercontent.com/26833433/187296922-545c5498-f64a-4d8c-8300-5fa764360da6.png"></p>
|
56 |
+
|
57 |
+
- β
Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
|
58 |
+
but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ β Bruce Lee
|
59 |
+
|
60 |
+
## Submitting a Bug Report π
|
61 |
+
|
62 |
+
If you spot a problem with YOLOv5 please submit a Bug Report!
|
63 |
+
|
64 |
+
For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few
|
65 |
+
short guidelines below to help users provide what we need in order to get started.
|
66 |
+
|
67 |
+
When asking a question, people will be better able to provide help if you provide **code** that they can easily
|
68 |
+
understand and use to **reproduce** the problem. This is referred to by community members as creating
|
69 |
+
a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
|
70 |
+
the problem should be:
|
71 |
+
|
72 |
+
- β
**Minimal** β Use as little code as possible that still produces the same problem
|
73 |
+
- β
**Complete** β Provide **all** parts someone else needs to reproduce your problem in the question itself
|
74 |
+
- β
**Reproducible** β Test the code you're about to provide to make sure it reproduces the problem
|
75 |
+
|
76 |
+
In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
|
77 |
+
should be:
|
78 |
+
|
79 |
+
- β
**Current** β Verify that your code is up-to-date with current
|
80 |
+
GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
|
81 |
+
copy to ensure your problem has not already been resolved by previous commits.
|
82 |
+
- β
**Unmodified** β Your problem must be reproducible without any modifications to the codebase in this
|
83 |
+
repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code β οΈ.
|
84 |
+
|
85 |
+
If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the π
|
86 |
+
**Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing
|
87 |
+
a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
|
88 |
+
understand and diagnose your problem.
|
89 |
+
|
90 |
+
## License
|
91 |
+
|
92 |
+
By contributing, you agree that your contributions will be licensed under
|
93 |
+
the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/)
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<http://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Detect Bees
|
3 |
-
emoji: π
|
4 |
-
colorFrom: green
|
5 |
-
colorTo: red
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.34.0
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: openrail
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from sample_solution import main as detect_bees
|
3 |
+
|
4 |
+
badges = """
|
5 |
+
<div style="display: flex">
|
6 |
+
<span style="margin-right: 5px">
|
7 |
+
<a href="https://www.linkedin.com/in/mnauf/" target="_blank"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/LinkedIn_Logo.svg/2560px-LinkedIn_Logo.svg.png" alt="Linkedin" width=100 height=auto> </a>
|
8 |
+
</span>
|
9 |
+
<span style="margin-right: 5px">
|
10 |
+
<a href="https://github.com/mnauf/Bees-ML-Challenge" target="_blank"> <img src="https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white" alt="Github"> </a>
|
11 |
+
</span>
|
12 |
+
<span style="margin-right: 5px">
|
13 |
+
<a href="https://twitter.com/MNaufil" target="_blank"> <img src="https://img.shields.io/badge/Twitter-%231DA1F2.svg?style=for-the-badge&logo=Twitter&logoColor=white" alt="Twitter"> </a>
|
14 |
+
</span>
|
15 |
+
</div>
|
16 |
+
"""
|
17 |
+
|
18 |
+
description="""Detect bees in the image"""
|
19 |
+
with gr.Blocks() as block:
|
20 |
+
# gr.Markdown("""![Imgur](https://i.imgur.com/iPZlUa8.png)""")
|
21 |
+
gr.HTML("<img src=https://i.imgur.com/mG2WSlK.png width=auto height=200>")
|
22 |
+
gr.Markdown(badges)
|
23 |
+
gr.Markdown(description)
|
24 |
+
with gr.Row():
|
25 |
+
file_input = gr.Image()
|
26 |
+
file_output = gr.Image()
|
27 |
+
|
28 |
+
btn = gr.Button(value="Count the number of Bees")
|
29 |
+
btn.click(detect_bees, inputs=[file_input], outputs=[file_output], queue=True)
|
30 |
+
|
31 |
+
block.queue(concurrency_count=5).launch(server_name="localhost", share=True)
|
32 |
+
# block.queue().launch()
|
benchmarks.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Run YOLOv5 benchmarks on all supported export formats
|
4 |
+
|
5 |
+
Format | `export.py --include` | Model
|
6 |
+
--- | --- | ---
|
7 |
+
PyTorch | - | yolov5s.pt
|
8 |
+
TorchScript | `torchscript` | yolov5s.torchscript
|
9 |
+
ONNX | `onnx` | yolov5s.onnx
|
10 |
+
OpenVINO | `openvino` | yolov5s_openvino_model/
|
11 |
+
TensorRT | `engine` | yolov5s.engine
|
12 |
+
CoreML | `coreml` | yolov5s.mlmodel
|
13 |
+
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
|
14 |
+
TensorFlow GraphDef | `pb` | yolov5s.pb
|
15 |
+
TensorFlow Lite | `tflite` | yolov5s.tflite
|
16 |
+
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
|
17 |
+
TensorFlow.js | `tfjs` | yolov5s_web_model/
|
18 |
+
|
19 |
+
Requirements:
|
20 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
|
21 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
|
22 |
+
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
23 |
+
|
24 |
+
Usage:
|
25 |
+
$ python utils/benchmarks.py --weights yolov5s.pt --img 640
|
26 |
+
"""
|
27 |
+
|
28 |
+
import argparse
|
29 |
+
import platform
|
30 |
+
import sys
|
31 |
+
import time
|
32 |
+
from pathlib import Path
|
33 |
+
|
34 |
+
import pandas as pd
|
35 |
+
|
36 |
+
FILE = Path(__file__).resolve()
|
37 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
38 |
+
if str(ROOT) not in sys.path:
|
39 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
40 |
+
# ROOT = ROOT.relative_to(Path.cwd()) # relative
|
41 |
+
|
42 |
+
import export
|
43 |
+
from models.experimental import attempt_load
|
44 |
+
from models.yolo import SegmentationModel
|
45 |
+
from segment.val import run as val_seg
|
46 |
+
from utils import notebook_init
|
47 |
+
from utils.general import LOGGER, check_yaml, file_size, print_args
|
48 |
+
from utils.torch_utils import select_device
|
49 |
+
from val import run as val_det
|
50 |
+
|
51 |
+
|
52 |
+
def run(
|
53 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
54 |
+
imgsz=640, # inference size (pixels)
|
55 |
+
batch_size=1, # batch size
|
56 |
+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
57 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
58 |
+
half=False, # use FP16 half-precision inference
|
59 |
+
test=False, # test exports only
|
60 |
+
pt_only=False, # test PyTorch only
|
61 |
+
hard_fail=False, # throw error on benchmark failure
|
62 |
+
):
|
63 |
+
y, t = [], time.time()
|
64 |
+
device = select_device(device)
|
65 |
+
model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
|
66 |
+
for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
|
67 |
+
try:
|
68 |
+
assert i not in (9, 10), 'inference not supported' # Edge TPU and TF.js are unsupported
|
69 |
+
assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13' # CoreML
|
70 |
+
if 'cpu' in device.type:
|
71 |
+
assert cpu, 'inference not supported on CPU'
|
72 |
+
if 'cuda' in device.type:
|
73 |
+
assert gpu, 'inference not supported on GPU'
|
74 |
+
|
75 |
+
# Export
|
76 |
+
if f == '-':
|
77 |
+
w = weights # PyTorch format
|
78 |
+
else:
|
79 |
+
w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others
|
80 |
+
assert suffix in str(w), 'export failed'
|
81 |
+
|
82 |
+
# Validate
|
83 |
+
if model_type == SegmentationModel:
|
84 |
+
result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task='speed', half=half)
|
85 |
+
metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
|
86 |
+
else: # DetectionModel:
|
87 |
+
result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task='speed', half=half)
|
88 |
+
metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
|
89 |
+
speed = result[2][1] # times (preprocess, inference, postprocess)
|
90 |
+
y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
|
91 |
+
except Exception as e:
|
92 |
+
if hard_fail:
|
93 |
+
assert type(e) is AssertionError, f'Benchmark --hard-fail for {name}: {e}'
|
94 |
+
LOGGER.warning(f'WARNING β οΈ Benchmark failure for {name}: {e}')
|
95 |
+
y.append([name, None, None, None]) # mAP, t_inference
|
96 |
+
if pt_only and i == 0:
|
97 |
+
break # break after PyTorch
|
98 |
+
|
99 |
+
# Print results
|
100 |
+
LOGGER.info('\n')
|
101 |
+
parse_opt()
|
102 |
+
notebook_init() # print system info
|
103 |
+
c = ['Format', 'Size (MB)', 'mAP50-95', 'Inference time (ms)'] if map else ['Format', 'Export', '', '']
|
104 |
+
py = pd.DataFrame(y, columns=c)
|
105 |
+
LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
|
106 |
+
LOGGER.info(str(py if map else py.iloc[:, :2]))
|
107 |
+
if hard_fail and isinstance(hard_fail, str):
|
108 |
+
metrics = py['mAP50-95'].array # values to compare to floor
|
109 |
+
floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
|
110 |
+
assert all(x > floor for x in metrics if pd.notna(x)), f'HARD FAIL: mAP50-95 < floor {floor}'
|
111 |
+
return py
|
112 |
+
|
113 |
+
|
114 |
+
def test(
|
115 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
116 |
+
imgsz=640, # inference size (pixels)
|
117 |
+
batch_size=1, # batch size
|
118 |
+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
119 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
120 |
+
half=False, # use FP16 half-precision inference
|
121 |
+
test=False, # test exports only
|
122 |
+
pt_only=False, # test PyTorch only
|
123 |
+
hard_fail=False, # throw error on benchmark failure
|
124 |
+
):
|
125 |
+
y, t = [], time.time()
|
126 |
+
device = select_device(device)
|
127 |
+
for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
|
128 |
+
try:
|
129 |
+
w = weights if f == '-' else \
|
130 |
+
export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights
|
131 |
+
assert suffix in str(w), 'export failed'
|
132 |
+
y.append([name, True])
|
133 |
+
except Exception:
|
134 |
+
y.append([name, False]) # mAP, t_inference
|
135 |
+
|
136 |
+
# Print results
|
137 |
+
LOGGER.info('\n')
|
138 |
+
parse_opt()
|
139 |
+
notebook_init() # print system info
|
140 |
+
py = pd.DataFrame(y, columns=['Format', 'Export'])
|
141 |
+
LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)')
|
142 |
+
LOGGER.info(str(py))
|
143 |
+
return py
|
144 |
+
|
145 |
+
|
146 |
+
def parse_opt():
|
147 |
+
parser = argparse.ArgumentParser()
|
148 |
+
parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
|
149 |
+
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
|
150 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
151 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
152 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
153 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
154 |
+
parser.add_argument('--test', action='store_true', help='test exports only')
|
155 |
+
parser.add_argument('--pt-only', action='store_true', help='test PyTorch only')
|
156 |
+
parser.add_argument('--hard-fail', nargs='?', const=True, default=False, help='Exception on error or < min metric')
|
157 |
+
opt = parser.parse_args()
|
158 |
+
opt.data = check_yaml(opt.data) # check YAML
|
159 |
+
print_args(vars(opt))
|
160 |
+
return opt
|
161 |
+
|
162 |
+
|
163 |
+
def main(opt):
|
164 |
+
test(**vars(opt)) if opt.test else run(**vars(opt))
|
165 |
+
|
166 |
+
|
167 |
+
if __name__ == "__main__":
|
168 |
+
opt = parse_opt()
|
169 |
+
main(opt)
|
classify/predict.py
ADDED
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
|
4 |
+
|
5 |
+
Usage - sources:
|
6 |
+
$ python classify/predict.py --weights yolov5s-cls.pt --source 0 # webcam
|
7 |
+
img.jpg # image
|
8 |
+
vid.mp4 # video
|
9 |
+
path/ # directory
|
10 |
+
'path/*.jpg' # glob
|
11 |
+
'https://youtu.be/Zgi9g1ksQHc' # YouTube
|
12 |
+
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
13 |
+
|
14 |
+
Usage - formats:
|
15 |
+
$ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
|
16 |
+
yolov5s-cls.torchscript # TorchScript
|
17 |
+
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
18 |
+
yolov5s-cls_openvino_model # OpenVINO
|
19 |
+
yolov5s-cls.engine # TensorRT
|
20 |
+
yolov5s-cls.mlmodel # CoreML (macOS-only)
|
21 |
+
yolov5s-cls_saved_model # TensorFlow SavedModel
|
22 |
+
yolov5s-cls.pb # TensorFlow GraphDef
|
23 |
+
yolov5s-cls.tflite # TensorFlow Lite
|
24 |
+
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
|
25 |
+
yolov5s-cls_paddle_model # PaddlePaddle
|
26 |
+
"""
|
27 |
+
|
28 |
+
import argparse
|
29 |
+
import os
|
30 |
+
import platform
|
31 |
+
import sys
|
32 |
+
from pathlib import Path
|
33 |
+
|
34 |
+
import torch
|
35 |
+
import torch.nn.functional as F
|
36 |
+
|
37 |
+
FILE = Path(__file__).resolve()
|
38 |
+
ROOT = FILE.parents[1] # YOLOv5 root directory
|
39 |
+
if str(ROOT) not in sys.path:
|
40 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
41 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
42 |
+
|
43 |
+
from models.common import DetectMultiBackend
|
44 |
+
from utils.augmentations import classify_transforms
|
45 |
+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
|
46 |
+
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
|
47 |
+
increment_path, print_args, strip_optimizer)
|
48 |
+
from utils.plots import Annotator
|
49 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
50 |
+
|
51 |
+
|
52 |
+
@smart_inference_mode()
|
53 |
+
def run(
|
54 |
+
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
|
55 |
+
source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)
|
56 |
+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
57 |
+
imgsz=(224, 224), # inference size (height, width)
|
58 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
59 |
+
view_img=False, # show results
|
60 |
+
save_txt=False, # save results to *.txt
|
61 |
+
nosave=False, # do not save images/videos
|
62 |
+
augment=False, # augmented inference
|
63 |
+
visualize=False, # visualize features
|
64 |
+
update=False, # update all models
|
65 |
+
project=ROOT / 'runs/predict-cls', # save results to project/name
|
66 |
+
name='exp', # save results to project/name
|
67 |
+
exist_ok=False, # existing project/name ok, do not increment
|
68 |
+
half=False, # use FP16 half-precision inference
|
69 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
70 |
+
vid_stride=1, # video frame-rate stride
|
71 |
+
):
|
72 |
+
source = str(source)
|
73 |
+
save_img = not nosave and not source.endswith('.txt') # save inference images
|
74 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
75 |
+
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
76 |
+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
77 |
+
screenshot = source.lower().startswith('screen')
|
78 |
+
if is_url and is_file:
|
79 |
+
source = check_file(source) # download
|
80 |
+
|
81 |
+
# Directories
|
82 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
83 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
84 |
+
|
85 |
+
# Load model
|
86 |
+
device = select_device(device)
|
87 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
88 |
+
stride, names, pt = model.stride, model.names, model.pt
|
89 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
90 |
+
|
91 |
+
# Dataloader
|
92 |
+
bs = 1 # batch_size
|
93 |
+
if webcam:
|
94 |
+
view_img = check_imshow(warn=True)
|
95 |
+
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
|
96 |
+
bs = len(dataset)
|
97 |
+
elif screenshot:
|
98 |
+
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
|
99 |
+
else:
|
100 |
+
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
|
101 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
102 |
+
|
103 |
+
# Run inference
|
104 |
+
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
|
105 |
+
seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
|
106 |
+
for path, im, im0s, vid_cap, s in dataset:
|
107 |
+
with dt[0]:
|
108 |
+
im = torch.Tensor(im).to(model.device)
|
109 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
110 |
+
if len(im.shape) == 3:
|
111 |
+
im = im[None] # expand for batch dim
|
112 |
+
|
113 |
+
# Inference
|
114 |
+
with dt[1]:
|
115 |
+
results = model(im)
|
116 |
+
|
117 |
+
# Post-process
|
118 |
+
with dt[2]:
|
119 |
+
pred = F.softmax(results, dim=1) # probabilities
|
120 |
+
|
121 |
+
# Process predictions
|
122 |
+
for i, prob in enumerate(pred): # per image
|
123 |
+
seen += 1
|
124 |
+
if webcam: # batch_size >= 1
|
125 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
126 |
+
s += f'{i}: '
|
127 |
+
else:
|
128 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
|
129 |
+
|
130 |
+
p = Path(p) # to Path
|
131 |
+
save_path = str(save_dir / p.name) # im.jpg
|
132 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
|
133 |
+
|
134 |
+
s += '%gx%g ' % im.shape[2:] # print string
|
135 |
+
annotator = Annotator(im0, example=str(names), pil=True)
|
136 |
+
|
137 |
+
# Print results
|
138 |
+
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
|
139 |
+
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
|
140 |
+
|
141 |
+
# Write results
|
142 |
+
text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)
|
143 |
+
if save_img or view_img: # Add bbox to image
|
144 |
+
annotator.text((32, 32), text, txt_color=(255, 255, 255))
|
145 |
+
if save_txt: # Write to file
|
146 |
+
with open(f'{txt_path}.txt', 'a') as f:
|
147 |
+
f.write(text + '\n')
|
148 |
+
|
149 |
+
# Stream results
|
150 |
+
im0 = annotator.result()
|
151 |
+
if view_img:
|
152 |
+
if platform.system() == 'Linux' and p not in windows:
|
153 |
+
windows.append(p)
|
154 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
155 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
156 |
+
cv2.imshow(str(p), im0)
|
157 |
+
cv2.waitKey(1) # 1 millisecond
|
158 |
+
|
159 |
+
# Save results (image with detections)
|
160 |
+
if save_img:
|
161 |
+
if dataset.mode == 'image':
|
162 |
+
cv2.imwrite(save_path, im0)
|
163 |
+
else: # 'video' or 'stream'
|
164 |
+
if vid_path[i] != save_path: # new video
|
165 |
+
vid_path[i] = save_path
|
166 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
167 |
+
vid_writer[i].release() # release previous video writer
|
168 |
+
if vid_cap: # video
|
169 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
170 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
171 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
172 |
+
else: # stream
|
173 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
174 |
+
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
|
175 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
176 |
+
vid_writer[i].write(im0)
|
177 |
+
|
178 |
+
# Print time (inference-only)
|
179 |
+
LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms")
|
180 |
+
|
181 |
+
# Print results
|
182 |
+
t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
|
183 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
|
184 |
+
if save_txt or save_img:
|
185 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
186 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
187 |
+
if update:
|
188 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
189 |
+
|
190 |
+
|
191 |
+
def parse_opt():
|
192 |
+
parser = argparse.ArgumentParser()
|
193 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')
|
194 |
+
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
|
195 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
|
196 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')
|
197 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
198 |
+
parser.add_argument('--view-img', action='store_true', help='show results')
|
199 |
+
parser.add_argument('--save-txt', action='store_false', help='save results to *.txt')
|
200 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
201 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
202 |
+
parser.add_argument('--visualize', action='store_true', help='visualize features')
|
203 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
204 |
+
parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')
|
205 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
206 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
207 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
208 |
+
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
209 |
+
parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
|
210 |
+
opt = parser.parse_args()
|
211 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
212 |
+
print_args(vars(opt))
|
213 |
+
return opt
|
214 |
+
|
215 |
+
|
216 |
+
def main(opt):
|
217 |
+
check_requirements(exclude=('tensorboard', 'thop'))
|
218 |
+
run(**vars(opt))
|
219 |
+
|
220 |
+
|
221 |
+
if __name__ == "__main__":
|
222 |
+
opt = parse_opt()
|
223 |
+
main(opt)
|
classify/train.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Train a YOLOv5 classifier model on a classification dataset
|
4 |
+
|
5 |
+
Usage - Single-GPU training:
|
6 |
+
$ python classify/train.py --model yolov5s-cls.pt --data imagenette160 --epochs 5 --img 224
|
7 |
+
|
8 |
+
Usage - Multi-GPU DDP training:
|
9 |
+
$ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
|
10 |
+
|
11 |
+
Datasets: --data mnist, fashion-mnist, cifar10, cifar100, imagenette, imagewoof, imagenet, or 'path/to/data'
|
12 |
+
YOLOv5-cls models: --model yolov5n-cls.pt, yolov5s-cls.pt, yolov5m-cls.pt, yolov5l-cls.pt, yolov5x-cls.pt
|
13 |
+
Torchvision models: --model resnet50, efficientnet_b0, etc. See https://pytorch.org/vision/stable/models.html
|
14 |
+
"""
|
15 |
+
|
16 |
+
import argparse
|
17 |
+
import os
|
18 |
+
import subprocess
|
19 |
+
import sys
|
20 |
+
import time
|
21 |
+
from copy import deepcopy
|
22 |
+
from datetime import datetime
|
23 |
+
from pathlib import Path
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.distributed as dist
|
27 |
+
import torch.hub as hub
|
28 |
+
import torch.optim.lr_scheduler as lr_scheduler
|
29 |
+
import torchvision
|
30 |
+
from torch.cuda import amp
|
31 |
+
from tqdm import tqdm
|
32 |
+
|
33 |
+
FILE = Path(__file__).resolve()
|
34 |
+
ROOT = FILE.parents[1] # YOLOv5 root directory
|
35 |
+
if str(ROOT) not in sys.path:
|
36 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
37 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
38 |
+
|
39 |
+
from classify import val as validate
|
40 |
+
from models.experimental import attempt_load
|
41 |
+
from models.yolo import ClassificationModel, DetectionModel
|
42 |
+
from utils.dataloaders import create_classification_dataloader
|
43 |
+
from utils.general import (DATASETS_DIR, LOGGER, WorkingDirectory, check_git_status, check_requirements, colorstr,
|
44 |
+
download, increment_path, init_seeds, print_args, yaml_save)
|
45 |
+
from utils.loggers import GenericLogger
|
46 |
+
from utils.plots import imshow_cls
|
47 |
+
from utils.torch_utils import (ModelEMA, model_info, reshape_classifier_output, select_device, smart_DDP,
|
48 |
+
smart_optimizer, smartCrossEntropyLoss, torch_distributed_zero_first)
|
49 |
+
|
50 |
+
LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
|
51 |
+
RANK = int(os.getenv('RANK', -1))
|
52 |
+
WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
|
53 |
+
|
54 |
+
|
55 |
+
def train(opt, device):
|
56 |
+
init_seeds(opt.seed + 1 + RANK, deterministic=True)
|
57 |
+
save_dir, data, bs, epochs, nw, imgsz, pretrained = \
|
58 |
+
opt.save_dir, Path(opt.data), opt.batch_size, opt.epochs, min(os.cpu_count() - 1, opt.workers), \
|
59 |
+
opt.imgsz, str(opt.pretrained).lower() == 'true'
|
60 |
+
cuda = device.type != 'cpu'
|
61 |
+
|
62 |
+
# Directories
|
63 |
+
wdir = save_dir / 'weights'
|
64 |
+
wdir.mkdir(parents=True, exist_ok=True) # make dir
|
65 |
+
last, best = wdir / 'last.pt', wdir / 'best.pt'
|
66 |
+
|
67 |
+
# Save run settings
|
68 |
+
yaml_save(save_dir / 'opt.yaml', vars(opt))
|
69 |
+
|
70 |
+
# Logger
|
71 |
+
logger = GenericLogger(opt=opt, console_logger=LOGGER) if RANK in {-1, 0} else None
|
72 |
+
|
73 |
+
# Download Dataset
|
74 |
+
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
|
75 |
+
data_dir = data if data.is_dir() else (DATASETS_DIR / data)
|
76 |
+
if not data_dir.is_dir():
|
77 |
+
LOGGER.info(f'\nDataset not found β οΈ, missing path {data_dir}, attempting download...')
|
78 |
+
t = time.time()
|
79 |
+
if str(data) == 'imagenet':
|
80 |
+
subprocess.run(f"bash {ROOT / 'data/scripts/get_imagenet.sh'}", shell=True, check=True)
|
81 |
+
else:
|
82 |
+
url = f'https://github.com/ultralytics/yolov5/releases/download/v1.0/{data}.zip'
|
83 |
+
download(url, dir=data_dir.parent)
|
84 |
+
s = f"Dataset download success β
({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\n"
|
85 |
+
LOGGER.info(s)
|
86 |
+
|
87 |
+
# Dataloaders
|
88 |
+
nc = len([x for x in (data_dir / 'train').glob('*') if x.is_dir()]) # number of classes
|
89 |
+
trainloader = create_classification_dataloader(path=data_dir / 'train',
|
90 |
+
imgsz=imgsz,
|
91 |
+
batch_size=bs // WORLD_SIZE,
|
92 |
+
augment=True,
|
93 |
+
cache=opt.cache,
|
94 |
+
rank=LOCAL_RANK,
|
95 |
+
workers=nw)
|
96 |
+
|
97 |
+
test_dir = data_dir / 'test' if (data_dir / 'test').exists() else data_dir / 'val' # data/test or data/val
|
98 |
+
if RANK in {-1, 0}:
|
99 |
+
testloader = create_classification_dataloader(path=test_dir,
|
100 |
+
imgsz=imgsz,
|
101 |
+
batch_size=bs // WORLD_SIZE * 2,
|
102 |
+
augment=False,
|
103 |
+
cache=opt.cache,
|
104 |
+
rank=-1,
|
105 |
+
workers=nw)
|
106 |
+
|
107 |
+
# Model
|
108 |
+
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
|
109 |
+
if Path(opt.model).is_file() or opt.model.endswith('.pt'):
|
110 |
+
model = attempt_load(opt.model, device='cpu', fuse=False)
|
111 |
+
elif opt.model in torchvision.models.__dict__: # TorchVision models i.e. resnet50, efficientnet_b0
|
112 |
+
model = torchvision.models.__dict__[opt.model](weights='IMAGENET1K_V1' if pretrained else None)
|
113 |
+
else:
|
114 |
+
m = hub.list('ultralytics/yolov5') # + hub.list('pytorch/vision') # models
|
115 |
+
raise ModuleNotFoundError(f'--model {opt.model} not found. Available models are: \n' + '\n'.join(m))
|
116 |
+
if isinstance(model, DetectionModel):
|
117 |
+
LOGGER.warning("WARNING β οΈ pass YOLOv5 classifier model with '-cls' suffix, i.e. '--model yolov5s-cls.pt'")
|
118 |
+
model = ClassificationModel(model=model, nc=nc, cutoff=opt.cutoff or 10) # convert to classification model
|
119 |
+
reshape_classifier_output(model, nc) # update class count
|
120 |
+
for m in model.modules():
|
121 |
+
if not pretrained and hasattr(m, 'reset_parameters'):
|
122 |
+
m.reset_parameters()
|
123 |
+
if isinstance(m, torch.nn.Dropout) and opt.dropout is not None:
|
124 |
+
m.p = opt.dropout # set dropout
|
125 |
+
for p in model.parameters():
|
126 |
+
p.requires_grad = True # for training
|
127 |
+
model = model.to(device)
|
128 |
+
|
129 |
+
# Info
|
130 |
+
if RANK in {-1, 0}:
|
131 |
+
model.names = trainloader.dataset.classes # attach class names
|
132 |
+
model.transforms = testloader.dataset.torch_transforms # attach inference transforms
|
133 |
+
model_info(model)
|
134 |
+
if opt.verbose:
|
135 |
+
LOGGER.info(model)
|
136 |
+
images, labels = next(iter(trainloader))
|
137 |
+
file = imshow_cls(images[:25], labels[:25], names=model.names, f=save_dir / 'train_images.jpg')
|
138 |
+
logger.log_images(file, name='Train Examples')
|
139 |
+
logger.log_graph(model, imgsz) # log model
|
140 |
+
|
141 |
+
# Optimizer
|
142 |
+
optimizer = smart_optimizer(model, opt.optimizer, opt.lr0, momentum=0.9, decay=opt.decay)
|
143 |
+
|
144 |
+
# Scheduler
|
145 |
+
lrf = 0.01 # final lr (fraction of lr0)
|
146 |
+
# lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - lrf) + lrf # cosine
|
147 |
+
lf = lambda x: (1 - x / epochs) * (1 - lrf) + lrf # linear
|
148 |
+
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
|
149 |
+
# scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=lr0, total_steps=epochs, pct_start=0.1,
|
150 |
+
# final_div_factor=1 / 25 / lrf)
|
151 |
+
|
152 |
+
# EMA
|
153 |
+
ema = ModelEMA(model) if RANK in {-1, 0} else None
|
154 |
+
|
155 |
+
# DDP mode
|
156 |
+
if cuda and RANK != -1:
|
157 |
+
model = smart_DDP(model)
|
158 |
+
|
159 |
+
# Train
|
160 |
+
t0 = time.time()
|
161 |
+
criterion = smartCrossEntropyLoss(label_smoothing=opt.label_smoothing) # loss function
|
162 |
+
best_fitness = 0.0
|
163 |
+
scaler = amp.GradScaler(enabled=cuda)
|
164 |
+
val = test_dir.stem # 'val' or 'test'
|
165 |
+
LOGGER.info(f'Image sizes {imgsz} train, {imgsz} test\n'
|
166 |
+
f'Using {nw * WORLD_SIZE} dataloader workers\n'
|
167 |
+
f"Logging results to {colorstr('bold', save_dir)}\n"
|
168 |
+
f'Starting {opt.model} training on {data} dataset with {nc} classes for {epochs} epochs...\n\n'
|
169 |
+
f"{'Epoch':>10}{'GPU_mem':>10}{'train_loss':>12}{f'{val}_loss':>12}{'top1_acc':>12}{'top5_acc':>12}")
|
170 |
+
for epoch in range(epochs): # loop over the dataset multiple times
|
171 |
+
tloss, vloss, fitness = 0.0, 0.0, 0.0 # train loss, val loss, fitness
|
172 |
+
model.train()
|
173 |
+
if RANK != -1:
|
174 |
+
trainloader.sampler.set_epoch(epoch)
|
175 |
+
pbar = enumerate(trainloader)
|
176 |
+
if RANK in {-1, 0}:
|
177 |
+
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}')
|
178 |
+
for i, (images, labels) in pbar: # progress bar
|
179 |
+
images, labels = images.to(device, non_blocking=True), labels.to(device)
|
180 |
+
|
181 |
+
# Forward
|
182 |
+
with amp.autocast(enabled=cuda): # stability issues when enabled
|
183 |
+
loss = criterion(model(images), labels)
|
184 |
+
|
185 |
+
# Backward
|
186 |
+
scaler.scale(loss).backward()
|
187 |
+
|
188 |
+
# Optimize
|
189 |
+
scaler.unscale_(optimizer) # unscale gradients
|
190 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
|
191 |
+
scaler.step(optimizer)
|
192 |
+
scaler.update()
|
193 |
+
optimizer.zero_grad()
|
194 |
+
if ema:
|
195 |
+
ema.update(model)
|
196 |
+
|
197 |
+
if RANK in {-1, 0}:
|
198 |
+
# Print
|
199 |
+
tloss = (tloss * i + loss.item()) / (i + 1) # update mean losses
|
200 |
+
mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
|
201 |
+
pbar.desc = f"{f'{epoch + 1}/{epochs}':>10}{mem:>10}{tloss:>12.3g}" + ' ' * 36
|
202 |
+
|
203 |
+
# Test
|
204 |
+
if i == len(pbar) - 1: # last batch
|
205 |
+
top1, top5, vloss = validate.run(model=ema.ema,
|
206 |
+
dataloader=testloader,
|
207 |
+
criterion=criterion,
|
208 |
+
pbar=pbar) # test accuracy, loss
|
209 |
+
fitness = top1 # define fitness as top1 accuracy
|
210 |
+
|
211 |
+
# Scheduler
|
212 |
+
scheduler.step()
|
213 |
+
|
214 |
+
# Log metrics
|
215 |
+
if RANK in {-1, 0}:
|
216 |
+
# Best fitness
|
217 |
+
if fitness > best_fitness:
|
218 |
+
best_fitness = fitness
|
219 |
+
|
220 |
+
# Log
|
221 |
+
metrics = {
|
222 |
+
"train/loss": tloss,
|
223 |
+
f"{val}/loss": vloss,
|
224 |
+
"metrics/accuracy_top1": top1,
|
225 |
+
"metrics/accuracy_top5": top5,
|
226 |
+
"lr/0": optimizer.param_groups[0]['lr']} # learning rate
|
227 |
+
logger.log_metrics(metrics, epoch)
|
228 |
+
|
229 |
+
# Save model
|
230 |
+
final_epoch = epoch + 1 == epochs
|
231 |
+
if (not opt.nosave) or final_epoch:
|
232 |
+
ckpt = {
|
233 |
+
'epoch': epoch,
|
234 |
+
'best_fitness': best_fitness,
|
235 |
+
'model': deepcopy(ema.ema).half(), # deepcopy(de_parallel(model)).half(),
|
236 |
+
'ema': None, # deepcopy(ema.ema).half(),
|
237 |
+
'updates': ema.updates,
|
238 |
+
'optimizer': None, # optimizer.state_dict(),
|
239 |
+
'opt': vars(opt),
|
240 |
+
'date': datetime.now().isoformat()}
|
241 |
+
|
242 |
+
# Save last, best and delete
|
243 |
+
torch.save(ckpt, last)
|
244 |
+
if best_fitness == fitness:
|
245 |
+
torch.save(ckpt, best)
|
246 |
+
del ckpt
|
247 |
+
|
248 |
+
# Train complete
|
249 |
+
if RANK in {-1, 0} and final_epoch:
|
250 |
+
LOGGER.info(f'\nTraining complete ({(time.time() - t0) / 3600:.3f} hours)'
|
251 |
+
f"\nResults saved to {colorstr('bold', save_dir)}"
|
252 |
+
f"\nPredict: python classify/predict.py --weights {best} --source im.jpg"
|
253 |
+
f"\nValidate: python classify/val.py --weights {best} --data {data_dir}"
|
254 |
+
f"\nExport: python export.py --weights {best} --include onnx"
|
255 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{best}')"
|
256 |
+
f"\nVisualize: https://netron.app\n")
|
257 |
+
|
258 |
+
# Plot examples
|
259 |
+
images, labels = (x[:25] for x in next(iter(testloader))) # first 25 images and labels
|
260 |
+
pred = torch.max(ema.ema(images.to(device)), 1)[1]
|
261 |
+
file = imshow_cls(images, labels, pred, model.names, verbose=False, f=save_dir / 'test_images.jpg')
|
262 |
+
|
263 |
+
# Log results
|
264 |
+
meta = {"epochs": epochs, "top1_acc": best_fitness, "date": datetime.now().isoformat()}
|
265 |
+
logger.log_images(file, name='Test Examples (true-predicted)', epoch=epoch)
|
266 |
+
logger.log_model(best, epochs, metadata=meta)
|
267 |
+
|
268 |
+
|
269 |
+
def parse_opt(known=False):
|
270 |
+
parser = argparse.ArgumentParser()
|
271 |
+
parser.add_argument('--model', type=str, default='yolov5s-cls.pt', help='initial weights path')
|
272 |
+
parser.add_argument('--data', type=str, default='imagenette160', help='cifar10, cifar100, mnist, imagenet, ...')
|
273 |
+
parser.add_argument('--epochs', type=int, default=10, help='total training epochs')
|
274 |
+
parser.add_argument('--batch-size', type=int, default=64, help='total batch size for all GPUs')
|
275 |
+
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=224, help='train, val image size (pixels)')
|
276 |
+
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
|
277 |
+
parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
|
278 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
279 |
+
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
|
280 |
+
parser.add_argument('--project', default=ROOT / 'runs/train-cls', help='save to project/name')
|
281 |
+
parser.add_argument('--name', default='exp', help='save to project/name')
|
282 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
283 |
+
parser.add_argument('--pretrained', nargs='?', const=True, default=True, help='start from i.e. --pretrained False')
|
284 |
+
parser.add_argument('--optimizer', choices=['SGD', 'Adam', 'AdamW', 'RMSProp'], default='Adam', help='optimizer')
|
285 |
+
parser.add_argument('--lr0', type=float, default=0.001, help='initial learning rate')
|
286 |
+
parser.add_argument('--decay', type=float, default=5e-5, help='weight decay')
|
287 |
+
parser.add_argument('--label-smoothing', type=float, default=0.1, help='Label smoothing epsilon')
|
288 |
+
parser.add_argument('--cutoff', type=int, default=None, help='Model layer cutoff index for Classify() head')
|
289 |
+
parser.add_argument('--dropout', type=float, default=None, help='Dropout (fraction)')
|
290 |
+
parser.add_argument('--verbose', action='store_true', help='Verbose mode')
|
291 |
+
parser.add_argument('--seed', type=int, default=0, help='Global training seed')
|
292 |
+
parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
|
293 |
+
return parser.parse_known_args()[0] if known else parser.parse_args()
|
294 |
+
|
295 |
+
|
296 |
+
def main(opt):
|
297 |
+
# Checks
|
298 |
+
if RANK in {-1, 0}:
|
299 |
+
print_args(vars(opt))
|
300 |
+
check_git_status()
|
301 |
+
check_requirements()
|
302 |
+
|
303 |
+
# DDP mode
|
304 |
+
device = select_device(opt.device, batch_size=opt.batch_size)
|
305 |
+
if LOCAL_RANK != -1:
|
306 |
+
assert opt.batch_size != -1, 'AutoBatch is coming soon for classification, please pass a valid --batch-size'
|
307 |
+
assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
|
308 |
+
assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
|
309 |
+
torch.cuda.set_device(LOCAL_RANK)
|
310 |
+
device = torch.device('cuda', LOCAL_RANK)
|
311 |
+
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
|
312 |
+
|
313 |
+
# Parameters
|
314 |
+
opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
|
315 |
+
|
316 |
+
# Train
|
317 |
+
train(opt, device)
|
318 |
+
|
319 |
+
|
320 |
+
def run(**kwargs):
|
321 |
+
# Usage: from yolov5 import classify; classify.train.run(data=mnist, imgsz=320, model='yolov5m')
|
322 |
+
opt = parse_opt(True)
|
323 |
+
for k, v in kwargs.items():
|
324 |
+
setattr(opt, k, v)
|
325 |
+
main(opt)
|
326 |
+
return opt
|
327 |
+
|
328 |
+
|
329 |
+
if __name__ == "__main__":
|
330 |
+
opt = parse_opt()
|
331 |
+
main(opt)
|
classify/val.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Validate a trained YOLOv5 classification model on a classification dataset
|
4 |
+
|
5 |
+
Usage:
|
6 |
+
$ bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
|
7 |
+
$ python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate ImageNet
|
8 |
+
|
9 |
+
Usage - formats:
|
10 |
+
$ python classify/val.py --weights yolov5s-cls.pt # PyTorch
|
11 |
+
yolov5s-cls.torchscript # TorchScript
|
12 |
+
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
13 |
+
yolov5s-cls_openvino_model # OpenVINO
|
14 |
+
yolov5s-cls.engine # TensorRT
|
15 |
+
yolov5s-cls.mlmodel # CoreML (macOS-only)
|
16 |
+
yolov5s-cls_saved_model # TensorFlow SavedModel
|
17 |
+
yolov5s-cls.pb # TensorFlow GraphDef
|
18 |
+
yolov5s-cls.tflite # TensorFlow Lite
|
19 |
+
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
|
20 |
+
yolov5s-cls_paddle_model # PaddlePaddle
|
21 |
+
"""
|
22 |
+
|
23 |
+
import argparse
|
24 |
+
import os
|
25 |
+
import sys
|
26 |
+
from pathlib import Path
|
27 |
+
|
28 |
+
import torch
|
29 |
+
from tqdm import tqdm
|
30 |
+
|
31 |
+
FILE = Path(__file__).resolve()
|
32 |
+
ROOT = FILE.parents[1] # YOLOv5 root directory
|
33 |
+
if str(ROOT) not in sys.path:
|
34 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
35 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
36 |
+
|
37 |
+
from models.common import DetectMultiBackend
|
38 |
+
from utils.dataloaders import create_classification_dataloader
|
39 |
+
from utils.general import LOGGER, Profile, check_img_size, check_requirements, colorstr, increment_path, print_args
|
40 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
41 |
+
|
42 |
+
|
43 |
+
@smart_inference_mode()
|
44 |
+
def run(
|
45 |
+
data=ROOT / '../datasets/mnist', # dataset dir
|
46 |
+
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
|
47 |
+
batch_size=128, # batch size
|
48 |
+
imgsz=224, # inference size (pixels)
|
49 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
50 |
+
workers=8, # max dataloader workers (per RANK in DDP mode)
|
51 |
+
verbose=False, # verbose output
|
52 |
+
project=ROOT / 'runs/val-cls', # save to project/name
|
53 |
+
name='exp', # save to project/name
|
54 |
+
exist_ok=False, # existing project/name ok, do not increment
|
55 |
+
half=False, # use FP16 half-precision inference
|
56 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
57 |
+
model=None,
|
58 |
+
dataloader=None,
|
59 |
+
criterion=None,
|
60 |
+
pbar=None,
|
61 |
+
):
|
62 |
+
# Initialize/load model and set device
|
63 |
+
training = model is not None
|
64 |
+
if training: # called by train.py
|
65 |
+
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
|
66 |
+
half &= device.type != 'cpu' # half precision only supported on CUDA
|
67 |
+
model.half() if half else model.float()
|
68 |
+
else: # called directly
|
69 |
+
device = select_device(device, batch_size=batch_size)
|
70 |
+
|
71 |
+
# Directories
|
72 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
73 |
+
save_dir.mkdir(parents=True, exist_ok=True) # make dir
|
74 |
+
|
75 |
+
# Load model
|
76 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, fp16=half)
|
77 |
+
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
|
78 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
79 |
+
half = model.fp16 # FP16 supported on limited backends with CUDA
|
80 |
+
if engine:
|
81 |
+
batch_size = model.batch_size
|
82 |
+
else:
|
83 |
+
device = model.device
|
84 |
+
if not (pt or jit):
|
85 |
+
batch_size = 1 # export.py models default to batch-size 1
|
86 |
+
LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
|
87 |
+
|
88 |
+
# Dataloader
|
89 |
+
data = Path(data)
|
90 |
+
test_dir = data / 'test' if (data / 'test').exists() else data / 'val' # data/test or data/val
|
91 |
+
dataloader = create_classification_dataloader(path=test_dir,
|
92 |
+
imgsz=imgsz,
|
93 |
+
batch_size=batch_size,
|
94 |
+
augment=False,
|
95 |
+
rank=-1,
|
96 |
+
workers=workers)
|
97 |
+
|
98 |
+
model.eval()
|
99 |
+
pred, targets, loss, dt = [], [], 0, (Profile(), Profile(), Profile())
|
100 |
+
n = len(dataloader) # number of batches
|
101 |
+
action = 'validating' if dataloader.dataset.root.stem == 'val' else 'testing'
|
102 |
+
desc = f"{pbar.desc[:-36]}{action:>36}" if pbar else f"{action}"
|
103 |
+
bar = tqdm(dataloader, desc, n, not training, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}', position=0)
|
104 |
+
with torch.cuda.amp.autocast(enabled=device.type != 'cpu'):
|
105 |
+
for images, labels in bar:
|
106 |
+
with dt[0]:
|
107 |
+
images, labels = images.to(device, non_blocking=True), labels.to(device)
|
108 |
+
|
109 |
+
with dt[1]:
|
110 |
+
y = model(images)
|
111 |
+
|
112 |
+
with dt[2]:
|
113 |
+
pred.append(y.argsort(1, descending=True)[:, :5])
|
114 |
+
targets.append(labels)
|
115 |
+
if criterion:
|
116 |
+
loss += criterion(y, labels)
|
117 |
+
|
118 |
+
loss /= n
|
119 |
+
pred, targets = torch.cat(pred), torch.cat(targets)
|
120 |
+
correct = (targets[:, None] == pred).float()
|
121 |
+
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
|
122 |
+
top1, top5 = acc.mean(0).tolist()
|
123 |
+
|
124 |
+
if pbar:
|
125 |
+
pbar.desc = f"{pbar.desc[:-36]}{loss:>12.3g}{top1:>12.3g}{top5:>12.3g}"
|
126 |
+
if verbose: # all classes
|
127 |
+
LOGGER.info(f"{'Class':>24}{'Images':>12}{'top1_acc':>12}{'top5_acc':>12}")
|
128 |
+
LOGGER.info(f"{'all':>24}{targets.shape[0]:>12}{top1:>12.3g}{top5:>12.3g}")
|
129 |
+
for i, c in model.names.items():
|
130 |
+
aci = acc[targets == i]
|
131 |
+
top1i, top5i = aci.mean(0).tolist()
|
132 |
+
LOGGER.info(f"{c:>24}{aci.shape[0]:>12}{top1i:>12.3g}{top5i:>12.3g}")
|
133 |
+
|
134 |
+
# Print results
|
135 |
+
t = tuple(x.t / len(dataloader.dataset.samples) * 1E3 for x in dt) # speeds per image
|
136 |
+
shape = (1, 3, imgsz, imgsz)
|
137 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms post-process per image at shape {shape}' % t)
|
138 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
|
139 |
+
|
140 |
+
return top1, top5, loss
|
141 |
+
|
142 |
+
|
143 |
+
def parse_opt():
|
144 |
+
parser = argparse.ArgumentParser()
|
145 |
+
parser.add_argument('--data', type=str, default=ROOT / '../datasets/mnist', help='dataset path')
|
146 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model.pt path(s)')
|
147 |
+
parser.add_argument('--batch-size', type=int, default=128, help='batch size')
|
148 |
+
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=224, help='inference size (pixels)')
|
149 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
150 |
+
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
|
151 |
+
parser.add_argument('--verbose', nargs='?', const=True, default=True, help='verbose output')
|
152 |
+
parser.add_argument('--project', default=ROOT / 'runs/val-cls', help='save to project/name')
|
153 |
+
parser.add_argument('--name', default='exp', help='save to project/name')
|
154 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
155 |
+
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
156 |
+
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
157 |
+
opt = parser.parse_args()
|
158 |
+
print_args(vars(opt))
|
159 |
+
return opt
|
160 |
+
|
161 |
+
|
162 |
+
def main(opt):
|
163 |
+
check_requirements(exclude=('tensorboard', 'thop'))
|
164 |
+
run(**vars(opt))
|
165 |
+
|
166 |
+
|
167 |
+
if __name__ == "__main__":
|
168 |
+
opt = parse_opt()
|
169 |
+
main(opt)
|
data/Argoverse.yaml
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI
|
3 |
+
# Example usage: python train.py --data Argoverse.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ Argoverse β downloads here (31.3 GB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/Argoverse # dataset root dir
|
12 |
+
train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
|
13 |
+
val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
|
14 |
+
test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: person
|
19 |
+
1: bicycle
|
20 |
+
2: car
|
21 |
+
3: motorcycle
|
22 |
+
4: bus
|
23 |
+
5: truck
|
24 |
+
6: traffic_light
|
25 |
+
7: stop_sign
|
26 |
+
|
27 |
+
|
28 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
29 |
+
download: |
|
30 |
+
import json
|
31 |
+
|
32 |
+
from tqdm import tqdm
|
33 |
+
from utils.general import download, Path
|
34 |
+
|
35 |
+
|
36 |
+
def argoverse2yolo(set):
|
37 |
+
labels = {}
|
38 |
+
a = json.load(open(set, "rb"))
|
39 |
+
for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
|
40 |
+
img_id = annot['image_id']
|
41 |
+
img_name = a['images'][img_id]['name']
|
42 |
+
img_label_name = f'{img_name[:-3]}txt'
|
43 |
+
|
44 |
+
cls = annot['category_id'] # instance class id
|
45 |
+
x_center, y_center, width, height = annot['bbox']
|
46 |
+
x_center = (x_center + width / 2) / 1920.0 # offset and scale
|
47 |
+
y_center = (y_center + height / 2) / 1200.0 # offset and scale
|
48 |
+
width /= 1920.0 # scale
|
49 |
+
height /= 1200.0 # scale
|
50 |
+
|
51 |
+
img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
|
52 |
+
if not img_dir.exists():
|
53 |
+
img_dir.mkdir(parents=True, exist_ok=True)
|
54 |
+
|
55 |
+
k = str(img_dir / img_label_name)
|
56 |
+
if k not in labels:
|
57 |
+
labels[k] = []
|
58 |
+
labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
|
59 |
+
|
60 |
+
for k in labels:
|
61 |
+
with open(k, "w") as f:
|
62 |
+
f.writelines(labels[k])
|
63 |
+
|
64 |
+
|
65 |
+
# Download
|
66 |
+
dir = Path(yaml['path']) # dataset root dir
|
67 |
+
urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
|
68 |
+
download(urls, dir=dir, delete=False)
|
69 |
+
|
70 |
+
# Convert
|
71 |
+
annotations_dir = 'Argoverse-HD/annotations/'
|
72 |
+
(dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
|
73 |
+
for d in "train.json", "val.json":
|
74 |
+
argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
|
data/GlobalWheat2020.yaml
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan
|
3 |
+
# Example usage: python train.py --data GlobalWheat2020.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ GlobalWheat2020 β downloads here (7.0 GB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/GlobalWheat2020 # dataset root dir
|
12 |
+
train: # train images (relative to 'path') 3422 images
|
13 |
+
- images/arvalis_1
|
14 |
+
- images/arvalis_2
|
15 |
+
- images/arvalis_3
|
16 |
+
- images/ethz_1
|
17 |
+
- images/rres_1
|
18 |
+
- images/inrae_1
|
19 |
+
- images/usask_1
|
20 |
+
val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
|
21 |
+
- images/ethz_1
|
22 |
+
test: # test images (optional) 1276 images
|
23 |
+
- images/utokyo_1
|
24 |
+
- images/utokyo_2
|
25 |
+
- images/nau_1
|
26 |
+
- images/uq_1
|
27 |
+
|
28 |
+
# Classes
|
29 |
+
names:
|
30 |
+
0: wheat_head
|
31 |
+
|
32 |
+
|
33 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
34 |
+
download: |
|
35 |
+
from utils.general import download, Path
|
36 |
+
|
37 |
+
|
38 |
+
# Download
|
39 |
+
dir = Path(yaml['path']) # dataset root dir
|
40 |
+
urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
|
41 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
|
42 |
+
download(urls, dir=dir)
|
43 |
+
|
44 |
+
# Make Directories
|
45 |
+
for p in 'annotations', 'images', 'labels':
|
46 |
+
(dir / p).mkdir(parents=True, exist_ok=True)
|
47 |
+
|
48 |
+
# Move
|
49 |
+
for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
|
50 |
+
'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
|
51 |
+
(dir / p).rename(dir / 'images' / p) # move to /images
|
52 |
+
f = (dir / p).with_suffix('.json') # json file
|
53 |
+
if f.exists():
|
54 |
+
f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
|
data/ImageNet.yaml
ADDED
@@ -0,0 +1,1022 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# ImageNet-1k dataset https://www.image-net.org/index.php by Stanford University
|
3 |
+
# Simplified class names from https://github.com/anishathalye/imagenet-simple-labels
|
4 |
+
# Example usage: python classify/train.py --data imagenet
|
5 |
+
# parent
|
6 |
+
# βββ yolov5
|
7 |
+
# βββ datasets
|
8 |
+
# βββ imagenet β downloads here (144 GB)
|
9 |
+
|
10 |
+
|
11 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
12 |
+
path: ../datasets/imagenet # dataset root dir
|
13 |
+
train: train # train images (relative to 'path') 1281167 images
|
14 |
+
val: val # val images (relative to 'path') 50000 images
|
15 |
+
test: # test images (optional)
|
16 |
+
|
17 |
+
# Classes
|
18 |
+
names:
|
19 |
+
0: tench
|
20 |
+
1: goldfish
|
21 |
+
2: great white shark
|
22 |
+
3: tiger shark
|
23 |
+
4: hammerhead shark
|
24 |
+
5: electric ray
|
25 |
+
6: stingray
|
26 |
+
7: cock
|
27 |
+
8: hen
|
28 |
+
9: ostrich
|
29 |
+
10: brambling
|
30 |
+
11: goldfinch
|
31 |
+
12: house finch
|
32 |
+
13: junco
|
33 |
+
14: indigo bunting
|
34 |
+
15: American robin
|
35 |
+
16: bulbul
|
36 |
+
17: jay
|
37 |
+
18: magpie
|
38 |
+
19: chickadee
|
39 |
+
20: American dipper
|
40 |
+
21: kite
|
41 |
+
22: bald eagle
|
42 |
+
23: vulture
|
43 |
+
24: great grey owl
|
44 |
+
25: fire salamander
|
45 |
+
26: smooth newt
|
46 |
+
27: newt
|
47 |
+
28: spotted salamander
|
48 |
+
29: axolotl
|
49 |
+
30: American bullfrog
|
50 |
+
31: tree frog
|
51 |
+
32: tailed frog
|
52 |
+
33: loggerhead sea turtle
|
53 |
+
34: leatherback sea turtle
|
54 |
+
35: mud turtle
|
55 |
+
36: terrapin
|
56 |
+
37: box turtle
|
57 |
+
38: banded gecko
|
58 |
+
39: green iguana
|
59 |
+
40: Carolina anole
|
60 |
+
41: desert grassland whiptail lizard
|
61 |
+
42: agama
|
62 |
+
43: frilled-necked lizard
|
63 |
+
44: alligator lizard
|
64 |
+
45: Gila monster
|
65 |
+
46: European green lizard
|
66 |
+
47: chameleon
|
67 |
+
48: Komodo dragon
|
68 |
+
49: Nile crocodile
|
69 |
+
50: American alligator
|
70 |
+
51: triceratops
|
71 |
+
52: worm snake
|
72 |
+
53: ring-necked snake
|
73 |
+
54: eastern hog-nosed snake
|
74 |
+
55: smooth green snake
|
75 |
+
56: kingsnake
|
76 |
+
57: garter snake
|
77 |
+
58: water snake
|
78 |
+
59: vine snake
|
79 |
+
60: night snake
|
80 |
+
61: boa constrictor
|
81 |
+
62: African rock python
|
82 |
+
63: Indian cobra
|
83 |
+
64: green mamba
|
84 |
+
65: sea snake
|
85 |
+
66: Saharan horned viper
|
86 |
+
67: eastern diamondback rattlesnake
|
87 |
+
68: sidewinder
|
88 |
+
69: trilobite
|
89 |
+
70: harvestman
|
90 |
+
71: scorpion
|
91 |
+
72: yellow garden spider
|
92 |
+
73: barn spider
|
93 |
+
74: European garden spider
|
94 |
+
75: southern black widow
|
95 |
+
76: tarantula
|
96 |
+
77: wolf spider
|
97 |
+
78: tick
|
98 |
+
79: centipede
|
99 |
+
80: black grouse
|
100 |
+
81: ptarmigan
|
101 |
+
82: ruffed grouse
|
102 |
+
83: prairie grouse
|
103 |
+
84: peacock
|
104 |
+
85: quail
|
105 |
+
86: partridge
|
106 |
+
87: grey parrot
|
107 |
+
88: macaw
|
108 |
+
89: sulphur-crested cockatoo
|
109 |
+
90: lorikeet
|
110 |
+
91: coucal
|
111 |
+
92: bee eater
|
112 |
+
93: hornbill
|
113 |
+
94: hummingbird
|
114 |
+
95: jacamar
|
115 |
+
96: toucan
|
116 |
+
97: duck
|
117 |
+
98: red-breasted merganser
|
118 |
+
99: goose
|
119 |
+
100: black swan
|
120 |
+
101: tusker
|
121 |
+
102: echidna
|
122 |
+
103: platypus
|
123 |
+
104: wallaby
|
124 |
+
105: koala
|
125 |
+
106: wombat
|
126 |
+
107: jellyfish
|
127 |
+
108: sea anemone
|
128 |
+
109: brain coral
|
129 |
+
110: flatworm
|
130 |
+
111: nematode
|
131 |
+
112: conch
|
132 |
+
113: snail
|
133 |
+
114: slug
|
134 |
+
115: sea slug
|
135 |
+
116: chiton
|
136 |
+
117: chambered nautilus
|
137 |
+
118: Dungeness crab
|
138 |
+
119: rock crab
|
139 |
+
120: fiddler crab
|
140 |
+
121: red king crab
|
141 |
+
122: American lobster
|
142 |
+
123: spiny lobster
|
143 |
+
124: crayfish
|
144 |
+
125: hermit crab
|
145 |
+
126: isopod
|
146 |
+
127: white stork
|
147 |
+
128: black stork
|
148 |
+
129: spoonbill
|
149 |
+
130: flamingo
|
150 |
+
131: little blue heron
|
151 |
+
132: great egret
|
152 |
+
133: bittern
|
153 |
+
134: crane (bird)
|
154 |
+
135: limpkin
|
155 |
+
136: common gallinule
|
156 |
+
137: American coot
|
157 |
+
138: bustard
|
158 |
+
139: ruddy turnstone
|
159 |
+
140: dunlin
|
160 |
+
141: common redshank
|
161 |
+
142: dowitcher
|
162 |
+
143: oystercatcher
|
163 |
+
144: pelican
|
164 |
+
145: king penguin
|
165 |
+
146: albatross
|
166 |
+
147: grey whale
|
167 |
+
148: killer whale
|
168 |
+
149: dugong
|
169 |
+
150: sea lion
|
170 |
+
151: Chihuahua
|
171 |
+
152: Japanese Chin
|
172 |
+
153: Maltese
|
173 |
+
154: Pekingese
|
174 |
+
155: Shih Tzu
|
175 |
+
156: King Charles Spaniel
|
176 |
+
157: Papillon
|
177 |
+
158: toy terrier
|
178 |
+
159: Rhodesian Ridgeback
|
179 |
+
160: Afghan Hound
|
180 |
+
161: Basset Hound
|
181 |
+
162: Beagle
|
182 |
+
163: Bloodhound
|
183 |
+
164: Bluetick Coonhound
|
184 |
+
165: Black and Tan Coonhound
|
185 |
+
166: Treeing Walker Coonhound
|
186 |
+
167: English foxhound
|
187 |
+
168: Redbone Coonhound
|
188 |
+
169: borzoi
|
189 |
+
170: Irish Wolfhound
|
190 |
+
171: Italian Greyhound
|
191 |
+
172: Whippet
|
192 |
+
173: Ibizan Hound
|
193 |
+
174: Norwegian Elkhound
|
194 |
+
175: Otterhound
|
195 |
+
176: Saluki
|
196 |
+
177: Scottish Deerhound
|
197 |
+
178: Weimaraner
|
198 |
+
179: Staffordshire Bull Terrier
|
199 |
+
180: American Staffordshire Terrier
|
200 |
+
181: Bedlington Terrier
|
201 |
+
182: Border Terrier
|
202 |
+
183: Kerry Blue Terrier
|
203 |
+
184: Irish Terrier
|
204 |
+
185: Norfolk Terrier
|
205 |
+
186: Norwich Terrier
|
206 |
+
187: Yorkshire Terrier
|
207 |
+
188: Wire Fox Terrier
|
208 |
+
189: Lakeland Terrier
|
209 |
+
190: Sealyham Terrier
|
210 |
+
191: Airedale Terrier
|
211 |
+
192: Cairn Terrier
|
212 |
+
193: Australian Terrier
|
213 |
+
194: Dandie Dinmont Terrier
|
214 |
+
195: Boston Terrier
|
215 |
+
196: Miniature Schnauzer
|
216 |
+
197: Giant Schnauzer
|
217 |
+
198: Standard Schnauzer
|
218 |
+
199: Scottish Terrier
|
219 |
+
200: Tibetan Terrier
|
220 |
+
201: Australian Silky Terrier
|
221 |
+
202: Soft-coated Wheaten Terrier
|
222 |
+
203: West Highland White Terrier
|
223 |
+
204: Lhasa Apso
|
224 |
+
205: Flat-Coated Retriever
|
225 |
+
206: Curly-coated Retriever
|
226 |
+
207: Golden Retriever
|
227 |
+
208: Labrador Retriever
|
228 |
+
209: Chesapeake Bay Retriever
|
229 |
+
210: German Shorthaired Pointer
|
230 |
+
211: Vizsla
|
231 |
+
212: English Setter
|
232 |
+
213: Irish Setter
|
233 |
+
214: Gordon Setter
|
234 |
+
215: Brittany
|
235 |
+
216: Clumber Spaniel
|
236 |
+
217: English Springer Spaniel
|
237 |
+
218: Welsh Springer Spaniel
|
238 |
+
219: Cocker Spaniels
|
239 |
+
220: Sussex Spaniel
|
240 |
+
221: Irish Water Spaniel
|
241 |
+
222: Kuvasz
|
242 |
+
223: Schipperke
|
243 |
+
224: Groenendael
|
244 |
+
225: Malinois
|
245 |
+
226: Briard
|
246 |
+
227: Australian Kelpie
|
247 |
+
228: Komondor
|
248 |
+
229: Old English Sheepdog
|
249 |
+
230: Shetland Sheepdog
|
250 |
+
231: collie
|
251 |
+
232: Border Collie
|
252 |
+
233: Bouvier des Flandres
|
253 |
+
234: Rottweiler
|
254 |
+
235: German Shepherd Dog
|
255 |
+
236: Dobermann
|
256 |
+
237: Miniature Pinscher
|
257 |
+
238: Greater Swiss Mountain Dog
|
258 |
+
239: Bernese Mountain Dog
|
259 |
+
240: Appenzeller Sennenhund
|
260 |
+
241: Entlebucher Sennenhund
|
261 |
+
242: Boxer
|
262 |
+
243: Bullmastiff
|
263 |
+
244: Tibetan Mastiff
|
264 |
+
245: French Bulldog
|
265 |
+
246: Great Dane
|
266 |
+
247: St. Bernard
|
267 |
+
248: husky
|
268 |
+
249: Alaskan Malamute
|
269 |
+
250: Siberian Husky
|
270 |
+
251: Dalmatian
|
271 |
+
252: Affenpinscher
|
272 |
+
253: Basenji
|
273 |
+
254: pug
|
274 |
+
255: Leonberger
|
275 |
+
256: Newfoundland
|
276 |
+
257: Pyrenean Mountain Dog
|
277 |
+
258: Samoyed
|
278 |
+
259: Pomeranian
|
279 |
+
260: Chow Chow
|
280 |
+
261: Keeshond
|
281 |
+
262: Griffon Bruxellois
|
282 |
+
263: Pembroke Welsh Corgi
|
283 |
+
264: Cardigan Welsh Corgi
|
284 |
+
265: Toy Poodle
|
285 |
+
266: Miniature Poodle
|
286 |
+
267: Standard Poodle
|
287 |
+
268: Mexican hairless dog
|
288 |
+
269: grey wolf
|
289 |
+
270: Alaskan tundra wolf
|
290 |
+
271: red wolf
|
291 |
+
272: coyote
|
292 |
+
273: dingo
|
293 |
+
274: dhole
|
294 |
+
275: African wild dog
|
295 |
+
276: hyena
|
296 |
+
277: red fox
|
297 |
+
278: kit fox
|
298 |
+
279: Arctic fox
|
299 |
+
280: grey fox
|
300 |
+
281: tabby cat
|
301 |
+
282: tiger cat
|
302 |
+
283: Persian cat
|
303 |
+
284: Siamese cat
|
304 |
+
285: Egyptian Mau
|
305 |
+
286: cougar
|
306 |
+
287: lynx
|
307 |
+
288: leopard
|
308 |
+
289: snow leopard
|
309 |
+
290: jaguar
|
310 |
+
291: lion
|
311 |
+
292: tiger
|
312 |
+
293: cheetah
|
313 |
+
294: brown bear
|
314 |
+
295: American black bear
|
315 |
+
296: polar bear
|
316 |
+
297: sloth bear
|
317 |
+
298: mongoose
|
318 |
+
299: meerkat
|
319 |
+
300: tiger beetle
|
320 |
+
301: ladybug
|
321 |
+
302: ground beetle
|
322 |
+
303: longhorn beetle
|
323 |
+
304: leaf beetle
|
324 |
+
305: dung beetle
|
325 |
+
306: rhinoceros beetle
|
326 |
+
307: weevil
|
327 |
+
308: fly
|
328 |
+
309: bee
|
329 |
+
310: ant
|
330 |
+
311: grasshopper
|
331 |
+
312: cricket
|
332 |
+
313: stick insect
|
333 |
+
314: cockroach
|
334 |
+
315: mantis
|
335 |
+
316: cicada
|
336 |
+
317: leafhopper
|
337 |
+
318: lacewing
|
338 |
+
319: dragonfly
|
339 |
+
320: damselfly
|
340 |
+
321: red admiral
|
341 |
+
322: ringlet
|
342 |
+
323: monarch butterfly
|
343 |
+
324: small white
|
344 |
+
325: sulphur butterfly
|
345 |
+
326: gossamer-winged butterfly
|
346 |
+
327: starfish
|
347 |
+
328: sea urchin
|
348 |
+
329: sea cucumber
|
349 |
+
330: cottontail rabbit
|
350 |
+
331: hare
|
351 |
+
332: Angora rabbit
|
352 |
+
333: hamster
|
353 |
+
334: porcupine
|
354 |
+
335: fox squirrel
|
355 |
+
336: marmot
|
356 |
+
337: beaver
|
357 |
+
338: guinea pig
|
358 |
+
339: common sorrel
|
359 |
+
340: zebra
|
360 |
+
341: pig
|
361 |
+
342: wild boar
|
362 |
+
343: warthog
|
363 |
+
344: hippopotamus
|
364 |
+
345: ox
|
365 |
+
346: water buffalo
|
366 |
+
347: bison
|
367 |
+
348: ram
|
368 |
+
349: bighorn sheep
|
369 |
+
350: Alpine ibex
|
370 |
+
351: hartebeest
|
371 |
+
352: impala
|
372 |
+
353: gazelle
|
373 |
+
354: dromedary
|
374 |
+
355: llama
|
375 |
+
356: weasel
|
376 |
+
357: mink
|
377 |
+
358: European polecat
|
378 |
+
359: black-footed ferret
|
379 |
+
360: otter
|
380 |
+
361: skunk
|
381 |
+
362: badger
|
382 |
+
363: armadillo
|
383 |
+
364: three-toed sloth
|
384 |
+
365: orangutan
|
385 |
+
366: gorilla
|
386 |
+
367: chimpanzee
|
387 |
+
368: gibbon
|
388 |
+
369: siamang
|
389 |
+
370: guenon
|
390 |
+
371: patas monkey
|
391 |
+
372: baboon
|
392 |
+
373: macaque
|
393 |
+
374: langur
|
394 |
+
375: black-and-white colobus
|
395 |
+
376: proboscis monkey
|
396 |
+
377: marmoset
|
397 |
+
378: white-headed capuchin
|
398 |
+
379: howler monkey
|
399 |
+
380: titi
|
400 |
+
381: Geoffroy's spider monkey
|
401 |
+
382: common squirrel monkey
|
402 |
+
383: ring-tailed lemur
|
403 |
+
384: indri
|
404 |
+
385: Asian elephant
|
405 |
+
386: African bush elephant
|
406 |
+
387: red panda
|
407 |
+
388: giant panda
|
408 |
+
389: snoek
|
409 |
+
390: eel
|
410 |
+
391: coho salmon
|
411 |
+
392: rock beauty
|
412 |
+
393: clownfish
|
413 |
+
394: sturgeon
|
414 |
+
395: garfish
|
415 |
+
396: lionfish
|
416 |
+
397: pufferfish
|
417 |
+
398: abacus
|
418 |
+
399: abaya
|
419 |
+
400: academic gown
|
420 |
+
401: accordion
|
421 |
+
402: acoustic guitar
|
422 |
+
403: aircraft carrier
|
423 |
+
404: airliner
|
424 |
+
405: airship
|
425 |
+
406: altar
|
426 |
+
407: ambulance
|
427 |
+
408: amphibious vehicle
|
428 |
+
409: analog clock
|
429 |
+
410: apiary
|
430 |
+
411: apron
|
431 |
+
412: waste container
|
432 |
+
413: assault rifle
|
433 |
+
414: backpack
|
434 |
+
415: bakery
|
435 |
+
416: balance beam
|
436 |
+
417: balloon
|
437 |
+
418: ballpoint pen
|
438 |
+
419: Band-Aid
|
439 |
+
420: banjo
|
440 |
+
421: baluster
|
441 |
+
422: barbell
|
442 |
+
423: barber chair
|
443 |
+
424: barbershop
|
444 |
+
425: barn
|
445 |
+
426: barometer
|
446 |
+
427: barrel
|
447 |
+
428: wheelbarrow
|
448 |
+
429: baseball
|
449 |
+
430: basketball
|
450 |
+
431: bassinet
|
451 |
+
432: bassoon
|
452 |
+
433: swimming cap
|
453 |
+
434: bath towel
|
454 |
+
435: bathtub
|
455 |
+
436: station wagon
|
456 |
+
437: lighthouse
|
457 |
+
438: beaker
|
458 |
+
439: military cap
|
459 |
+
440: beer bottle
|
460 |
+
441: beer glass
|
461 |
+
442: bell-cot
|
462 |
+
443: bib
|
463 |
+
444: tandem bicycle
|
464 |
+
445: bikini
|
465 |
+
446: ring binder
|
466 |
+
447: binoculars
|
467 |
+
448: birdhouse
|
468 |
+
449: boathouse
|
469 |
+
450: bobsleigh
|
470 |
+
451: bolo tie
|
471 |
+
452: poke bonnet
|
472 |
+
453: bookcase
|
473 |
+
454: bookstore
|
474 |
+
455: bottle cap
|
475 |
+
456: bow
|
476 |
+
457: bow tie
|
477 |
+
458: brass
|
478 |
+
459: bra
|
479 |
+
460: breakwater
|
480 |
+
461: breastplate
|
481 |
+
462: broom
|
482 |
+
463: bucket
|
483 |
+
464: buckle
|
484 |
+
465: bulletproof vest
|
485 |
+
466: high-speed train
|
486 |
+
467: butcher shop
|
487 |
+
468: taxicab
|
488 |
+
469: cauldron
|
489 |
+
470: candle
|
490 |
+
471: cannon
|
491 |
+
472: canoe
|
492 |
+
473: can opener
|
493 |
+
474: cardigan
|
494 |
+
475: car mirror
|
495 |
+
476: carousel
|
496 |
+
477: tool kit
|
497 |
+
478: carton
|
498 |
+
479: car wheel
|
499 |
+
480: automated teller machine
|
500 |
+
481: cassette
|
501 |
+
482: cassette player
|
502 |
+
483: castle
|
503 |
+
484: catamaran
|
504 |
+
485: CD player
|
505 |
+
486: cello
|
506 |
+
487: mobile phone
|
507 |
+
488: chain
|
508 |
+
489: chain-link fence
|
509 |
+
490: chain mail
|
510 |
+
491: chainsaw
|
511 |
+
492: chest
|
512 |
+
493: chiffonier
|
513 |
+
494: chime
|
514 |
+
495: china cabinet
|
515 |
+
496: Christmas stocking
|
516 |
+
497: church
|
517 |
+
498: movie theater
|
518 |
+
499: cleaver
|
519 |
+
500: cliff dwelling
|
520 |
+
501: cloak
|
521 |
+
502: clogs
|
522 |
+
503: cocktail shaker
|
523 |
+
504: coffee mug
|
524 |
+
505: coffeemaker
|
525 |
+
506: coil
|
526 |
+
507: combination lock
|
527 |
+
508: computer keyboard
|
528 |
+
509: confectionery store
|
529 |
+
510: container ship
|
530 |
+
511: convertible
|
531 |
+
512: corkscrew
|
532 |
+
513: cornet
|
533 |
+
514: cowboy boot
|
534 |
+
515: cowboy hat
|
535 |
+
516: cradle
|
536 |
+
517: crane (machine)
|
537 |
+
518: crash helmet
|
538 |
+
519: crate
|
539 |
+
520: infant bed
|
540 |
+
521: Crock Pot
|
541 |
+
522: croquet ball
|
542 |
+
523: crutch
|
543 |
+
524: cuirass
|
544 |
+
525: dam
|
545 |
+
526: desk
|
546 |
+
527: desktop computer
|
547 |
+
528: rotary dial telephone
|
548 |
+
529: diaper
|
549 |
+
530: digital clock
|
550 |
+
531: digital watch
|
551 |
+
532: dining table
|
552 |
+
533: dishcloth
|
553 |
+
534: dishwasher
|
554 |
+
535: disc brake
|
555 |
+
536: dock
|
556 |
+
537: dog sled
|
557 |
+
538: dome
|
558 |
+
539: doormat
|
559 |
+
540: drilling rig
|
560 |
+
541: drum
|
561 |
+
542: drumstick
|
562 |
+
543: dumbbell
|
563 |
+
544: Dutch oven
|
564 |
+
545: electric fan
|
565 |
+
546: electric guitar
|
566 |
+
547: electric locomotive
|
567 |
+
548: entertainment center
|
568 |
+
549: envelope
|
569 |
+
550: espresso machine
|
570 |
+
551: face powder
|
571 |
+
552: feather boa
|
572 |
+
553: filing cabinet
|
573 |
+
554: fireboat
|
574 |
+
555: fire engine
|
575 |
+
556: fire screen sheet
|
576 |
+
557: flagpole
|
577 |
+
558: flute
|
578 |
+
559: folding chair
|
579 |
+
560: football helmet
|
580 |
+
561: forklift
|
581 |
+
562: fountain
|
582 |
+
563: fountain pen
|
583 |
+
564: four-poster bed
|
584 |
+
565: freight car
|
585 |
+
566: French horn
|
586 |
+
567: frying pan
|
587 |
+
568: fur coat
|
588 |
+
569: garbage truck
|
589 |
+
570: gas mask
|
590 |
+
571: gas pump
|
591 |
+
572: goblet
|
592 |
+
573: go-kart
|
593 |
+
574: golf ball
|
594 |
+
575: golf cart
|
595 |
+
576: gondola
|
596 |
+
577: gong
|
597 |
+
578: gown
|
598 |
+
579: grand piano
|
599 |
+
580: greenhouse
|
600 |
+
581: grille
|
601 |
+
582: grocery store
|
602 |
+
583: guillotine
|
603 |
+
584: barrette
|
604 |
+
585: hair spray
|
605 |
+
586: half-track
|
606 |
+
587: hammer
|
607 |
+
588: hamper
|
608 |
+
589: hair dryer
|
609 |
+
590: hand-held computer
|
610 |
+
591: handkerchief
|
611 |
+
592: hard disk drive
|
612 |
+
593: harmonica
|
613 |
+
594: harp
|
614 |
+
595: harvester
|
615 |
+
596: hatchet
|
616 |
+
597: holster
|
617 |
+
598: home theater
|
618 |
+
599: honeycomb
|
619 |
+
600: hook
|
620 |
+
601: hoop skirt
|
621 |
+
602: horizontal bar
|
622 |
+
603: horse-drawn vehicle
|
623 |
+
604: hourglass
|
624 |
+
605: iPod
|
625 |
+
606: clothes iron
|
626 |
+
607: jack-o'-lantern
|
627 |
+
608: jeans
|
628 |
+
609: jeep
|
629 |
+
610: T-shirt
|
630 |
+
611: jigsaw puzzle
|
631 |
+
612: pulled rickshaw
|
632 |
+
613: joystick
|
633 |
+
614: kimono
|
634 |
+
615: knee pad
|
635 |
+
616: knot
|
636 |
+
617: lab coat
|
637 |
+
618: ladle
|
638 |
+
619: lampshade
|
639 |
+
620: laptop computer
|
640 |
+
621: lawn mower
|
641 |
+
622: lens cap
|
642 |
+
623: paper knife
|
643 |
+
624: library
|
644 |
+
625: lifeboat
|
645 |
+
626: lighter
|
646 |
+
627: limousine
|
647 |
+
628: ocean liner
|
648 |
+
629: lipstick
|
649 |
+
630: slip-on shoe
|
650 |
+
631: lotion
|
651 |
+
632: speaker
|
652 |
+
633: loupe
|
653 |
+
634: sawmill
|
654 |
+
635: magnetic compass
|
655 |
+
636: mail bag
|
656 |
+
637: mailbox
|
657 |
+
638: tights
|
658 |
+
639: tank suit
|
659 |
+
640: manhole cover
|
660 |
+
641: maraca
|
661 |
+
642: marimba
|
662 |
+
643: mask
|
663 |
+
644: match
|
664 |
+
645: maypole
|
665 |
+
646: maze
|
666 |
+
647: measuring cup
|
667 |
+
648: medicine chest
|
668 |
+
649: megalith
|
669 |
+
650: microphone
|
670 |
+
651: microwave oven
|
671 |
+
652: military uniform
|
672 |
+
653: milk can
|
673 |
+
654: minibus
|
674 |
+
655: miniskirt
|
675 |
+
656: minivan
|
676 |
+
657: missile
|
677 |
+
658: mitten
|
678 |
+
659: mixing bowl
|
679 |
+
660: mobile home
|
680 |
+
661: Model T
|
681 |
+
662: modem
|
682 |
+
663: monastery
|
683 |
+
664: monitor
|
684 |
+
665: moped
|
685 |
+
666: mortar
|
686 |
+
667: square academic cap
|
687 |
+
668: mosque
|
688 |
+
669: mosquito net
|
689 |
+
670: scooter
|
690 |
+
671: mountain bike
|
691 |
+
672: tent
|
692 |
+
673: computer mouse
|
693 |
+
674: mousetrap
|
694 |
+
675: moving van
|
695 |
+
676: muzzle
|
696 |
+
677: nail
|
697 |
+
678: neck brace
|
698 |
+
679: necklace
|
699 |
+
680: nipple
|
700 |
+
681: notebook computer
|
701 |
+
682: obelisk
|
702 |
+
683: oboe
|
703 |
+
684: ocarina
|
704 |
+
685: odometer
|
705 |
+
686: oil filter
|
706 |
+
687: organ
|
707 |
+
688: oscilloscope
|
708 |
+
689: overskirt
|
709 |
+
690: bullock cart
|
710 |
+
691: oxygen mask
|
711 |
+
692: packet
|
712 |
+
693: paddle
|
713 |
+
694: paddle wheel
|
714 |
+
695: padlock
|
715 |
+
696: paintbrush
|
716 |
+
697: pajamas
|
717 |
+
698: palace
|
718 |
+
699: pan flute
|
719 |
+
700: paper towel
|
720 |
+
701: parachute
|
721 |
+
702: parallel bars
|
722 |
+
703: park bench
|
723 |
+
704: parking meter
|
724 |
+
705: passenger car
|
725 |
+
706: patio
|
726 |
+
707: payphone
|
727 |
+
708: pedestal
|
728 |
+
709: pencil case
|
729 |
+
710: pencil sharpener
|
730 |
+
711: perfume
|
731 |
+
712: Petri dish
|
732 |
+
713: photocopier
|
733 |
+
714: plectrum
|
734 |
+
715: Pickelhaube
|
735 |
+
716: picket fence
|
736 |
+
717: pickup truck
|
737 |
+
718: pier
|
738 |
+
719: piggy bank
|
739 |
+
720: pill bottle
|
740 |
+
721: pillow
|
741 |
+
722: ping-pong ball
|
742 |
+
723: pinwheel
|
743 |
+
724: pirate ship
|
744 |
+
725: pitcher
|
745 |
+
726: hand plane
|
746 |
+
727: planetarium
|
747 |
+
728: plastic bag
|
748 |
+
729: plate rack
|
749 |
+
730: plow
|
750 |
+
731: plunger
|
751 |
+
732: Polaroid camera
|
752 |
+
733: pole
|
753 |
+
734: police van
|
754 |
+
735: poncho
|
755 |
+
736: billiard table
|
756 |
+
737: soda bottle
|
757 |
+
738: pot
|
758 |
+
739: potter's wheel
|
759 |
+
740: power drill
|
760 |
+
741: prayer rug
|
761 |
+
742: printer
|
762 |
+
743: prison
|
763 |
+
744: projectile
|
764 |
+
745: projector
|
765 |
+
746: hockey puck
|
766 |
+
747: punching bag
|
767 |
+
748: purse
|
768 |
+
749: quill
|
769 |
+
750: quilt
|
770 |
+
751: race car
|
771 |
+
752: racket
|
772 |
+
753: radiator
|
773 |
+
754: radio
|
774 |
+
755: radio telescope
|
775 |
+
756: rain barrel
|
776 |
+
757: recreational vehicle
|
777 |
+
758: reel
|
778 |
+
759: reflex camera
|
779 |
+
760: refrigerator
|
780 |
+
761: remote control
|
781 |
+
762: restaurant
|
782 |
+
763: revolver
|
783 |
+
764: rifle
|
784 |
+
765: rocking chair
|
785 |
+
766: rotisserie
|
786 |
+
767: eraser
|
787 |
+
768: rugby ball
|
788 |
+
769: ruler
|
789 |
+
770: running shoe
|
790 |
+
771: safe
|
791 |
+
772: safety pin
|
792 |
+
773: salt shaker
|
793 |
+
774: sandal
|
794 |
+
775: sarong
|
795 |
+
776: saxophone
|
796 |
+
777: scabbard
|
797 |
+
778: weighing scale
|
798 |
+
779: school bus
|
799 |
+
780: schooner
|
800 |
+
781: scoreboard
|
801 |
+
782: CRT screen
|
802 |
+
783: screw
|
803 |
+
784: screwdriver
|
804 |
+
785: seat belt
|
805 |
+
786: sewing machine
|
806 |
+
787: shield
|
807 |
+
788: shoe store
|
808 |
+
789: shoji
|
809 |
+
790: shopping basket
|
810 |
+
791: shopping cart
|
811 |
+
792: shovel
|
812 |
+
793: shower cap
|
813 |
+
794: shower curtain
|
814 |
+
795: ski
|
815 |
+
796: ski mask
|
816 |
+
797: sleeping bag
|
817 |
+
798: slide rule
|
818 |
+
799: sliding door
|
819 |
+
800: slot machine
|
820 |
+
801: snorkel
|
821 |
+
802: snowmobile
|
822 |
+
803: snowplow
|
823 |
+
804: soap dispenser
|
824 |
+
805: soccer ball
|
825 |
+
806: sock
|
826 |
+
807: solar thermal collector
|
827 |
+
808: sombrero
|
828 |
+
809: soup bowl
|
829 |
+
810: space bar
|
830 |
+
811: space heater
|
831 |
+
812: space shuttle
|
832 |
+
813: spatula
|
833 |
+
814: motorboat
|
834 |
+
815: spider web
|
835 |
+
816: spindle
|
836 |
+
817: sports car
|
837 |
+
818: spotlight
|
838 |
+
819: stage
|
839 |
+
820: steam locomotive
|
840 |
+
821: through arch bridge
|
841 |
+
822: steel drum
|
842 |
+
823: stethoscope
|
843 |
+
824: scarf
|
844 |
+
825: stone wall
|
845 |
+
826: stopwatch
|
846 |
+
827: stove
|
847 |
+
828: strainer
|
848 |
+
829: tram
|
849 |
+
830: stretcher
|
850 |
+
831: couch
|
851 |
+
832: stupa
|
852 |
+
833: submarine
|
853 |
+
834: suit
|
854 |
+
835: sundial
|
855 |
+
836: sunglass
|
856 |
+
837: sunglasses
|
857 |
+
838: sunscreen
|
858 |
+
839: suspension bridge
|
859 |
+
840: mop
|
860 |
+
841: sweatshirt
|
861 |
+
842: swimsuit
|
862 |
+
843: swing
|
863 |
+
844: switch
|
864 |
+
845: syringe
|
865 |
+
846: table lamp
|
866 |
+
847: tank
|
867 |
+
848: tape player
|
868 |
+
849: teapot
|
869 |
+
850: teddy bear
|
870 |
+
851: television
|
871 |
+
852: tennis ball
|
872 |
+
853: thatched roof
|
873 |
+
854: front curtain
|
874 |
+
855: thimble
|
875 |
+
856: threshing machine
|
876 |
+
857: throne
|
877 |
+
858: tile roof
|
878 |
+
859: toaster
|
879 |
+
860: tobacco shop
|
880 |
+
861: toilet seat
|
881 |
+
862: torch
|
882 |
+
863: totem pole
|
883 |
+
864: tow truck
|
884 |
+
865: toy store
|
885 |
+
866: tractor
|
886 |
+
867: semi-trailer truck
|
887 |
+
868: tray
|
888 |
+
869: trench coat
|
889 |
+
870: tricycle
|
890 |
+
871: trimaran
|
891 |
+
872: tripod
|
892 |
+
873: triumphal arch
|
893 |
+
874: trolleybus
|
894 |
+
875: trombone
|
895 |
+
876: tub
|
896 |
+
877: turnstile
|
897 |
+
878: typewriter keyboard
|
898 |
+
879: umbrella
|
899 |
+
880: unicycle
|
900 |
+
881: upright piano
|
901 |
+
882: vacuum cleaner
|
902 |
+
883: vase
|
903 |
+
884: vault
|
904 |
+
885: velvet
|
905 |
+
886: vending machine
|
906 |
+
887: vestment
|
907 |
+
888: viaduct
|
908 |
+
889: violin
|
909 |
+
890: volleyball
|
910 |
+
891: waffle iron
|
911 |
+
892: wall clock
|
912 |
+
893: wallet
|
913 |
+
894: wardrobe
|
914 |
+
895: military aircraft
|
915 |
+
896: sink
|
916 |
+
897: washing machine
|
917 |
+
898: water bottle
|
918 |
+
899: water jug
|
919 |
+
900: water tower
|
920 |
+
901: whiskey jug
|
921 |
+
902: whistle
|
922 |
+
903: wig
|
923 |
+
904: window screen
|
924 |
+
905: window shade
|
925 |
+
906: Windsor tie
|
926 |
+
907: wine bottle
|
927 |
+
908: wing
|
928 |
+
909: wok
|
929 |
+
910: wooden spoon
|
930 |
+
911: wool
|
931 |
+
912: split-rail fence
|
932 |
+
913: shipwreck
|
933 |
+
914: yawl
|
934 |
+
915: yurt
|
935 |
+
916: website
|
936 |
+
917: comic book
|
937 |
+
918: crossword
|
938 |
+
919: traffic sign
|
939 |
+
920: traffic light
|
940 |
+
921: dust jacket
|
941 |
+
922: menu
|
942 |
+
923: plate
|
943 |
+
924: guacamole
|
944 |
+
925: consomme
|
945 |
+
926: hot pot
|
946 |
+
927: trifle
|
947 |
+
928: ice cream
|
948 |
+
929: ice pop
|
949 |
+
930: baguette
|
950 |
+
931: bagel
|
951 |
+
932: pretzel
|
952 |
+
933: cheeseburger
|
953 |
+
934: hot dog
|
954 |
+
935: mashed potato
|
955 |
+
936: cabbage
|
956 |
+
937: broccoli
|
957 |
+
938: cauliflower
|
958 |
+
939: zucchini
|
959 |
+
940: spaghetti squash
|
960 |
+
941: acorn squash
|
961 |
+
942: butternut squash
|
962 |
+
943: cucumber
|
963 |
+
944: artichoke
|
964 |
+
945: bell pepper
|
965 |
+
946: cardoon
|
966 |
+
947: mushroom
|
967 |
+
948: Granny Smith
|
968 |
+
949: strawberry
|
969 |
+
950: orange
|
970 |
+
951: lemon
|
971 |
+
952: fig
|
972 |
+
953: pineapple
|
973 |
+
954: banana
|
974 |
+
955: jackfruit
|
975 |
+
956: custard apple
|
976 |
+
957: pomegranate
|
977 |
+
958: hay
|
978 |
+
959: carbonara
|
979 |
+
960: chocolate syrup
|
980 |
+
961: dough
|
981 |
+
962: meatloaf
|
982 |
+
963: pizza
|
983 |
+
964: pot pie
|
984 |
+
965: burrito
|
985 |
+
966: red wine
|
986 |
+
967: espresso
|
987 |
+
968: cup
|
988 |
+
969: eggnog
|
989 |
+
970: alp
|
990 |
+
971: bubble
|
991 |
+
972: cliff
|
992 |
+
973: coral reef
|
993 |
+
974: geyser
|
994 |
+
975: lakeshore
|
995 |
+
976: promontory
|
996 |
+
977: shoal
|
997 |
+
978: seashore
|
998 |
+
979: valley
|
999 |
+
980: volcano
|
1000 |
+
981: baseball player
|
1001 |
+
982: bridegroom
|
1002 |
+
983: scuba diver
|
1003 |
+
984: rapeseed
|
1004 |
+
985: daisy
|
1005 |
+
986: yellow lady's slipper
|
1006 |
+
987: corn
|
1007 |
+
988: acorn
|
1008 |
+
989: rose hip
|
1009 |
+
990: horse chestnut seed
|
1010 |
+
991: coral fungus
|
1011 |
+
992: agaric
|
1012 |
+
993: gyromitra
|
1013 |
+
994: stinkhorn mushroom
|
1014 |
+
995: earth star
|
1015 |
+
996: hen-of-the-woods
|
1016 |
+
997: bolete
|
1017 |
+
998: ear
|
1018 |
+
999: toilet paper
|
1019 |
+
|
1020 |
+
|
1021 |
+
# Download script/URL (optional)
|
1022 |
+
download: data/scripts/get_imagenet.sh
|
data/Objects365.yaml
ADDED
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Objects365 dataset https://www.objects365.org/ by Megvii
|
3 |
+
# Example usage: python train.py --data Objects365.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ Objects365 β downloads here (712 GB = 367G data + 345G zips)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/Objects365 # dataset root dir
|
12 |
+
train: images/train # train images (relative to 'path') 1742289 images
|
13 |
+
val: images/val # val images (relative to 'path') 80000 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: Person
|
19 |
+
1: Sneakers
|
20 |
+
2: Chair
|
21 |
+
3: Other Shoes
|
22 |
+
4: Hat
|
23 |
+
5: Car
|
24 |
+
6: Lamp
|
25 |
+
7: Glasses
|
26 |
+
8: Bottle
|
27 |
+
9: Desk
|
28 |
+
10: Cup
|
29 |
+
11: Street Lights
|
30 |
+
12: Cabinet/shelf
|
31 |
+
13: Handbag/Satchel
|
32 |
+
14: Bracelet
|
33 |
+
15: Plate
|
34 |
+
16: Picture/Frame
|
35 |
+
17: Helmet
|
36 |
+
18: Book
|
37 |
+
19: Gloves
|
38 |
+
20: Storage box
|
39 |
+
21: Boat
|
40 |
+
22: Leather Shoes
|
41 |
+
23: Flower
|
42 |
+
24: Bench
|
43 |
+
25: Potted Plant
|
44 |
+
26: Bowl/Basin
|
45 |
+
27: Flag
|
46 |
+
28: Pillow
|
47 |
+
29: Boots
|
48 |
+
30: Vase
|
49 |
+
31: Microphone
|
50 |
+
32: Necklace
|
51 |
+
33: Ring
|
52 |
+
34: SUV
|
53 |
+
35: Wine Glass
|
54 |
+
36: Belt
|
55 |
+
37: Monitor/TV
|
56 |
+
38: Backpack
|
57 |
+
39: Umbrella
|
58 |
+
40: Traffic Light
|
59 |
+
41: Speaker
|
60 |
+
42: Watch
|
61 |
+
43: Tie
|
62 |
+
44: Trash bin Can
|
63 |
+
45: Slippers
|
64 |
+
46: Bicycle
|
65 |
+
47: Stool
|
66 |
+
48: Barrel/bucket
|
67 |
+
49: Van
|
68 |
+
50: Couch
|
69 |
+
51: Sandals
|
70 |
+
52: Basket
|
71 |
+
53: Drum
|
72 |
+
54: Pen/Pencil
|
73 |
+
55: Bus
|
74 |
+
56: Wild Bird
|
75 |
+
57: High Heels
|
76 |
+
58: Motorcycle
|
77 |
+
59: Guitar
|
78 |
+
60: Carpet
|
79 |
+
61: Cell Phone
|
80 |
+
62: Bread
|
81 |
+
63: Camera
|
82 |
+
64: Canned
|
83 |
+
65: Truck
|
84 |
+
66: Traffic cone
|
85 |
+
67: Cymbal
|
86 |
+
68: Lifesaver
|
87 |
+
69: Towel
|
88 |
+
70: Stuffed Toy
|
89 |
+
71: Candle
|
90 |
+
72: Sailboat
|
91 |
+
73: Laptop
|
92 |
+
74: Awning
|
93 |
+
75: Bed
|
94 |
+
76: Faucet
|
95 |
+
77: Tent
|
96 |
+
78: Horse
|
97 |
+
79: Mirror
|
98 |
+
80: Power outlet
|
99 |
+
81: Sink
|
100 |
+
82: Apple
|
101 |
+
83: Air Conditioner
|
102 |
+
84: Knife
|
103 |
+
85: Hockey Stick
|
104 |
+
86: Paddle
|
105 |
+
87: Pickup Truck
|
106 |
+
88: Fork
|
107 |
+
89: Traffic Sign
|
108 |
+
90: Balloon
|
109 |
+
91: Tripod
|
110 |
+
92: Dog
|
111 |
+
93: Spoon
|
112 |
+
94: Clock
|
113 |
+
95: Pot
|
114 |
+
96: Cow
|
115 |
+
97: Cake
|
116 |
+
98: Dinning Table
|
117 |
+
99: Sheep
|
118 |
+
100: Hanger
|
119 |
+
101: Blackboard/Whiteboard
|
120 |
+
102: Napkin
|
121 |
+
103: Other Fish
|
122 |
+
104: Orange/Tangerine
|
123 |
+
105: Toiletry
|
124 |
+
106: Keyboard
|
125 |
+
107: Tomato
|
126 |
+
108: Lantern
|
127 |
+
109: Machinery Vehicle
|
128 |
+
110: Fan
|
129 |
+
111: Green Vegetables
|
130 |
+
112: Banana
|
131 |
+
113: Baseball Glove
|
132 |
+
114: Airplane
|
133 |
+
115: Mouse
|
134 |
+
116: Train
|
135 |
+
117: Pumpkin
|
136 |
+
118: Soccer
|
137 |
+
119: Skiboard
|
138 |
+
120: Luggage
|
139 |
+
121: Nightstand
|
140 |
+
122: Tea pot
|
141 |
+
123: Telephone
|
142 |
+
124: Trolley
|
143 |
+
125: Head Phone
|
144 |
+
126: Sports Car
|
145 |
+
127: Stop Sign
|
146 |
+
128: Dessert
|
147 |
+
129: Scooter
|
148 |
+
130: Stroller
|
149 |
+
131: Crane
|
150 |
+
132: Remote
|
151 |
+
133: Refrigerator
|
152 |
+
134: Oven
|
153 |
+
135: Lemon
|
154 |
+
136: Duck
|
155 |
+
137: Baseball Bat
|
156 |
+
138: Surveillance Camera
|
157 |
+
139: Cat
|
158 |
+
140: Jug
|
159 |
+
141: Broccoli
|
160 |
+
142: Piano
|
161 |
+
143: Pizza
|
162 |
+
144: Elephant
|
163 |
+
145: Skateboard
|
164 |
+
146: Surfboard
|
165 |
+
147: Gun
|
166 |
+
148: Skating and Skiing shoes
|
167 |
+
149: Gas stove
|
168 |
+
150: Donut
|
169 |
+
151: Bow Tie
|
170 |
+
152: Carrot
|
171 |
+
153: Toilet
|
172 |
+
154: Kite
|
173 |
+
155: Strawberry
|
174 |
+
156: Other Balls
|
175 |
+
157: Shovel
|
176 |
+
158: Pepper
|
177 |
+
159: Computer Box
|
178 |
+
160: Toilet Paper
|
179 |
+
161: Cleaning Products
|
180 |
+
162: Chopsticks
|
181 |
+
163: Microwave
|
182 |
+
164: Pigeon
|
183 |
+
165: Baseball
|
184 |
+
166: Cutting/chopping Board
|
185 |
+
167: Coffee Table
|
186 |
+
168: Side Table
|
187 |
+
169: Scissors
|
188 |
+
170: Marker
|
189 |
+
171: Pie
|
190 |
+
172: Ladder
|
191 |
+
173: Snowboard
|
192 |
+
174: Cookies
|
193 |
+
175: Radiator
|
194 |
+
176: Fire Hydrant
|
195 |
+
177: Basketball
|
196 |
+
178: Zebra
|
197 |
+
179: Grape
|
198 |
+
180: Giraffe
|
199 |
+
181: Potato
|
200 |
+
182: Sausage
|
201 |
+
183: Tricycle
|
202 |
+
184: Violin
|
203 |
+
185: Egg
|
204 |
+
186: Fire Extinguisher
|
205 |
+
187: Candy
|
206 |
+
188: Fire Truck
|
207 |
+
189: Billiards
|
208 |
+
190: Converter
|
209 |
+
191: Bathtub
|
210 |
+
192: Wheelchair
|
211 |
+
193: Golf Club
|
212 |
+
194: Briefcase
|
213 |
+
195: Cucumber
|
214 |
+
196: Cigar/Cigarette
|
215 |
+
197: Paint Brush
|
216 |
+
198: Pear
|
217 |
+
199: Heavy Truck
|
218 |
+
200: Hamburger
|
219 |
+
201: Extractor
|
220 |
+
202: Extension Cord
|
221 |
+
203: Tong
|
222 |
+
204: Tennis Racket
|
223 |
+
205: Folder
|
224 |
+
206: American Football
|
225 |
+
207: earphone
|
226 |
+
208: Mask
|
227 |
+
209: Kettle
|
228 |
+
210: Tennis
|
229 |
+
211: Ship
|
230 |
+
212: Swing
|
231 |
+
213: Coffee Machine
|
232 |
+
214: Slide
|
233 |
+
215: Carriage
|
234 |
+
216: Onion
|
235 |
+
217: Green beans
|
236 |
+
218: Projector
|
237 |
+
219: Frisbee
|
238 |
+
220: Washing Machine/Drying Machine
|
239 |
+
221: Chicken
|
240 |
+
222: Printer
|
241 |
+
223: Watermelon
|
242 |
+
224: Saxophone
|
243 |
+
225: Tissue
|
244 |
+
226: Toothbrush
|
245 |
+
227: Ice cream
|
246 |
+
228: Hot-air balloon
|
247 |
+
229: Cello
|
248 |
+
230: French Fries
|
249 |
+
231: Scale
|
250 |
+
232: Trophy
|
251 |
+
233: Cabbage
|
252 |
+
234: Hot dog
|
253 |
+
235: Blender
|
254 |
+
236: Peach
|
255 |
+
237: Rice
|
256 |
+
238: Wallet/Purse
|
257 |
+
239: Volleyball
|
258 |
+
240: Deer
|
259 |
+
241: Goose
|
260 |
+
242: Tape
|
261 |
+
243: Tablet
|
262 |
+
244: Cosmetics
|
263 |
+
245: Trumpet
|
264 |
+
246: Pineapple
|
265 |
+
247: Golf Ball
|
266 |
+
248: Ambulance
|
267 |
+
249: Parking meter
|
268 |
+
250: Mango
|
269 |
+
251: Key
|
270 |
+
252: Hurdle
|
271 |
+
253: Fishing Rod
|
272 |
+
254: Medal
|
273 |
+
255: Flute
|
274 |
+
256: Brush
|
275 |
+
257: Penguin
|
276 |
+
258: Megaphone
|
277 |
+
259: Corn
|
278 |
+
260: Lettuce
|
279 |
+
261: Garlic
|
280 |
+
262: Swan
|
281 |
+
263: Helicopter
|
282 |
+
264: Green Onion
|
283 |
+
265: Sandwich
|
284 |
+
266: Nuts
|
285 |
+
267: Speed Limit Sign
|
286 |
+
268: Induction Cooker
|
287 |
+
269: Broom
|
288 |
+
270: Trombone
|
289 |
+
271: Plum
|
290 |
+
272: Rickshaw
|
291 |
+
273: Goldfish
|
292 |
+
274: Kiwi fruit
|
293 |
+
275: Router/modem
|
294 |
+
276: Poker Card
|
295 |
+
277: Toaster
|
296 |
+
278: Shrimp
|
297 |
+
279: Sushi
|
298 |
+
280: Cheese
|
299 |
+
281: Notepaper
|
300 |
+
282: Cherry
|
301 |
+
283: Pliers
|
302 |
+
284: CD
|
303 |
+
285: Pasta
|
304 |
+
286: Hammer
|
305 |
+
287: Cue
|
306 |
+
288: Avocado
|
307 |
+
289: Hamimelon
|
308 |
+
290: Flask
|
309 |
+
291: Mushroom
|
310 |
+
292: Screwdriver
|
311 |
+
293: Soap
|
312 |
+
294: Recorder
|
313 |
+
295: Bear
|
314 |
+
296: Eggplant
|
315 |
+
297: Board Eraser
|
316 |
+
298: Coconut
|
317 |
+
299: Tape Measure/Ruler
|
318 |
+
300: Pig
|
319 |
+
301: Showerhead
|
320 |
+
302: Globe
|
321 |
+
303: Chips
|
322 |
+
304: Steak
|
323 |
+
305: Crosswalk Sign
|
324 |
+
306: Stapler
|
325 |
+
307: Camel
|
326 |
+
308: Formula 1
|
327 |
+
309: Pomegranate
|
328 |
+
310: Dishwasher
|
329 |
+
311: Crab
|
330 |
+
312: Hoverboard
|
331 |
+
313: Meat ball
|
332 |
+
314: Rice Cooker
|
333 |
+
315: Tuba
|
334 |
+
316: Calculator
|
335 |
+
317: Papaya
|
336 |
+
318: Antelope
|
337 |
+
319: Parrot
|
338 |
+
320: Seal
|
339 |
+
321: Butterfly
|
340 |
+
322: Dumbbell
|
341 |
+
323: Donkey
|
342 |
+
324: Lion
|
343 |
+
325: Urinal
|
344 |
+
326: Dolphin
|
345 |
+
327: Electric Drill
|
346 |
+
328: Hair Dryer
|
347 |
+
329: Egg tart
|
348 |
+
330: Jellyfish
|
349 |
+
331: Treadmill
|
350 |
+
332: Lighter
|
351 |
+
333: Grapefruit
|
352 |
+
334: Game board
|
353 |
+
335: Mop
|
354 |
+
336: Radish
|
355 |
+
337: Baozi
|
356 |
+
338: Target
|
357 |
+
339: French
|
358 |
+
340: Spring Rolls
|
359 |
+
341: Monkey
|
360 |
+
342: Rabbit
|
361 |
+
343: Pencil Case
|
362 |
+
344: Yak
|
363 |
+
345: Red Cabbage
|
364 |
+
346: Binoculars
|
365 |
+
347: Asparagus
|
366 |
+
348: Barbell
|
367 |
+
349: Scallop
|
368 |
+
350: Noddles
|
369 |
+
351: Comb
|
370 |
+
352: Dumpling
|
371 |
+
353: Oyster
|
372 |
+
354: Table Tennis paddle
|
373 |
+
355: Cosmetics Brush/Eyeliner Pencil
|
374 |
+
356: Chainsaw
|
375 |
+
357: Eraser
|
376 |
+
358: Lobster
|
377 |
+
359: Durian
|
378 |
+
360: Okra
|
379 |
+
361: Lipstick
|
380 |
+
362: Cosmetics Mirror
|
381 |
+
363: Curling
|
382 |
+
364: Table Tennis
|
383 |
+
|
384 |
+
|
385 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
386 |
+
download: |
|
387 |
+
from tqdm import tqdm
|
388 |
+
|
389 |
+
from utils.general import Path, check_requirements, download, np, xyxy2xywhn
|
390 |
+
|
391 |
+
check_requirements(('pycocotools>=2.0',))
|
392 |
+
from pycocotools.coco import COCO
|
393 |
+
|
394 |
+
# Make Directories
|
395 |
+
dir = Path(yaml['path']) # dataset root dir
|
396 |
+
for p in 'images', 'labels':
|
397 |
+
(dir / p).mkdir(parents=True, exist_ok=True)
|
398 |
+
for q in 'train', 'val':
|
399 |
+
(dir / p / q).mkdir(parents=True, exist_ok=True)
|
400 |
+
|
401 |
+
# Train, Val Splits
|
402 |
+
for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:
|
403 |
+
print(f"Processing {split} in {patches} patches ...")
|
404 |
+
images, labels = dir / 'images' / split, dir / 'labels' / split
|
405 |
+
|
406 |
+
# Download
|
407 |
+
url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/"
|
408 |
+
if split == 'train':
|
409 |
+
download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json
|
410 |
+
download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8)
|
411 |
+
elif split == 'val':
|
412 |
+
download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json
|
413 |
+
download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8)
|
414 |
+
download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8)
|
415 |
+
|
416 |
+
# Move
|
417 |
+
for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):
|
418 |
+
f.rename(images / f.name) # move to /images/{split}
|
419 |
+
|
420 |
+
# Labels
|
421 |
+
coco = COCO(dir / f'zhiyuan_objv2_{split}.json')
|
422 |
+
names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
|
423 |
+
for cid, cat in enumerate(names):
|
424 |
+
catIds = coco.getCatIds(catNms=[cat])
|
425 |
+
imgIds = coco.getImgIds(catIds=catIds)
|
426 |
+
for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
|
427 |
+
width, height = im["width"], im["height"]
|
428 |
+
path = Path(im["file_name"]) # image filename
|
429 |
+
try:
|
430 |
+
with open(labels / path.with_suffix('.txt').name, 'a') as file:
|
431 |
+
annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
|
432 |
+
for a in coco.loadAnns(annIds):
|
433 |
+
x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
|
434 |
+
xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4)
|
435 |
+
x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped
|
436 |
+
file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n")
|
437 |
+
except Exception as e:
|
438 |
+
print(e)
|
data/SKU-110K.yaml
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail
|
3 |
+
# Example usage: python train.py --data SKU-110K.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ SKU-110K β downloads here (13.6 GB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/SKU-110K # dataset root dir
|
12 |
+
train: train.txt # train images (relative to 'path') 8219 images
|
13 |
+
val: val.txt # val images (relative to 'path') 588 images
|
14 |
+
test: test.txt # test images (optional) 2936 images
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: object
|
19 |
+
|
20 |
+
|
21 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
22 |
+
download: |
|
23 |
+
import shutil
|
24 |
+
from tqdm import tqdm
|
25 |
+
from utils.general import np, pd, Path, download, xyxy2xywh
|
26 |
+
|
27 |
+
|
28 |
+
# Download
|
29 |
+
dir = Path(yaml['path']) # dataset root dir
|
30 |
+
parent = Path(dir.parent) # download dir
|
31 |
+
urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
|
32 |
+
download(urls, dir=parent, delete=False)
|
33 |
+
|
34 |
+
# Rename directories
|
35 |
+
if dir.exists():
|
36 |
+
shutil.rmtree(dir)
|
37 |
+
(parent / 'SKU110K_fixed').rename(dir) # rename dir
|
38 |
+
(dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
|
39 |
+
|
40 |
+
# Convert labels
|
41 |
+
names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
|
42 |
+
for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
|
43 |
+
x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
|
44 |
+
images, unique_images = x[:, 0], np.unique(x[:, 0])
|
45 |
+
with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
|
46 |
+
f.writelines(f'./images/{s}\n' for s in unique_images)
|
47 |
+
for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
|
48 |
+
cls = 0 # single-class dataset
|
49 |
+
with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
|
50 |
+
for r in x[images == im]:
|
51 |
+
w, h = r[6], r[7] # image width, height
|
52 |
+
xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
|
53 |
+
f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
|
data/VOC.yaml
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford
|
3 |
+
# Example usage: python train.py --data VOC.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ VOC β downloads here (2.8 GB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/VOC
|
12 |
+
train: # train images (relative to 'path') 16551 images
|
13 |
+
- images/train2012
|
14 |
+
- images/train2007
|
15 |
+
- images/val2012
|
16 |
+
- images/val2007
|
17 |
+
val: # val images (relative to 'path') 4952 images
|
18 |
+
- images/test2007
|
19 |
+
test: # test images (optional)
|
20 |
+
- images/test2007
|
21 |
+
|
22 |
+
# Classes
|
23 |
+
names:
|
24 |
+
0: aeroplane
|
25 |
+
1: bicycle
|
26 |
+
2: bird
|
27 |
+
3: boat
|
28 |
+
4: bottle
|
29 |
+
5: bus
|
30 |
+
6: car
|
31 |
+
7: cat
|
32 |
+
8: chair
|
33 |
+
9: cow
|
34 |
+
10: diningtable
|
35 |
+
11: dog
|
36 |
+
12: horse
|
37 |
+
13: motorbike
|
38 |
+
14: person
|
39 |
+
15: pottedplant
|
40 |
+
16: sheep
|
41 |
+
17: sofa
|
42 |
+
18: train
|
43 |
+
19: tvmonitor
|
44 |
+
|
45 |
+
|
46 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
47 |
+
download: |
|
48 |
+
import xml.etree.ElementTree as ET
|
49 |
+
|
50 |
+
from tqdm import tqdm
|
51 |
+
from utils.general import download, Path
|
52 |
+
|
53 |
+
|
54 |
+
def convert_label(path, lb_path, year, image_id):
|
55 |
+
def convert_box(size, box):
|
56 |
+
dw, dh = 1. / size[0], 1. / size[1]
|
57 |
+
x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
|
58 |
+
return x * dw, y * dh, w * dw, h * dh
|
59 |
+
|
60 |
+
in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
|
61 |
+
out_file = open(lb_path, 'w')
|
62 |
+
tree = ET.parse(in_file)
|
63 |
+
root = tree.getroot()
|
64 |
+
size = root.find('size')
|
65 |
+
w = int(size.find('width').text)
|
66 |
+
h = int(size.find('height').text)
|
67 |
+
|
68 |
+
names = list(yaml['names'].values()) # names list
|
69 |
+
for obj in root.iter('object'):
|
70 |
+
cls = obj.find('name').text
|
71 |
+
if cls in names and int(obj.find('difficult').text) != 1:
|
72 |
+
xmlbox = obj.find('bndbox')
|
73 |
+
bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
|
74 |
+
cls_id = names.index(cls) # class id
|
75 |
+
out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
|
76 |
+
|
77 |
+
|
78 |
+
# Download
|
79 |
+
dir = Path(yaml['path']) # dataset root dir
|
80 |
+
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
81 |
+
urls = [f'{url}VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
|
82 |
+
f'{url}VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
|
83 |
+
f'{url}VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
|
84 |
+
download(urls, dir=dir / 'images', delete=False, curl=True, threads=3)
|
85 |
+
|
86 |
+
# Convert
|
87 |
+
path = dir / 'images/VOCdevkit'
|
88 |
+
for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
|
89 |
+
imgs_path = dir / 'images' / f'{image_set}{year}'
|
90 |
+
lbs_path = dir / 'labels' / f'{image_set}{year}'
|
91 |
+
imgs_path.mkdir(exist_ok=True, parents=True)
|
92 |
+
lbs_path.mkdir(exist_ok=True, parents=True)
|
93 |
+
|
94 |
+
with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:
|
95 |
+
image_ids = f.read().strip().split()
|
96 |
+
for id in tqdm(image_ids, desc=f'{image_set}{year}'):
|
97 |
+
f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
|
98 |
+
lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
|
99 |
+
f.rename(imgs_path / f.name) # move image
|
100 |
+
convert_label(path, lb_path, year, id) # convert labels to YOLO format
|
data/VisDrone.yaml
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University
|
3 |
+
# Example usage: python train.py --data VisDrone.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ VisDrone β downloads here (2.3 GB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/VisDrone # dataset root dir
|
12 |
+
train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
|
13 |
+
val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
|
14 |
+
test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: pedestrian
|
19 |
+
1: people
|
20 |
+
2: bicycle
|
21 |
+
3: car
|
22 |
+
4: van
|
23 |
+
5: truck
|
24 |
+
6: tricycle
|
25 |
+
7: awning-tricycle
|
26 |
+
8: bus
|
27 |
+
9: motor
|
28 |
+
|
29 |
+
|
30 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
31 |
+
download: |
|
32 |
+
from utils.general import download, os, Path
|
33 |
+
|
34 |
+
def visdrone2yolo(dir):
|
35 |
+
from PIL import Image
|
36 |
+
from tqdm import tqdm
|
37 |
+
|
38 |
+
def convert_box(size, box):
|
39 |
+
# Convert VisDrone box to YOLO xywh box
|
40 |
+
dw = 1. / size[0]
|
41 |
+
dh = 1. / size[1]
|
42 |
+
return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
|
43 |
+
|
44 |
+
(dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
|
45 |
+
pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
|
46 |
+
for f in pbar:
|
47 |
+
img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
|
48 |
+
lines = []
|
49 |
+
with open(f, 'r') as file: # read annotation.txt
|
50 |
+
for row in [x.split(',') for x in file.read().strip().splitlines()]:
|
51 |
+
if row[4] == '0': # VisDrone 'ignored regions' class 0
|
52 |
+
continue
|
53 |
+
cls = int(row[5]) - 1
|
54 |
+
box = convert_box(img_size, tuple(map(int, row[:4])))
|
55 |
+
lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
|
56 |
+
with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
|
57 |
+
fl.writelines(lines) # write label.txt
|
58 |
+
|
59 |
+
|
60 |
+
# Download
|
61 |
+
dir = Path(yaml['path']) # dataset root dir
|
62 |
+
urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
|
63 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
|
64 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
|
65 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
|
66 |
+
download(urls, dir=dir, curl=True, threads=4)
|
67 |
+
|
68 |
+
# Convert
|
69 |
+
for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
|
70 |
+
visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
|
data/coco.yaml
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# COCO 2017 dataset http://cocodataset.org by Microsoft
|
3 |
+
# Example usage: python train.py --data coco.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ coco β downloads here (20.1 GB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/coco # dataset root dir
|
12 |
+
train: train2017.txt # train images (relative to 'path') 118287 images
|
13 |
+
val: val2017.txt # val images (relative to 'path') 5000 images
|
14 |
+
test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: person
|
19 |
+
1: bicycle
|
20 |
+
2: car
|
21 |
+
3: motorcycle
|
22 |
+
4: airplane
|
23 |
+
5: bus
|
24 |
+
6: train
|
25 |
+
7: truck
|
26 |
+
8: boat
|
27 |
+
9: traffic light
|
28 |
+
10: fire hydrant
|
29 |
+
11: stop sign
|
30 |
+
12: parking meter
|
31 |
+
13: bench
|
32 |
+
14: bird
|
33 |
+
15: cat
|
34 |
+
16: dog
|
35 |
+
17: horse
|
36 |
+
18: sheep
|
37 |
+
19: cow
|
38 |
+
20: elephant
|
39 |
+
21: bear
|
40 |
+
22: zebra
|
41 |
+
23: giraffe
|
42 |
+
24: backpack
|
43 |
+
25: umbrella
|
44 |
+
26: handbag
|
45 |
+
27: tie
|
46 |
+
28: suitcase
|
47 |
+
29: frisbee
|
48 |
+
30: skis
|
49 |
+
31: snowboard
|
50 |
+
32: sports ball
|
51 |
+
33: kite
|
52 |
+
34: baseball bat
|
53 |
+
35: baseball glove
|
54 |
+
36: skateboard
|
55 |
+
37: surfboard
|
56 |
+
38: tennis racket
|
57 |
+
39: bottle
|
58 |
+
40: wine glass
|
59 |
+
41: cup
|
60 |
+
42: fork
|
61 |
+
43: knife
|
62 |
+
44: spoon
|
63 |
+
45: bowl
|
64 |
+
46: banana
|
65 |
+
47: apple
|
66 |
+
48: sandwich
|
67 |
+
49: orange
|
68 |
+
50: broccoli
|
69 |
+
51: carrot
|
70 |
+
52: hot dog
|
71 |
+
53: pizza
|
72 |
+
54: donut
|
73 |
+
55: cake
|
74 |
+
56: chair
|
75 |
+
57: couch
|
76 |
+
58: potted plant
|
77 |
+
59: bed
|
78 |
+
60: dining table
|
79 |
+
61: toilet
|
80 |
+
62: tv
|
81 |
+
63: laptop
|
82 |
+
64: mouse
|
83 |
+
65: remote
|
84 |
+
66: keyboard
|
85 |
+
67: cell phone
|
86 |
+
68: microwave
|
87 |
+
69: oven
|
88 |
+
70: toaster
|
89 |
+
71: sink
|
90 |
+
72: refrigerator
|
91 |
+
73: book
|
92 |
+
74: clock
|
93 |
+
75: vase
|
94 |
+
76: scissors
|
95 |
+
77: teddy bear
|
96 |
+
78: hair drier
|
97 |
+
79: toothbrush
|
98 |
+
|
99 |
+
|
100 |
+
# Download script/URL (optional)
|
101 |
+
download: |
|
102 |
+
from utils.general import download, Path
|
103 |
+
|
104 |
+
|
105 |
+
# Download labels
|
106 |
+
segments = False # segment or box labels
|
107 |
+
dir = Path(yaml['path']) # dataset root dir
|
108 |
+
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
109 |
+
urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
|
110 |
+
download(urls, dir=dir.parent)
|
111 |
+
|
112 |
+
# Download data
|
113 |
+
urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
|
114 |
+
'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
|
115 |
+
'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
|
116 |
+
download(urls, dir=dir / 'images', threads=3)
|
data/coco128-seg.yaml
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# COCO128-seg dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics
|
3 |
+
# Example usage: python train.py --data coco128.yaml
|
4 |
+
# parent
|
5 |
+
# βββ yolov5
|
6 |
+
# βββ datasets
|
7 |
+
# βββ coco128-seg β downloads here (7 MB)
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/coco128-seg # dataset root dir
|
12 |
+
train: images/train2017 # train images (relative to 'path') 128 images
|
13 |
+
val: images/train2017 # val images (relative to 'path') 128 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: person
|
19 |
+
1: bicycle
|
20 |
+
2: car
|
21 |
+
3: motorcycle
|
22 |
+
4: airplane
|
23 |
+
5: bus
|
24 |
+
6: train
|
25 |
+
7: truck
|
26 |
+
8: boat
|
27 |
+
9: traffic light
|
28 |
+
10: fire hydrant
|
29 |
+
11: stop sign
|
30 |
+
12: parking meter
|
31 |
+
13: bench
|
32 |
+
14: bird
|
33 |
+
15: cat
|
34 |
+
16: dog
|
35 |
+
17: horse
|
36 |
+
18: sheep
|
37 |
+
19: cow
|
38 |
+
20: elephant
|
39 |
+
21: bear
|
40 |
+
22: zebra
|
41 |
+
23: giraffe
|
42 |
+
24: backpack
|
43 |
+
25: umbrella
|
44 |
+
26: handbag
|
45 |
+
27: tie
|
46 |
+
28: suitcase
|
47 |
+
29: frisbee
|
48 |
+
30: skis
|
49 |
+
31: snowboard
|
50 |
+
32: sports ball
|
51 |
+
33: kite
|
52 |
+
34: baseball bat
|
53 |
+
35: baseball glove
|
54 |
+
36: skateboard
|
55 |
+
37: surfboard
|
56 |
+
38: tennis racket
|
57 |
+
39: bottle
|
58 |
+
40: wine glass
|
59 |
+
41: cup
|
60 |
+
42: fork
|
61 |
+
43: knife
|
62 |
+
44: spoon
|
63 |
+
45: bowl
|
64 |
+
46: banana
|
65 |
+
47: apple
|
66 |
+
48: sandwich
|
67 |
+
49: orange
|
68 |
+
50: broccoli
|
69 |
+
51: carrot
|
70 |
+
52: hot dog
|
71 |
+
53: pizza
|
72 |
+
54: donut
|
73 |
+
55: cake
|
74 |
+
56: chair
|
75 |
+
57: couch
|
76 |
+
58: potted plant
|
77 |
+
59: bed
|
78 |
+
60: dining table
|
79 |
+
61: toilet
|
80 |
+
62: tv
|
81 |
+
63: laptop
|
82 |
+
64: mouse
|
83 |
+
65: remote
|
84 |
+
66: keyboard
|
85 |
+
67: cell phone
|
86 |
+
68: microwave
|
87 |
+
69: oven
|
88 |
+
70: toaster
|
89 |
+
71: sink
|
90 |
+
72: refrigerator
|
91 |
+
73: book
|
92 |
+
74: clock
|
93 |
+
75: vase
|
94 |
+
76: scissors
|
95 |
+
77: teddy bear
|
96 |
+
78: hair drier
|
97 |
+
79: toothbrush
|
98 |
+
|
99 |
+
|
100 |
+
# Download script/URL (optional)
|
101 |
+
download: https://ultralytics.com/assets/coco128-seg.zip
|
data/coco128.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
path: ./data/train_data/images # dataset root dir
|
2 |
+
train: train # train images (relative to 'path') 128 images
|
3 |
+
val: val # val images (relative to 'path') 128 images
|
4 |
+
|
5 |
+
# Classes
|
6 |
+
names:
|
7 |
+
0: bee
|
data/custom_data.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
path: ./data/train_data/images # dataset root dir
|
2 |
+
train: train # train images (relative to 'path') 128 images
|
3 |
+
val: val # val images (relative to 'path') 128 images
|
4 |
+
|
5 |
+
# Classes
|
6 |
+
names:
|
7 |
+
0: bee
|
data/hyps/hyp.Objects365.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for Objects365 training
|
3 |
+
# python train.py --weights yolov5m.pt --data Objects365.yaml --evolve
|
4 |
+
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.00258
|
7 |
+
lrf: 0.17
|
8 |
+
momentum: 0.779
|
9 |
+
weight_decay: 0.00058
|
10 |
+
warmup_epochs: 1.33
|
11 |
+
warmup_momentum: 0.86
|
12 |
+
warmup_bias_lr: 0.0711
|
13 |
+
box: 0.0539
|
14 |
+
cls: 0.299
|
15 |
+
cls_pw: 0.825
|
16 |
+
obj: 0.632
|
17 |
+
obj_pw: 1.0
|
18 |
+
iou_t: 0.2
|
19 |
+
anchor_t: 3.44
|
20 |
+
anchors: 3.2
|
21 |
+
fl_gamma: 0.0
|
22 |
+
hsv_h: 0.0188
|
23 |
+
hsv_s: 0.704
|
24 |
+
hsv_v: 0.36
|
25 |
+
degrees: 0.0
|
26 |
+
translate: 0.0902
|
27 |
+
scale: 0.491
|
28 |
+
shear: 0.0
|
29 |
+
perspective: 0.0
|
30 |
+
flipud: 0.0
|
31 |
+
fliplr: 0.5
|
32 |
+
mosaic: 1.0
|
33 |
+
mixup: 0.0
|
34 |
+
copy_paste: 0.0
|
data/hyps/hyp.VOC.yaml
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for VOC training
|
3 |
+
# python train.py --batch 128 --weights yolov5m6.pt --data VOC.yaml --epochs 50 --img 512 --hyp hyp.scratch-med.yaml --evolve
|
4 |
+
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
# YOLOv5 Hyperparameter Evolution Results
|
7 |
+
# Best generation: 467
|
8 |
+
# Last generation: 996
|
9 |
+
# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss
|
10 |
+
# 0.87729, 0.85125, 0.91286, 0.72664, 0.0076739, 0.0042529, 0.0013865
|
11 |
+
|
12 |
+
lr0: 0.00334
|
13 |
+
lrf: 0.15135
|
14 |
+
momentum: 0.74832
|
15 |
+
weight_decay: 0.00025
|
16 |
+
warmup_epochs: 3.3835
|
17 |
+
warmup_momentum: 0.59462
|
18 |
+
warmup_bias_lr: 0.18657
|
19 |
+
box: 0.02
|
20 |
+
cls: 0.21638
|
21 |
+
cls_pw: 0.5
|
22 |
+
obj: 0.51728
|
23 |
+
obj_pw: 0.67198
|
24 |
+
iou_t: 0.2
|
25 |
+
anchor_t: 3.3744
|
26 |
+
fl_gamma: 0.0
|
27 |
+
hsv_h: 0.01041
|
28 |
+
hsv_s: 0.54703
|
29 |
+
hsv_v: 0.27739
|
30 |
+
degrees: 0.0
|
31 |
+
translate: 0.04591
|
32 |
+
scale: 0.75544
|
33 |
+
shear: 0.0
|
34 |
+
perspective: 0.0
|
35 |
+
flipud: 0.0
|
36 |
+
fliplr: 0.5
|
37 |
+
mosaic: 0.85834
|
38 |
+
mixup: 0.04266
|
39 |
+
copy_paste: 0.0
|
40 |
+
anchors: 3.412
|
data/hyps/hyp.scratch-high.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for high-augmentation COCO training from scratch
|
3 |
+
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.3 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 0.7 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.9 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.1 # image mixup (probability)
|
34 |
+
copy_paste: 0.1 # segment copy-paste (probability)
|
data/hyps/hyp.scratch-low.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for low-augmentation COCO training from scratch
|
3 |
+
# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.5 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 1.0 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.5 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.0 # image mixup (probability)
|
34 |
+
copy_paste: 0.0 # segment copy-paste (probability)
|
data/hyps/hyp.scratch-med.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for medium-augmentation COCO training from scratch
|
3 |
+
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.3 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 0.7 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.9 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.1 # image mixup (probability)
|
34 |
+
copy_paste: 0.0 # segment copy-paste (probability)
|
data/scripts/download_weights.sh
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
3 |
+
# Download latest models from https://github.com/ultralytics/yolov5/releases
|
4 |
+
# Example usage: bash data/scripts/download_weights.sh
|
5 |
+
# parent
|
6 |
+
# βββ yolov5
|
7 |
+
# βββ yolov5s.pt β downloads here
|
8 |
+
# βββ yolov5m.pt
|
9 |
+
# βββ ...
|
10 |
+
|
11 |
+
python - <<EOF
|
12 |
+
from utils.downloads import attempt_download
|
13 |
+
|
14 |
+
p5 = ['n', 's', 'm', 'l', 'x'] # P5 models
|
15 |
+
p6 = [f'{x}6' for x in p5] # P6 models
|
16 |
+
cls = [f'{x}-cls' for x in p5] # classification models
|
17 |
+
|
18 |
+
for x in p5 + p6 + cls:
|
19 |
+
attempt_download(f'weights/yolov5{x}.pt')
|
20 |
+
|
21 |
+
EOF
|
data/scripts/get_coco.sh
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
3 |
+
# Download COCO 2017 dataset http://cocodataset.org
|
4 |
+
# Example usage: bash data/scripts/get_coco.sh
|
5 |
+
# parent
|
6 |
+
# βββ yolov5
|
7 |
+
# βββ datasets
|
8 |
+
# βββ coco β downloads here
|
9 |
+
|
10 |
+
# Arguments (optional) Usage: bash data/scripts/get_coco.sh --train --val --test --segments
|
11 |
+
if [ "$#" -gt 0 ]; then
|
12 |
+
for opt in "$@"; do
|
13 |
+
case "${opt}" in
|
14 |
+
--train) train=true ;;
|
15 |
+
--val) val=true ;;
|
16 |
+
--test) test=true ;;
|
17 |
+
--segments) segments=true ;;
|
18 |
+
esac
|
19 |
+
done
|
20 |
+
else
|
21 |
+
train=true
|
22 |
+
val=true
|
23 |
+
test=false
|
24 |
+
segments=false
|
25 |
+
fi
|
26 |
+
|
27 |
+
# Download/unzip labels
|
28 |
+
d='../datasets' # unzip directory
|
29 |
+
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
30 |
+
if [ "$segments" == "true" ]; then
|
31 |
+
f='coco2017labels-segments.zip' # 168 MB
|
32 |
+
else
|
33 |
+
f='coco2017labels.zip' # 168 MB
|
34 |
+
fi
|
35 |
+
echo 'Downloading' $url$f ' ...'
|
36 |
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
37 |
+
|
38 |
+
# Download/unzip images
|
39 |
+
d='../datasets/coco/images' # unzip directory
|
40 |
+
url=http://images.cocodataset.org/zips/
|
41 |
+
if [ "$train" == "true" ]; then
|
42 |
+
f='train2017.zip' # 19G, 118k images
|
43 |
+
echo 'Downloading' $url$f '...'
|
44 |
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
45 |
+
fi
|
46 |
+
if [ "$val" == "true" ]; then
|
47 |
+
f='val2017.zip' # 1G, 5k images
|
48 |
+
echo 'Downloading' $url$f '...'
|
49 |
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
50 |
+
fi
|
51 |
+
if [ "$test" == "true" ]; then
|
52 |
+
f='test2017.zip' # 7G, 41k images (optional)
|
53 |
+
echo 'Downloading' $url$f '...'
|
54 |
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
55 |
+
fi
|
56 |
+
wait # finish background tasks
|
data/scripts/get_coco128.sh
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
3 |
+
# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
|
4 |
+
# Example usage: bash data/scripts/get_coco128.sh
|
5 |
+
# parent
|
6 |
+
# βββ yolov5
|
7 |
+
# βββ datasets
|
8 |
+
# βββ coco128 β downloads here
|
9 |
+
|
10 |
+
# Download/unzip images and labels
|
11 |
+
d='../datasets' # unzip directory
|
12 |
+
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
13 |
+
f='coco128.zip' # or 'coco128-segments.zip', 68 MB
|
14 |
+
echo 'Downloading' $url$f ' ...'
|
15 |
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
16 |
+
|
17 |
+
wait # finish background tasks
|
data/scripts/get_imagenet.sh
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
3 |
+
# Download ILSVRC2012 ImageNet dataset https://image-net.org
|
4 |
+
# Example usage: bash data/scripts/get_imagenet.sh
|
5 |
+
# parent
|
6 |
+
# βββ yolov5
|
7 |
+
# βββ datasets
|
8 |
+
# βββ imagenet β downloads here
|
9 |
+
|
10 |
+
# Arguments (optional) Usage: bash data/scripts/get_imagenet.sh --train --val
|
11 |
+
if [ "$#" -gt 0 ]; then
|
12 |
+
for opt in "$@"; do
|
13 |
+
case "${opt}" in
|
14 |
+
--train) train=true ;;
|
15 |
+
--val) val=true ;;
|
16 |
+
esac
|
17 |
+
done
|
18 |
+
else
|
19 |
+
train=true
|
20 |
+
val=true
|
21 |
+
fi
|
22 |
+
|
23 |
+
# Make dir
|
24 |
+
d='../datasets/imagenet' # unzip directory
|
25 |
+
mkdir -p $d && cd $d
|
26 |
+
|
27 |
+
# Download/unzip train
|
28 |
+
if [ "$train" == "true" ]; then
|
29 |
+
wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_train.tar # download 138G, 1281167 images
|
30 |
+
mkdir train && mv ILSVRC2012_img_train.tar train/ && cd train
|
31 |
+
tar -xf ILSVRC2012_img_train.tar && rm -f ILSVRC2012_img_train.tar
|
32 |
+
find . -name "*.tar" | while read NAME; do
|
33 |
+
mkdir -p "${NAME%.tar}"
|
34 |
+
tar -xf "${NAME}" -C "${NAME%.tar}"
|
35 |
+
rm -f "${NAME}"
|
36 |
+
done
|
37 |
+
cd ..
|
38 |
+
fi
|
39 |
+
|
40 |
+
# Download/unzip val
|
41 |
+
if [ "$val" == "true" ]; then
|
42 |
+
wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar # download 6.3G, 50000 images
|
43 |
+
mkdir val && mv ILSVRC2012_img_val.tar val/ && cd val && tar -xf ILSVRC2012_img_val.tar
|
44 |
+
wget -qO- https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh | bash # move into subdirs
|
45 |
+
fi
|
46 |
+
|
47 |
+
# Delete corrupted image (optional: PNG under JPEG name that may cause dataloaders to fail)
|
48 |
+
# rm train/n04266014/n04266014_10835.JPEG
|
49 |
+
|
50 |
+
# TFRecords (optional)
|
51 |
+
# wget https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_lsvrc_2015_synsets.txt
|
data/xView.yaml
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# DIUx xView 2018 Challenge https://challenge.xviewdataset.org by U.S. National Geospatial-Intelligence Agency (NGA)
|
3 |
+
# -------- DOWNLOAD DATA MANUALLY and jar xf val_images.zip to 'datasets/xView' before running train command! --------
|
4 |
+
# Example usage: python train.py --data xView.yaml
|
5 |
+
# parent
|
6 |
+
# βββ yolov5
|
7 |
+
# βββ datasets
|
8 |
+
# βββ xView β downloads here (20.7 GB)
|
9 |
+
|
10 |
+
|
11 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
12 |
+
path: ../datasets/xView # dataset root dir
|
13 |
+
train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images
|
14 |
+
val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: Fixed-wing Aircraft
|
19 |
+
1: Small Aircraft
|
20 |
+
2: Cargo Plane
|
21 |
+
3: Helicopter
|
22 |
+
4: Passenger Vehicle
|
23 |
+
5: Small Car
|
24 |
+
6: Bus
|
25 |
+
7: Pickup Truck
|
26 |
+
8: Utility Truck
|
27 |
+
9: Truck
|
28 |
+
10: Cargo Truck
|
29 |
+
11: Truck w/Box
|
30 |
+
12: Truck Tractor
|
31 |
+
13: Trailer
|
32 |
+
14: Truck w/Flatbed
|
33 |
+
15: Truck w/Liquid
|
34 |
+
16: Crane Truck
|
35 |
+
17: Railway Vehicle
|
36 |
+
18: Passenger Car
|
37 |
+
19: Cargo Car
|
38 |
+
20: Flat Car
|
39 |
+
21: Tank car
|
40 |
+
22: Locomotive
|
41 |
+
23: Maritime Vessel
|
42 |
+
24: Motorboat
|
43 |
+
25: Sailboat
|
44 |
+
26: Tugboat
|
45 |
+
27: Barge
|
46 |
+
28: Fishing Vessel
|
47 |
+
29: Ferry
|
48 |
+
30: Yacht
|
49 |
+
31: Container Ship
|
50 |
+
32: Oil Tanker
|
51 |
+
33: Engineering Vehicle
|
52 |
+
34: Tower crane
|
53 |
+
35: Container Crane
|
54 |
+
36: Reach Stacker
|
55 |
+
37: Straddle Carrier
|
56 |
+
38: Mobile Crane
|
57 |
+
39: Dump Truck
|
58 |
+
40: Haul Truck
|
59 |
+
41: Scraper/Tractor
|
60 |
+
42: Front loader/Bulldozer
|
61 |
+
43: Excavator
|
62 |
+
44: Cement Mixer
|
63 |
+
45: Ground Grader
|
64 |
+
46: Hut/Tent
|
65 |
+
47: Shed
|
66 |
+
48: Building
|
67 |
+
49: Aircraft Hangar
|
68 |
+
50: Damaged Building
|
69 |
+
51: Facility
|
70 |
+
52: Construction Site
|
71 |
+
53: Vehicle Lot
|
72 |
+
54: Helipad
|
73 |
+
55: Storage Tank
|
74 |
+
56: Shipping container lot
|
75 |
+
57: Shipping Container
|
76 |
+
58: Pylon
|
77 |
+
59: Tower
|
78 |
+
|
79 |
+
|
80 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
81 |
+
download: |
|
82 |
+
import json
|
83 |
+
import os
|
84 |
+
from pathlib import Path
|
85 |
+
|
86 |
+
import numpy as np
|
87 |
+
from PIL import Image
|
88 |
+
from tqdm import tqdm
|
89 |
+
|
90 |
+
from utils.dataloaders import autosplit
|
91 |
+
from utils.general import download, xyxy2xywhn
|
92 |
+
|
93 |
+
|
94 |
+
def convert_labels(fname=Path('xView/xView_train.geojson')):
|
95 |
+
# Convert xView geoJSON labels to YOLO format
|
96 |
+
path = fname.parent
|
97 |
+
with open(fname) as f:
|
98 |
+
print(f'Loading {fname}...')
|
99 |
+
data = json.load(f)
|
100 |
+
|
101 |
+
# Make dirs
|
102 |
+
labels = Path(path / 'labels' / 'train')
|
103 |
+
os.system(f'rm -rf {labels}')
|
104 |
+
labels.mkdir(parents=True, exist_ok=True)
|
105 |
+
|
106 |
+
# xView classes 11-94 to 0-59
|
107 |
+
xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11,
|
108 |
+
12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,
|
109 |
+
29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,
|
110 |
+
47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]
|
111 |
+
|
112 |
+
shapes = {}
|
113 |
+
for feature in tqdm(data['features'], desc=f'Converting {fname}'):
|
114 |
+
p = feature['properties']
|
115 |
+
if p['bounds_imcoords']:
|
116 |
+
id = p['image_id']
|
117 |
+
file = path / 'train_images' / id
|
118 |
+
if file.exists(): # 1395.tif missing
|
119 |
+
try:
|
120 |
+
box = np.array([int(num) for num in p['bounds_imcoords'].split(",")])
|
121 |
+
assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'
|
122 |
+
cls = p['type_id']
|
123 |
+
cls = xview_class2index[int(cls)] # xView class to 0-60
|
124 |
+
assert 59 >= cls >= 0, f'incorrect class index {cls}'
|
125 |
+
|
126 |
+
# Write YOLO label
|
127 |
+
if id not in shapes:
|
128 |
+
shapes[id] = Image.open(file).size
|
129 |
+
box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)
|
130 |
+
with open((labels / id).with_suffix('.txt'), 'a') as f:
|
131 |
+
f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt
|
132 |
+
except Exception as e:
|
133 |
+
print(f'WARNING: skipping one label for {file}: {e}')
|
134 |
+
|
135 |
+
|
136 |
+
# Download manually from https://challenge.xviewdataset.org
|
137 |
+
dir = Path(yaml['path']) # dataset root dir
|
138 |
+
# urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels
|
139 |
+
# 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images
|
140 |
+
# 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels)
|
141 |
+
# download(urls, dir=dir, delete=False)
|
142 |
+
|
143 |
+
# Convert labels
|
144 |
+
convert_labels(dir / 'xView_train.geojson')
|
145 |
+
|
146 |
+
# Move images
|
147 |
+
images = Path(dir / 'images')
|
148 |
+
images.mkdir(parents=True, exist_ok=True)
|
149 |
+
Path(dir / 'train_images').rename(dir / 'images' / 'train')
|
150 |
+
Path(dir / 'val_images').rename(dir / 'images' / 'val')
|
151 |
+
|
152 |
+
# Split
|
153 |
+
autosplit(dir / 'images' / 'train')
|
export.py
ADDED
@@ -0,0 +1,617 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
|
4 |
+
|
5 |
+
Format | `export.py --include` | Model
|
6 |
+
--- | --- | ---
|
7 |
+
PyTorch | - | yolov5s.pt
|
8 |
+
TorchScript | `torchscript` | yolov5s.torchscript
|
9 |
+
ONNX | `onnx` | yolov5s.onnx
|
10 |
+
OpenVINO | `openvino` | yolov5s_openvino_model/
|
11 |
+
TensorRT | `engine` | yolov5s.engine
|
12 |
+
CoreML | `coreml` | yolov5s.mlmodel
|
13 |
+
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
|
14 |
+
TensorFlow GraphDef | `pb` | yolov5s.pb
|
15 |
+
TensorFlow Lite | `tflite` | yolov5s.tflite
|
16 |
+
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
|
17 |
+
TensorFlow.js | `tfjs` | yolov5s_web_model/
|
18 |
+
PaddlePaddle | `paddle` | yolov5s_paddle_model/
|
19 |
+
|
20 |
+
Requirements:
|
21 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
|
22 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
|
23 |
+
|
24 |
+
Usage:
|
25 |
+
$ python export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
|
26 |
+
|
27 |
+
Inference:
|
28 |
+
$ python sample_solution.py --weights yolov5s.pt # PyTorch
|
29 |
+
yolov5s.torchscript # TorchScript
|
30 |
+
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
31 |
+
yolov5s_openvino_model # OpenVINO
|
32 |
+
yolov5s.engine # TensorRT
|
33 |
+
yolov5s.mlmodel # CoreML (macOS-only)
|
34 |
+
yolov5s_saved_model # TensorFlow SavedModel
|
35 |
+
yolov5s.pb # TensorFlow GraphDef
|
36 |
+
yolov5s.tflite # TensorFlow Lite
|
37 |
+
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
38 |
+
yolov5s_paddle_model # PaddlePaddle
|
39 |
+
|
40 |
+
TensorFlow.js:
|
41 |
+
$ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
|
42 |
+
$ npm install
|
43 |
+
$ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
|
44 |
+
$ npm start
|
45 |
+
"""
|
46 |
+
|
47 |
+
import argparse
|
48 |
+
import json
|
49 |
+
import os
|
50 |
+
import platform
|
51 |
+
import re
|
52 |
+
import subprocess
|
53 |
+
import sys
|
54 |
+
import time
|
55 |
+
import warnings
|
56 |
+
from pathlib import Path
|
57 |
+
|
58 |
+
import pandas as pd
|
59 |
+
import torch
|
60 |
+
from torch.utils.mobile_optimizer import optimize_for_mobile
|
61 |
+
|
62 |
+
FILE = Path(__file__).resolve()
|
63 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
64 |
+
if str(ROOT) not in sys.path:
|
65 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
66 |
+
if platform.system() != 'Windows':
|
67 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
68 |
+
|
69 |
+
from models.experimental import attempt_load
|
70 |
+
from models.yolo import ClassificationModel, Detect, DetectionModel, SegmentationModel
|
71 |
+
from utils.dataloaders import LoadImages
|
72 |
+
from utils.general import (LOGGER, Profile, check_dataset, check_img_size, check_requirements, check_version,
|
73 |
+
check_yaml, colorstr, file_size, get_default_args, print_args, url2file, yaml_save)
|
74 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
75 |
+
|
76 |
+
MACOS = platform.system() == 'Darwin' # macOS environment
|
77 |
+
|
78 |
+
|
79 |
+
def export_formats():
|
80 |
+
# YOLOv5 export formats
|
81 |
+
x = [
|
82 |
+
['PyTorch', '-', '.pt', True, True],
|
83 |
+
['TorchScript', 'torchscript', '.torchscript', True, True],
|
84 |
+
['ONNX', 'onnx', '.onnx', True, True],
|
85 |
+
['OpenVINO', 'openvino', '_openvino_model', True, False],
|
86 |
+
['TensorRT', 'engine', '.engine', False, True],
|
87 |
+
['CoreML', 'coreml', '.mlmodel', True, False],
|
88 |
+
['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
|
89 |
+
['TensorFlow GraphDef', 'pb', '.pb', True, True],
|
90 |
+
['TensorFlow Lite', 'tflite', '.tflite', True, False],
|
91 |
+
['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
|
92 |
+
['TensorFlow.js', 'tfjs', '_web_model', False, False],
|
93 |
+
['PaddlePaddle', 'paddle', '_paddle_model', True, True],]
|
94 |
+
return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
|
95 |
+
|
96 |
+
|
97 |
+
def try_export(inner_func):
|
98 |
+
# YOLOv5 export decorator, i..e @try_export
|
99 |
+
inner_args = get_default_args(inner_func)
|
100 |
+
|
101 |
+
def outer_func(*args, **kwargs):
|
102 |
+
prefix = inner_args['prefix']
|
103 |
+
try:
|
104 |
+
with Profile() as dt:
|
105 |
+
f, model = inner_func(*args, **kwargs)
|
106 |
+
LOGGER.info(f'{prefix} export success β
{dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)')
|
107 |
+
return f, model
|
108 |
+
except Exception as e:
|
109 |
+
LOGGER.info(f'{prefix} export failure β {dt.t:.1f}s: {e}')
|
110 |
+
return None, None
|
111 |
+
|
112 |
+
return outer_func
|
113 |
+
|
114 |
+
|
115 |
+
@try_export
|
116 |
+
def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
|
117 |
+
# YOLOv5 TorchScript model export
|
118 |
+
LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
|
119 |
+
f = file.with_suffix('.torchscript')
|
120 |
+
|
121 |
+
ts = torch.jit.trace(model, im, strict=False)
|
122 |
+
d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
|
123 |
+
extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
|
124 |
+
if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
|
125 |
+
optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
|
126 |
+
else:
|
127 |
+
ts.save(str(f), _extra_files=extra_files)
|
128 |
+
return f, None
|
129 |
+
|
130 |
+
|
131 |
+
@try_export
|
132 |
+
def export_onnx(model, im, file, opset, dynamic, simplify, prefix=colorstr('ONNX:')):
|
133 |
+
# YOLOv5 ONNX export
|
134 |
+
check_requirements('onnx')
|
135 |
+
import onnx
|
136 |
+
|
137 |
+
LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
|
138 |
+
f = file.with_suffix('.onnx')
|
139 |
+
|
140 |
+
output_names = ['output0', 'output1'] if isinstance(model, SegmentationModel) else ['output0']
|
141 |
+
if dynamic:
|
142 |
+
dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}} # shape(1,3,640,640)
|
143 |
+
if isinstance(model, SegmentationModel):
|
144 |
+
dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
|
145 |
+
dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'} # shape(1,32,160,160)
|
146 |
+
elif isinstance(model, DetectionModel):
|
147 |
+
dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
|
148 |
+
|
149 |
+
torch.onnx.export(
|
150 |
+
model.cpu() if dynamic else model, # --dynamic only compatible with cpu
|
151 |
+
im.cpu() if dynamic else im,
|
152 |
+
f,
|
153 |
+
verbose=False,
|
154 |
+
opset_version=opset,
|
155 |
+
do_constant_folding=True,
|
156 |
+
input_names=['images'],
|
157 |
+
output_names=output_names,
|
158 |
+
dynamic_axes=dynamic or None)
|
159 |
+
|
160 |
+
# Checks
|
161 |
+
model_onnx = onnx.load(f) # load onnx model
|
162 |
+
onnx.checker.check_model(model_onnx) # check onnx model
|
163 |
+
|
164 |
+
# Metadata
|
165 |
+
d = {'stride': int(max(model.stride)), 'names': model.names}
|
166 |
+
for k, v in d.items():
|
167 |
+
meta = model_onnx.metadata_props.add()
|
168 |
+
meta.key, meta.value = k, str(v)
|
169 |
+
onnx.save(model_onnx, f)
|
170 |
+
|
171 |
+
# Simplify
|
172 |
+
if simplify:
|
173 |
+
try:
|
174 |
+
cuda = torch.cuda.is_available()
|
175 |
+
check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1'))
|
176 |
+
import onnxsim
|
177 |
+
|
178 |
+
LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
179 |
+
model_onnx, check = onnxsim.simplify(model_onnx)
|
180 |
+
assert check, 'assert check failed'
|
181 |
+
onnx.save(model_onnx, f)
|
182 |
+
except Exception as e:
|
183 |
+
LOGGER.info(f'{prefix} simplifier failure: {e}')
|
184 |
+
return f, model_onnx
|
185 |
+
|
186 |
+
|
187 |
+
@try_export
|
188 |
+
def export_openvino(file, metadata, half, prefix=colorstr('OpenVINO:')):
|
189 |
+
# YOLOv5 OpenVINO export
|
190 |
+
check_requirements('openvino-dev') # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
191 |
+
import openvino.inference_engine as ie
|
192 |
+
|
193 |
+
LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
|
194 |
+
f = str(file).replace('.pt', f'_openvino_model{os.sep}')
|
195 |
+
|
196 |
+
cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
|
197 |
+
subprocess.run(cmd.split(), check=True, env=os.environ) # export
|
198 |
+
yaml_save(Path(f) / file.with_suffix('.yaml').name, metadata) # add metadata.yaml
|
199 |
+
return f, None
|
200 |
+
|
201 |
+
|
202 |
+
@try_export
|
203 |
+
def export_paddle(model, im, file, metadata, prefix=colorstr('PaddlePaddle:')):
|
204 |
+
# YOLOv5 Paddle export
|
205 |
+
check_requirements(('paddlepaddle', 'x2paddle'))
|
206 |
+
import x2paddle
|
207 |
+
from x2paddle.convert import pytorch2paddle
|
208 |
+
|
209 |
+
LOGGER.info(f'\n{prefix} starting export with X2Paddle {x2paddle.__version__}...')
|
210 |
+
f = str(file).replace('.pt', f'_paddle_model{os.sep}')
|
211 |
+
|
212 |
+
pytorch2paddle(module=model, save_dir=f, jit_type='trace', input_examples=[im]) # export
|
213 |
+
yaml_save(Path(f) / file.with_suffix('.yaml').name, metadata) # add metadata.yaml
|
214 |
+
return f, None
|
215 |
+
|
216 |
+
|
217 |
+
@try_export
|
218 |
+
def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
|
219 |
+
# YOLOv5 CoreML export
|
220 |
+
check_requirements('coremltools')
|
221 |
+
import coremltools as ct
|
222 |
+
|
223 |
+
LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
|
224 |
+
f = file.with_suffix('.mlmodel')
|
225 |
+
|
226 |
+
ts = torch.jit.trace(model, im, strict=False) # TorchScript model
|
227 |
+
ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
|
228 |
+
bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
|
229 |
+
if bits < 32:
|
230 |
+
if MACOS: # quantization only supported on macOS
|
231 |
+
with warnings.catch_warnings():
|
232 |
+
warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
|
233 |
+
ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
|
234 |
+
else:
|
235 |
+
print(f'{prefix} quantization only supported on macOS, skipping...')
|
236 |
+
ct_model.save(f)
|
237 |
+
return f, ct_model
|
238 |
+
|
239 |
+
|
240 |
+
@try_export
|
241 |
+
def export_engine(model, im, file, half, dynamic, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
|
242 |
+
# YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
|
243 |
+
assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
|
244 |
+
try:
|
245 |
+
import tensorrt as trt
|
246 |
+
except Exception:
|
247 |
+
if platform.system() == 'Linux':
|
248 |
+
check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')
|
249 |
+
import tensorrt as trt
|
250 |
+
|
251 |
+
if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
|
252 |
+
grid = model.model[-1].anchor_grid
|
253 |
+
model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
|
254 |
+
export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
|
255 |
+
model.model[-1].anchor_grid = grid
|
256 |
+
else: # TensorRT >= 8
|
257 |
+
check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
|
258 |
+
export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
|
259 |
+
onnx = file.with_suffix('.onnx')
|
260 |
+
|
261 |
+
LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
|
262 |
+
assert onnx.exists(), f'failed to export ONNX file: {onnx}'
|
263 |
+
f = file.with_suffix('.engine') # TensorRT engine file
|
264 |
+
logger = trt.Logger(trt.Logger.INFO)
|
265 |
+
if verbose:
|
266 |
+
logger.min_severity = trt.Logger.Severity.VERBOSE
|
267 |
+
|
268 |
+
builder = trt.Builder(logger)
|
269 |
+
config = builder.create_builder_config()
|
270 |
+
config.max_workspace_size = workspace * 1 << 30
|
271 |
+
# config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
|
272 |
+
|
273 |
+
flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
|
274 |
+
network = builder.create_network(flag)
|
275 |
+
parser = trt.OnnxParser(network, logger)
|
276 |
+
if not parser.parse_from_file(str(onnx)):
|
277 |
+
raise RuntimeError(f'failed to load ONNX file: {onnx}')
|
278 |
+
|
279 |
+
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
280 |
+
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
281 |
+
for inp in inputs:
|
282 |
+
LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
|
283 |
+
for out in outputs:
|
284 |
+
LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
|
285 |
+
|
286 |
+
if dynamic:
|
287 |
+
if im.shape[0] <= 1:
|
288 |
+
LOGGER.warning(f"{prefix} WARNING β οΈ --dynamic model requires maximum --batch-size argument")
|
289 |
+
profile = builder.create_optimization_profile()
|
290 |
+
for inp in inputs:
|
291 |
+
profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape)
|
292 |
+
config.add_optimization_profile(profile)
|
293 |
+
|
294 |
+
LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine as {f}')
|
295 |
+
if builder.platform_has_fast_fp16 and half:
|
296 |
+
config.set_flag(trt.BuilderFlag.FP16)
|
297 |
+
with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
|
298 |
+
t.write(engine.serialize())
|
299 |
+
return f, None
|
300 |
+
|
301 |
+
|
302 |
+
@try_export
|
303 |
+
def export_saved_model(model,
|
304 |
+
im,
|
305 |
+
file,
|
306 |
+
dynamic,
|
307 |
+
tf_nms=False,
|
308 |
+
agnostic_nms=False,
|
309 |
+
topk_per_class=100,
|
310 |
+
topk_all=100,
|
311 |
+
iou_thres=0.45,
|
312 |
+
conf_thres=0.25,
|
313 |
+
keras=False,
|
314 |
+
prefix=colorstr('TensorFlow SavedModel:')):
|
315 |
+
# YOLOv5 TensorFlow SavedModel export
|
316 |
+
try:
|
317 |
+
import tensorflow as tf
|
318 |
+
except Exception:
|
319 |
+
check_requirements(f"tensorflow{'' if torch.cuda.is_available() else '-macos' if MACOS else '-cpu'}")
|
320 |
+
import tensorflow as tf
|
321 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
322 |
+
|
323 |
+
from models.tf import TFModel
|
324 |
+
|
325 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
326 |
+
f = str(file).replace('.pt', '_saved_model')
|
327 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
328 |
+
|
329 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
330 |
+
im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
|
331 |
+
_ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
332 |
+
inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
|
333 |
+
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
334 |
+
keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
|
335 |
+
keras_model.trainable = False
|
336 |
+
keras_model.summary()
|
337 |
+
if keras:
|
338 |
+
keras_model.save(f, save_format='tf')
|
339 |
+
else:
|
340 |
+
spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
|
341 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
342 |
+
m = m.get_concrete_function(spec)
|
343 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
344 |
+
tfm = tf.Module()
|
345 |
+
tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x), [spec])
|
346 |
+
tfm.__call__(im)
|
347 |
+
tf.saved_model.save(tfm,
|
348 |
+
f,
|
349 |
+
options=tf.saved_model.SaveOptions(experimental_custom_gradients=False) if check_version(
|
350 |
+
tf.__version__, '2.6') else tf.saved_model.SaveOptions())
|
351 |
+
return f, keras_model
|
352 |
+
|
353 |
+
|
354 |
+
@try_export
|
355 |
+
def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
|
356 |
+
# YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
|
357 |
+
import tensorflow as tf
|
358 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
359 |
+
|
360 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
361 |
+
f = file.with_suffix('.pb')
|
362 |
+
|
363 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
364 |
+
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
|
365 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
366 |
+
frozen_func.graph.as_graph_def()
|
367 |
+
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
|
368 |
+
return f, None
|
369 |
+
|
370 |
+
|
371 |
+
@try_export
|
372 |
+
def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
|
373 |
+
# YOLOv5 TensorFlow Lite export
|
374 |
+
import tensorflow as tf
|
375 |
+
|
376 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
377 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
378 |
+
f = str(file).replace('.pt', '-fp16.tflite')
|
379 |
+
|
380 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
|
381 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
|
382 |
+
converter.target_spec.supported_types = [tf.float16]
|
383 |
+
converter.optimizations = [tf.lite.Optimize.DEFAULT]
|
384 |
+
if int8:
|
385 |
+
from models.tf import representative_dataset_gen
|
386 |
+
dataset = LoadImages(check_dataset(check_yaml(data))['train'], img_size=imgsz, auto=False)
|
387 |
+
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
|
388 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
389 |
+
converter.target_spec.supported_types = []
|
390 |
+
converter.inference_input_type = tf.uint8 # or tf.int8
|
391 |
+
converter.inference_output_type = tf.uint8 # or tf.int8
|
392 |
+
converter.experimental_new_quantizer = True
|
393 |
+
f = str(file).replace('.pt', '-int8.tflite')
|
394 |
+
if nms or agnostic_nms:
|
395 |
+
converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
|
396 |
+
|
397 |
+
tflite_model = converter.convert()
|
398 |
+
open(f, "wb").write(tflite_model)
|
399 |
+
return f, None
|
400 |
+
|
401 |
+
|
402 |
+
@try_export
|
403 |
+
def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
|
404 |
+
# YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
|
405 |
+
cmd = 'edgetpu_compiler --version'
|
406 |
+
help_url = 'https://coral.ai/docs/edgetpu/compiler/'
|
407 |
+
assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
|
408 |
+
if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
|
409 |
+
LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
|
410 |
+
sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
|
411 |
+
for c in (
|
412 |
+
'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
|
413 |
+
'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
|
414 |
+
'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
|
415 |
+
subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
|
416 |
+
ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
|
417 |
+
|
418 |
+
LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
|
419 |
+
f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
|
420 |
+
f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
|
421 |
+
|
422 |
+
cmd = f"edgetpu_compiler -s -d -k 10 --out_dir {file.parent} {f_tfl}"
|
423 |
+
subprocess.run(cmd.split(), check=True)
|
424 |
+
return f, None
|
425 |
+
|
426 |
+
|
427 |
+
@try_export
|
428 |
+
def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
|
429 |
+
# YOLOv5 TensorFlow.js export
|
430 |
+
check_requirements('tensorflowjs')
|
431 |
+
import tensorflowjs as tfjs
|
432 |
+
|
433 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
|
434 |
+
f = str(file).replace('.pt', '_web_model') # js dir
|
435 |
+
f_pb = file.with_suffix('.pb') # *.pb path
|
436 |
+
f_json = f'{f}/model.json' # *.json path
|
437 |
+
|
438 |
+
cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
|
439 |
+
f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
|
440 |
+
subprocess.run(cmd.split())
|
441 |
+
|
442 |
+
json = Path(f_json).read_text()
|
443 |
+
with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
|
444 |
+
subst = re.sub(
|
445 |
+
r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
|
446 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
447 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
448 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
|
449 |
+
r'"Identity_1": {"name": "Identity_1"}, '
|
450 |
+
r'"Identity_2": {"name": "Identity_2"}, '
|
451 |
+
r'"Identity_3": {"name": "Identity_3"}}}', json)
|
452 |
+
j.write(subst)
|
453 |
+
return f, None
|
454 |
+
|
455 |
+
|
456 |
+
@smart_inference_mode()
|
457 |
+
def run(
|
458 |
+
data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
|
459 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
460 |
+
imgsz=(640, 640), # image (height, width)
|
461 |
+
batch_size=1, # batch size
|
462 |
+
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
463 |
+
include=('torchscript', 'onnx'), # include formats
|
464 |
+
half=False, # FP16 half-precision export
|
465 |
+
inplace=False, # set YOLOv5 Detect() inplace=True
|
466 |
+
keras=False, # use Keras
|
467 |
+
optimize=False, # TorchScript: optimize for mobile
|
468 |
+
int8=False, # CoreML/TF INT8 quantization
|
469 |
+
dynamic=False, # ONNX/TF/TensorRT: dynamic axes
|
470 |
+
simplify=False, # ONNX: simplify model
|
471 |
+
opset=12, # ONNX: opset version
|
472 |
+
verbose=False, # TensorRT: verbose log
|
473 |
+
workspace=4, # TensorRT: workspace size (GB)
|
474 |
+
nms=False, # TF: add NMS to model
|
475 |
+
agnostic_nms=False, # TF: add agnostic NMS to model
|
476 |
+
topk_per_class=100, # TF.js NMS: topk per class to keep
|
477 |
+
topk_all=100, # TF.js NMS: topk for all classes to keep
|
478 |
+
iou_thres=0.45, # TF.js NMS: IoU threshold
|
479 |
+
conf_thres=0.25, # TF.js NMS: confidence threshold
|
480 |
+
):
|
481 |
+
t = time.time()
|
482 |
+
include = [x.lower() for x in include] # to lowercase
|
483 |
+
fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
|
484 |
+
flags = [x in include for x in fmts]
|
485 |
+
assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
|
486 |
+
jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle = flags # export booleans
|
487 |
+
file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
|
488 |
+
|
489 |
+
# Load PyTorch model
|
490 |
+
device = select_device(device)
|
491 |
+
if half:
|
492 |
+
assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
|
493 |
+
assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
|
494 |
+
model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
|
495 |
+
|
496 |
+
# Checks
|
497 |
+
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
|
498 |
+
if optimize:
|
499 |
+
assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'
|
500 |
+
|
501 |
+
# Input
|
502 |
+
gs = int(max(model.stride)) # grid size (max stride)
|
503 |
+
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
|
504 |
+
im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
|
505 |
+
|
506 |
+
# Update model
|
507 |
+
model.eval()
|
508 |
+
for k, m in model.named_modules():
|
509 |
+
if isinstance(m, Detect):
|
510 |
+
m.inplace = inplace
|
511 |
+
m.dynamic = dynamic
|
512 |
+
m.export = True
|
513 |
+
|
514 |
+
for _ in range(2):
|
515 |
+
y = model(im) # dry runs
|
516 |
+
if half and not coreml:
|
517 |
+
im, model = im.half(), model.half() # to FP16
|
518 |
+
shape = tuple((y[0] if isinstance(y, tuple) else y).shape) # model output shape
|
519 |
+
metadata = {'stride': int(max(model.stride)), 'names': model.names} # model metadata
|
520 |
+
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
|
521 |
+
|
522 |
+
# Exports
|
523 |
+
f = [''] * len(fmts) # exported filenames
|
524 |
+
warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
|
525 |
+
if jit: # TorchScript
|
526 |
+
f[0], _ = export_torchscript(model, im, file, optimize)
|
527 |
+
if engine: # TensorRT required before ONNX
|
528 |
+
f[1], _ = export_engine(model, im, file, half, dynamic, simplify, workspace, verbose)
|
529 |
+
if onnx or xml: # OpenVINO requires ONNX
|
530 |
+
f[2], _ = export_onnx(model, im, file, opset, dynamic, simplify)
|
531 |
+
if xml: # OpenVINO
|
532 |
+
f[3], _ = export_openvino(file, metadata, half)
|
533 |
+
if coreml: # CoreML
|
534 |
+
f[4], _ = export_coreml(model, im, file, int8, half)
|
535 |
+
if any((saved_model, pb, tflite, edgetpu, tfjs)): # TensorFlow formats
|
536 |
+
assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
|
537 |
+
assert not isinstance(model, ClassificationModel), 'ClassificationModel export to TF formats not yet supported.'
|
538 |
+
f[5], s_model = export_saved_model(model.cpu(),
|
539 |
+
im,
|
540 |
+
file,
|
541 |
+
dynamic,
|
542 |
+
tf_nms=nms or agnostic_nms or tfjs,
|
543 |
+
agnostic_nms=agnostic_nms or tfjs,
|
544 |
+
topk_per_class=topk_per_class,
|
545 |
+
topk_all=topk_all,
|
546 |
+
iou_thres=iou_thres,
|
547 |
+
conf_thres=conf_thres,
|
548 |
+
keras=keras)
|
549 |
+
if pb or tfjs: # pb prerequisite to tfjs
|
550 |
+
f[6], _ = export_pb(s_model, file)
|
551 |
+
if tflite or edgetpu:
|
552 |
+
f[7], _ = export_tflite(s_model, im, file, int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
|
553 |
+
if edgetpu:
|
554 |
+
f[8], _ = export_edgetpu(file)
|
555 |
+
if tfjs:
|
556 |
+
f[9], _ = export_tfjs(file)
|
557 |
+
if paddle: # PaddlePaddle
|
558 |
+
f[10], _ = export_paddle(model, im, file, metadata)
|
559 |
+
|
560 |
+
# Finish
|
561 |
+
f = [str(x) for x in f if x] # filter out '' and None
|
562 |
+
if any(f):
|
563 |
+
cls, det, seg = (isinstance(model, x) for x in (ClassificationModel, DetectionModel, SegmentationModel)) # type
|
564 |
+
dir = Path('segment' if seg else 'classify' if cls else '')
|
565 |
+
h = '--half' if half else '' # --half FP16 inference arg
|
566 |
+
s = "# WARNING β οΈ ClassificationModel not yet supported for PyTorch Hub AutoShape inference" if cls else \
|
567 |
+
"# WARNING β οΈ SegmentationModel not yet supported for PyTorch Hub AutoShape inference" if seg else ''
|
568 |
+
LOGGER.info(f'\nExport complete ({time.time() - t:.1f}s)'
|
569 |
+
f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
|
570 |
+
f"\nDetect: python {dir / ('sample_solution.py' if det else 'predict.py')} --weights {f[-1]} {h}"
|
571 |
+
f"\nValidate: python {dir / 'val.py'} --weights {f[-1]} {h}"
|
572 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}') {s}"
|
573 |
+
f"\nVisualize: https://netron.app")
|
574 |
+
return f # return list of exported files/dirs
|
575 |
+
|
576 |
+
|
577 |
+
def parse_opt():
|
578 |
+
parser = argparse.ArgumentParser()
|
579 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
580 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
|
581 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
|
582 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
583 |
+
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
584 |
+
parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
|
585 |
+
parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
|
586 |
+
parser.add_argument('--keras', action='store_true', help='TF: use Keras')
|
587 |
+
parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
|
588 |
+
parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
|
589 |
+
parser.add_argument('--dynamic', action='store_true', help='ONNX/TF/TensorRT: dynamic axes')
|
590 |
+
parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
|
591 |
+
parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
|
592 |
+
parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
|
593 |
+
parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
|
594 |
+
parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
|
595 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
|
596 |
+
parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
|
597 |
+
parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
|
598 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
|
599 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
|
600 |
+
parser.add_argument(
|
601 |
+
'--include',
|
602 |
+
nargs='+',
|
603 |
+
default=['torchscript'],
|
604 |
+
help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle')
|
605 |
+
opt = parser.parse_args()
|
606 |
+
print_args(vars(opt))
|
607 |
+
return opt
|
608 |
+
|
609 |
+
|
610 |
+
def main(opt):
|
611 |
+
for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
|
612 |
+
run(**vars(opt))
|
613 |
+
|
614 |
+
|
615 |
+
if __name__ == "__main__":
|
616 |
+
opt = parse_opt()
|
617 |
+
main(opt)
|
hubconf.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5
|
4 |
+
|
5 |
+
Usage:
|
6 |
+
import torch
|
7 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # official model
|
8 |
+
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s') # from branch
|
9 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt') # custom/local model
|
10 |
+
model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local') # local repo
|
11 |
+
"""
|
12 |
+
|
13 |
+
import torch
|
14 |
+
|
15 |
+
|
16 |
+
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
|
17 |
+
"""Creates or loads a YOLOv5 model
|
18 |
+
|
19 |
+
Arguments:
|
20 |
+
name (str): model name 'yolov5s' or path 'path/to/best.pt'
|
21 |
+
pretrained (bool): load pretrained weights into the model
|
22 |
+
channels (int): number of input channels
|
23 |
+
classes (int): number of model classes
|
24 |
+
autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
|
25 |
+
verbose (bool): print all information to screen
|
26 |
+
device (str, torch.device, None): device to use for model parameters
|
27 |
+
|
28 |
+
Returns:
|
29 |
+
YOLOv5 model
|
30 |
+
"""
|
31 |
+
from pathlib import Path
|
32 |
+
|
33 |
+
from models.common import AutoShape, DetectMultiBackend
|
34 |
+
from models.experimental import attempt_load
|
35 |
+
from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
|
36 |
+
from utils.downloads import attempt_download
|
37 |
+
from utils.general import LOGGER, check_requirements, intersect_dicts, logging
|
38 |
+
from utils.torch_utils import select_device
|
39 |
+
|
40 |
+
if not verbose:
|
41 |
+
LOGGER.setLevel(logging.WARNING)
|
42 |
+
check_requirements(exclude=('opencv-python', 'tensorboard', 'thop'))
|
43 |
+
name = Path(name)
|
44 |
+
path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
|
45 |
+
try:
|
46 |
+
device = select_device(device)
|
47 |
+
if pretrained and channels == 3 and classes == 80:
|
48 |
+
try:
|
49 |
+
model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
|
50 |
+
if autoshape:
|
51 |
+
if model.pt and isinstance(model.model, ClassificationModel):
|
52 |
+
LOGGER.warning('WARNING β οΈ YOLOv5 ClassificationModel is not yet AutoShape compatible. '
|
53 |
+
'You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224).')
|
54 |
+
elif model.pt and isinstance(model.model, SegmentationModel):
|
55 |
+
LOGGER.warning('WARNING β οΈ YOLOv5 SegmentationModel is not yet AutoShape compatible. '
|
56 |
+
'You will not be able to run inference with this model.')
|
57 |
+
else:
|
58 |
+
model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
|
59 |
+
except Exception:
|
60 |
+
model = attempt_load(path, device=device, fuse=False) # arbitrary model
|
61 |
+
else:
|
62 |
+
cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
|
63 |
+
model = DetectionModel(cfg, channels, classes) # create model
|
64 |
+
if pretrained:
|
65 |
+
ckpt = torch.load(attempt_download(path), map_location=device) # load
|
66 |
+
csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
|
67 |
+
csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
|
68 |
+
model.load_state_dict(csd, strict=False) # load
|
69 |
+
if len(ckpt['model'].names) == classes:
|
70 |
+
model.names = ckpt['model'].names # set class names attribute
|
71 |
+
if not verbose:
|
72 |
+
LOGGER.setLevel(logging.INFO) # reset to default
|
73 |
+
return model.to(device)
|
74 |
+
|
75 |
+
except Exception as e:
|
76 |
+
help_url = 'https://github.com/ultralytics/yolov5/issues/36'
|
77 |
+
s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
|
78 |
+
raise Exception(s) from e
|
79 |
+
|
80 |
+
|
81 |
+
def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
|
82 |
+
# YOLOv5 custom or local model
|
83 |
+
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
|
84 |
+
|
85 |
+
|
86 |
+
def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
87 |
+
# YOLOv5-nano model https://github.com/ultralytics/yolov5
|
88 |
+
return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
|
89 |
+
|
90 |
+
|
91 |
+
def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
92 |
+
# YOLOv5-small model https://github.com/ultralytics/yolov5
|
93 |
+
return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
|
94 |
+
|
95 |
+
|
96 |
+
def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
97 |
+
# YOLOv5-medium model https://github.com/ultralytics/yolov5
|
98 |
+
return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
|
99 |
+
|
100 |
+
|
101 |
+
def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
102 |
+
# YOLOv5-large model https://github.com/ultralytics/yolov5
|
103 |
+
return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
|
104 |
+
|
105 |
+
|
106 |
+
def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
107 |
+
# YOLOv5-xlarge model https://github.com/ultralytics/yolov5
|
108 |
+
return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
|
109 |
+
|
110 |
+
|
111 |
+
def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
112 |
+
# YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
|
113 |
+
return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
|
114 |
+
|
115 |
+
|
116 |
+
def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
117 |
+
# YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
|
118 |
+
return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
|
119 |
+
|
120 |
+
|
121 |
+
def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
122 |
+
# YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
|
123 |
+
return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
|
124 |
+
|
125 |
+
|
126 |
+
def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
127 |
+
# YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
|
128 |
+
return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
|
129 |
+
|
130 |
+
|
131 |
+
def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
132 |
+
# YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
|
133 |
+
return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
|
134 |
+
|
135 |
+
|
136 |
+
if __name__ == '__main__':
|
137 |
+
import argparse
|
138 |
+
from pathlib import Path
|
139 |
+
|
140 |
+
import numpy as np
|
141 |
+
from PIL import Image
|
142 |
+
|
143 |
+
from utils.general import cv2, print_args
|
144 |
+
|
145 |
+
# Argparser
|
146 |
+
parser = argparse.ArgumentParser()
|
147 |
+
parser.add_argument('--model', type=str, default='yolov5s', help='model name')
|
148 |
+
opt = parser.parse_args()
|
149 |
+
print_args(vars(opt))
|
150 |
+
|
151 |
+
# Model
|
152 |
+
model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
|
153 |
+
# model = custom(path='path/to/model.pt') # custom
|
154 |
+
|
155 |
+
# Images
|
156 |
+
imgs = [
|
157 |
+
'data/images/zidane.jpg', # filename
|
158 |
+
Path('data/images/zidane.jpg'), # Path
|
159 |
+
'https://ultralytics.com/images/zidane.jpg', # URI
|
160 |
+
cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
|
161 |
+
Image.open('data/images/bus.jpg'), # PIL
|
162 |
+
np.zeros((320, 640, 3))] # numpy
|
163 |
+
|
164 |
+
# Inference
|
165 |
+
results = model(imgs, size=320) # batched inference
|
166 |
+
|
167 |
+
# Results
|
168 |
+
results.print()
|
169 |
+
results.save()
|
models/__init__.py
ADDED
File without changes
|
models/common.py
ADDED
@@ -0,0 +1,851 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Common modules
|
4 |
+
"""
|
5 |
+
|
6 |
+
import json
|
7 |
+
import math
|
8 |
+
import platform
|
9 |
+
import warnings
|
10 |
+
from collections import OrderedDict, namedtuple
|
11 |
+
from copy import copy
|
12 |
+
from pathlib import Path
|
13 |
+
from urllib.parse import urlparse
|
14 |
+
|
15 |
+
import cv2
|
16 |
+
import numpy as np
|
17 |
+
import pandas as pd
|
18 |
+
import requests
|
19 |
+
import torch
|
20 |
+
import torch.nn as nn
|
21 |
+
from IPython.display import display
|
22 |
+
from PIL import Image
|
23 |
+
from torch.cuda import amp
|
24 |
+
|
25 |
+
from utils import TryExcept
|
26 |
+
from utils.dataloaders import exif_transpose, letterbox
|
27 |
+
from utils.general import (LOGGER, ROOT, Profile, check_requirements, check_suffix, check_version, colorstr,
|
28 |
+
increment_path, is_notebook, make_divisible, non_max_suppression, scale_boxes, xywh2xyxy,
|
29 |
+
xyxy2xywh, yaml_load)
|
30 |
+
from utils.plots import Annotator, colors, save_one_box
|
31 |
+
from utils.torch_utils import copy_attr, smart_inference_mode
|
32 |
+
|
33 |
+
|
34 |
+
def autopad(k, p=None, d=1): # kernel, padding, dilation
|
35 |
+
# Pad to 'same' shape outputs
|
36 |
+
if d > 1:
|
37 |
+
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
|
38 |
+
if p is None:
|
39 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
40 |
+
return p
|
41 |
+
|
42 |
+
|
43 |
+
class Conv(nn.Module):
|
44 |
+
# Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
|
45 |
+
default_act = nn.SiLU() # default activation
|
46 |
+
|
47 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
|
48 |
+
super().__init__()
|
49 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
|
50 |
+
self.bn = nn.BatchNorm2d(c2)
|
51 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
52 |
+
|
53 |
+
def forward(self, x):
|
54 |
+
return self.act(self.bn(self.conv(x)))
|
55 |
+
|
56 |
+
def forward_fuse(self, x):
|
57 |
+
return self.act(self.conv(x))
|
58 |
+
|
59 |
+
|
60 |
+
class DWConv(Conv):
|
61 |
+
# Depth-wise convolution
|
62 |
+
def __init__(self, c1, c2, k=1, s=1, d=1, act=True): # ch_in, ch_out, kernel, stride, dilation, activation
|
63 |
+
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
|
64 |
+
|
65 |
+
|
66 |
+
class DWConvTranspose2d(nn.ConvTranspose2d):
|
67 |
+
# Depth-wise transpose convolution
|
68 |
+
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
|
69 |
+
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
|
70 |
+
|
71 |
+
|
72 |
+
class TransformerLayer(nn.Module):
|
73 |
+
# Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
|
74 |
+
def __init__(self, c, num_heads):
|
75 |
+
super().__init__()
|
76 |
+
self.q = nn.Linear(c, c, bias=False)
|
77 |
+
self.k = nn.Linear(c, c, bias=False)
|
78 |
+
self.v = nn.Linear(c, c, bias=False)
|
79 |
+
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
|
80 |
+
self.fc1 = nn.Linear(c, c, bias=False)
|
81 |
+
self.fc2 = nn.Linear(c, c, bias=False)
|
82 |
+
|
83 |
+
def forward(self, x):
|
84 |
+
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
|
85 |
+
x = self.fc2(self.fc1(x)) + x
|
86 |
+
return x
|
87 |
+
|
88 |
+
|
89 |
+
class TransformerBlock(nn.Module):
|
90 |
+
# Vision Transformer https://arxiv.org/abs/2010.11929
|
91 |
+
def __init__(self, c1, c2, num_heads, num_layers):
|
92 |
+
super().__init__()
|
93 |
+
self.conv = None
|
94 |
+
if c1 != c2:
|
95 |
+
self.conv = Conv(c1, c2)
|
96 |
+
self.linear = nn.Linear(c2, c2) # learnable position embedding
|
97 |
+
self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
|
98 |
+
self.c2 = c2
|
99 |
+
|
100 |
+
def forward(self, x):
|
101 |
+
if self.conv is not None:
|
102 |
+
x = self.conv(x)
|
103 |
+
b, _, w, h = x.shape
|
104 |
+
p = x.flatten(2).permute(2, 0, 1)
|
105 |
+
return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
|
106 |
+
|
107 |
+
|
108 |
+
class Bottleneck(nn.Module):
|
109 |
+
# Standard bottleneck
|
110 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
111 |
+
super().__init__()
|
112 |
+
c_ = int(c2 * e) # hidden channels
|
113 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
114 |
+
self.cv2 = Conv(c_, c2, 3, 1, g=g)
|
115 |
+
self.add = shortcut and c1 == c2
|
116 |
+
|
117 |
+
def forward(self, x):
|
118 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
119 |
+
|
120 |
+
|
121 |
+
class BottleneckCSP(nn.Module):
|
122 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
123 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
124 |
+
super().__init__()
|
125 |
+
c_ = int(c2 * e) # hidden channels
|
126 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
127 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
128 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
129 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
130 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
131 |
+
self.act = nn.SiLU()
|
132 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
133 |
+
|
134 |
+
def forward(self, x):
|
135 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
136 |
+
y2 = self.cv2(x)
|
137 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
|
138 |
+
|
139 |
+
|
140 |
+
class CrossConv(nn.Module):
|
141 |
+
# Cross Convolution Downsample
|
142 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
|
143 |
+
# ch_in, ch_out, kernel, stride, groups, expansion, shortcut
|
144 |
+
super().__init__()
|
145 |
+
c_ = int(c2 * e) # hidden channels
|
146 |
+
self.cv1 = Conv(c1, c_, (1, k), (1, s))
|
147 |
+
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
|
148 |
+
self.add = shortcut and c1 == c2
|
149 |
+
|
150 |
+
def forward(self, x):
|
151 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
152 |
+
|
153 |
+
|
154 |
+
class C3(nn.Module):
|
155 |
+
# CSP Bottleneck with 3 convolutions
|
156 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
157 |
+
super().__init__()
|
158 |
+
c_ = int(c2 * e) # hidden channels
|
159 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
160 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
161 |
+
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
|
162 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
163 |
+
|
164 |
+
def forward(self, x):
|
165 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
166 |
+
|
167 |
+
|
168 |
+
class C3x(C3):
|
169 |
+
# C3 module with cross-convolutions
|
170 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
171 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
172 |
+
c_ = int(c2 * e)
|
173 |
+
self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
|
174 |
+
|
175 |
+
|
176 |
+
class C3TR(C3):
|
177 |
+
# C3 module with TransformerBlock()
|
178 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
179 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
180 |
+
c_ = int(c2 * e)
|
181 |
+
self.m = TransformerBlock(c_, c_, 4, n)
|
182 |
+
|
183 |
+
|
184 |
+
class C3SPP(C3):
|
185 |
+
# C3 module with SPP()
|
186 |
+
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
|
187 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
188 |
+
c_ = int(c2 * e)
|
189 |
+
self.m = SPP(c_, c_, k)
|
190 |
+
|
191 |
+
|
192 |
+
class C3Ghost(C3):
|
193 |
+
# C3 module with GhostBottleneck()
|
194 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
195 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
196 |
+
c_ = int(c2 * e) # hidden channels
|
197 |
+
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
|
198 |
+
|
199 |
+
|
200 |
+
class SPP(nn.Module):
|
201 |
+
# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
|
202 |
+
def __init__(self, c1, c2, k=(5, 9, 13)):
|
203 |
+
super().__init__()
|
204 |
+
c_ = c1 // 2 # hidden channels
|
205 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
206 |
+
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
207 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
208 |
+
|
209 |
+
def forward(self, x):
|
210 |
+
x = self.cv1(x)
|
211 |
+
with warnings.catch_warnings():
|
212 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
213 |
+
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
214 |
+
|
215 |
+
|
216 |
+
class SPPF(nn.Module):
|
217 |
+
# Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
|
218 |
+
def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
|
219 |
+
super().__init__()
|
220 |
+
c_ = c1 // 2 # hidden channels
|
221 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
222 |
+
self.cv2 = Conv(c_ * 4, c2, 1, 1)
|
223 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
|
224 |
+
|
225 |
+
def forward(self, x):
|
226 |
+
x = self.cv1(x)
|
227 |
+
with warnings.catch_warnings():
|
228 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
229 |
+
y1 = self.m(x)
|
230 |
+
y2 = self.m(y1)
|
231 |
+
return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
|
232 |
+
|
233 |
+
|
234 |
+
class Focus(nn.Module):
|
235 |
+
# Focus wh information into c-space
|
236 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
237 |
+
super().__init__()
|
238 |
+
self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
|
239 |
+
# self.contract = Contract(gain=2)
|
240 |
+
|
241 |
+
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
|
242 |
+
return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
|
243 |
+
# return self.conv(self.contract(x))
|
244 |
+
|
245 |
+
|
246 |
+
class GhostConv(nn.Module):
|
247 |
+
# Ghost Convolution https://github.com/huawei-noah/ghostnet
|
248 |
+
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
|
249 |
+
super().__init__()
|
250 |
+
c_ = c2 // 2 # hidden channels
|
251 |
+
self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
|
252 |
+
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
|
253 |
+
|
254 |
+
def forward(self, x):
|
255 |
+
y = self.cv1(x)
|
256 |
+
return torch.cat((y, self.cv2(y)), 1)
|
257 |
+
|
258 |
+
|
259 |
+
class GhostBottleneck(nn.Module):
|
260 |
+
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
|
261 |
+
def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
|
262 |
+
super().__init__()
|
263 |
+
c_ = c2 // 2
|
264 |
+
self.conv = nn.Sequential(
|
265 |
+
GhostConv(c1, c_, 1, 1), # pw
|
266 |
+
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
|
267 |
+
GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
|
268 |
+
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,
|
269 |
+
act=False)) if s == 2 else nn.Identity()
|
270 |
+
|
271 |
+
def forward(self, x):
|
272 |
+
return self.conv(x) + self.shortcut(x)
|
273 |
+
|
274 |
+
|
275 |
+
class Contract(nn.Module):
|
276 |
+
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
|
277 |
+
def __init__(self, gain=2):
|
278 |
+
super().__init__()
|
279 |
+
self.gain = gain
|
280 |
+
|
281 |
+
def forward(self, x):
|
282 |
+
b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
|
283 |
+
s = self.gain
|
284 |
+
x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
|
285 |
+
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
|
286 |
+
return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
|
287 |
+
|
288 |
+
|
289 |
+
class Expand(nn.Module):
|
290 |
+
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
|
291 |
+
def __init__(self, gain=2):
|
292 |
+
super().__init__()
|
293 |
+
self.gain = gain
|
294 |
+
|
295 |
+
def forward(self, x):
|
296 |
+
b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
|
297 |
+
s = self.gain
|
298 |
+
x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
|
299 |
+
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
|
300 |
+
return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
|
301 |
+
|
302 |
+
|
303 |
+
class Concat(nn.Module):
|
304 |
+
# Concatenate a list of tensors along dimension
|
305 |
+
def __init__(self, dimension=1):
|
306 |
+
super().__init__()
|
307 |
+
self.d = dimension
|
308 |
+
|
309 |
+
def forward(self, x):
|
310 |
+
return torch.cat(x, self.d)
|
311 |
+
|
312 |
+
|
313 |
+
class DetectMultiBackend(nn.Module):
|
314 |
+
# YOLOv5 MultiBackend class for python inference on various backends
|
315 |
+
def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):
|
316 |
+
# Usage:
|
317 |
+
# PyTorch: weights = *.pt
|
318 |
+
# TorchScript: *.torchscript
|
319 |
+
# ONNX Runtime: *.onnx
|
320 |
+
# ONNX OpenCV DNN: *.onnx --dnn
|
321 |
+
# OpenVINO: *_openvino_model
|
322 |
+
# CoreML: *.mlmodel
|
323 |
+
# TensorRT: *.engine
|
324 |
+
# TensorFlow SavedModel: *_saved_model
|
325 |
+
# TensorFlow GraphDef: *.pb
|
326 |
+
# TensorFlow Lite: *.tflite
|
327 |
+
# TensorFlow Edge TPU: *_edgetpu.tflite
|
328 |
+
# PaddlePaddle: *_paddle_model
|
329 |
+
from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
|
330 |
+
|
331 |
+
super().__init__()
|
332 |
+
w = str(weights[0] if isinstance(weights, list) else weights)
|
333 |
+
pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)
|
334 |
+
fp16 &= pt or jit or onnx or engine # FP16
|
335 |
+
nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)
|
336 |
+
stride = 32 # default stride
|
337 |
+
cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA
|
338 |
+
if not (pt or triton):
|
339 |
+
w = attempt_download(w) # download if not local
|
340 |
+
|
341 |
+
if pt: # PyTorch
|
342 |
+
model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
|
343 |
+
stride = max(int(model.stride.max()), 32) # model stride
|
344 |
+
names = model.module.names if hasattr(model, 'module') else model.names # get class names
|
345 |
+
model.half() if fp16 else model.float()
|
346 |
+
self.model = model # explicitly assign for to(), cpu(), cuda(), half()
|
347 |
+
elif jit: # TorchScript
|
348 |
+
LOGGER.info(f'Loading {w} for TorchScript inference...')
|
349 |
+
extra_files = {'config.txt': ''} # model metadata
|
350 |
+
model = torch.jit.load(w, _extra_files=extra_files, map_location=device)
|
351 |
+
model.half() if fp16 else model.float()
|
352 |
+
if extra_files['config.txt']: # load metadata dict
|
353 |
+
d = json.loads(extra_files['config.txt'],
|
354 |
+
object_hook=lambda d: {int(k) if k.isdigit() else k: v
|
355 |
+
for k, v in d.items()})
|
356 |
+
stride, names = int(d['stride']), d['names']
|
357 |
+
elif dnn: # ONNX OpenCV DNN
|
358 |
+
LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')
|
359 |
+
check_requirements('opencv-python>=4.5.4')
|
360 |
+
net = cv2.dnn.readNetFromONNX(w)
|
361 |
+
elif onnx: # ONNX Runtime
|
362 |
+
LOGGER.info(f'Loading {w} for ONNX Runtime inference...')
|
363 |
+
check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))
|
364 |
+
import onnxruntime
|
365 |
+
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
|
366 |
+
session = onnxruntime.InferenceSession(w, providers=providers)
|
367 |
+
output_names = [x.name for x in session.get_outputs()]
|
368 |
+
meta = session.get_modelmeta().custom_metadata_map # metadata
|
369 |
+
if 'stride' in meta:
|
370 |
+
stride, names = int(meta['stride']), eval(meta['names'])
|
371 |
+
elif xml: # OpenVINO
|
372 |
+
LOGGER.info(f'Loading {w} for OpenVINO inference...')
|
373 |
+
check_requirements('openvino') # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
374 |
+
from openvino.runtime import Core, Layout, get_batch
|
375 |
+
ie = Core()
|
376 |
+
if not Path(w).is_file(): # if not *.xml
|
377 |
+
w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir
|
378 |
+
network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin'))
|
379 |
+
if network.get_parameters()[0].get_layout().empty:
|
380 |
+
network.get_parameters()[0].set_layout(Layout("NCHW"))
|
381 |
+
batch_dim = get_batch(network)
|
382 |
+
if batch_dim.is_static:
|
383 |
+
batch_size = batch_dim.get_length()
|
384 |
+
executable_network = ie.compile_model(network, device_name="CPU") # device_name="MYRIAD" for Intel NCS2
|
385 |
+
stride, names = self._load_metadata(Path(w).with_suffix('.yaml')) # load metadata
|
386 |
+
elif engine: # TensorRT
|
387 |
+
LOGGER.info(f'Loading {w} for TensorRT inference...')
|
388 |
+
import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
|
389 |
+
check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
|
390 |
+
if device.type == 'cpu':
|
391 |
+
device = torch.device('cuda:0')
|
392 |
+
Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))
|
393 |
+
logger = trt.Logger(trt.Logger.INFO)
|
394 |
+
with open(w, 'rb') as f, trt.Runtime(logger) as runtime:
|
395 |
+
model = runtime.deserialize_cuda_engine(f.read())
|
396 |
+
context = model.create_execution_context()
|
397 |
+
bindings = OrderedDict()
|
398 |
+
output_names = []
|
399 |
+
fp16 = False # default updated below
|
400 |
+
dynamic = False
|
401 |
+
for i in range(model.num_bindings):
|
402 |
+
name = model.get_binding_name(i)
|
403 |
+
dtype = trt.nptype(model.get_binding_dtype(i))
|
404 |
+
if model.binding_is_input(i):
|
405 |
+
if -1 in tuple(model.get_binding_shape(i)): # dynamic
|
406 |
+
dynamic = True
|
407 |
+
context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))
|
408 |
+
if dtype == np.float16:
|
409 |
+
fp16 = True
|
410 |
+
else: # output
|
411 |
+
output_names.append(name)
|
412 |
+
shape = tuple(context.get_binding_shape(i))
|
413 |
+
im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)
|
414 |
+
bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))
|
415 |
+
binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
|
416 |
+
batch_size = bindings['images'].shape[0] # if dynamic, this is instead max batch size
|
417 |
+
elif coreml: # CoreML
|
418 |
+
LOGGER.info(f'Loading {w} for CoreML inference...')
|
419 |
+
import coremltools as ct
|
420 |
+
model = ct.models.MLModel(w)
|
421 |
+
elif saved_model: # TF SavedModel
|
422 |
+
LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')
|
423 |
+
import tensorflow as tf
|
424 |
+
keras = False # assume TF1 saved_model
|
425 |
+
model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
|
426 |
+
elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
|
427 |
+
LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')
|
428 |
+
import tensorflow as tf
|
429 |
+
|
430 |
+
def wrap_frozen_graph(gd, inputs, outputs):
|
431 |
+
x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
|
432 |
+
ge = x.graph.as_graph_element
|
433 |
+
return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
|
434 |
+
|
435 |
+
def gd_outputs(gd):
|
436 |
+
name_list, input_list = [], []
|
437 |
+
for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef
|
438 |
+
name_list.append(node.name)
|
439 |
+
input_list.extend(node.input)
|
440 |
+
return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))
|
441 |
+
|
442 |
+
gd = tf.Graph().as_graph_def() # TF GraphDef
|
443 |
+
with open(w, 'rb') as f:
|
444 |
+
gd.ParseFromString(f.read())
|
445 |
+
frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs=gd_outputs(gd))
|
446 |
+
elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
|
447 |
+
try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
|
448 |
+
from tflite_runtime.interpreter import Interpreter, load_delegate
|
449 |
+
except ImportError:
|
450 |
+
import tensorflow as tf
|
451 |
+
Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,
|
452 |
+
if edgetpu: # TF Edge TPU https://coral.ai/software/#edgetpu-runtime
|
453 |
+
LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')
|
454 |
+
delegate = {
|
455 |
+
'Linux': 'libedgetpu.so.1',
|
456 |
+
'Darwin': 'libedgetpu.1.dylib',
|
457 |
+
'Windows': 'edgetpu.dll'}[platform.system()]
|
458 |
+
interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
|
459 |
+
else: # TFLite
|
460 |
+
LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')
|
461 |
+
interpreter = Interpreter(model_path=w) # load TFLite model
|
462 |
+
interpreter.allocate_tensors() # allocate
|
463 |
+
input_details = interpreter.get_input_details() # inputs
|
464 |
+
output_details = interpreter.get_output_details() # outputs
|
465 |
+
elif tfjs: # TF.js
|
466 |
+
raise NotImplementedError('ERROR: YOLOv5 TF.js inference is not supported')
|
467 |
+
elif paddle: # PaddlePaddle
|
468 |
+
LOGGER.info(f'Loading {w} for PaddlePaddle inference...')
|
469 |
+
check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')
|
470 |
+
import paddle.inference as pdi
|
471 |
+
if not Path(w).is_file(): # if not *.pdmodel
|
472 |
+
w = next(Path(w).rglob('*.pdmodel')) # get *.pdmodel file from *_paddle_model dir
|
473 |
+
weights = Path(w).with_suffix('.pdiparams')
|
474 |
+
config = pdi.Config(str(w), str(weights))
|
475 |
+
if cuda:
|
476 |
+
config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)
|
477 |
+
predictor = pdi.create_predictor(config)
|
478 |
+
input_handle = predictor.get_input_handle(predictor.get_input_names()[0])
|
479 |
+
output_names = predictor.get_output_names()
|
480 |
+
elif triton: # NVIDIA Triton Inference Server
|
481 |
+
LOGGER.info(f'Using {w} as Triton Inference Server...')
|
482 |
+
check_requirements('tritonclient[all]')
|
483 |
+
from utils.triton import TritonRemoteModel
|
484 |
+
model = TritonRemoteModel(url=w)
|
485 |
+
nhwc = model.runtime.startswith("tensorflow")
|
486 |
+
else:
|
487 |
+
raise NotImplementedError(f'ERROR: {w} is not a supported format')
|
488 |
+
|
489 |
+
# class names
|
490 |
+
if 'names' not in locals():
|
491 |
+
names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}
|
492 |
+
if names[0] == 'n01440764' and len(names) == 1000: # ImageNet
|
493 |
+
names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names
|
494 |
+
|
495 |
+
self.__dict__.update(locals()) # assign all variables to self
|
496 |
+
|
497 |
+
def forward(self, im, augment=False, visualize=False):
|
498 |
+
# YOLOv5 MultiBackend inference
|
499 |
+
b, ch, h, w = im.shape # batch, channel, height, width
|
500 |
+
if self.fp16 and im.dtype != torch.float16:
|
501 |
+
im = im.half() # to FP16
|
502 |
+
if self.nhwc:
|
503 |
+
im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)
|
504 |
+
|
505 |
+
if self.pt: # PyTorch
|
506 |
+
y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
|
507 |
+
elif self.jit: # TorchScript
|
508 |
+
y = self.model(im)
|
509 |
+
elif self.dnn: # ONNX OpenCV DNN
|
510 |
+
im = im.cpu().numpy() # torch to numpy
|
511 |
+
self.net.setInput(im)
|
512 |
+
y = self.net.forward()
|
513 |
+
elif self.onnx: # ONNX Runtime
|
514 |
+
im = im.cpu().numpy() # torch to numpy
|
515 |
+
y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})
|
516 |
+
elif self.xml: # OpenVINO
|
517 |
+
im = im.cpu().numpy() # FP32
|
518 |
+
y = list(self.executable_network([im]).values())
|
519 |
+
elif self.engine: # TensorRT
|
520 |
+
if self.dynamic and im.shape != self.bindings['images'].shape:
|
521 |
+
i = self.model.get_binding_index('images')
|
522 |
+
self.context.set_binding_shape(i, im.shape) # reshape if dynamic
|
523 |
+
self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)
|
524 |
+
for name in self.output_names:
|
525 |
+
i = self.model.get_binding_index(name)
|
526 |
+
self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))
|
527 |
+
s = self.bindings['images'].shape
|
528 |
+
assert im.shape == s, f"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}"
|
529 |
+
self.binding_addrs['images'] = int(im.data_ptr())
|
530 |
+
self.context.execute_v2(list(self.binding_addrs.values()))
|
531 |
+
y = [self.bindings[x].data for x in sorted(self.output_names)]
|
532 |
+
elif self.coreml: # CoreML
|
533 |
+
im = im.cpu().numpy()
|
534 |
+
im = Image.fromarray((im[0] * 255).astype('uint8'))
|
535 |
+
# im = im.resize((192, 320), Image.ANTIALIAS)
|
536 |
+
y = self.model.predict({'image': im}) # coordinates are xywh normalized
|
537 |
+
if 'confidence' in y:
|
538 |
+
box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
|
539 |
+
conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
|
540 |
+
y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
|
541 |
+
else:
|
542 |
+
y = list(reversed(y.values())) # reversed for segmentation models (pred, proto)
|
543 |
+
elif self.paddle: # PaddlePaddle
|
544 |
+
im = im.cpu().numpy().astype(np.float32)
|
545 |
+
self.input_handle.copy_from_cpu(im)
|
546 |
+
self.predictor.run()
|
547 |
+
y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]
|
548 |
+
elif self.triton: # NVIDIA Triton Inference Server
|
549 |
+
y = self.model(im)
|
550 |
+
else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
|
551 |
+
im = im.cpu().numpy()
|
552 |
+
if self.saved_model: # SavedModel
|
553 |
+
y = self.model(im, training=False) if self.keras else self.model(im)
|
554 |
+
elif self.pb: # GraphDef
|
555 |
+
y = self.frozen_func(x=self.tf.constant(im))
|
556 |
+
else: # Lite or Edge TPU
|
557 |
+
input = self.input_details[0]
|
558 |
+
int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
|
559 |
+
if int8:
|
560 |
+
scale, zero_point = input['quantization']
|
561 |
+
im = (im / scale + zero_point).astype(np.uint8) # de-scale
|
562 |
+
self.interpreter.set_tensor(input['index'], im)
|
563 |
+
self.interpreter.invoke()
|
564 |
+
y = []
|
565 |
+
for output in self.output_details:
|
566 |
+
x = self.interpreter.get_tensor(output['index'])
|
567 |
+
if int8:
|
568 |
+
scale, zero_point = output['quantization']
|
569 |
+
x = (x.astype(np.float32) - zero_point) * scale # re-scale
|
570 |
+
y.append(x)
|
571 |
+
y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]
|
572 |
+
y[0][..., :4] *= [w, h, w, h] # xywh normalized to pixels
|
573 |
+
|
574 |
+
if isinstance(y, (list, tuple)):
|
575 |
+
return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]
|
576 |
+
else:
|
577 |
+
return self.from_numpy(y)
|
578 |
+
|
579 |
+
def from_numpy(self, x):
|
580 |
+
return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x
|
581 |
+
|
582 |
+
def warmup(self, imgsz=(1, 3, 640, 640)):
|
583 |
+
# Warmup model by running inference once
|
584 |
+
warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton
|
585 |
+
if any(warmup_types) and (self.device.type != 'cpu' or self.triton):
|
586 |
+
im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
|
587 |
+
for _ in range(2 if self.jit else 1): #
|
588 |
+
self.forward(im) # warmup
|
589 |
+
|
590 |
+
@staticmethod
|
591 |
+
def _model_type(p='path/to/model.pt'):
|
592 |
+
# Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx
|
593 |
+
# types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]
|
594 |
+
from export import export_formats
|
595 |
+
from utils.downloads import is_url
|
596 |
+
sf = list(export_formats().Suffix) # export suffixes
|
597 |
+
if not is_url(p, check=False):
|
598 |
+
check_suffix(p, sf) # checks
|
599 |
+
url = urlparse(p) # if url may be Triton inference server
|
600 |
+
types = [s in Path(p).name for s in sf]
|
601 |
+
types[8] &= not types[9] # tflite &= not edgetpu
|
602 |
+
triton = not any(types) and all([any(s in url.scheme for s in ["http", "grpc"]), url.netloc])
|
603 |
+
return types + [triton]
|
604 |
+
|
605 |
+
@staticmethod
|
606 |
+
def _load_metadata(f=Path('path/to/meta.yaml')):
|
607 |
+
# Load metadata from meta.yaml if it exists
|
608 |
+
if f.exists():
|
609 |
+
d = yaml_load(f)
|
610 |
+
return d['stride'], d['names'] # assign stride, names
|
611 |
+
return None, None
|
612 |
+
|
613 |
+
|
614 |
+
class AutoShape(nn.Module):
|
615 |
+
# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
|
616 |
+
conf = 0.25 # NMS confidence threshold
|
617 |
+
iou = 0.45 # NMS IoU threshold
|
618 |
+
agnostic = False # NMS class-agnostic
|
619 |
+
multi_label = False # NMS multiple labels per box
|
620 |
+
classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
|
621 |
+
max_det = 1000 # maximum number of detections per image
|
622 |
+
amp = False # Automatic Mixed Precision (AMP) inference
|
623 |
+
|
624 |
+
def __init__(self, model, verbose=True):
|
625 |
+
super().__init__()
|
626 |
+
if verbose:
|
627 |
+
LOGGER.info('Adding AutoShape... ')
|
628 |
+
copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
|
629 |
+
self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
|
630 |
+
self.pt = not self.dmb or model.pt # PyTorch model
|
631 |
+
self.model = model.eval()
|
632 |
+
if self.pt:
|
633 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
634 |
+
m.inplace = False # Detect.inplace=False for safe multithread inference
|
635 |
+
m.export = True # do not output loss values
|
636 |
+
|
637 |
+
def _apply(self, fn):
|
638 |
+
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
|
639 |
+
self = super()._apply(fn)
|
640 |
+
if self.pt:
|
641 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
642 |
+
m.stride = fn(m.stride)
|
643 |
+
m.grid = list(map(fn, m.grid))
|
644 |
+
if isinstance(m.anchor_grid, list):
|
645 |
+
m.anchor_grid = list(map(fn, m.anchor_grid))
|
646 |
+
return self
|
647 |
+
|
648 |
+
@smart_inference_mode()
|
649 |
+
def forward(self, ims, size=640, augment=False, profile=False):
|
650 |
+
# Inference from various sources. For size(height=640, width=1280), RGB images example inputs are:
|
651 |
+
# file: ims = 'data/images/zidane.jpg' # str or PosixPath
|
652 |
+
# URI: = 'https://ultralytics.com/images/zidane.jpg'
|
653 |
+
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
|
654 |
+
# PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
|
655 |
+
# numpy: = np.zeros((640,1280,3)) # HWC
|
656 |
+
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
|
657 |
+
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
|
658 |
+
|
659 |
+
dt = (Profile(), Profile(), Profile())
|
660 |
+
with dt[0]:
|
661 |
+
if isinstance(size, int): # expand
|
662 |
+
size = (size, size)
|
663 |
+
p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) # param
|
664 |
+
autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
|
665 |
+
if isinstance(ims, torch.Tensor): # torch
|
666 |
+
with amp.autocast(autocast):
|
667 |
+
return self.model(ims.to(p.device).type_as(p), augment=augment) # inference
|
668 |
+
|
669 |
+
# Pre-process
|
670 |
+
n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of images
|
671 |
+
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
|
672 |
+
for i, im in enumerate(ims):
|
673 |
+
f = f'image{i}' # filename
|
674 |
+
if isinstance(im, (str, Path)): # filename or uri
|
675 |
+
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
|
676 |
+
im = np.asarray(exif_transpose(im))
|
677 |
+
elif isinstance(im, Image.Image): # PIL Image
|
678 |
+
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
|
679 |
+
files.append(Path(f).with_suffix('.jpg').name)
|
680 |
+
if im.shape[0] < 5: # image in CHW
|
681 |
+
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
|
682 |
+
im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch input
|
683 |
+
s = im.shape[:2] # HWC
|
684 |
+
shape0.append(s) # image shape
|
685 |
+
g = max(size) / max(s) # gain
|
686 |
+
shape1.append([y * g for y in s])
|
687 |
+
ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
|
688 |
+
shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] if self.pt else size # inf shape
|
689 |
+
x = [letterbox(im, shape1, auto=False)[0] for im in ims] # pad
|
690 |
+
x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
|
691 |
+
x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
|
692 |
+
|
693 |
+
with amp.autocast(autocast):
|
694 |
+
# Inference
|
695 |
+
with dt[1]:
|
696 |
+
y = self.model(x, augment=augment) # forward
|
697 |
+
|
698 |
+
# Post-process
|
699 |
+
with dt[2]:
|
700 |
+
y = non_max_suppression(y if self.dmb else y[0],
|
701 |
+
self.conf,
|
702 |
+
self.iou,
|
703 |
+
self.classes,
|
704 |
+
self.agnostic,
|
705 |
+
self.multi_label,
|
706 |
+
max_det=self.max_det) # NMS
|
707 |
+
for i in range(n):
|
708 |
+
scale_boxes(shape1, y[i][:, :4], shape0[i])
|
709 |
+
|
710 |
+
return Detections(ims, y, files, dt, self.names, x.shape)
|
711 |
+
|
712 |
+
|
713 |
+
class Detections:
|
714 |
+
# YOLOv5 detections class for inference results
|
715 |
+
def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
|
716 |
+
super().__init__()
|
717 |
+
d = pred[0].device # device
|
718 |
+
gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] # normalizations
|
719 |
+
self.ims = ims # list of images as numpy arrays
|
720 |
+
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
|
721 |
+
self.names = names # class names
|
722 |
+
self.files = files # image filenames
|
723 |
+
self.times = times # profiling times
|
724 |
+
self.xyxy = pred # xyxy pixels
|
725 |
+
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
|
726 |
+
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
|
727 |
+
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
|
728 |
+
self.n = len(self.pred) # number of images (batch size)
|
729 |
+
self.t = tuple(x.t / self.n * 1E3 for x in times) # timestamps (ms)
|
730 |
+
self.s = tuple(shape) # inference BCHW shape
|
731 |
+
|
732 |
+
def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
|
733 |
+
s, crops = '', []
|
734 |
+
for i, (im, pred) in enumerate(zip(self.ims, self.pred)):
|
735 |
+
s += f'\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
|
736 |
+
if pred.shape[0]:
|
737 |
+
for c in pred[:, -1].unique():
|
738 |
+
n = (pred[:, -1] == c).sum() # detections per class
|
739 |
+
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
|
740 |
+
s = s.rstrip(', ')
|
741 |
+
if show or save or render or crop:
|
742 |
+
annotator = Annotator(im, example=str(self.names))
|
743 |
+
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
|
744 |
+
label = f'{self.names[int(cls)]} {conf:.2f}'
|
745 |
+
if crop:
|
746 |
+
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
|
747 |
+
crops.append({
|
748 |
+
'box': box,
|
749 |
+
'conf': conf,
|
750 |
+
'cls': cls,
|
751 |
+
'label': label,
|
752 |
+
'im': save_one_box(box, im, file=file, save=save)})
|
753 |
+
else: # all others
|
754 |
+
annotator.box_label(box, label if labels else '', color=colors(cls))
|
755 |
+
im = annotator.im
|
756 |
+
else:
|
757 |
+
s += '(no detections)'
|
758 |
+
|
759 |
+
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
|
760 |
+
if show:
|
761 |
+
display(im) if is_notebook() else im.show(self.files[i])
|
762 |
+
if save:
|
763 |
+
f = self.files[i]
|
764 |
+
im.save(save_dir / f) # save
|
765 |
+
if i == self.n - 1:
|
766 |
+
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
|
767 |
+
if render:
|
768 |
+
self.ims[i] = np.asarray(im)
|
769 |
+
if pprint:
|
770 |
+
s = s.lstrip('\n')
|
771 |
+
return f'{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t
|
772 |
+
if crop:
|
773 |
+
if save:
|
774 |
+
LOGGER.info(f'Saved results to {save_dir}\n')
|
775 |
+
return crops
|
776 |
+
|
777 |
+
@TryExcept('Showing images is not supported in this environment')
|
778 |
+
def show(self, labels=True):
|
779 |
+
self._run(show=True, labels=labels) # show results
|
780 |
+
|
781 |
+
def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):
|
782 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) # increment save_dir
|
783 |
+
self._run(save=True, labels=labels, save_dir=save_dir) # save results
|
784 |
+
|
785 |
+
def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):
|
786 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
|
787 |
+
return self._run(crop=True, save=save, save_dir=save_dir) # crop results
|
788 |
+
|
789 |
+
def render(self, labels=True):
|
790 |
+
self._run(render=True, labels=labels) # render results
|
791 |
+
return self.ims
|
792 |
+
|
793 |
+
def pandas(self):
|
794 |
+
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
|
795 |
+
new = copy(self) # return copy
|
796 |
+
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
|
797 |
+
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
|
798 |
+
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
|
799 |
+
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
|
800 |
+
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
|
801 |
+
return new
|
802 |
+
|
803 |
+
def tolist(self):
|
804 |
+
# return a list of Detections objects, i.e. 'for result in results.tolist():'
|
805 |
+
r = range(self.n) # iterable
|
806 |
+
x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
|
807 |
+
# for d in x:
|
808 |
+
# for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
|
809 |
+
# setattr(d, k, getattr(d, k)[0]) # pop out of list
|
810 |
+
return x
|
811 |
+
|
812 |
+
def print(self):
|
813 |
+
LOGGER.info(self.__str__())
|
814 |
+
|
815 |
+
def __len__(self): # override len(results)
|
816 |
+
return self.n
|
817 |
+
|
818 |
+
def __str__(self): # override print(results)
|
819 |
+
return self._run(pprint=True) # print results
|
820 |
+
|
821 |
+
def __repr__(self):
|
822 |
+
return f'YOLOv5 {self.__class__} instance\n' + self.__str__()
|
823 |
+
|
824 |
+
|
825 |
+
class Proto(nn.Module):
|
826 |
+
# YOLOv5 mask Proto module for segmentation models
|
827 |
+
def __init__(self, c1, c_=256, c2=32): # ch_in, number of protos, number of masks
|
828 |
+
super().__init__()
|
829 |
+
self.cv1 = Conv(c1, c_, k=3)
|
830 |
+
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
|
831 |
+
self.cv2 = Conv(c_, c_, k=3)
|
832 |
+
self.cv3 = Conv(c_, c2)
|
833 |
+
|
834 |
+
def forward(self, x):
|
835 |
+
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
|
836 |
+
|
837 |
+
|
838 |
+
class Classify(nn.Module):
|
839 |
+
# YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
840 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
|
841 |
+
super().__init__()
|
842 |
+
c_ = 1280 # efficientnet_b0 size
|
843 |
+
self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
|
844 |
+
self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
|
845 |
+
self.drop = nn.Dropout(p=0.0, inplace=True)
|
846 |
+
self.linear = nn.Linear(c_, c2) # to x(b,c2)
|
847 |
+
|
848 |
+
def forward(self, x):
|
849 |
+
if isinstance(x, list):
|
850 |
+
x = torch.cat(x, 1)
|
851 |
+
return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
|
models/experimental.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Experimental modules
|
4 |
+
"""
|
5 |
+
import math
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
|
11 |
+
from utils.downloads import attempt_download
|
12 |
+
|
13 |
+
|
14 |
+
class Sum(nn.Module):
|
15 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
16 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
17 |
+
super().__init__()
|
18 |
+
self.weight = weight # apply weights boolean
|
19 |
+
self.iter = range(n - 1) # iter object
|
20 |
+
if weight:
|
21 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
22 |
+
|
23 |
+
def forward(self, x):
|
24 |
+
y = x[0] # no weight
|
25 |
+
if self.weight:
|
26 |
+
w = torch.sigmoid(self.w) * 2
|
27 |
+
for i in self.iter:
|
28 |
+
y = y + x[i + 1] * w[i]
|
29 |
+
else:
|
30 |
+
for i in self.iter:
|
31 |
+
y = y + x[i + 1]
|
32 |
+
return y
|
33 |
+
|
34 |
+
|
35 |
+
class MixConv2d(nn.Module):
|
36 |
+
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
37 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
38 |
+
super().__init__()
|
39 |
+
n = len(k) # number of convolutions
|
40 |
+
if equal_ch: # equal c_ per group
|
41 |
+
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
42 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
43 |
+
else: # equal weight.numel() per group
|
44 |
+
b = [c2] + [0] * n
|
45 |
+
a = np.eye(n + 1, n, k=-1)
|
46 |
+
a -= np.roll(a, 1, axis=1)
|
47 |
+
a *= np.array(k) ** 2
|
48 |
+
a[0] = 1
|
49 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
50 |
+
|
51 |
+
self.m = nn.ModuleList([
|
52 |
+
nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
53 |
+
self.bn = nn.BatchNorm2d(c2)
|
54 |
+
self.act = nn.SiLU()
|
55 |
+
|
56 |
+
def forward(self, x):
|
57 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
58 |
+
|
59 |
+
|
60 |
+
class Ensemble(nn.ModuleList):
|
61 |
+
# Ensemble of models
|
62 |
+
def __init__(self):
|
63 |
+
super().__init__()
|
64 |
+
|
65 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
66 |
+
y = [module(x, augment, profile, visualize)[0] for module in self]
|
67 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
68 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
69 |
+
y = torch.cat(y, 1) # nms ensemble
|
70 |
+
return y, None # inference, train output
|
71 |
+
|
72 |
+
|
73 |
+
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
74 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
75 |
+
from models.yolo import Detect, Model
|
76 |
+
|
77 |
+
model = Ensemble()
|
78 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
79 |
+
ckpt = torch.load(attempt_download(w), map_location='cpu') # load
|
80 |
+
ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
|
81 |
+
|
82 |
+
# Model compatibility updates
|
83 |
+
if not hasattr(ckpt, 'stride'):
|
84 |
+
ckpt.stride = torch.tensor([32.])
|
85 |
+
if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):
|
86 |
+
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
|
87 |
+
|
88 |
+
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode
|
89 |
+
|
90 |
+
# Module compatibility updates
|
91 |
+
for m in model.modules():
|
92 |
+
t = type(m)
|
93 |
+
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
94 |
+
m.inplace = inplace # torch 1.7.0 compatibility
|
95 |
+
if t is Detect and not isinstance(m.anchor_grid, list):
|
96 |
+
delattr(m, 'anchor_grid')
|
97 |
+
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
98 |
+
elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
|
99 |
+
m.recompute_scale_factor = None # torch 1.11.0 compatibility
|
100 |
+
|
101 |
+
# Return model
|
102 |
+
if len(model) == 1:
|
103 |
+
return model[-1]
|
104 |
+
|
105 |
+
# Return detection ensemble
|
106 |
+
print(f'Ensemble created with {weights}\n')
|
107 |
+
for k in 'names', 'nc', 'yaml':
|
108 |
+
setattr(model, k, getattr(model[0], k))
|
109 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
110 |
+
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
|
111 |
+
return model
|
models/hub/anchors.yaml
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
# Default anchors for COCO data
|
3 |
+
|
4 |
+
|
5 |
+
# P5 -------------------------------------------------------------------------------------------------------------------
|
6 |
+
# P5-640:
|
7 |
+
anchors_p5_640:
|
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 |
+
|
13 |
+
# P6 -------------------------------------------------------------------------------------------------------------------
|
14 |
+
# 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
|
15 |
+
anchors_p6_640:
|
16 |
+
- [9,11, 21,19, 17,41] # P3/8
|
17 |
+
- [43,32, 39,70, 86,64] # P4/16
|
18 |
+
- [65,131, 134,130, 120,265] # P5/32
|
19 |
+
- [282,180, 247,354, 512,387] # P6/64
|
20 |
+
|
21 |
+
# 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
|
22 |
+
anchors_p6_1280:
|
23 |
+
- [19,27, 44,40, 38,94] # P3/8
|
24 |
+
- [96,68, 86,152, 180,137] # P4/16
|
25 |
+
- [140,301, 303,264, 238,542] # P5/32
|
26 |
+
- [436,615, 739,380, 925,792] # P6/64
|
27 |
+
|
28 |
+
# 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
|
29 |
+
anchors_p6_1920:
|
30 |
+
- [28,41, 67,59, 57,141] # P3/8
|
31 |
+
- [144,103, 129,227, 270,205] # P4/16
|
32 |
+
- [209,452, 455,396, 358,812] # P5/32
|
33 |
+
- [653,922, 1109,570, 1387,1187] # P6/64
|
34 |
+
|
35 |
+
|
36 |
+
# P7 -------------------------------------------------------------------------------------------------------------------
|
37 |
+
# 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
|
38 |
+
anchors_p7_640:
|
39 |
+
- [11,11, 13,30, 29,20] # P3/8
|
40 |
+
- [30,46, 61,38, 39,92] # P4/16
|
41 |
+
- [78,80, 146,66, 79,163] # P5/32
|
42 |
+
- [149,150, 321,143, 157,303] # P6/64
|
43 |
+
- [257,402, 359,290, 524,372] # P7/128
|
44 |
+
|
45 |
+
# 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
|
46 |
+
anchors_p7_1280:
|
47 |
+
- [19,22, 54,36, 32,77] # P3/8
|
48 |
+
- [70,83, 138,71, 75,173] # P4/16
|
49 |
+
- [165,159, 148,334, 375,151] # P5/32
|
50 |
+
- [334,317, 251,626, 499,474] # P6/64
|
51 |
+
- [750,326, 534,814, 1079,818] # P7/128
|
52 |
+
|
53 |
+
# 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
|
54 |
+
anchors_p7_1920:
|
55 |
+
- [29,34, 81,55, 47,115] # P3/8
|
56 |
+
- [105,124, 207,107, 113,259] # P4/16
|
57 |
+
- [247,238, 222,500, 563,227] # P5/32
|
58 |
+
- [501,476, 376,939, 749,711] # P6/64
|
59 |
+
- [1126,489, 801,1222, 1618,1227] # P7/128
|
models/hub/yolov3-spp.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 |
+
]
|
models/hub/yolov3-tiny.yaml
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 |
+
]
|
models/hub/yolov3.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 |
+
]
|
models/hub/yolov5-bifpn.yaml
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 v6.0 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1024]],
|
24 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
25 |
+
]
|
26 |
+
|
27 |
+
# YOLOv5 v6.0 BiFPN 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, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change
|
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 |
+
]
|
models/hub/yolov5-fpn.yaml
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 v6.0 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1024]],
|
24 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
25 |
+
]
|
26 |
+
|
27 |
+
# YOLOv5 v6.0 FPN head
|
28 |
+
head:
|
29 |
+
[[-1, 3, C3, [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, C3, [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, C3, [256, False]], # 18 (P3/8-small)
|
40 |
+
|
41 |
+
[[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
42 |
+
]
|
models/hub/yolov5-p2.yaml
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1024]],
|
21 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
22 |
+
]
|
23 |
+
|
24 |
+
# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs
|
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 |
+
[[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
|
54 |
+
]
|
models/hub/yolov5-p34.yaml
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.50 # layer channel multiple
|
7 |
+
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 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, 6, 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, 3, C3, [ 1024 ] ],
|
21 |
+
[ -1, 1, SPPF, [ 1024, 5 ] ], # 9
|
22 |
+
]
|
23 |
+
|
24 |
+
# YOLOv5 v6.0 head with (P3, P4) outputs
|
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, [ 256, 3, 2 ] ],
|
37 |
+
[ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
|
38 |
+
[ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium)
|
39 |
+
|
40 |
+
[ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4)
|
41 |
+
]
|
models/hub/yolov5-p6.yaml
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, SPPF, [1024, 5]], # 11
|
24 |
+
]
|
25 |
+
|
26 |
+
# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs
|
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 (P6/64-xlarge)
|
54 |
+
|
55 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
56 |
+
]
|
models/hub/yolov5-p7.yaml
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1280]],
|
25 |
+
[-1, 1, SPPF, [1280, 5]], # 13
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs
|
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 |
+
]
|
models/hub/yolov5-panet.yaml
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 v6.0 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1024]],
|
24 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
25 |
+
]
|
26 |
+
|
27 |
+
# YOLOv5 v6.0 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, 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 |
+
]
|
models/hub/yolov5l6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
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 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 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 |
+
]
|
models/hub/yolov5m6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 π by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 0.67 # model depth multiple
|
6 |
+
width_multiple: 0.75 # layer channel multiple
|
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 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 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 |
+
]
|