Spaces:
Sleeping
Sleeping
uploading yolov5 model
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- yolov5/.dockerignore +222 -0
- yolov5/.gitattributes +2 -0
- yolov5/.gitignore +258 -0
- yolov5/CITATION.cff +14 -0
- yolov5/CONTRIBUTING.md +76 -0
- yolov5/LICENSE +661 -0
- yolov5/README.md +472 -0
- yolov5/README.zh-CN.md +471 -0
- yolov5/benchmarks.py +294 -0
- yolov5/classify/predict.py +241 -0
- yolov5/classify/train.py +382 -0
- yolov5/classify/tutorial.ipynb +0 -0
- yolov5/classify/val.py +178 -0
- yolov5/data/Argoverse.yaml +72 -0
- yolov5/data/GlobalWheat2020.yaml +52 -0
- yolov5/data/ImageNet.yaml +1020 -0
- yolov5/data/ImageNet10.yaml +30 -0
- yolov5/data/ImageNet100.yaml +119 -0
- yolov5/data/ImageNet1000.yaml +1020 -0
- yolov5/data/Objects365.yaml +436 -0
- yolov5/data/SKU-110K.yaml +51 -0
- yolov5/data/VOC.yaml +98 -0
- yolov5/data/VisDrone.yaml +68 -0
- yolov5/data/coco.yaml +114 -0
- yolov5/data/coco128-seg.yaml +99 -0
- yolov5/data/coco128.yaml +99 -0
- yolov5/data/hyps/hyp.Objects365.yaml +34 -0
- yolov5/data/hyps/hyp.VOC.yaml +40 -0
- yolov5/data/hyps/hyp.no-augmentation.yaml +35 -0
- yolov5/data/hyps/hyp.scratch-high.yaml +34 -0
- yolov5/data/hyps/hyp.scratch-low.yaml +34 -0
- yolov5/data/hyps/hyp.scratch-med.yaml +34 -0
- yolov5/data/images/bus.jpg +0 -0
- yolov5/data/images/zidane.jpg +0 -0
- yolov5/data/scripts/download_weights.sh +22 -0
- yolov5/data/scripts/get_coco.sh +56 -0
- yolov5/data/scripts/get_coco128.sh +17 -0
- yolov5/data/scripts/get_imagenet.sh +51 -0
- yolov5/data/scripts/get_imagenet10.sh +29 -0
- yolov5/data/scripts/get_imagenet100.sh +29 -0
- yolov5/data/scripts/get_imagenet1000.sh +29 -0
- yolov5/data/xView.yaml +151 -0
- yolov5/detect.py +425 -0
- yolov5/export.py +1538 -0
- yolov5/hubconf.py +510 -0
- yolov5/models/__init__.py +0 -0
- yolov5/models/common.py +1083 -0
- yolov5/models/experimental.py +130 -0
- yolov5/models/hub/anchors.yaml +56 -0
- yolov5/models/hub/yolov3-spp.yaml +52 -0
yolov5/.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
|
yolov5/.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# this drop notebooks from GitHub language stats
|
2 |
+
*.ipynb linguist-vendored
|
yolov5/.gitignore
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
*.mlpackage
|
58 |
+
*.torchscript
|
59 |
+
*.tflite
|
60 |
+
*.h5
|
61 |
+
*_saved_model/
|
62 |
+
*_web_model/
|
63 |
+
*_openvino_model/
|
64 |
+
*_paddle_model/
|
65 |
+
darknet53.conv.74
|
66 |
+
yolov3-tiny.conv.15
|
67 |
+
|
68 |
+
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
69 |
+
# Byte-compiled / optimized / DLL files
|
70 |
+
__pycache__/
|
71 |
+
*.py[cod]
|
72 |
+
*$py.class
|
73 |
+
|
74 |
+
# C extensions
|
75 |
+
*.so
|
76 |
+
|
77 |
+
# Distribution / packaging
|
78 |
+
.Python
|
79 |
+
env/
|
80 |
+
build/
|
81 |
+
develop-eggs/
|
82 |
+
dist/
|
83 |
+
downloads/
|
84 |
+
eggs/
|
85 |
+
.eggs/
|
86 |
+
lib/
|
87 |
+
lib64/
|
88 |
+
parts/
|
89 |
+
sdist/
|
90 |
+
var/
|
91 |
+
wheels/
|
92 |
+
*.egg-info/
|
93 |
+
/wandb/
|
94 |
+
.installed.cfg
|
95 |
+
*.egg
|
96 |
+
|
97 |
+
|
98 |
+
# PyInstaller
|
99 |
+
# Usually these files are written by a python script from a template
|
100 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
101 |
+
*.manifest
|
102 |
+
*.spec
|
103 |
+
|
104 |
+
# Installer logs
|
105 |
+
pip-log.txt
|
106 |
+
pip-delete-this-directory.txt
|
107 |
+
|
108 |
+
# Unit test / coverage reports
|
109 |
+
htmlcov/
|
110 |
+
.tox/
|
111 |
+
.coverage
|
112 |
+
.coverage.*
|
113 |
+
.cache
|
114 |
+
nosetests.xml
|
115 |
+
coverage.xml
|
116 |
+
*.cover
|
117 |
+
.hypothesis/
|
118 |
+
|
119 |
+
# Translations
|
120 |
+
*.mo
|
121 |
+
*.pot
|
122 |
+
|
123 |
+
# Django stuff:
|
124 |
+
*.log
|
125 |
+
local_settings.py
|
126 |
+
|
127 |
+
# Flask stuff:
|
128 |
+
instance/
|
129 |
+
.webassets-cache
|
130 |
+
|
131 |
+
# Scrapy stuff:
|
132 |
+
.scrapy
|
133 |
+
|
134 |
+
# Sphinx documentation
|
135 |
+
docs/_build/
|
136 |
+
|
137 |
+
# PyBuilder
|
138 |
+
target/
|
139 |
+
|
140 |
+
# Jupyter Notebook
|
141 |
+
.ipynb_checkpoints
|
142 |
+
|
143 |
+
# pyenv
|
144 |
+
.python-version
|
145 |
+
|
146 |
+
# celery beat schedule file
|
147 |
+
celerybeat-schedule
|
148 |
+
|
149 |
+
# SageMath parsed files
|
150 |
+
*.sage.py
|
151 |
+
|
152 |
+
# dotenv
|
153 |
+
.env
|
154 |
+
|
155 |
+
# virtualenv
|
156 |
+
.venv*
|
157 |
+
venv*/
|
158 |
+
ENV*/
|
159 |
+
|
160 |
+
# Spyder project settings
|
161 |
+
.spyderproject
|
162 |
+
.spyproject
|
163 |
+
|
164 |
+
# Rope project settings
|
165 |
+
.ropeproject
|
166 |
+
|
167 |
+
# mkdocs documentation
|
168 |
+
/site
|
169 |
+
|
170 |
+
# mypy
|
171 |
+
.mypy_cache/
|
172 |
+
|
173 |
+
|
174 |
+
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
175 |
+
|
176 |
+
# General
|
177 |
+
.DS_Store
|
178 |
+
.AppleDouble
|
179 |
+
.LSOverride
|
180 |
+
|
181 |
+
# Icon must end with two \r
|
182 |
+
Icon
|
183 |
+
Icon?
|
184 |
+
|
185 |
+
# Thumbnails
|
186 |
+
._*
|
187 |
+
|
188 |
+
# Files that might appear in the root of a volume
|
189 |
+
.DocumentRevisions-V100
|
190 |
+
.fseventsd
|
191 |
+
.Spotlight-V100
|
192 |
+
.TemporaryItems
|
193 |
+
.Trashes
|
194 |
+
.VolumeIcon.icns
|
195 |
+
.com.apple.timemachine.donotpresent
|
196 |
+
|
197 |
+
# Directories potentially created on remote AFP share
|
198 |
+
.AppleDB
|
199 |
+
.AppleDesktop
|
200 |
+
Network Trash Folder
|
201 |
+
Temporary Items
|
202 |
+
.apdisk
|
203 |
+
|
204 |
+
|
205 |
+
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
206 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
207 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
208 |
+
|
209 |
+
# User-specific stuff:
|
210 |
+
.idea/*
|
211 |
+
.idea/**/workspace.xml
|
212 |
+
.idea/**/tasks.xml
|
213 |
+
.idea/dictionaries
|
214 |
+
.html # Bokeh Plots
|
215 |
+
.pg # TensorFlow Frozen Graphs
|
216 |
+
.avi # videos
|
217 |
+
|
218 |
+
# Sensitive or high-churn files:
|
219 |
+
.idea/**/dataSources/
|
220 |
+
.idea/**/dataSources.ids
|
221 |
+
.idea/**/dataSources.local.xml
|
222 |
+
.idea/**/sqlDataSources.xml
|
223 |
+
.idea/**/dynamic.xml
|
224 |
+
.idea/**/uiDesigner.xml
|
225 |
+
|
226 |
+
# Gradle:
|
227 |
+
.idea/**/gradle.xml
|
228 |
+
.idea/**/libraries
|
229 |
+
|
230 |
+
# CMake
|
231 |
+
cmake-build-debug/
|
232 |
+
cmake-build-release/
|
233 |
+
|
234 |
+
# Mongo Explorer plugin:
|
235 |
+
.idea/**/mongoSettings.xml
|
236 |
+
|
237 |
+
## File-based project format:
|
238 |
+
*.iws
|
239 |
+
|
240 |
+
## Plugin-specific files:
|
241 |
+
|
242 |
+
# IntelliJ
|
243 |
+
out/
|
244 |
+
|
245 |
+
# mpeltonen/sbt-idea plugin
|
246 |
+
.idea_modules/
|
247 |
+
|
248 |
+
# JIRA plugin
|
249 |
+
atlassian-ide-plugin.xml
|
250 |
+
|
251 |
+
# Cursive Clojure plugin
|
252 |
+
.idea/replstate.xml
|
253 |
+
|
254 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
255 |
+
com_crashlytics_export_strings.xml
|
256 |
+
crashlytics.properties
|
257 |
+
crashlytics-build.properties
|
258 |
+
fabric.properties
|
yolov5/CITATION.cff
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cff-version: 1.2.0
|
2 |
+
preferred-citation:
|
3 |
+
type: software
|
4 |
+
message: If you use YOLOv5, please cite it as below.
|
5 |
+
authors:
|
6 |
+
- family-names: Jocher
|
7 |
+
given-names: Glenn
|
8 |
+
orcid: "https://orcid.org/0000-0001-5950-6979"
|
9 |
+
title: "YOLOv5 by Ultralytics"
|
10 |
+
version: 7.0
|
11 |
+
doi: 10.5281/zenodo.3908559
|
12 |
+
date-released: 2020-5-29
|
13 |
+
license: AGPL-3.0
|
14 |
+
url: "https://github.com/ultralytics/yolov5"
|
yolov5/CONTRIBUTING.md
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 helping push the frontiers of what's possible in AI 😃!
|
12 |
+
|
13 |
+
## Submitting a Pull Request (PR) 🛠️
|
14 |
+
|
15 |
+
Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
|
16 |
+
|
17 |
+
### 1. Select File to Update
|
18 |
+
|
19 |
+
Select `requirements.txt` to update by clicking on it in GitHub.
|
20 |
+
|
21 |
+
<p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
|
22 |
+
|
23 |
+
### 2. Click 'Edit this file'
|
24 |
+
|
25 |
+
The button is in the top-right corner.
|
26 |
+
|
27 |
+
<p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
|
28 |
+
|
29 |
+
### 3. Make Changes
|
30 |
+
|
31 |
+
Change the `matplotlib` version from `3.2.2` to `3.3`.
|
32 |
+
|
33 |
+
<p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
|
34 |
+
|
35 |
+
### 4. Preview Changes and Submit PR
|
36 |
+
|
37 |
+
Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch** for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
|
38 |
+
|
39 |
+
<p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
|
40 |
+
|
41 |
+
### PR recommendations
|
42 |
+
|
43 |
+
To allow your work to be integrated as seamlessly as possible, we advise you to:
|
44 |
+
|
45 |
+
- ✅ Verify your PR is **up-to-date** with `ultralytics/yolov5` `master` branch. If your PR is behind you can update your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
|
46 |
+
|
47 |
+
<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>
|
48 |
+
|
49 |
+
- ✅ Verify all YOLOv5 Continuous Integration (CI) **checks are passing**.
|
50 |
+
|
51 |
+
<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>
|
52 |
+
|
53 |
+
- ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
|
54 |
+
|
55 |
+
## Submitting a Bug Report 🐛
|
56 |
+
|
57 |
+
If you spot a problem with YOLOv5 please submit a Bug Report!
|
58 |
+
|
59 |
+
For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few short guidelines below to help users provide what we need to get started.
|
60 |
+
|
61 |
+
When asking a question, people will be better able to provide help if you provide **code** that they can easily understand and use to **reproduce** the problem. This is referred to by community members as creating a [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/). Your code that reproduces the problem should be:
|
62 |
+
|
63 |
+
- ✅ **Minimal** – Use as little code as possible that still produces the same problem
|
64 |
+
- ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
|
65 |
+
- ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
|
66 |
+
|
67 |
+
In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code should be:
|
68 |
+
|
69 |
+
- ✅ **Current** – Verify that your code is up-to-date with the current GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new copy to ensure your problem has not already been resolved by previous commits.
|
70 |
+
- ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
|
71 |
+
|
72 |
+
If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛 **Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and provide a [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/) to help us better understand and diagnose your problem.
|
73 |
+
|
74 |
+
## License
|
75 |
+
|
76 |
+
By contributing, you agree that your contributions will be licensed under the [AGPL-3.0 license](https://choosealicense.com/licenses/agpl-3.0/)
|
yolov5/LICENSE
ADDED
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 Affero General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works, specifically designed to ensure
|
12 |
+
cooperation with the community in the case of network server software.
|
13 |
+
|
14 |
+
The licenses for most software and other practical works are designed
|
15 |
+
to take away your freedom to share and change the works. By contrast,
|
16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
17 |
+
share and change all versions of a program--to make sure it remains free
|
18 |
+
software for all its users.
|
19 |
+
|
20 |
+
When we speak of free software, we are referring to freedom, not
|
21 |
+
price. Our General Public Licenses are designed to make sure that you
|
22 |
+
have the freedom to distribute copies of free software (and charge for
|
23 |
+
them if you wish), that you receive source code or can get it if you
|
24 |
+
want it, that you can change the software or use pieces of it in new
|
25 |
+
free programs, and that you know you can do these things.
|
26 |
+
|
27 |
+
Developers that use our General Public Licenses protect your rights
|
28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
29 |
+
you this License which gives you legal permission to copy, distribute
|
30 |
+
and/or modify the software.
|
31 |
+
|
32 |
+
A secondary benefit of defending all users' freedom is that
|
33 |
+
improvements made in alternate versions of the program, if they
|
34 |
+
receive widespread use, become available for other developers to
|
35 |
+
incorporate. Many developers of free software are heartened and
|
36 |
+
encouraged by the resulting cooperation. However, in the case of
|
37 |
+
software used on network servers, this result may fail to come about.
|
38 |
+
The GNU General Public License permits making a modified version and
|
39 |
+
letting the public access it on a server without ever releasing its
|
40 |
+
source code to the public.
|
41 |
+
|
42 |
+
The GNU Affero General Public License is designed specifically to
|
43 |
+
ensure that, in such cases, the modified source code becomes available
|
44 |
+
to the community. It requires the operator of a network server to
|
45 |
+
provide the source code of the modified version running there to the
|
46 |
+
users of that server. Therefore, public use of a modified version, on
|
47 |
+
a publicly accessible server, gives the public access to the source
|
48 |
+
code of the modified version.
|
49 |
+
|
50 |
+
An older license, called the Affero General Public License and
|
51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
53 |
+
released a new version of the Affero GPL which permits relicensing under
|
54 |
+
this license.
|
55 |
+
|
56 |
+
The precise terms and conditions for copying, distribution and
|
57 |
+
modification follow.
|
58 |
+
|
59 |
+
TERMS AND CONDITIONS
|
60 |
+
|
61 |
+
0. Definitions.
|
62 |
+
|
63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
64 |
+
|
65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
66 |
+
works, such as semiconductor masks.
|
67 |
+
|
68 |
+
"The Program" refers to any copyrightable work licensed under this
|
69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
70 |
+
"recipients" may be individuals or organizations.
|
71 |
+
|
72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
73 |
+
in a fashion requiring copyright permission, other than the making of an
|
74 |
+
exact copy. The resulting work is called a "modified version" of the
|
75 |
+
earlier work or a work "based on" the earlier work.
|
76 |
+
|
77 |
+
A "covered work" means either the unmodified Program or a work based
|
78 |
+
on the Program.
|
79 |
+
|
80 |
+
To "propagate" a work means to do anything with it that, without
|
81 |
+
permission, would make you directly or secondarily liable for
|
82 |
+
infringement under applicable copyright law, except executing it on a
|
83 |
+
computer or modifying a private copy. Propagation includes copying,
|
84 |
+
distribution (with or without modification), making available to the
|
85 |
+
public, and in some countries other activities as well.
|
86 |
+
|
87 |
+
To "convey" a work means any kind of propagation that enables other
|
88 |
+
parties to make or receive copies. Mere interaction with a user through
|
89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
90 |
+
|
91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
92 |
+
to the extent that it includes a convenient and prominently visible
|
93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
94 |
+
tells the user that there is no warranty for the work (except to the
|
95 |
+
extent that warranties are provided), that licensees may convey the
|
96 |
+
work under this License, and how to view a copy of this License. If
|
97 |
+
the interface presents a list of user commands or options, such as a
|
98 |
+
menu, a prominent item in the list meets this criterion.
|
99 |
+
|
100 |
+
1. Source Code.
|
101 |
+
|
102 |
+
The "source code" for a work means the preferred form of the work
|
103 |
+
for making modifications to it. "Object code" means any non-source
|
104 |
+
form of a work.
|
105 |
+
|
106 |
+
A "Standard Interface" means an interface that either is an official
|
107 |
+
standard defined by a recognized standards body, or, in the case of
|
108 |
+
interfaces specified for a particular programming language, one that
|
109 |
+
is widely used among developers working in that language.
|
110 |
+
|
111 |
+
The "System Libraries" of an executable work include anything, other
|
112 |
+
than the work as a whole, that (a) is included in the normal form of
|
113 |
+
packaging a Major Component, but which is not part of that Major
|
114 |
+
Component, and (b) serves only to enable use of the work with that
|
115 |
+
Major Component, or to implement a Standard Interface for which an
|
116 |
+
implementation is available to the public in source code form. A
|
117 |
+
"Major Component", in this context, means a major essential component
|
118 |
+
(kernel, window system, and so on) of the specific operating system
|
119 |
+
(if any) on which the executable work runs, or a compiler used to
|
120 |
+
produce the work, or an object code interpreter used to run it.
|
121 |
+
|
122 |
+
The "Corresponding Source" for a work in object code form means all
|
123 |
+
the source code needed to generate, install, and (for an executable
|
124 |
+
work) run the object code and to modify the work, including scripts to
|
125 |
+
control those activities. However, it does not include the work's
|
126 |
+
System Libraries, or general-purpose tools or generally available free
|
127 |
+
programs which are used unmodified in performing those activities but
|
128 |
+
which are not part of the work. For example, Corresponding Source
|
129 |
+
includes interface definition files associated with source files for
|
130 |
+
the work, and the source code for shared libraries and dynamically
|
131 |
+
linked subprograms that the work is specifically designed to require,
|
132 |
+
such as by intimate data communication or control flow between those
|
133 |
+
subprograms and other parts of the work.
|
134 |
+
|
135 |
+
The Corresponding Source need not include anything that users
|
136 |
+
can regenerate automatically from other parts of the Corresponding
|
137 |
+
Source.
|
138 |
+
|
139 |
+
The Corresponding Source for a work in source code form is that
|
140 |
+
same work.
|
141 |
+
|
142 |
+
2. Basic Permissions.
|
143 |
+
|
144 |
+
All rights granted under this License are granted for the term of
|
145 |
+
copyright on the Program, and are irrevocable provided the stated
|
146 |
+
conditions are met. This License explicitly affirms your unlimited
|
147 |
+
permission to run the unmodified Program. The output from running a
|
148 |
+
covered work is covered by this License only if the output, given its
|
149 |
+
content, constitutes a covered work. This License acknowledges your
|
150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
151 |
+
|
152 |
+
You may make, run and propagate covered works that you do not
|
153 |
+
convey, without conditions so long as your license otherwise remains
|
154 |
+
in force. You may convey covered works to others for the sole purpose
|
155 |
+
of having them make modifications exclusively for you, or provide you
|
156 |
+
with facilities for running those works, provided that you comply with
|
157 |
+
the terms of this License in conveying all material for which you do
|
158 |
+
not control copyright. Those thus making or running the covered works
|
159 |
+
for you must do so exclusively on your behalf, under your direction
|
160 |
+
and control, on terms that prohibit them from making any copies of
|
161 |
+
your copyrighted material outside their relationship with you.
|
162 |
+
|
163 |
+
Conveying under any other circumstances is permitted solely under
|
164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
165 |
+
makes it unnecessary.
|
166 |
+
|
167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
168 |
+
|
169 |
+
No covered work shall be deemed part of an effective technological
|
170 |
+
measure under any applicable law fulfilling obligations under article
|
171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
172 |
+
similar laws prohibiting or restricting circumvention of such
|
173 |
+
measures.
|
174 |
+
|
175 |
+
When you convey a covered work, you waive any legal power to forbid
|
176 |
+
circumvention of technological measures to the extent such circumvention
|
177 |
+
is effected by exercising rights under this License with respect to
|
178 |
+
the covered work, and you disclaim any intention to limit operation or
|
179 |
+
modification of the work as a means of enforcing, against the work's
|
180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
181 |
+
technological measures.
|
182 |
+
|
183 |
+
4. Conveying Verbatim Copies.
|
184 |
+
|
185 |
+
You may convey verbatim copies of the Program's source code as you
|
186 |
+
receive it, in any medium, provided that you conspicuously and
|
187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
188 |
+
keep intact all notices stating that this License and any
|
189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
190 |
+
keep intact all notices of the absence of any warranty; and give all
|
191 |
+
recipients a copy of this License along with the Program.
|
192 |
+
|
193 |
+
You may charge any price or no price for each copy that you convey,
|
194 |
+
and you may offer support or warranty protection for a fee.
|
195 |
+
|
196 |
+
5. Conveying Modified Source Versions.
|
197 |
+
|
198 |
+
You may convey a work based on the Program, or the modifications to
|
199 |
+
produce it from the Program, in the form of source code under the
|
200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
201 |
+
|
202 |
+
a) The work must carry prominent notices stating that you modified
|
203 |
+
it, and giving a relevant date.
|
204 |
+
|
205 |
+
b) The work must carry prominent notices stating that it is
|
206 |
+
released under this License and any conditions added under section
|
207 |
+
7. This requirement modifies the requirement in section 4 to
|
208 |
+
"keep intact all notices".
|
209 |
+
|
210 |
+
c) You must license the entire work, as a whole, under this
|
211 |
+
License to anyone who comes into possession of a copy. This
|
212 |
+
License will therefore apply, along with any applicable section 7
|
213 |
+
additional terms, to the whole of the work, and all its parts,
|
214 |
+
regardless of how they are packaged. This License gives no
|
215 |
+
permission to license the work in any other way, but it does not
|
216 |
+
invalidate such permission if you have separately received it.
|
217 |
+
|
218 |
+
d) If the work has interactive user interfaces, each must display
|
219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
221 |
+
work need not make them do so.
|
222 |
+
|
223 |
+
A compilation of a covered work with other separate and independent
|
224 |
+
works, which are not by their nature extensions of the covered work,
|
225 |
+
and which are not combined with it such as to form a larger program,
|
226 |
+
in or on a volume of a storage or distribution medium, is called an
|
227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
228 |
+
used to limit the access or legal rights of the compilation's users
|
229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
230 |
+
in an aggregate does not cause this License to apply to the other
|
231 |
+
parts of the aggregate.
|
232 |
+
|
233 |
+
6. Conveying Non-Source Forms.
|
234 |
+
|
235 |
+
You may convey a covered work in object code form under the terms
|
236 |
+
of sections 4 and 5, provided that you also convey the
|
237 |
+
machine-readable Corresponding Source under the terms of this License,
|
238 |
+
in one of these ways:
|
239 |
+
|
240 |
+
a) Convey the object code in, or embodied in, a physical product
|
241 |
+
(including a physical distribution medium), accompanied by the
|
242 |
+
Corresponding Source fixed on a durable physical medium
|
243 |
+
customarily used for software interchange.
|
244 |
+
|
245 |
+
b) Convey the object code in, or embodied in, a physical product
|
246 |
+
(including a physical distribution medium), accompanied by a
|
247 |
+
written offer, valid for at least three years and valid for as
|
248 |
+
long as you offer spare parts or customer support for that product
|
249 |
+
model, to give anyone who possesses the object code either (1) a
|
250 |
+
copy of the Corresponding Source for all the software in the
|
251 |
+
product that is covered by this License, on a durable physical
|
252 |
+
medium customarily used for software interchange, for a price no
|
253 |
+
more than your reasonable cost of physically performing this
|
254 |
+
conveying of source, or (2) access to copy the
|
255 |
+
Corresponding Source from a network server at no charge.
|
256 |
+
|
257 |
+
c) Convey individual copies of the object code with a copy of the
|
258 |
+
written offer to provide the Corresponding Source. This
|
259 |
+
alternative is allowed only occasionally and noncommercially, and
|
260 |
+
only if you received the object code with such an offer, in accord
|
261 |
+
with subsection 6b.
|
262 |
+
|
263 |
+
d) Convey the object code by offering access from a designated
|
264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
265 |
+
Corresponding Source in the same way through the same place at no
|
266 |
+
further charge. You need not require recipients to copy the
|
267 |
+
Corresponding Source along with the object code. If the place to
|
268 |
+
copy the object code is a network server, the Corresponding Source
|
269 |
+
may be on a different server (operated by you or a third party)
|
270 |
+
that supports equivalent copying facilities, provided you maintain
|
271 |
+
clear directions next to the object code saying where to find the
|
272 |
+
Corresponding Source. Regardless of what server hosts the
|
273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
274 |
+
available for as long as needed to satisfy these requirements.
|
275 |
+
|
276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
277 |
+
you inform other peers where the object code and Corresponding
|
278 |
+
Source of the work are being offered to the general public at no
|
279 |
+
charge under subsection 6d.
|
280 |
+
|
281 |
+
A separable portion of the object code, whose source code is excluded
|
282 |
+
from the Corresponding Source as a System Library, need not be
|
283 |
+
included in conveying the object code work.
|
284 |
+
|
285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
286 |
+
tangible personal property which is normally used for personal, family,
|
287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
290 |
+
product received by a particular user, "normally used" refers to a
|
291 |
+
typical or common use of that class of product, regardless of the status
|
292 |
+
of the particular user or of the way in which the particular user
|
293 |
+
actually uses, or expects or is expected to use, the product. A product
|
294 |
+
is a consumer product regardless of whether the product has substantial
|
295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
296 |
+
the only significant mode of use of the product.
|
297 |
+
|
298 |
+
"Installation Information" for a User Product means any methods,
|
299 |
+
procedures, authorization keys, or other information required to install
|
300 |
+
and execute modified versions of a covered work in that User Product from
|
301 |
+
a modified version of its Corresponding Source. The information must
|
302 |
+
suffice to ensure that the continued functioning of the modified object
|
303 |
+
code is in no case prevented or interfered with solely because
|
304 |
+
modification has been made.
|
305 |
+
|
306 |
+
If you convey an object code work under this section in, or with, or
|
307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
308 |
+
part of a transaction in which the right of possession and use of the
|
309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
310 |
+
fixed term (regardless of how the transaction is characterized), the
|
311 |
+
Corresponding Source conveyed under this section must be accompanied
|
312 |
+
by the Installation Information. But this requirement does not apply
|
313 |
+
if neither you nor any third party retains the ability to install
|
314 |
+
modified object code on the User Product (for example, the work has
|
315 |
+
been installed in ROM).
|
316 |
+
|
317 |
+
The requirement to provide Installation Information does not include a
|
318 |
+
requirement to continue to provide support service, warranty, or updates
|
319 |
+
for a work that has been modified or installed by the recipient, or for
|
320 |
+
the User Product in which it has been modified or installed. Access to a
|
321 |
+
network may be denied when the modification itself materially and
|
322 |
+
adversely affects the operation of the network or violates the rules and
|
323 |
+
protocols for communication across the network.
|
324 |
+
|
325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
326 |
+
in accord with this section must be in a format that is publicly
|
327 |
+
documented (and with an implementation available to the public in
|
328 |
+
source code form), and must require no special password or key for
|
329 |
+
unpacking, reading or copying.
|
330 |
+
|
331 |
+
7. Additional Terms.
|
332 |
+
|
333 |
+
"Additional permissions" are terms that supplement the terms of this
|
334 |
+
License by making exceptions from one or more of its conditions.
|
335 |
+
Additional permissions that are applicable to the entire Program shall
|
336 |
+
be treated as though they were included in this License, to the extent
|
337 |
+
that they are valid under applicable law. If additional permissions
|
338 |
+
apply only to part of the Program, that part may be used separately
|
339 |
+
under those permissions, but the entire Program remains governed by
|
340 |
+
this License without regard to the additional permissions.
|
341 |
+
|
342 |
+
When you convey a copy of a covered work, you may at your option
|
343 |
+
remove any additional permissions from that copy, or from any part of
|
344 |
+
it. (Additional permissions may be written to require their own
|
345 |
+
removal in certain cases when you modify the work.) You may place
|
346 |
+
additional permissions on material, added by you to a covered work,
|
347 |
+
for which you have or can give appropriate copyright permission.
|
348 |
+
|
349 |
+
Notwithstanding any other provision of this License, for material you
|
350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
351 |
+
that material) supplement the terms of this License with terms:
|
352 |
+
|
353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
354 |
+
terms of sections 15 and 16 of this License; or
|
355 |
+
|
356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
357 |
+
author attributions in that material or in the Appropriate Legal
|
358 |
+
Notices displayed by works containing it; or
|
359 |
+
|
360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
361 |
+
requiring that modified versions of such material be marked in
|
362 |
+
reasonable ways as different from the original version; or
|
363 |
+
|
364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
365 |
+
authors of the material; or
|
366 |
+
|
367 |
+
e) Declining to grant rights under trademark law for use of some
|
368 |
+
trade names, trademarks, or service marks; or
|
369 |
+
|
370 |
+
f) Requiring indemnification of licensors and authors of that
|
371 |
+
material by anyone who conveys the material (or modified versions of
|
372 |
+
it) with contractual assumptions of liability to the recipient, for
|
373 |
+
any liability that these contractual assumptions directly impose on
|
374 |
+
those licensors and authors.
|
375 |
+
|
376 |
+
All other non-permissive additional terms are considered "further
|
377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
378 |
+
received it, or any part of it, contains a notice stating that it is
|
379 |
+
governed by this License along with a term that is a further
|
380 |
+
restriction, you may remove that term. If a license document contains
|
381 |
+
a further restriction but permits relicensing or conveying under this
|
382 |
+
License, you may add to a covered work material governed by the terms
|
383 |
+
of that license document, provided that the further restriction does
|
384 |
+
not survive such relicensing or conveying.
|
385 |
+
|
386 |
+
If you add terms to a covered work in accord with this section, you
|
387 |
+
must place, in the relevant source files, a statement of the
|
388 |
+
additional terms that apply to those files, or a notice indicating
|
389 |
+
where to find the applicable terms.
|
390 |
+
|
391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
392 |
+
form of a separately written license, or stated as exceptions;
|
393 |
+
the above requirements apply either way.
|
394 |
+
|
395 |
+
8. Termination.
|
396 |
+
|
397 |
+
You may not propagate or modify a covered work except as expressly
|
398 |
+
provided under this License. Any attempt otherwise to propagate or
|
399 |
+
modify it is void, and will automatically terminate your rights under
|
400 |
+
this License (including any patent licenses granted under the third
|
401 |
+
paragraph of section 11).
|
402 |
+
|
403 |
+
However, if you cease all violation of this License, then your
|
404 |
+
license from a particular copyright holder is reinstated (a)
|
405 |
+
provisionally, unless and until the copyright holder explicitly and
|
406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
407 |
+
holder fails to notify you of the violation by some reasonable means
|
408 |
+
prior to 60 days after the cessation.
|
409 |
+
|
410 |
+
Moreover, your license from a particular copyright holder is
|
411 |
+
reinstated permanently if the copyright holder notifies you of the
|
412 |
+
violation by some reasonable means, this is the first time you have
|
413 |
+
received notice of violation of this License (for any work) from that
|
414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
415 |
+
your receipt of the notice.
|
416 |
+
|
417 |
+
Termination of your rights under this section does not terminate the
|
418 |
+
licenses of parties who have received copies or rights from you under
|
419 |
+
this License. If your rights have been terminated and not permanently
|
420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
421 |
+
material under section 10.
|
422 |
+
|
423 |
+
9. Acceptance Not Required for Having Copies.
|
424 |
+
|
425 |
+
You are not required to accept this License in order to receive or
|
426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
428 |
+
to receive a copy likewise does not require acceptance. However,
|
429 |
+
nothing other than this License grants you permission to propagate or
|
430 |
+
modify any covered work. These actions infringe copyright if you do
|
431 |
+
not accept this License. Therefore, by modifying or propagating a
|
432 |
+
covered work, you indicate your acceptance of this License to do so.
|
433 |
+
|
434 |
+
10. Automatic Licensing of Downstream Recipients.
|
435 |
+
|
436 |
+
Each time you convey a covered work, the recipient automatically
|
437 |
+
receives a license from the original licensors, to run, modify and
|
438 |
+
propagate that work, subject to this License. You are not responsible
|
439 |
+
for enforcing compliance by third parties with this License.
|
440 |
+
|
441 |
+
An "entity transaction" is a transaction transferring control of an
|
442 |
+
organization, or substantially all assets of one, or subdividing an
|
443 |
+
organization, or merging organizations. If propagation of a covered
|
444 |
+
work results from an entity transaction, each party to that
|
445 |
+
transaction who receives a copy of the work also receives whatever
|
446 |
+
licenses to the work the party's predecessor in interest had or could
|
447 |
+
give under the previous paragraph, plus a right to possession of the
|
448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
449 |
+
the predecessor has it or can get it with reasonable efforts.
|
450 |
+
|
451 |
+
You may not impose any further restrictions on the exercise of the
|
452 |
+
rights granted or affirmed under this License. For example, you may
|
453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
454 |
+
rights granted under this License, and you may not initiate litigation
|
455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
456 |
+
any patent claim is infringed by making, using, selling, offering for
|
457 |
+
sale, or importing the Program or any portion of it.
|
458 |
+
|
459 |
+
11. Patents.
|
460 |
+
|
461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
462 |
+
License of the Program or a work on which the Program is based. The
|
463 |
+
work thus licensed is called the contributor's "contributor version".
|
464 |
+
|
465 |
+
A contributor's "essential patent claims" are all patent claims
|
466 |
+
owned or controlled by the contributor, whether already acquired or
|
467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
468 |
+
by this License, of making, using, or selling its contributor version,
|
469 |
+
but do not include claims that would be infringed only as a
|
470 |
+
consequence of further modification of the contributor version. For
|
471 |
+
purposes of this definition, "control" includes the right to grant
|
472 |
+
patent sublicenses in a manner consistent with the requirements of
|
473 |
+
this License.
|
474 |
+
|
475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
476 |
+
patent license under the contributor's essential patent claims, to
|
477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
478 |
+
propagate the contents of its contributor version.
|
479 |
+
|
480 |
+
In the following three paragraphs, a "patent license" is any express
|
481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
482 |
+
(such as an express permission to practice a patent or covenant not to
|
483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
484 |
+
party means to make such an agreement or commitment not to enforce a
|
485 |
+
patent against the party.
|
486 |
+
|
487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
488 |
+
and the Corresponding Source of the work is not available for anyone
|
489 |
+
to copy, free of charge and under the terms of this License, through a
|
490 |
+
publicly available network server or other readily accessible means,
|
491 |
+
then you must either (1) cause the Corresponding Source to be so
|
492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
494 |
+
consistent with the requirements of this License, to extend the patent
|
495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
496 |
+
actual knowledge that, but for the patent license, your conveying the
|
497 |
+
covered work in a country, or your recipient's use of the covered work
|
498 |
+
in a country, would infringe one or more identifiable patents in that
|
499 |
+
country that you have reason to believe are valid.
|
500 |
+
|
501 |
+
If, pursuant to or in connection with a single transaction or
|
502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
503 |
+
covered work, and grant a patent license to some of the parties
|
504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
505 |
+
or convey a specific copy of the covered work, then the patent license
|
506 |
+
you grant is automatically extended to all recipients of the covered
|
507 |
+
work and works based on it.
|
508 |
+
|
509 |
+
A patent license is "discriminatory" if it does not include within
|
510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
512 |
+
specifically granted under this License. You may not convey a covered
|
513 |
+
work if you are a party to an arrangement with a third party that is
|
514 |
+
in the business of distributing software, under which you make payment
|
515 |
+
to the third party based on the extent of your activity of conveying
|
516 |
+
the work, and under which the third party grants, to any of the
|
517 |
+
parties who would receive the covered work from you, a discriminatory
|
518 |
+
patent license (a) in connection with copies of the covered work
|
519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
520 |
+
for and in connection with specific products or compilations that
|
521 |
+
contain the covered work, unless you entered into that arrangement,
|
522 |
+
or that patent license was granted, prior to 28 March 2007.
|
523 |
+
|
524 |
+
Nothing in this License shall be construed as excluding or limiting
|
525 |
+
any implied license or other defenses to infringement that may
|
526 |
+
otherwise be available to you under applicable patent law.
|
527 |
+
|
528 |
+
12. No Surrender of Others' Freedom.
|
529 |
+
|
530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
531 |
+
otherwise) that contradict the conditions of this License, they do not
|
532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
534 |
+
License and any other pertinent obligations, then as a consequence you may
|
535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
536 |
+
to collect a royalty for further conveying from those to whom you convey
|
537 |
+
the Program, the only way you could satisfy both those terms and this
|
538 |
+
License would be to refrain entirely from conveying the Program.
|
539 |
+
|
540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
541 |
+
|
542 |
+
Notwithstanding any other provision of this License, if you modify the
|
543 |
+
Program, your modified version must prominently offer all users
|
544 |
+
interacting with it remotely through a computer network (if your version
|
545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
546 |
+
Source of your version by providing access to the Corresponding Source
|
547 |
+
from a network server at no charge, through some standard or customary
|
548 |
+
means of facilitating copying of software. This Corresponding Source
|
549 |
+
shall include the Corresponding Source for any work covered by version 3
|
550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
551 |
+
following paragraph.
|
552 |
+
|
553 |
+
Notwithstanding any other provision of this License, you have
|
554 |
+
permission to link or combine any covered work with a work licensed
|
555 |
+
under version 3 of the GNU General Public License into a single
|
556 |
+
combined work, and to convey the resulting work. The terms of this
|
557 |
+
License will continue to apply to the part which is the covered work,
|
558 |
+
but the work with which it is combined will remain governed by version
|
559 |
+
3 of the GNU General Public License.
|
560 |
+
|
561 |
+
14. Revised Versions of this License.
|
562 |
+
|
563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
566 |
+
address new problems or concerns.
|
567 |
+
|
568 |
+
Each version is given a distinguishing version number. If the
|
569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
570 |
+
Public License "or any later version" applies to it, you have the
|
571 |
+
option of following the terms and conditions either of that numbered
|
572 |
+
version or of any later version published by the Free Software
|
573 |
+
Foundation. If the Program does not specify a version number of the
|
574 |
+
GNU Affero General Public License, you may choose any version ever published
|
575 |
+
by the Free Software Foundation.
|
576 |
+
|
577 |
+
If the Program specifies that a proxy can decide which future
|
578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
579 |
+
public statement of acceptance of a version permanently authorizes you
|
580 |
+
to choose that version for the Program.
|
581 |
+
|
582 |
+
Later license versions may give you additional or different
|
583 |
+
permissions. However, no additional obligations are imposed on any
|
584 |
+
author or copyright holder as a result of your choosing to follow a
|
585 |
+
later version.
|
586 |
+
|
587 |
+
15. Disclaimer of Warranty.
|
588 |
+
|
589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
597 |
+
|
598 |
+
16. Limitation of Liability.
|
599 |
+
|
600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
608 |
+
SUCH DAMAGES.
|
609 |
+
|
610 |
+
17. Interpretation of Sections 15 and 16.
|
611 |
+
|
612 |
+
If the disclaimer of warranty and limitation of liability provided
|
613 |
+
above cannot be given local legal effect according to their terms,
|
614 |
+
reviewing courts shall apply local law that most closely approximates
|
615 |
+
an absolute waiver of all civil liability in connection with the
|
616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
617 |
+
copy of the Program in return for a fee.
|
618 |
+
|
619 |
+
END OF TERMS AND CONDITIONS
|
620 |
+
|
621 |
+
How to Apply These Terms to Your New Programs
|
622 |
+
|
623 |
+
If you develop a new program, and you want it to be of the greatest
|
624 |
+
possible use to the public, the best way to achieve this is to make it
|
625 |
+
free software which everyone can redistribute and change under these terms.
|
626 |
+
|
627 |
+
To do so, attach the following notices to the program. It is safest
|
628 |
+
to attach them to the start of each source file to most effectively
|
629 |
+
state the exclusion of warranty; and each file should have at least
|
630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
631 |
+
|
632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
633 |
+
Copyright (C) <year> <name of author>
|
634 |
+
|
635 |
+
This program is free software: you can redistribute it and/or modify
|
636 |
+
it under the terms of the GNU Affero General Public License as published by
|
637 |
+
the Free Software Foundation, either version 3 of the License, or
|
638 |
+
(at your option) any later version.
|
639 |
+
|
640 |
+
This program is distributed in the hope that it will be useful,
|
641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
643 |
+
GNU Affero General Public License for more details.
|
644 |
+
|
645 |
+
You should have received a copy of the GNU Affero General Public License
|
646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
647 |
+
|
648 |
+
Also add information on how to contact you by electronic and paper mail.
|
649 |
+
|
650 |
+
If your software can interact with users remotely through a computer
|
651 |
+
network, you should also make sure that it provides a way for users to
|
652 |
+
get its source. For example, if your program is a web application, its
|
653 |
+
interface could display a "Source" link that leads users to an archive
|
654 |
+
of the code. There are many ways you could offer source, and different
|
655 |
+
solutions will be better for different programs; see section 13 for the
|
656 |
+
specific requirements.
|
657 |
+
|
658 |
+
You should also get your employer (if you work as a programmer) or school,
|
659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
661 |
+
<https://www.gnu.org/licenses/>.
|
yolov5/README.md
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
<p>
|
3 |
+
<a href="http://www.ultralytics.com/blog/ultralytics-yolov8-turns-one-a-year-of-breakthroughs-and-innovations" target="_blank">
|
4 |
+
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png"></a>
|
5 |
+
<!--
|
6 |
+
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
7 |
+
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov5/v70/splash.png"></a>
|
8 |
+
-->
|
9 |
+
</p>
|
10 |
+
|
11 |
+
[中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [Türkçe](https://docs.ultralytics.com/tr/) | [Tiếng Việt](https://docs.ultralytics.com/vi/) | [हिन्दी](https://docs.ultralytics.com/hi/) | [العربية](https://docs.ultralytics.com/ar/)
|
12 |
+
|
13 |
+
<div>
|
14 |
+
<a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="YOLOv5 CI"></a>
|
15 |
+
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
|
16 |
+
<a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
|
17 |
+
<a href="https://ultralytics.com/discord"><img alt="Discord" src="https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue"></a> <a href="https://community.ultralytics.com"><img alt="Ultralytics Forums" src="https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue"></a>
|
18 |
+
<br>
|
19 |
+
<a href="https://bit.ly/yolov5-paperspace-notebook"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"></a>
|
20 |
+
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
|
21 |
+
<a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
|
22 |
+
</div>
|
23 |
+
<br>
|
24 |
+
|
25 |
+
YOLOv5 🚀 is the world's most loved vision AI, representing <a href="https://ultralytics.com">Ultralytics</a> open-source research into future vision AI methods, incorporating lessons learned and best practices evolved over thousands of hours of research and development.
|
26 |
+
|
27 |
+
We hope that the resources here will help you get the most out of YOLOv5. Please browse the YOLOv5 <a href="https://docs.ultralytics.com/yolov5">Docs</a> for details, raise an issue on <a href="https://github.com/ultralytics/yolov5/issues/new/choose">GitHub</a> for support, and join our <a href="https://ultralytics.com/discord">Discord</a> community for questions and discussions!
|
28 |
+
|
29 |
+
To request an Enterprise License please complete the form at [Ultralytics Licensing](https://ultralytics.com/license).
|
30 |
+
|
31 |
+
<div align="center">
|
32 |
+
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="2%" alt="Ultralytics GitHub"></a>
|
33 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
34 |
+
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="2%" alt="Ultralytics LinkedIn"></a>
|
35 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
36 |
+
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="2%" alt="Ultralytics Twitter"></a>
|
37 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
38 |
+
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="2%" alt="Ultralytics YouTube"></a>
|
39 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
40 |
+
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="2%" alt="Ultralytics TikTok"></a>
|
41 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
42 |
+
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="2%" alt="Ultralytics BiliBili"></a>
|
43 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
44 |
+
<a href="https://ultralytics.com/discord"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="2%" alt="Ultralytics Discord"></a>
|
45 |
+
</div>
|
46 |
+
|
47 |
+
</div>
|
48 |
+
<br>
|
49 |
+
|
50 |
+
## <div align="center">YOLOv8 🚀 NEW</div>
|
51 |
+
|
52 |
+
We are thrilled to announce the launch of Ultralytics YOLOv8 🚀, our NEW cutting-edge, state-of-the-art (SOTA) model released at **[https://github.com/ultralytics/ultralytics](https://github.com/ultralytics/ultralytics)**. YOLOv8 is designed to be fast, accurate, and easy to use, making it an excellent choice for a wide range of object detection, image segmentation and image classification tasks.
|
53 |
+
|
54 |
+
See the [YOLOv8 Docs](https://docs.ultralytics.com) for details and get started with:
|
55 |
+
|
56 |
+
[](https://badge.fury.io/py/ultralytics) [](https://pepy.tech/project/ultralytics)
|
57 |
+
|
58 |
+
```bash
|
59 |
+
pip install ultralytics
|
60 |
+
```
|
61 |
+
|
62 |
+
<div align="center">
|
63 |
+
<a href="https://ultralytics.com/yolov8" target="_blank">
|
64 |
+
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/yolo-comparison-plots.png"></a>
|
65 |
+
</div>
|
66 |
+
|
67 |
+
## <div align="center">Documentation</div>
|
68 |
+
|
69 |
+
See the [YOLOv5 Docs](https://docs.ultralytics.com/yolov5) for full documentation on training, testing and deployment. See below for quickstart examples.
|
70 |
+
|
71 |
+
<details open>
|
72 |
+
<summary>Install</summary>
|
73 |
+
|
74 |
+
Clone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.8.0**](https://www.python.org/) environment, including [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/).
|
75 |
+
|
76 |
+
```bash
|
77 |
+
git clone https://github.com/ultralytics/yolov5 # clone
|
78 |
+
cd yolov5
|
79 |
+
pip install -r requirements.txt # install
|
80 |
+
```
|
81 |
+
|
82 |
+
</details>
|
83 |
+
|
84 |
+
<details>
|
85 |
+
<summary>Inference</summary>
|
86 |
+
|
87 |
+
YOLOv5 [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).
|
88 |
+
|
89 |
+
```python
|
90 |
+
import torch
|
91 |
+
|
92 |
+
# Model
|
93 |
+
model = torch.hub.load("ultralytics/yolov5", "yolov5s") # or yolov5n - yolov5x6, custom
|
94 |
+
|
95 |
+
# Images
|
96 |
+
img = "https://ultralytics.com/images/zidane.jpg" # or file, Path, PIL, OpenCV, numpy, list
|
97 |
+
|
98 |
+
# Inference
|
99 |
+
results = model(img)
|
100 |
+
|
101 |
+
# Results
|
102 |
+
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
|
103 |
+
```
|
104 |
+
|
105 |
+
</details>
|
106 |
+
|
107 |
+
<details>
|
108 |
+
<summary>Inference with detect.py</summary>
|
109 |
+
|
110 |
+
`detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
|
111 |
+
|
112 |
+
```bash
|
113 |
+
python detect.py --weights yolov5s.pt --source 0 # webcam
|
114 |
+
img.jpg # image
|
115 |
+
vid.mp4 # video
|
116 |
+
screen # screenshot
|
117 |
+
path/ # directory
|
118 |
+
list.txt # list of images
|
119 |
+
list.streams # list of streams
|
120 |
+
'path/*.jpg' # glob
|
121 |
+
'https://youtu.be/LNwODJXcvt4' # YouTube
|
122 |
+
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
123 |
+
```
|
124 |
+
|
125 |
+
</details>
|
126 |
+
|
127 |
+
<details>
|
128 |
+
<summary>Training</summary>
|
129 |
+
|
130 |
+
The commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) results. [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are 1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training) times faster). Use the largest `--batch-size` possible, or pass `--batch-size -1` for YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB.
|
131 |
+
|
132 |
+
```bash
|
133 |
+
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5n.yaml --batch-size 128
|
134 |
+
yolov5s 64
|
135 |
+
yolov5m 40
|
136 |
+
yolov5l 24
|
137 |
+
yolov5x 16
|
138 |
+
```
|
139 |
+
|
140 |
+
<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
|
141 |
+
|
142 |
+
</details>
|
143 |
+
|
144 |
+
<details open>
|
145 |
+
<summary>Tutorials</summary>
|
146 |
+
|
147 |
+
- [Train Custom Data](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data) 🚀 RECOMMENDED
|
148 |
+
- [Tips for Best Training Results](https://docs.ultralytics.com/guides/model-training-tips/) ☘️
|
149 |
+
- [Multi-GPU Training](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training)
|
150 |
+
- [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) 🌟 NEW
|
151 |
+
- [TFLite, ONNX, CoreML, TensorRT Export](https://docs.ultralytics.com/yolov5/tutorials/model_export) 🚀
|
152 |
+
- [NVIDIA Jetson platform Deployment](https://docs.ultralytics.com/yolov5/tutorials/running_on_jetson_nano) 🌟 NEW
|
153 |
+
- [Test-Time Augmentation (TTA)](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation)
|
154 |
+
- [Model Ensembling](https://docs.ultralytics.com/yolov5/tutorials/model_ensembling)
|
155 |
+
- [Model Pruning/Sparsity](https://docs.ultralytics.com/yolov5/tutorials/model_pruning_and_sparsity)
|
156 |
+
- [Hyperparameter Evolution](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution)
|
157 |
+
- [Transfer Learning with Frozen Layers](https://docs.ultralytics.com/yolov5/tutorials/transfer_learning_with_frozen_layers)
|
158 |
+
- [Architecture Summary](https://docs.ultralytics.com/yolov5/tutorials/architecture_description) 🌟 NEW
|
159 |
+
- [Roboflow for Datasets, Labeling, and Active Learning](https://docs.ultralytics.com/yolov5/tutorials/roboflow_datasets_integration)
|
160 |
+
- [ClearML Logging](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration) 🌟 NEW
|
161 |
+
- [YOLOv5 with Neural Magic's Deepsparse](https://docs.ultralytics.com/yolov5/tutorials/neural_magic_pruning_quantization) 🌟 NEW
|
162 |
+
- [Comet Logging](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration) 🌟 NEW
|
163 |
+
|
164 |
+
</details>
|
165 |
+
|
166 |
+
## <div align="center">Integrations</div>
|
167 |
+
|
168 |
+
<br>
|
169 |
+
<a align="center" href="https://ultralytics.com/hub" target="_blank">
|
170 |
+
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/im/integrations-loop.png"></a>
|
171 |
+
<br>
|
172 |
+
<br>
|
173 |
+
|
174 |
+
<div align="center">
|
175 |
+
<a href="https://roboflow.com/?ref=ultralytics">
|
176 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-roboflow.png" width="10%" /></a>
|
177 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="" />
|
178 |
+
<a href="https://cutt.ly/yolov5-readme-clearml">
|
179 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-clearml.png" width="10%" /></a>
|
180 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="" />
|
181 |
+
<a href="https://bit.ly/yolov5-readme-comet2">
|
182 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-comet.png" width="10%" /></a>
|
183 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="" />
|
184 |
+
<a href="https://bit.ly/yolov5-neuralmagic">
|
185 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-neuralmagic.png" width="10%" /></a>
|
186 |
+
</div>
|
187 |
+
|
188 |
+
| Roboflow | ClearML ⭐ NEW | Comet ⭐ NEW | Neural Magic ⭐ NEW |
|
189 |
+
| :--------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------: |
|
190 |
+
| Label and export your custom datasets directly to YOLOv5 for training with [Roboflow](https://roboflow.com/?ref=ultralytics) | Automatically track, visualize and even remotely train YOLOv5 using [ClearML](https://cutt.ly/yolov5-readme-clearml) (open-source!) | Free forever, [Comet](https://bit.ly/yolov5-readme-comet2) lets you save YOLOv5 models, resume training, and interactively visualise and debug predictions | Run YOLOv5 inference up to 6x faster with [Neural Magic DeepSparse](https://bit.ly/yolov5-neuralmagic) |
|
191 |
+
|
192 |
+
## <div align="center">Ultralytics HUB</div>
|
193 |
+
|
194 |
+
Experience seamless AI with [Ultralytics HUB](https://ultralytics.com/hub) ⭐, the all-in-one solution for data visualization, YOLOv5 and YOLOv8 🚀 model training and deployment, without any coding. Transform images into actionable insights and bring your AI visions to life with ease using our cutting-edge platform and user-friendly [Ultralytics App](https://ultralytics.com/app_install). Start your journey for **Free** now!
|
195 |
+
|
196 |
+
<a align="center" href="https://ultralytics.com/hub" target="_blank">
|
197 |
+
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png"></a>
|
198 |
+
|
199 |
+
## <div align="center">Why YOLOv5</div>
|
200 |
+
|
201 |
+
YOLOv5 has been designed to be super easy to get started and simple to learn. We prioritize real-world results.
|
202 |
+
|
203 |
+
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040763-93c22a27-347c-4e3c-847a-8094621d3f4e.png"></p>
|
204 |
+
<details>
|
205 |
+
<summary>YOLOv5-P5 640 Figure</summary>
|
206 |
+
|
207 |
+
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040757-ce0934a3-06a6-43dc-a979-2edbbd69ea0e.png"></p>
|
208 |
+
</details>
|
209 |
+
<details>
|
210 |
+
<summary>Figure Notes</summary>
|
211 |
+
|
212 |
+
- **COCO AP val** denotes [email protected]:0.95 metric measured on the 5000-image [COCO val2017](http://cocodataset.org) dataset over various inference sizes from 256 to 1536.
|
213 |
+
- **GPU Speed** measures average inference time per image on [COCO val2017](http://cocodataset.org) dataset using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100 instance at batch-size 32.
|
214 |
+
- **EfficientDet** data from [google/automl](https://github.com/google/automl) at batch size 8.
|
215 |
+
- **Reproduce** by `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
|
216 |
+
|
217 |
+
</details>
|
218 |
+
|
219 |
+
### Pretrained Checkpoints
|
220 |
+
|
221 |
+
| Model | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | mAP<sup>val<br>50 | Speed<br><sup>CPU b1<br>(ms) | Speed<br><sup>V100 b1<br>(ms) | Speed<br><sup>V100 b32<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|
222 |
+
| ----------------------------------------------------------------------------------------------- | --------------------- | -------------------- | ----------------- | ---------------------------- | ----------------------------- | ------------------------------ | ------------------ | ---------------------- |
|
223 |
+
| [YOLOv5n](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n.pt) | 640 | 28.0 | 45.7 | **45** | **6.3** | **0.6** | **1.9** | **4.5** |
|
224 |
+
| [YOLOv5s](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s.pt) | 640 | 37.4 | 56.8 | 98 | 6.4 | 0.9 | 7.2 | 16.5 |
|
225 |
+
| [YOLOv5m](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m.pt) | 640 | 45.4 | 64.1 | 224 | 8.2 | 1.7 | 21.2 | 49.0 |
|
226 |
+
| [YOLOv5l](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l.pt) | 640 | 49.0 | 67.3 | 430 | 10.1 | 2.7 | 46.5 | 109.1 |
|
227 |
+
| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x.pt) | 640 | 50.7 | 68.9 | 766 | 12.1 | 4.8 | 86.7 | 205.7 |
|
228 |
+
| | | | | | | | | |
|
229 |
+
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n6.pt) | 1280 | 36.0 | 54.4 | 153 | 8.1 | 2.1 | 3.2 | 4.6 |
|
230 |
+
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s6.pt) | 1280 | 44.8 | 63.7 | 385 | 8.2 | 3.6 | 12.6 | 16.8 |
|
231 |
+
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m6.pt) | 1280 | 51.3 | 69.3 | 887 | 11.1 | 6.8 | 35.7 | 50.0 |
|
232 |
+
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l6.pt) | 1280 | 53.7 | 71.3 | 1784 | 15.8 | 10.5 | 76.8 | 111.4 |
|
233 |
+
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x6.pt)<br>+ [TTA] | 1280<br>1536 | 55.0<br>**55.8** | 72.7<br>**72.7** | 3136<br>- | 26.2<br>- | 19.4<br>- | 140.7<br>- | 209.8<br>- |
|
234 |
+
|
235 |
+
<details>
|
236 |
+
<summary>Table Notes</summary>
|
237 |
+
|
238 |
+
- All checkpoints are trained to 300 epochs with default settings. Nano and Small models use [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyps, all others use [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml).
|
239 |
+
- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.<br>Reproduce by `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
|
240 |
+
- **Speed** averaged over COCO val images using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) instance. NMS times (~1 ms/img) not included.<br>Reproduce by `python val.py --data coco.yaml --img 640 --task speed --batch 1`
|
241 |
+
- **TTA** [Test Time Augmentation](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation) includes reflection and scale augmentations.<br>Reproduce by `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
|
242 |
+
|
243 |
+
</details>
|
244 |
+
|
245 |
+
## <div align="center">Segmentation</div>
|
246 |
+
|
247 |
+
Our new YOLOv5 [release v7.0](https://github.com/ultralytics/yolov5/releases/v7.0) instance segmentation models are the fastest and most accurate in the world, beating all current [SOTA benchmarks](https://paperswithcode.com/sota/real-time-instance-segmentation-on-mscoco). We've made them super simple to train, validate and deploy. See full details in our [Release Notes](https://github.com/ultralytics/yolov5/releases/v7.0) and visit our [YOLOv5 Segmentation Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/segment/tutorial.ipynb) for quickstart tutorials.
|
248 |
+
|
249 |
+
<details>
|
250 |
+
<summary>Segmentation Checkpoints</summary>
|
251 |
+
|
252 |
+
<div align="center">
|
253 |
+
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
254 |
+
<img width="800" src="https://user-images.githubusercontent.com/61612323/204180385-84f3aca9-a5e9-43d8-a617-dda7ca12e54a.png"></a>
|
255 |
+
</div>
|
256 |
+
|
257 |
+
We trained YOLOv5 segmentations models on COCO for 300 epochs at image size 640 using A100 GPUs. We exported all models to ONNX FP32 for CPU speed tests and to TensorRT FP16 for GPU speed tests. We ran all speed tests on Google [Colab Pro](https://colab.research.google.com/signup) notebooks for easy reproducibility.
|
258 |
+
|
259 |
+
| Model | size<br><sup>(pixels) | mAP<sup>box<br>50-95 | mAP<sup>mask<br>50-95 | Train time<br><sup>300 epochs<br>A100 (hours) | Speed<br><sup>ONNX CPU<br>(ms) | Speed<br><sup>TRT A100<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|
260 |
+
| ------------------------------------------------------------------------------------------ | --------------------- | -------------------- | --------------------- | --------------------------------------------- | ------------------------------ | ------------------------------ | ------------------ | ---------------------- |
|
261 |
+
| [YOLOv5n-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-seg.pt) | 640 | 27.6 | 23.4 | 80:17 | **62.7** | **1.2** | **2.0** | **7.1** |
|
262 |
+
| [YOLOv5s-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-seg.pt) | 640 | 37.6 | 31.7 | 88:16 | 173.3 | 1.4 | 7.6 | 26.4 |
|
263 |
+
| [YOLOv5m-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-seg.pt) | 640 | 45.0 | 37.1 | 108:36 | 427.0 | 2.2 | 22.0 | 70.8 |
|
264 |
+
| [YOLOv5l-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-seg.pt) | 640 | 49.0 | 39.9 | 66:43 (2x) | 857.4 | 2.9 | 47.9 | 147.7 |
|
265 |
+
| [YOLOv5x-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-seg.pt) | 640 | **50.7** | **41.4** | 62:56 (3x) | 1579.2 | 4.5 | 88.8 | 265.7 |
|
266 |
+
|
267 |
+
- All checkpoints are trained to 300 epochs with SGD optimizer with `lr0=0.01` and `weight_decay=5e-5` at image size 640 and all default settings.<br>Runs logged to https://wandb.ai/glenn-jocher/YOLOv5_v70_official
|
268 |
+
- **Accuracy** values are for single-model single-scale on COCO dataset.<br>Reproduce by `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt`
|
269 |
+
- **Speed** averaged over 100 inference images using a [Colab Pro](https://colab.research.google.com/signup) A100 High-RAM instance. Values indicate inference speed only (NMS adds about 1ms per image). <br>Reproduce by `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt --batch 1`
|
270 |
+
- **Export** to ONNX at FP32 and TensorRT at FP16 done with `export.py`. <br>Reproduce by `python export.py --weights yolov5s-seg.pt --include engine --device 0 --half`
|
271 |
+
|
272 |
+
</details>
|
273 |
+
|
274 |
+
<details>
|
275 |
+
<summary>Segmentation Usage Examples <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/segment/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a></summary>
|
276 |
+
|
277 |
+
### Train
|
278 |
+
|
279 |
+
YOLOv5 segmentation training supports auto-download COCO128-seg segmentation dataset with `--data coco128-seg.yaml` argument and manual download of COCO-segments dataset with `bash data/scripts/get_coco.sh --train --val --segments` and then `python train.py --data coco.yaml`.
|
280 |
+
|
281 |
+
```bash
|
282 |
+
# Single-GPU
|
283 |
+
python segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640
|
284 |
+
|
285 |
+
# Multi-GPU DDP
|
286 |
+
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 --device 0,1,2,3
|
287 |
+
```
|
288 |
+
|
289 |
+
### Val
|
290 |
+
|
291 |
+
Validate YOLOv5s-seg mask mAP on COCO dataset:
|
292 |
+
|
293 |
+
```bash
|
294 |
+
bash data/scripts/get_coco.sh --val --segments # download COCO val segments split (780MB, 5000 images)
|
295 |
+
python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640 # validate
|
296 |
+
```
|
297 |
+
|
298 |
+
### Predict
|
299 |
+
|
300 |
+
Use pretrained YOLOv5m-seg.pt to predict bus.jpg:
|
301 |
+
|
302 |
+
```bash
|
303 |
+
python segment/predict.py --weights yolov5m-seg.pt --source data/images/bus.jpg
|
304 |
+
```
|
305 |
+
|
306 |
+
```python
|
307 |
+
model = torch.hub.load(
|
308 |
+
"ultralytics/yolov5", "custom", "yolov5m-seg.pt"
|
309 |
+
) # load from PyTorch Hub (WARNING: inference not yet supported)
|
310 |
+
```
|
311 |
+
|
312 |
+
|  |  |
|
313 |
+
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
314 |
+
|
315 |
+
### Export
|
316 |
+
|
317 |
+
Export YOLOv5s-seg model to ONNX and TensorRT:
|
318 |
+
|
319 |
+
```bash
|
320 |
+
python export.py --weights yolov5s-seg.pt --include onnx engine --img 640 --device 0
|
321 |
+
```
|
322 |
+
|
323 |
+
</details>
|
324 |
+
|
325 |
+
## <div align="center">Classification</div>
|
326 |
+
|
327 |
+
YOLOv5 [release v6.2](https://github.com/ultralytics/yolov5/releases) brings support for classification model training, validation and deployment! See full details in our [Release Notes](https://github.com/ultralytics/yolov5/releases/v6.2) and visit our [YOLOv5 Classification Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/classify/tutorial.ipynb) for quickstart tutorials.
|
328 |
+
|
329 |
+
<details>
|
330 |
+
<summary>Classification Checkpoints</summary>
|
331 |
+
|
332 |
+
<br>
|
333 |
+
|
334 |
+
We trained YOLOv5-cls classification models on ImageNet for 90 epochs using a 4xA100 instance, and we trained ResNet and EfficientNet models alongside with the same default training settings to compare. We exported all models to ONNX FP32 for CPU speed tests and to TensorRT FP16 for GPU speed tests. We ran all speed tests on Google [Colab Pro](https://colab.research.google.com/signup) for easy reproducibility.
|
335 |
+
|
336 |
+
| Model | size<br><sup>(pixels) | acc<br><sup>top1 | acc<br><sup>top5 | Training<br><sup>90 epochs<br>4xA100 (hours) | Speed<br><sup>ONNX CPU<br>(ms) | Speed<br><sup>TensorRT V100<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@224 (B) |
|
337 |
+
| -------------------------------------------------------------------------------------------------- | --------------------- | ---------------- | ---------------- | -------------------------------------------- | ------------------------------ | ----------------------------------- | ------------------ | ---------------------- |
|
338 |
+
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-cls.pt) | 224 | 64.6 | 85.4 | 7:59 | **3.3** | **0.5** | **2.5** | **0.5** |
|
339 |
+
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-cls.pt) | 224 | 71.5 | 90.2 | 8:09 | 6.6 | 0.6 | 5.4 | 1.4 |
|
340 |
+
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-cls.pt) | 224 | 75.9 | 92.9 | 10:06 | 15.5 | 0.9 | 12.9 | 3.9 |
|
341 |
+
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-cls.pt) | 224 | 78.0 | 94.0 | 11:56 | 26.9 | 1.4 | 26.5 | 8.5 |
|
342 |
+
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-cls.pt) | 224 | **79.0** | **94.4** | 15:04 | 54.3 | 1.8 | 48.1 | 15.9 |
|
343 |
+
| | | | | | | | | |
|
344 |
+
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet18.pt) | 224 | 70.3 | 89.5 | **6:47** | 11.2 | 0.5 | 11.7 | 3.7 |
|
345 |
+
| [ResNet34](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet34.pt) | 224 | 73.9 | 91.8 | 8:33 | 20.6 | 0.9 | 21.8 | 7.4 |
|
346 |
+
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet50.pt) | 224 | 76.8 | 93.4 | 11:10 | 23.4 | 1.0 | 25.6 | 8.5 |
|
347 |
+
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet101.pt) | 224 | 78.5 | 94.3 | 17:10 | 42.1 | 1.9 | 44.5 | 15.9 |
|
348 |
+
| | | | | | | | | |
|
349 |
+
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b0.pt) | 224 | 75.1 | 92.4 | 13:03 | 12.5 | 1.3 | 5.3 | 1.0 |
|
350 |
+
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b1.pt) | 224 | 76.4 | 93.2 | 17:04 | 14.9 | 1.6 | 7.8 | 1.5 |
|
351 |
+
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b2.pt) | 224 | 76.6 | 93.4 | 17:10 | 15.9 | 1.6 | 9.1 | 1.7 |
|
352 |
+
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b3.pt) | 224 | 77.7 | 94.0 | 19:19 | 18.9 | 1.9 | 12.2 | 2.4 |
|
353 |
+
|
354 |
+
<details>
|
355 |
+
<summary>Table Notes (click to expand)</summary>
|
356 |
+
|
357 |
+
- All checkpoints are trained to 90 epochs with SGD optimizer with `lr0=0.001` and `weight_decay=5e-5` at image size 224 and all default settings.<br>Runs logged to https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2
|
358 |
+
- **Accuracy** values are for single-model single-scale on [ImageNet-1k](https://www.image-net.org/index.php) dataset.<br>Reproduce by `python classify/val.py --data ../datasets/imagenet --img 224`
|
359 |
+
- **Speed** averaged over 100 inference images using a Google [Colab Pro](https://colab.research.google.com/signup) V100 High-RAM instance.<br>Reproduce by `python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`
|
360 |
+
- **Export** to ONNX at FP32 and TensorRT at FP16 done with `export.py`. <br>Reproduce by `python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`
|
361 |
+
|
362 |
+
</details>
|
363 |
+
</details>
|
364 |
+
|
365 |
+
<details>
|
366 |
+
<summary>Classification Usage Examples <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/classify/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a></summary>
|
367 |
+
|
368 |
+
### Train
|
369 |
+
|
370 |
+
YOLOv5 classification training supports auto-download of MNIST, Fashion-MNIST, CIFAR10, CIFAR100, Imagenette, Imagewoof, and ImageNet datasets with the `--data` argument. To start training on MNIST for example use `--data mnist`.
|
371 |
+
|
372 |
+
```bash
|
373 |
+
# Single-GPU
|
374 |
+
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128
|
375 |
+
|
376 |
+
# Multi-GPU DDP
|
377 |
+
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
|
378 |
+
```
|
379 |
+
|
380 |
+
### Val
|
381 |
+
|
382 |
+
Validate YOLOv5m-cls accuracy on ImageNet-1k dataset:
|
383 |
+
|
384 |
+
```bash
|
385 |
+
bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
|
386 |
+
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate
|
387 |
+
```
|
388 |
+
|
389 |
+
### Predict
|
390 |
+
|
391 |
+
Use pretrained YOLOv5s-cls.pt to predict bus.jpg:
|
392 |
+
|
393 |
+
```bash
|
394 |
+
python classify/predict.py --weights yolov5s-cls.pt --source data/images/bus.jpg
|
395 |
+
```
|
396 |
+
|
397 |
+
```python
|
398 |
+
model = torch.hub.load("ultralytics/yolov5", "custom", "yolov5s-cls.pt") # load from PyTorch Hub
|
399 |
+
```
|
400 |
+
|
401 |
+
### Export
|
402 |
+
|
403 |
+
Export a group of trained YOLOv5s-cls, ResNet and EfficientNet models to ONNX and TensorRT:
|
404 |
+
|
405 |
+
```bash
|
406 |
+
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
|
407 |
+
```
|
408 |
+
|
409 |
+
</details>
|
410 |
+
|
411 |
+
## <div align="center">Environments</div>
|
412 |
+
|
413 |
+
Get started in seconds with our verified environments. Click each icon below for details.
|
414 |
+
|
415 |
+
<div align="center">
|
416 |
+
<a href="https://bit.ly/yolov5-paperspace-notebook">
|
417 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gradient.png" width="10%" /></a>
|
418 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
419 |
+
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
|
420 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-colab-small.png" width="10%" /></a>
|
421 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
422 |
+
<a href="https://www.kaggle.com/ultralytics/yolov5">
|
423 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-kaggle-small.png" width="10%" /></a>
|
424 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
425 |
+
<a href="https://hub.docker.com/r/ultralytics/yolov5">
|
426 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-docker-small.png" width="10%" /></a>
|
427 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
428 |
+
<a href="https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/">
|
429 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-aws-small.png" width="10%" /></a>
|
430 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
431 |
+
<a href="https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/">
|
432 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gcp-small.png" width="10%" /></a>
|
433 |
+
</div>
|
434 |
+
|
435 |
+
## <div align="center">Contribute</div>
|
436 |
+
|
437 |
+
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing/) to get started, and fill out the [YOLOv5 Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experiences. Thank you to all our contributors!
|
438 |
+
|
439 |
+
<!-- SVG image from https://opencollective.com/ultralytics/contributors.svg?width=990 -->
|
440 |
+
|
441 |
+
<a href="https://github.com/ultralytics/yolov5/graphs/contributors">
|
442 |
+
<img src="https://github.com/ultralytics/assets/raw/main/im/image-contributors.png" /></a>
|
443 |
+
|
444 |
+
## <div align="center">License</div>
|
445 |
+
|
446 |
+
Ultralytics offers two licensing options to accommodate diverse use cases:
|
447 |
+
|
448 |
+
- **AGPL-3.0 License**: This [OSI-approved](https://opensource.org/licenses/) open-source license is ideal for students and enthusiasts, promoting open collaboration and knowledge sharing. See the [LICENSE](https://github.com/ultralytics/yolov5/blob/master/LICENSE) file for more details.
|
449 |
+
- **Enterprise License**: Designed for commercial use, this license permits seamless integration of Ultralytics software and AI models into commercial goods and services, bypassing the open-source requirements of AGPL-3.0. If your scenario involves embedding our solutions into a commercial offering, reach out through [Ultralytics Licensing](https://ultralytics.com/license).
|
450 |
+
|
451 |
+
## <div align="center">Contact</div>
|
452 |
+
|
453 |
+
For YOLOv5 bug reports and feature requests please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues), and join our [Discord](https://ultralytics.com/discord) community for questions and discussions!
|
454 |
+
|
455 |
+
<br>
|
456 |
+
<div align="center">
|
457 |
+
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="3%" alt="Ultralytics GitHub"></a>
|
458 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
459 |
+
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="3%" alt="Ultralytics LinkedIn"></a>
|
460 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
461 |
+
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="3%" alt="Ultralytics Twitter"></a>
|
462 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
463 |
+
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="3%" alt="Ultralytics YouTube"></a>
|
464 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
465 |
+
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="3%" alt="Ultralytics TikTok"></a>
|
466 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
467 |
+
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="3%" alt="Ultralytics BiliBili"></a>
|
468 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
469 |
+
<a href="https://ultralytics.com/discord"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="3%" alt="Ultralytics Discord"></a>
|
470 |
+
</div>
|
471 |
+
|
472 |
+
[tta]: https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation
|
yolov5/README.zh-CN.md
ADDED
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
<p>
|
3 |
+
<a href="http://www.ultralytics.com/blog/ultralytics-yolov8-turns-one-a-year-of-breakthroughs-and-innovations" target="_blank">
|
4 |
+
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png"></a>
|
5 |
+
<!--
|
6 |
+
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
7 |
+
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov5/v70/splash.png"></a>
|
8 |
+
-->
|
9 |
+
</p>
|
10 |
+
|
11 |
+
[中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [Türkçe](https://docs.ultralytics.com/tr/) | [Tiếng Việt](https://docs.ultralytics.com/vi/) | [हिन्दी](https://docs.ultralytics.com/hi/) | [العربية](https://docs.ultralytics.com/ar/)
|
12 |
+
|
13 |
+
<div>
|
14 |
+
<a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="YOLOv5 CI"></a>
|
15 |
+
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
|
16 |
+
<a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
|
17 |
+
<br>
|
18 |
+
<a href="https://bit.ly/yolov5-paperspace-notebook"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"></a>
|
19 |
+
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
|
20 |
+
<a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
|
21 |
+
</div>
|
22 |
+
<br>
|
23 |
+
|
24 |
+
YOLOv5 🚀 是世界上最受欢迎的视觉 AI,代表<a href="https://ultralytics.com"> Ultralytics </a>对未来视觉 AI 方法的开源研究,结合在数千小时的研究和开发中积累的经验教训和最佳实践。
|
25 |
+
|
26 |
+
我们希望这里的资源能帮助您充分利用 YOLOv5。请浏览 YOLOv5 <a href="https://docs.ultralytics.com/yolov5/">文档</a> 了解详细信息,在 <a href="https://github.com/ultralytics/yolov5/issues/new/choose">GitHub</a> 上提交问题以获得支持,并加入我们的 <a href="https://ultralytics.com/discord">Discord</a> 社区进行问题和讨论!
|
27 |
+
|
28 |
+
如需申请企业许可,请在 [Ultralytics Licensing](https://ultralytics.com/license) 处填写表格
|
29 |
+
|
30 |
+
<div align="center">
|
31 |
+
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="2%" alt="Ultralytics GitHub"></a>
|
32 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
33 |
+
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="2%" alt="Ultralytics LinkedIn"></a>
|
34 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
35 |
+
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="2%" alt="Ultralytics Twitter"></a>
|
36 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
37 |
+
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="2%" alt="Ultralytics YouTube"></a>
|
38 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
39 |
+
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="2%" alt="Ultralytics TikTok"></a>
|
40 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
41 |
+
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="2%" alt="Ultralytics BiliBili"></a>
|
42 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%">
|
43 |
+
<a href="https://ultralytics.com/discord"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="2%" alt="Ultralytics Discord"></a>
|
44 |
+
</div>
|
45 |
+
</div>
|
46 |
+
|
47 |
+
## <div align="center">YOLOv8 🚀 新品</div>
|
48 |
+
|
49 |
+
我们很高兴宣布 Ultralytics YOLOv8 🚀 的发布,这是我们新推出的领先水平、最先进的(SOTA)模型,发布于 **[https://github.com/ultralytics/ultralytics](https://github.com/ultralytics/ultralytics)**。 YOLOv8 ���在快速、准确且易于使用,使其成为广泛的物体检测、图像分割和图像分类任务的极佳选择。
|
50 |
+
|
51 |
+
请查看 [YOLOv8 文档](https://docs.ultralytics.com)了解详细信息,并开始使用:
|
52 |
+
|
53 |
+
[](https://badge.fury.io/py/ultralytics) [](https://pepy.tech/project/ultralytics)
|
54 |
+
|
55 |
+
```commandline
|
56 |
+
pip install ultralytics
|
57 |
+
```
|
58 |
+
|
59 |
+
<div align="center">
|
60 |
+
<a href="https://ultralytics.com/yolov8" target="_blank">
|
61 |
+
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/yolo-comparison-plots.png"></a>
|
62 |
+
</div>
|
63 |
+
|
64 |
+
## <div align="center">文档</div>
|
65 |
+
|
66 |
+
有关训练、测试和部署的完整文档见[YOLOv5 文档](https://docs.ultralytics.com/yolov5/)。请参阅下面的快速入门示例。
|
67 |
+
|
68 |
+
<details open>
|
69 |
+
<summary>安装</summary>
|
70 |
+
|
71 |
+
克隆 repo,并要求在 [**Python>=3.8.0**](https://www.python.org/) 环境中安装 [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) ,且要求 [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/) 。
|
72 |
+
|
73 |
+
```bash
|
74 |
+
git clone https://github.com/ultralytics/yolov5 # clone
|
75 |
+
cd yolov5
|
76 |
+
pip install -r requirements.txt # install
|
77 |
+
```
|
78 |
+
|
79 |
+
</details>
|
80 |
+
|
81 |
+
<details>
|
82 |
+
<summary>推理</summary>
|
83 |
+
|
84 |
+
使用 YOLOv5 [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) 推理。最新 [模型](https://github.com/ultralytics/yolov5/tree/master/models) 将自动的从 YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) 中下载。
|
85 |
+
|
86 |
+
```python
|
87 |
+
import torch
|
88 |
+
|
89 |
+
# Model
|
90 |
+
model = torch.hub.load("ultralytics/yolov5", "yolov5s") # or yolov5n - yolov5x6, custom
|
91 |
+
|
92 |
+
# Images
|
93 |
+
img = "https://ultralytics.com/images/zidane.jpg" # or file, Path, PIL, OpenCV, numpy, list
|
94 |
+
|
95 |
+
# Inference
|
96 |
+
results = model(img)
|
97 |
+
|
98 |
+
# Results
|
99 |
+
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
|
100 |
+
```
|
101 |
+
|
102 |
+
</details>
|
103 |
+
|
104 |
+
<details>
|
105 |
+
<summary>使用 detect.py 推理</summary>
|
106 |
+
|
107 |
+
`detect.py` 在各种来源上运行推理, [模型](https://github.com/ultralytics/yolov5/tree/master/models) 自动从 最新的YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) 中下载,并将结果保存到 `runs/detect` 。
|
108 |
+
|
109 |
+
```bash
|
110 |
+
python detect.py --weights yolov5s.pt --source 0 # webcam
|
111 |
+
img.jpg # image
|
112 |
+
vid.mp4 # video
|
113 |
+
screen # screenshot
|
114 |
+
path/ # directory
|
115 |
+
list.txt # list of images
|
116 |
+
list.streams # list of streams
|
117 |
+
'path/*.jpg' # glob
|
118 |
+
'https://youtu.be/LNwODJXcvt4' # YouTube
|
119 |
+
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
120 |
+
```
|
121 |
+
|
122 |
+
</details>
|
123 |
+
|
124 |
+
<details>
|
125 |
+
<summary>训练</summary>
|
126 |
+
|
127 |
+
下面的命令重现 YOLOv5 在 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) 数据集上的结果。 最新的 [模型](https://github.com/ultralytics/yolov5/tree/master/models) 和 [数据集](https://github.com/ultralytics/yolov5/tree/master/data)
|
128 |
+
将自动的从 YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) 中下载。 YOLOv5n/s/m/l/x 在 V100 GPU 的训练时间为 1/2/4/6/8 天( [多GPU](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training) 训练速度更快)。 尽可能使用更大的 `--batch-size` ,或通过 `--batch-size -1` 实现 YOLOv5 [自动批处理](https://github.com/ultralytics/yolov5/pull/5092) 。下方显示的 batchsize 适用于 V100-16GB。
|
129 |
+
|
130 |
+
```bash
|
131 |
+
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5n.yaml --batch-size 128
|
132 |
+
yolov5s 64
|
133 |
+
yolov5m 40
|
134 |
+
yolov5l 24
|
135 |
+
yolov5x 16
|
136 |
+
```
|
137 |
+
|
138 |
+
<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
|
139 |
+
|
140 |
+
</details>
|
141 |
+
|
142 |
+
<details open>
|
143 |
+
<summary>教程</summary>
|
144 |
+
|
145 |
+
- [训练自定义数据](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data) 🚀 推荐
|
146 |
+
- [获得最佳训练结果的技巧](https://docs.ultralytics.com/guides/model-training-tips/) ☘️
|
147 |
+
- [多GPU训练](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training)
|
148 |
+
- [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) 🌟 新
|
149 |
+
- [TFLite,ONNX,CoreML,TensorRT导出](https://docs.ultralytics.com/yolov5/tutorials/model_export) 🚀
|
150 |
+
- [NVIDIA Jetson平台部署](https://docs.ultralytics.com/yolov5/tutorials/running_on_jetson_nano) 🌟 新
|
151 |
+
- [测试时增强 (TTA)](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation)
|
152 |
+
- [模型集成](https://docs.ultralytics.com/yolov5/tutorials/model_ensembling)
|
153 |
+
- [模型剪枝/稀疏](https://docs.ultralytics.com/yolov5/tutorials/model_pruning_and_sparsity)
|
154 |
+
- [超参数进化](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution)
|
155 |
+
- [冻结层的迁移学习](https://docs.ultralytics.com/yolov5/tutorials/transfer_learning_with_frozen_layers)
|
156 |
+
- [架构概述](https://docs.ultralytics.com/yolov5/tutorials/architecture_description) 🌟 新
|
157 |
+
- [Roboflow用于数据集、标注和主动学习](https://docs.ultralytics.com/yolov5/tutorials/roboflow_datasets_integration)
|
158 |
+
- [ClearML日志记录](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration) 🌟 新
|
159 |
+
- [使用Neural Magic的Deepsparse的YOLOv5](https://docs.ultralytics.com/yolov5/tutorials/neural_magic_pruning_quantization) 🌟 新
|
160 |
+
- [Comet日志记录](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration) 🌟 新
|
161 |
+
|
162 |
+
</details>
|
163 |
+
|
164 |
+
## <div align="center">模块集成</div>
|
165 |
+
|
166 |
+
<br>
|
167 |
+
<a align="center" href="https://ultralytics.com/hub" target="_blank">
|
168 |
+
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/im/integrations-loop.png"></a>
|
169 |
+
<br>
|
170 |
+
<br>
|
171 |
+
|
172 |
+
<div align="center">
|
173 |
+
<a href="https://roboflow.com/?ref=ultralytics">
|
174 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-roboflow.png" width="10%" /></a>
|
175 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="" />
|
176 |
+
<a href="https://cutt.ly/yolov5-readme-clearml">
|
177 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-clearml.png" width="10%" /></a>
|
178 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="" />
|
179 |
+
<a href="https://bit.ly/yolov5-readme-comet2">
|
180 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-comet.png" width="10%" /></a>
|
181 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="" />
|
182 |
+
<a href="https://bit.ly/yolov5-neuralmagic">
|
183 |
+
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-neuralmagic.png" width="10%" /></a>
|
184 |
+
</div>
|
185 |
+
|
186 |
+
| Roboflow | ClearML ⭐ 新 | Comet ⭐ 新 | Neural Magic ⭐ 新 |
|
187 |
+
| :--------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------: |
|
188 |
+
| 将您的自定义数据集进行标注并直接导出到 YOLOv5 以进行训练 [Roboflow](https://roboflow.com/?ref=ultralytics) | 自动跟踪、可视化甚至远程训练 YOLOv5 [ClearML](https://cutt.ly/yolov5-readme-clearml)(开源!) | 永远免费,[Comet](https://bit.ly/yolov5-readme-comet2)可让您保存 YOLOv5 模型、恢复训练以及交互式可视化和调试预测 | 使用 [Neural Magic DeepSparse](https://bit.ly/yolov5-neuralmagic),运行 YOLOv5 推理的速度最高可提高6倍 |
|
189 |
+
|
190 |
+
## <div align="center">Ultralytics HUB</div>
|
191 |
+
|
192 |
+
[Ultralytics HUB](https://ultralytics.com/hub) 是我们的⭐**新的**用于可视化数据集、训练 YOLOv5 🚀 模型并以无缝体验部署到现实世界的无代码解决方案。现在开始 **免费** 使用他!
|
193 |
+
|
194 |
+
<a align="center" href="https://ultralytics.com/hub" target="_blank">
|
195 |
+
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png"></a>
|
196 |
+
|
197 |
+
## <div align="center">为什么选择 YOLOv5</div>
|
198 |
+
|
199 |
+
YOLOv5 超级容易上手,简单易学。我们优先考虑现实世界的结果。
|
200 |
+
|
201 |
+
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040763-93c22a27-347c-4e3c-847a-8094621d3f4e.png"></p>
|
202 |
+
<details>
|
203 |
+
<summary>YOLOv5-P5 640 图</summary>
|
204 |
+
|
205 |
+
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040757-ce0934a3-06a6-43dc-a979-2edbbd69ea0e.png"></p>
|
206 |
+
</details>
|
207 |
+
<details>
|
208 |
+
<summary>图表笔记</summary>
|
209 |
+
|
210 |
+
- **COCO AP val** 表示 [email protected]:0.95 指标,在 [COCO val2017](http://cocodataset.org) 数据集的 5000 张图像上测得, 图像包含 256 到 1536 各种推理大小。
|
211 |
+
- **显卡推理速度** 为在 [COCO val2017](http://cocodataset.org) 数据集上的平均推理时间,使用 [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100实例,batchsize 为 32 。
|
212 |
+
- **EfficientDet** 数据来自 [google/automl](https://github.com/google/automl) , batchsize 为32。
|
213 |
+
- **复现命令** 为 `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
|
214 |
+
|
215 |
+
</details>
|
216 |
+
|
217 |
+
### 预训练模型
|
218 |
+
|
219 |
+
| 模型 | 尺寸<br><sup>(像素) | mAP<sup>val<br>50-95 | mAP<sup>val<br>50 | 推理速度<br><sup>CPU b1<br>(ms) | 推理速度<br><sup>V100 b1<br>(ms) | 速度<br><sup>V100 b32<br>(ms) | 参数量<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|
220 |
+
| ---------------------------------------------------------------------------------------------- | --------------------- | -------------------- | ----------------- | --------------------------------- | ---------------------------------- | ------------------------------- | ------------------ | ---------------------- |
|
221 |
+
| [YOLOv5n](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n.pt) | 640 | 28.0 | 45.7 | **45** | **6.3** | **0.6** | **1.9** | **4.5** |
|
222 |
+
| [YOLOv5s](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s.pt) | 640 | 37.4 | 56.8 | 98 | 6.4 | 0.9 | 7.2 | 16.5 |
|
223 |
+
| [YOLOv5m](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m.pt) | 640 | 45.4 | 64.1 | 224 | 8.2 | 1.7 | 21.2 | 49.0 |
|
224 |
+
| [YOLOv5l](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l.pt) | 640 | 49.0 | 67.3 | 430 | 10.1 | 2.7 | 46.5 | 109.1 |
|
225 |
+
| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x.pt) | 640 | 50.7 | 68.9 | 766 | 12.1 | 4.8 | 86.7 | 205.7 |
|
226 |
+
| | | | | | | | | |
|
227 |
+
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n6.pt) | 1280 | 36.0 | 54.4 | 153 | 8.1 | 2.1 | 3.2 | 4.6 |
|
228 |
+
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s6.pt) | 1280 | 44.8 | 63.7 | 385 | 8.2 | 3.6 | 12.6 | 16.8 |
|
229 |
+
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m6.pt) | 1280 | 51.3 | 69.3 | 887 | 11.1 | 6.8 | 35.7 | 50.0 |
|
230 |
+
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l6.pt) | 1280 | 53.7 | 71.3 | 1784 | 15.8 | 10.5 | 76.8 | 111.4 |
|
231 |
+
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x6.pt)<br>+[TTA] | 1280<br>1536 | 55.0<br>**55.8** | 72.7<br>**72.7** | 3136<br>- | 26.2<br>- | 19.4<br>- | 140.7<br>- | 209.8<br>- |
|
232 |
+
|
233 |
+
<details>
|
234 |
+
<summary>笔记</summary>
|
235 |
+
|
236 |
+
- 所有模型都使用默认配置,训练 300 epochs。n和s模型使用 [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) ,其他模型都使用 [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml) 。
|
237 |
+
- \*\*mAP<sup>val</sup>\*\*在单模型单尺度上计算,数据集使用 [COCO val2017](http://cocodataset.org) 。<br>复现命令 `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
|
238 |
+
- **推理速度**在 COCO val 图像总体时间上进行平均得到,测试环境使用[AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/)实例。 NMS 时间 (大约 1 ms/img) 不包括在内。<br>复现命令 `python val.py --data coco.yaml --img 640 --task speed --batch 1`
|
239 |
+
- **TTA** [测试时数据增强](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation) 包括反射和尺度变换。<br>复现命令 `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
|
240 |
+
|
241 |
+
</details>
|
242 |
+
|
243 |
+
## <div align="center">实例分割模型 ⭐ 新</div>
|
244 |
+
|
245 |
+
我们新的 YOLOv5 [release v7.0](https://github.com/ultralytics/yolov5/releases/v7.0) 实例分割模型是世界上最快和最准确的模型,击败所有当前 [SOTA 基准](https://paperswithcode.com/sota/real-time-instance-segmentation-on-mscoco)。我们使它非常易于训练、验证和部署。更多细节请查看 [发行说明](https://github.com/ultralytics/yolov5/releases/v7.0) 或访问我们的 [YOLOv5 分割 Colab 笔记本](https://github.com/ultralytics/yolov5/blob/master/segment/tutorial.ipynb) 以快速入门。
|
246 |
+
|
247 |
+
<details>
|
248 |
+
<summary>实例分割模型列表</summary>
|
249 |
+
|
250 |
+
<br>
|
251 |
+
|
252 |
+
<div align="center">
|
253 |
+
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
254 |
+
<img width="800" src="https://user-images.githubusercontent.com/61612323/204180385-84f3aca9-a5e9-43d8-a617-dda7ca12e54a.png"></a>
|
255 |
+
</div>
|
256 |
+
|
257 |
+
我们使用 A100 GPU 在 COCO 上以 640 图像大小训练了 300 epochs 得到 YOLOv5 分割模型。我们将所有模型导出到 ONNX FP32 以进行 CPU 速度测试,并导出到 TensorRT FP16 以进行 GPU 速度测试。为了便于再现,我们在 Google [Colab Pro](https://colab.research.google.com/signup) 上进行了所有速度测试。
|
258 |
+
|
259 |
+
| 模型 | 尺寸<br><sup>(像素) | mAP<sup>box<br>50-95 | mAP<sup>mask<br>50-95 | 训练时长<br><sup>300 epochs<br>A100 GPU(小时) | 推理速度<br><sup>ONNX CPU<br>(ms) | 推理速度<br><sup>TRT A100<br>(ms) | 参数量<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|
260 |
+
| ------------------------------------------------------------------------------------------ | --------------------- | -------------------- | --------------------- | ----------------------------------------------- | ----------------------------------- | ----------------------------------- | ------------------ | ---------------------- |
|
261 |
+
| [YOLOv5n-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-seg.pt) | 640 | 27.6 | 23.4 | 80:17 | **62.7** | **1.2** | **2.0** | **7.1** |
|
262 |
+
| [YOLOv5s-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-seg.pt) | 640 | 37.6 | 31.7 | 88:16 | 173.3 | 1.4 | 7.6 | 26.4 |
|
263 |
+
| [YOLOv5m-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-seg.pt) | 640 | 45.0 | 37.1 | 108:36 | 427.0 | 2.2 | 22.0 | 70.8 |
|
264 |
+
| [YOLOv5l-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-seg.pt) | 640 | 49.0 | 39.9 | 66:43 (2x) | 857.4 | 2.9 | 47.9 | 147.7 |
|
265 |
+
| [YOLOv5x-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-seg.pt) | 640 | **50.7** | **41.4** | 62:56 (3x) | 1579.2 | 4.5 | 88.8 | 265.7 |
|
266 |
+
|
267 |
+
- 所有模型使用 SGD 优化器训练, 都使用 `lr0=0.01` 和 `weight_decay=5e-5` 参数, 图像大小为 640 。<br>训练 log 可以查看 https://wandb.ai/glenn-jocher/YOLOv5_v70_official
|
268 |
+
- **准确性**结果都在 COCO 数据集上,使用单模型单尺度测试得到。<br>复现命令 `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt`
|
269 |
+
- **推理速度**是使用 100 张图像推理时间进行平均得到,测试环境使用 [Colab Pro](https://colab.research.google.com/signup) 上 A100 高 RAM 实例。结果仅表示推理速度(NMS 每张图像增加约 1 毫秒)。<br>复现命令 `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt --batch 1`
|
270 |
+
- **模型转换**到 FP32 的 ONNX 和 FP16 的 TensorRT 脚本为 `export.py`.<br>运行命令 `python export.py --weights yolov5s-seg.pt --include engine --device 0 --half`
|
271 |
+
|
272 |
+
</details>
|
273 |
+
|
274 |
+
<details>
|
275 |
+
<summary>分割模型使用示例 <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/segment/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a></summary>
|
276 |
+
|
277 |
+
### 训练
|
278 |
+
|
279 |
+
YOLOv5分割训练支持自动下载 COCO128-seg 分割数据集,用户仅需在启动指令中包含 `--data coco128-seg.yaml` 参数。 若要手动下载,使用命令 `bash data/scripts/get_coco.sh --train --val --segments`, 在下载完毕后,使用命令 `python train.py --data coco.yaml` 开启训练。
|
280 |
+
|
281 |
+
```bash
|
282 |
+
# 单 GPU
|
283 |
+
python segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640
|
284 |
+
|
285 |
+
# 多 GPU, DDP 模式
|
286 |
+
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 --device 0,1,2,3
|
287 |
+
```
|
288 |
+
|
289 |
+
### 验证
|
290 |
+
|
291 |
+
在 COCO 数据集上验证 YOLOv5s-seg mask mAP:
|
292 |
+
|
293 |
+
```bash
|
294 |
+
bash data/scripts/get_coco.sh --val --segments # 下载 COCO val segments 数据集 (780MB, 5000 images)
|
295 |
+
python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640 # 验证
|
296 |
+
```
|
297 |
+
|
298 |
+
### 预测
|
299 |
+
|
300 |
+
使用预训练的 YOLOv5m-seg.pt 来预测 bus.jpg:
|
301 |
+
|
302 |
+
```bash
|
303 |
+
python segment/predict.py --weights yolov5m-seg.pt --source data/images/bus.jpg
|
304 |
+
```
|
305 |
+
|
306 |
+
```python
|
307 |
+
model = torch.hub.load(
|
308 |
+
"ultralytics/yolov5", "custom", "yolov5m-seg.pt"
|
309 |
+
) # 从load from PyTorch Hub 加载模型 (WARNING: 推理暂未支持)
|
310 |
+
```
|
311 |
+
|
312 |
+
|  |  |
|
313 |
+
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
314 |
+
|
315 |
+
### 模型导出
|
316 |
+
|
317 |
+
将 YOLOv5s-seg 模型导出到 ONNX 和 TensorRT:
|
318 |
+
|
319 |
+
```bash
|
320 |
+
python export.py --weights yolov5s-seg.pt --include onnx engine --img 640 --device 0
|
321 |
+
```
|
322 |
+
|
323 |
+
</details>
|
324 |
+
|
325 |
+
## <div align="center">分类网络 ⭐ 新</div>
|
326 |
+
|
327 |
+
YOLOv5 [release v6.2](https://github.com/ultralytics/yolov5/releases) 带来对分类模型训练、验证和部署的支持!详情请查看 [发行说明](https://github.com/ultralytics/yolov5/releases/v6.2) 或访问我们的 [YOLOv5 分类 Colab 笔记本](https://github.com/ultralytics/yolov5/blob/master/classify/tutorial.ipynb) 以快速入门。
|
328 |
+
|
329 |
+
<details>
|
330 |
+
<summary>分类网络模型</summary>
|
331 |
+
|
332 |
+
<br>
|
333 |
+
|
334 |
+
我们使用 4xA100 实例在 ImageNet 上训练了 90 个 epochs 得到 YOLOv5-cls 分类模型,我们训练了 ResNet 和 EfficientNet 模型以及相同的默认训练设置以进行比较。我们将所有模型导出到 ONNX FP32 以进行 CPU 速度测试,并导出到 TensorRT FP16 以进行 GPU 速度测试。为了便于重现,我们在 Google 上进行了所有速度测试 [Colab Pro](https://colab.research.google.com/signup) 。
|
335 |
+
|
336 |
+
| 模型 | 尺寸<br><sup>(像素) | acc<br><sup>top1 | acc<br><sup>top5 | 训练时长<br><sup>90 epochs<br>4xA100(小时) | 推理速度<br><sup>ONNX CPU<br>(ms) | 推理速度<br><sup>TensorRT V100<br>(ms) | 参数<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|
337 |
+
| -------------------------------------------------------------------------------------------------- | --------------------- | ---------------- | ---------------- | -------------------------------------------- | ----------------------------------- | ---------------------------------------- | ---------------- | ---------------------- |
|
338 |
+
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-cls.pt) | 224 | 64.6 | 85.4 | 7:59 | **3.3** | **0.5** | **2.5** | **0.5** |
|
339 |
+
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-cls.pt) | 224 | 71.5 | 90.2 | 8:09 | 6.6 | 0.6 | 5.4 | 1.4 |
|
340 |
+
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-cls.pt) | 224 | 75.9 | 92.9 | 10:06 | 15.5 | 0.9 | 12.9 | 3.9 |
|
341 |
+
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-cls.pt) | 224 | 78.0 | 94.0 | 11:56 | 26.9 | 1.4 | 26.5 | 8.5 |
|
342 |
+
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-cls.pt) | 224 | **79.0** | **94.4** | 15:04 | 54.3 | 1.8 | 48.1 | 15.9 |
|
343 |
+
| | | | | | | | | |
|
344 |
+
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet18.pt) | 224 | 70.3 | 89.5 | **6:47** | 11.2 | 0.5 | 11.7 | 3.7 |
|
345 |
+
| [Resnetzch](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet34.pt) | 224 | 73.9 | 91.8 | 8:33 | 20.6 | 0.9 | 21.8 | 7.4 |
|
346 |
+
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet50.pt) | 224 | 76.8 | 93.4 | 11:10 | 23.4 | 1.0 | 25.6 | 8.5 |
|
347 |
+
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet101.pt) | 224 | 78.5 | 94.3 | 17:10 | 42.1 | 1.9 | 44.5 | 15.9 |
|
348 |
+
| | | | | | | | | |
|
349 |
+
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b0.pt) | 224 | 75.1 | 92.4 | 13:03 | 12.5 | 1.3 | 5.3 | 1.0 |
|
350 |
+
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b1.pt) | 224 | 76.4 | 93.2 | 17:04 | 14.9 | 1.6 | 7.8 | 1.5 |
|
351 |
+
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b2.pt) | 224 | 76.6 | 93.4 | 17:10 | 15.9 | 1.6 | 9.1 | 1.7 |
|
352 |
+
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b3.pt) | 224 | 77.7 | 94.0 | 19:19 | 18.9 | 1.9 | 12.2 | 2.4 |
|
353 |
+
|
354 |
+
<details>
|
355 |
+
<summary>Table Notes (点击以展开)</summary>
|
356 |
+
|
357 |
+
- 所有模型都使用 SGD 优化器训练 90 个 epochs,都使用 `lr0=0.001` 和 `weight_decay=5e-5` 参数, 图像大小为 224 ,且都使用默认设置。<br>训练 log 可以查看 https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2
|
358 |
+
- **准确性**都在单模型单尺度上计算,数据集使用 [ImageNet-1k](https://www.image-net.org/index.php) 。<br>复现命令 `python classify/val.py --data ../datasets/imagenet --img 224`
|
359 |
+
- **推理速度**是使用 100 个推理图像进行平均得到,测试环境使用谷歌 [Colab Pro](https://colab.research.google.com/signup) V100 高 RAM 实例。<br>复现命令 `python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`
|
360 |
+
- **模型导出**到 FP32 的 ONNX 和 FP16 的 TensorRT 使用 `export.py` 。<br>复现命令 `python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`
|
361 |
+
</details>
|
362 |
+
</details>
|
363 |
+
|
364 |
+
<details>
|
365 |
+
<summary>分类训练示例 <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/classify/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a></summary>
|
366 |
+
|
367 |
+
### 训练
|
368 |
+
|
369 |
+
YOLOv5 分类训练支持自动下载 MNIST、Fashion-MNIST、CIFAR10、CIFAR100、Imagenette、Imagewoof 和 ImageNet 数据集,命令中使用 `--data` 即可。 MNIST 示例 `--data mnist` 。
|
370 |
+
|
371 |
+
```bash
|
372 |
+
# 单 GPU
|
373 |
+
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128
|
374 |
+
|
375 |
+
# 多 GPU, DDP 模式
|
376 |
+
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
|
377 |
+
```
|
378 |
+
|
379 |
+
### 验证
|
380 |
+
|
381 |
+
在 ImageNet-1k 数据集上验证 YOLOv5m-cls 的准确性:
|
382 |
+
|
383 |
+
```bash
|
384 |
+
bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
|
385 |
+
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate
|
386 |
+
```
|
387 |
+
|
388 |
+
### 预测
|
389 |
+
|
390 |
+
使用预训练的 YOLOv5s-cls.pt 来预测 bus.jpg:
|
391 |
+
|
392 |
+
```bash
|
393 |
+
python classify/predict.py --weights yolov5s-cls.pt --source data/images/bus.jpg
|
394 |
+
```
|
395 |
+
|
396 |
+
```python
|
397 |
+
model = torch.hub.load("ultralytics/yolov5", "custom", "yolov5s-cls.pt") # load from PyTorch Hub
|
398 |
+
```
|
399 |
+
|
400 |
+
### 模型导出
|
401 |
+
|
402 |
+
将一组经过训练的 YOLOv5s-cls、ResNet 和 EfficientNet 模型导出到 ONNX 和 TensorRT:
|
403 |
+
|
404 |
+
```bash
|
405 |
+
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
|
406 |
+
```
|
407 |
+
|
408 |
+
</details>
|
409 |
+
|
410 |
+
## <div align="center">环境</div>
|
411 |
+
|
412 |
+
使用下面我们经过验证的环境,在几秒钟内开始使用 YOLOv5 。单击下面的图标了解详细信息。
|
413 |
+
|
414 |
+
<div align="center">
|
415 |
+
<a href="https://bit.ly/yolov5-paperspace-notebook">
|
416 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gradient.png" width="10%" /></a>
|
417 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
418 |
+
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
|
419 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-colab-small.png" width="10%" /></a>
|
420 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
421 |
+
<a href="https://www.kaggle.com/ultralytics/yolov5">
|
422 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-kaggle-small.png" width="10%" /></a>
|
423 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
424 |
+
<a href="https://hub.docker.com/r/ultralytics/yolov5">
|
425 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-docker-small.png" width="10%" /></a>
|
426 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
427 |
+
<a href="https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/">
|
428 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-aws-small.png" width="10%" /></a>
|
429 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
|
430 |
+
<a href="https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/">
|
431 |
+
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gcp-small.png" width="10%" /></a>
|
432 |
+
</div>
|
433 |
+
|
434 |
+
## <div align="center">贡献</div>
|
435 |
+
|
436 |
+
我们喜欢您的意见或建议!我们希望尽可能简单和透明地为 YOLOv5 做出贡献。请看我们的 [投稿指南](https://docs.ultralytics.com/help/contributing/),并填写 [YOLOv5调查](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) 向我们发送您的体验反馈。感谢我们所有的贡献者!
|
437 |
+
|
438 |
+
<!-- SVG image from https://opencollective.com/ultralytics/contributors.svg?width=990 -->
|
439 |
+
|
440 |
+
<a href="https://github.com/ultralytics/yolov5/graphs/contributors">
|
441 |
+
<img src="https://github.com/ultralytics/assets/raw/main/im/image-contributors.png" /></a>
|
442 |
+
|
443 |
+
## <div align="center">许可证</div>
|
444 |
+
|
445 |
+
Ultralytics 提供两种许可证选项以适应各种使用场景:
|
446 |
+
|
447 |
+
- **AGPL-3.0 许可证**:这个[OSI 批准](https://opensource.org/licenses/)的开源许可证非常适合学生和爱好者,可以推动开放的协作和知识分享。请查看[LICENSE](https://github.com/ultralytics/yolov5/blob/master/LICENSE) 文件以了解更多细节。
|
448 |
+
- **企业许可证**:专为商业用途设计,该许可证允许将 Ultralytics 的软件和 AI 模型无缝集成到商业产品和服务中,从而绕过 AGPL-3.0 的开源要求。如果您的场景涉及将我们的解决方案嵌入到商业产品中,请通过 [Ultralytics Licensing](https://ultralytics.com/license)与我们���系。
|
449 |
+
|
450 |
+
## <div align="center">联系方式</div>
|
451 |
+
|
452 |
+
对于 Ultralytics 的错误报告和功能请求,请访问 [GitHub Issues](https://github.com/ultralytics/yolov5/issues),并加入我们的 [Discord](https://ultralytics.com/discord) 社区进行问题和讨论!
|
453 |
+
|
454 |
+
<br>
|
455 |
+
<div align="center">
|
456 |
+
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="3%" alt="Ultralytics GitHub"></a>
|
457 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
458 |
+
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="3%" alt="Ultralytics LinkedIn"></a>
|
459 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
460 |
+
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="3%" alt="Ultralytics Twitter"></a>
|
461 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
462 |
+
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="3%" alt="Ultralytics YouTube"></a>
|
463 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
464 |
+
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="3%" alt="Ultralytics TikTok"></a>
|
465 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
466 |
+
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="3%" alt="Ultralytics BiliBili"></a>
|
467 |
+
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%">
|
468 |
+
<a href="https://ultralytics.com/discord"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="3%" alt="Ultralytics Discord"></a>
|
469 |
+
</div>
|
470 |
+
|
471 |
+
[tta]: https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation
|
yolov5/benchmarks.py
ADDED
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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.mlpackage
|
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 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 |
+
"""
|
64 |
+
Run YOLOv5 benchmarks on multiple export formats and log results for model performance evaluation.
|
65 |
+
|
66 |
+
Args:
|
67 |
+
weights (Path | str): Path to the model weights file (default: ROOT / "yolov5s.pt").
|
68 |
+
imgsz (int): Inference size in pixels (default: 640).
|
69 |
+
batch_size (int): Batch size for inference (default: 1).
|
70 |
+
data (Path | str): Path to the dataset.yaml file (default: ROOT / "data/coco128.yaml").
|
71 |
+
device (str): CUDA device, e.g., '0' or '0,1,2,3' or 'cpu' (default: "").
|
72 |
+
half (bool): Use FP16 half-precision inference (default: False).
|
73 |
+
test (bool): Test export formats only (default: False).
|
74 |
+
pt_only (bool): Test PyTorch format only (default: False).
|
75 |
+
hard_fail (bool): Throw an error on benchmark failure if True (default: False).
|
76 |
+
|
77 |
+
Returns:
|
78 |
+
None. Logs information about the benchmark results, including the format, size, mAP50-95, and inference time.
|
79 |
+
|
80 |
+
Notes:
|
81 |
+
Supported export formats and models include PyTorch, TorchScript, ONNX, OpenVINO, TensorRT, CoreML,
|
82 |
+
TensorFlow SavedModel, TensorFlow GraphDef, TensorFlow Lite, and TensorFlow Edge TPU. Edge TPU and TF.js
|
83 |
+
are unsupported.
|
84 |
+
|
85 |
+
Example:
|
86 |
+
```python
|
87 |
+
$ python benchmarks.py --weights yolov5s.pt --img 640
|
88 |
+
```
|
89 |
+
|
90 |
+
Usage:
|
91 |
+
Install required packages:
|
92 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU support
|
93 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU support
|
94 |
+
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
95 |
+
|
96 |
+
Run benchmarks:
|
97 |
+
$ python benchmarks.py --weights yolov5s.pt --img 640
|
98 |
+
"""
|
99 |
+
y, t = [], time.time()
|
100 |
+
device = select_device(device)
|
101 |
+
model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
|
102 |
+
for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
|
103 |
+
try:
|
104 |
+
assert i not in (9, 10), "inference not supported" # Edge TPU and TF.js are unsupported
|
105 |
+
assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
|
106 |
+
if "cpu" in device.type:
|
107 |
+
assert cpu, "inference not supported on CPU"
|
108 |
+
if "cuda" in device.type:
|
109 |
+
assert gpu, "inference not supported on GPU"
|
110 |
+
|
111 |
+
# Export
|
112 |
+
if f == "-":
|
113 |
+
w = weights # PyTorch format
|
114 |
+
else:
|
115 |
+
w = export.run(
|
116 |
+
weights=weights, imgsz=[imgsz], include=[f], batch_size=batch_size, device=device, half=half
|
117 |
+
)[-1] # all others
|
118 |
+
assert suffix in str(w), "export failed"
|
119 |
+
|
120 |
+
# Validate
|
121 |
+
if model_type == SegmentationModel:
|
122 |
+
result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
|
123 |
+
metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
|
124 |
+
else: # DetectionModel:
|
125 |
+
result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
|
126 |
+
metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
|
127 |
+
speed = result[2][1] # times (preprocess, inference, postprocess)
|
128 |
+
y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
|
129 |
+
except Exception as e:
|
130 |
+
if hard_fail:
|
131 |
+
assert type(e) is AssertionError, f"Benchmark --hard-fail for {name}: {e}"
|
132 |
+
LOGGER.warning(f"WARNING ⚠️ Benchmark failure for {name}: {e}")
|
133 |
+
y.append([name, None, None, None]) # mAP, t_inference
|
134 |
+
if pt_only and i == 0:
|
135 |
+
break # break after PyTorch
|
136 |
+
|
137 |
+
# Print results
|
138 |
+
LOGGER.info("\n")
|
139 |
+
parse_opt()
|
140 |
+
notebook_init() # print system info
|
141 |
+
c = ["Format", "Size (MB)", "mAP50-95", "Inference time (ms)"] if map else ["Format", "Export", "", ""]
|
142 |
+
py = pd.DataFrame(y, columns=c)
|
143 |
+
LOGGER.info(f"\nBenchmarks complete ({time.time() - t:.2f}s)")
|
144 |
+
LOGGER.info(str(py if map else py.iloc[:, :2]))
|
145 |
+
if hard_fail and isinstance(hard_fail, str):
|
146 |
+
metrics = py["mAP50-95"].array # values to compare to floor
|
147 |
+
floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
|
148 |
+
assert all(x > floor for x in metrics if pd.notna(x)), f"HARD FAIL: mAP50-95 < floor {floor}"
|
149 |
+
return py
|
150 |
+
|
151 |
+
|
152 |
+
def test(
|
153 |
+
weights=ROOT / "yolov5s.pt", # weights path
|
154 |
+
imgsz=640, # inference size (pixels)
|
155 |
+
batch_size=1, # batch size
|
156 |
+
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
157 |
+
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
158 |
+
half=False, # use FP16 half-precision inference
|
159 |
+
test=False, # test exports only
|
160 |
+
pt_only=False, # test PyTorch only
|
161 |
+
hard_fail=False, # throw error on benchmark failure
|
162 |
+
):
|
163 |
+
"""
|
164 |
+
Run YOLOv5 export tests for all supported formats and log the results, including export statuses.
|
165 |
+
|
166 |
+
Args:
|
167 |
+
weights (Path | str): Path to the model weights file (.pt format). Default is 'ROOT / "yolov5s.pt"'.
|
168 |
+
imgsz (int): Inference image size (in pixels). Default is 640.
|
169 |
+
batch_size (int): Batch size for testing. Default is 1.
|
170 |
+
data (Path | str): Path to the dataset configuration file (.yaml format). Default is 'ROOT / "data/coco128.yaml"'.
|
171 |
+
device (str): Device for running the tests, can be 'cpu' or a specific CUDA device ('0', '0,1,2,3', etc.). Default is an empty string.
|
172 |
+
half (bool): Use FP16 half-precision for inference if True. Default is False.
|
173 |
+
test (bool): Test export formats only without running inference. Default is False.
|
174 |
+
pt_only (bool): Test only the PyTorch model if True. Default is False.
|
175 |
+
hard_fail (bool): Raise error on export or test failure if True. Default is False.
|
176 |
+
|
177 |
+
Returns:
|
178 |
+
pd.DataFrame: DataFrame containing the results of the export tests, including format names and export statuses.
|
179 |
+
|
180 |
+
Examples:
|
181 |
+
```python
|
182 |
+
$ python benchmarks.py --weights yolov5s.pt --img 640
|
183 |
+
```
|
184 |
+
|
185 |
+
Notes:
|
186 |
+
Supported export formats and models include PyTorch, TorchScript, ONNX, OpenVINO, TensorRT, CoreML, TensorFlow
|
187 |
+
SavedModel, TensorFlow GraphDef, TensorFlow Lite, and TensorFlow Edge TPU. Edge TPU and TF.js are unsupported.
|
188 |
+
|
189 |
+
Usage:
|
190 |
+
Install required packages:
|
191 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU support
|
192 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU support
|
193 |
+
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
194 |
+
Run export tests:
|
195 |
+
$ python benchmarks.py --weights yolov5s.pt --img 640
|
196 |
+
"""
|
197 |
+
y, t = [], time.time()
|
198 |
+
device = select_device(device)
|
199 |
+
for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
|
200 |
+
try:
|
201 |
+
w = (
|
202 |
+
weights
|
203 |
+
if f == "-"
|
204 |
+
else export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]
|
205 |
+
) # weights
|
206 |
+
assert suffix in str(w), "export failed"
|
207 |
+
y.append([name, True])
|
208 |
+
except Exception:
|
209 |
+
y.append([name, False]) # mAP, t_inference
|
210 |
+
|
211 |
+
# Print results
|
212 |
+
LOGGER.info("\n")
|
213 |
+
parse_opt()
|
214 |
+
notebook_init() # print system info
|
215 |
+
py = pd.DataFrame(y, columns=["Format", "Export"])
|
216 |
+
LOGGER.info(f"\nExports complete ({time.time() - t:.2f}s)")
|
217 |
+
LOGGER.info(str(py))
|
218 |
+
return py
|
219 |
+
|
220 |
+
|
221 |
+
def parse_opt():
|
222 |
+
"""
|
223 |
+
Parses command-line arguments for YOLOv5 model inference configuration.
|
224 |
+
|
225 |
+
Args:
|
226 |
+
weights (str): The path to the weights file. Defaults to 'ROOT / "yolov5s.pt"'.
|
227 |
+
imgsz (int): Inference size in pixels. Defaults to 640.
|
228 |
+
batch_size (int): Batch size. Defaults to 1.
|
229 |
+
data (str): Path to the dataset YAML file. Defaults to 'ROOT / "data/coco128.yaml"'.
|
230 |
+
device (str): CUDA device, e.g., '0' or '0,1,2,3' or 'cpu'. Defaults to an empty string (auto-select).
|
231 |
+
half (bool): Use FP16 half-precision inference. This is a flag and defaults to False.
|
232 |
+
test (bool): Test exports only. This is a flag and defaults to False.
|
233 |
+
pt_only (bool): Test PyTorch only. This is a flag and defaults to False.
|
234 |
+
hard_fail (bool | str): Throw an error on benchmark failure. Can be a boolean or a string representing a minimum
|
235 |
+
metric floor, e.g., '0.29'. Defaults to False.
|
236 |
+
|
237 |
+
Returns:
|
238 |
+
argparse.Namespace: Parsed command-line arguments encapsulated in an argparse Namespace object.
|
239 |
+
|
240 |
+
Notes:
|
241 |
+
The function modifies the 'opt.data' by checking and validating the YAML path using 'check_yaml()'.
|
242 |
+
The parsed arguments are printed for reference using 'print_args()'.
|
243 |
+
"""
|
244 |
+
parser = argparse.ArgumentParser()
|
245 |
+
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
|
246 |
+
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="inference size (pixels)")
|
247 |
+
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
|
248 |
+
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
|
249 |
+
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
250 |
+
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
251 |
+
parser.add_argument("--test", action="store_true", help="test exports only")
|
252 |
+
parser.add_argument("--pt-only", action="store_true", help="test PyTorch only")
|
253 |
+
parser.add_argument("--hard-fail", nargs="?", const=True, default=False, help="Exception on error or < min metric")
|
254 |
+
opt = parser.parse_args()
|
255 |
+
opt.data = check_yaml(opt.data) # check YAML
|
256 |
+
print_args(vars(opt))
|
257 |
+
return opt
|
258 |
+
|
259 |
+
|
260 |
+
def main(opt):
|
261 |
+
"""
|
262 |
+
Executes YOLOv5 benchmark tests or main training/inference routines based on the provided command-line arguments.
|
263 |
+
|
264 |
+
Args:
|
265 |
+
opt (argparse.Namespace): Parsed command-line arguments including options for weights, image size, batch size, data
|
266 |
+
configuration, device, and other flags for inference settings.
|
267 |
+
|
268 |
+
Returns:
|
269 |
+
None: This function does not return any value. It leverages side-effects such as logging and running benchmarks.
|
270 |
+
|
271 |
+
Example:
|
272 |
+
```python
|
273 |
+
if __name__ == "__main__":
|
274 |
+
opt = parse_opt()
|
275 |
+
main(opt)
|
276 |
+
```
|
277 |
+
|
278 |
+
Notes:
|
279 |
+
- For a complete list of supported export formats and their respective requirements, refer to the
|
280 |
+
[Ultralytics YOLOv5 Export Formats](https://github.com/ultralytics/yolov5#export-formats).
|
281 |
+
- Ensure that you have installed all necessary dependencies by following the installation instructions detailed in
|
282 |
+
the [main repository](https://github.com/ultralytics/yolov5#installation).
|
283 |
+
|
284 |
+
```shell
|
285 |
+
# Running benchmarks on default weights and image size
|
286 |
+
$ python benchmarks.py --weights yolov5s.pt --img 640
|
287 |
+
```
|
288 |
+
"""
|
289 |
+
test(**vars(opt)) if opt.test else run(**vars(opt))
|
290 |
+
|
291 |
+
|
292 |
+
if __name__ == "__main__":
|
293 |
+
opt = parse_opt()
|
294 |
+
main(opt)
|
yolov5/classify/predict.py
ADDED
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
screen # screenshot
|
10 |
+
path/ # directory
|
11 |
+
list.txt # list of images
|
12 |
+
list.streams # list of streams
|
13 |
+
'path/*.jpg' # glob
|
14 |
+
'https://youtu.be/LNwODJXcvt4' # YouTube
|
15 |
+
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
16 |
+
|
17 |
+
Usage - formats:
|
18 |
+
$ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
|
19 |
+
yolov5s-cls.torchscript # TorchScript
|
20 |
+
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
21 |
+
yolov5s-cls_openvino_model # OpenVINO
|
22 |
+
yolov5s-cls.engine # TensorRT
|
23 |
+
yolov5s-cls.mlmodel # CoreML (macOS-only)
|
24 |
+
yolov5s-cls_saved_model # TensorFlow SavedModel
|
25 |
+
yolov5s-cls.pb # TensorFlow GraphDef
|
26 |
+
yolov5s-cls.tflite # TensorFlow Lite
|
27 |
+
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
|
28 |
+
yolov5s-cls_paddle_model # PaddlePaddle
|
29 |
+
"""
|
30 |
+
|
31 |
+
import argparse
|
32 |
+
import os
|
33 |
+
import platform
|
34 |
+
import sys
|
35 |
+
from pathlib import Path
|
36 |
+
|
37 |
+
import torch
|
38 |
+
import torch.nn.functional as F
|
39 |
+
|
40 |
+
FILE = Path(__file__).resolve()
|
41 |
+
ROOT = FILE.parents[1] # YOLOv5 root directory
|
42 |
+
if str(ROOT) not in sys.path:
|
43 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
44 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
45 |
+
|
46 |
+
from ultralytics.utils.plotting import Annotator
|
47 |
+
|
48 |
+
from models.common import DetectMultiBackend
|
49 |
+
from utils.augmentations import classify_transforms
|
50 |
+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
|
51 |
+
from utils.general import (
|
52 |
+
LOGGER,
|
53 |
+
Profile,
|
54 |
+
check_file,
|
55 |
+
check_img_size,
|
56 |
+
check_imshow,
|
57 |
+
check_requirements,
|
58 |
+
colorstr,
|
59 |
+
cv2,
|
60 |
+
increment_path,
|
61 |
+
print_args,
|
62 |
+
strip_optimizer,
|
63 |
+
)
|
64 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
65 |
+
|
66 |
+
|
67 |
+
@smart_inference_mode()
|
68 |
+
def run(
|
69 |
+
weights=ROOT / "yolov5s-cls.pt", # model.pt path(s)
|
70 |
+
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
|
71 |
+
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
72 |
+
imgsz=(224, 224), # inference size (height, width)
|
73 |
+
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
74 |
+
view_img=False, # show results
|
75 |
+
save_txt=False, # save results to *.txt
|
76 |
+
nosave=False, # do not save images/videos
|
77 |
+
augment=False, # augmented inference
|
78 |
+
visualize=False, # visualize features
|
79 |
+
update=False, # update all models
|
80 |
+
project=ROOT / "runs/predict-cls", # save results to project/name
|
81 |
+
name="exp", # save results to project/name
|
82 |
+
exist_ok=False, # existing project/name ok, do not increment
|
83 |
+
half=False, # use FP16 half-precision inference
|
84 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
85 |
+
vid_stride=1, # video frame-rate stride
|
86 |
+
):
|
87 |
+
"""Conducts YOLOv5 classification inference on diverse input sources and saves results."""
|
88 |
+
source = str(source)
|
89 |
+
save_img = not nosave and not source.endswith(".txt") # save inference images
|
90 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
91 |
+
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
|
92 |
+
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
|
93 |
+
screenshot = source.lower().startswith("screen")
|
94 |
+
if is_url and is_file:
|
95 |
+
source = check_file(source) # download
|
96 |
+
|
97 |
+
# Directories
|
98 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
99 |
+
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
100 |
+
|
101 |
+
# Load model
|
102 |
+
device = select_device(device)
|
103 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
104 |
+
stride, names, pt = model.stride, model.names, model.pt
|
105 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
106 |
+
|
107 |
+
# Dataloader
|
108 |
+
bs = 1 # batch_size
|
109 |
+
if webcam:
|
110 |
+
view_img = check_imshow(warn=True)
|
111 |
+
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
|
112 |
+
bs = len(dataset)
|
113 |
+
elif screenshot:
|
114 |
+
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
|
115 |
+
else:
|
116 |
+
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
|
117 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
118 |
+
|
119 |
+
# Run inference
|
120 |
+
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
|
121 |
+
seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
|
122 |
+
for path, im, im0s, vid_cap, s in dataset:
|
123 |
+
with dt[0]:
|
124 |
+
im = torch.Tensor(im).to(model.device)
|
125 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
126 |
+
if len(im.shape) == 3:
|
127 |
+
im = im[None] # expand for batch dim
|
128 |
+
|
129 |
+
# Inference
|
130 |
+
with dt[1]:
|
131 |
+
results = model(im)
|
132 |
+
|
133 |
+
# Post-process
|
134 |
+
with dt[2]:
|
135 |
+
pred = F.softmax(results, dim=1) # probabilities
|
136 |
+
|
137 |
+
# Process predictions
|
138 |
+
for i, prob in enumerate(pred): # per image
|
139 |
+
seen += 1
|
140 |
+
if webcam: # batch_size >= 1
|
141 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
142 |
+
s += f"{i}: "
|
143 |
+
else:
|
144 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
|
145 |
+
|
146 |
+
p = Path(p) # to Path
|
147 |
+
save_path = str(save_dir / p.name) # im.jpg
|
148 |
+
txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
|
149 |
+
|
150 |
+
s += "%gx%g " % im.shape[2:] # print string
|
151 |
+
annotator = Annotator(im0, example=str(names), pil=True)
|
152 |
+
|
153 |
+
# Print results
|
154 |
+
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
|
155 |
+
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
|
156 |
+
|
157 |
+
# Write results
|
158 |
+
text = "\n".join(f"{prob[j]:.2f} {names[j]}" for j in top5i)
|
159 |
+
if save_img or view_img: # Add bbox to image
|
160 |
+
annotator.text([32, 32], text, txt_color=(255, 255, 255))
|
161 |
+
if save_txt: # Write to file
|
162 |
+
with open(f"{txt_path}.txt", "a") as f:
|
163 |
+
f.write(text + "\n")
|
164 |
+
|
165 |
+
# Stream results
|
166 |
+
im0 = annotator.result()
|
167 |
+
if view_img:
|
168 |
+
if platform.system() == "Linux" and p not in windows:
|
169 |
+
windows.append(p)
|
170 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
171 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
172 |
+
cv2.imshow(str(p), im0)
|
173 |
+
cv2.waitKey(1) # 1 millisecond
|
174 |
+
|
175 |
+
# Save results (image with detections)
|
176 |
+
if save_img:
|
177 |
+
if dataset.mode == "image":
|
178 |
+
cv2.imwrite(save_path, im0)
|
179 |
+
else: # 'video' or 'stream'
|
180 |
+
if vid_path[i] != save_path: # new video
|
181 |
+
vid_path[i] = save_path
|
182 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
183 |
+
vid_writer[i].release() # release previous video writer
|
184 |
+
if vid_cap: # video
|
185 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
186 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
187 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
188 |
+
else: # stream
|
189 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
190 |
+
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
|
191 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
|
192 |
+
vid_writer[i].write(im0)
|
193 |
+
|
194 |
+
# Print time (inference-only)
|
195 |
+
LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms")
|
196 |
+
|
197 |
+
# Print results
|
198 |
+
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
|
199 |
+
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
|
200 |
+
if save_txt or save_img:
|
201 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
|
202 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
203 |
+
if update:
|
204 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
205 |
+
|
206 |
+
|
207 |
+
def parse_opt():
|
208 |
+
"""Parses command line arguments for YOLOv5 inference settings including model, source, device, and image size."""
|
209 |
+
parser = argparse.ArgumentParser()
|
210 |
+
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model path(s)")
|
211 |
+
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
|
212 |
+
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
|
213 |
+
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[224], help="inference size h,w")
|
214 |
+
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
215 |
+
parser.add_argument("--view-img", action="store_true", help="show results")
|
216 |
+
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
|
217 |
+
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
|
218 |
+
parser.add_argument("--augment", action="store_true", help="augmented inference")
|
219 |
+
parser.add_argument("--visualize", action="store_true", help="visualize features")
|
220 |
+
parser.add_argument("--update", action="store_true", help="update all models")
|
221 |
+
parser.add_argument("--project", default=ROOT / "runs/predict-cls", help="save results to project/name")
|
222 |
+
parser.add_argument("--name", default="exp", help="save results to project/name")
|
223 |
+
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
224 |
+
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
225 |
+
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
|
226 |
+
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
|
227 |
+
opt = parser.parse_args()
|
228 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
229 |
+
print_args(vars(opt))
|
230 |
+
return opt
|
231 |
+
|
232 |
+
|
233 |
+
def main(opt):
|
234 |
+
"""Executes YOLOv5 model inference with options for ONNX DNN and video frame-rate stride adjustments."""
|
235 |
+
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
|
236 |
+
run(**vars(opt))
|
237 |
+
|
238 |
+
|
239 |
+
if __name__ == "__main__":
|
240 |
+
opt = parse_opt()
|
241 |
+
main(opt)
|
yolov5/classify/train.py
ADDED
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 2022 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 (
|
44 |
+
DATASETS_DIR,
|
45 |
+
LOGGER,
|
46 |
+
TQDM_BAR_FORMAT,
|
47 |
+
WorkingDirectory,
|
48 |
+
check_git_info,
|
49 |
+
check_git_status,
|
50 |
+
check_requirements,
|
51 |
+
colorstr,
|
52 |
+
download,
|
53 |
+
increment_path,
|
54 |
+
init_seeds,
|
55 |
+
print_args,
|
56 |
+
yaml_save,
|
57 |
+
)
|
58 |
+
from utils.loggers import GenericLogger
|
59 |
+
from utils.plots import imshow_cls
|
60 |
+
from utils.torch_utils import (
|
61 |
+
ModelEMA,
|
62 |
+
de_parallel,
|
63 |
+
model_info,
|
64 |
+
reshape_classifier_output,
|
65 |
+
select_device,
|
66 |
+
smart_DDP,
|
67 |
+
smart_optimizer,
|
68 |
+
smartCrossEntropyLoss,
|
69 |
+
torch_distributed_zero_first,
|
70 |
+
)
|
71 |
+
|
72 |
+
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
|
73 |
+
RANK = int(os.getenv("RANK", -1))
|
74 |
+
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
|
75 |
+
GIT_INFO = check_git_info()
|
76 |
+
|
77 |
+
|
78 |
+
def train(opt, device):
|
79 |
+
"""Trains a YOLOv5 model, managing datasets, model optimization, logging, and saving checkpoints."""
|
80 |
+
init_seeds(opt.seed + 1 + RANK, deterministic=True)
|
81 |
+
save_dir, data, bs, epochs, nw, imgsz, pretrained = (
|
82 |
+
opt.save_dir,
|
83 |
+
Path(opt.data),
|
84 |
+
opt.batch_size,
|
85 |
+
opt.epochs,
|
86 |
+
min(os.cpu_count() - 1, opt.workers),
|
87 |
+
opt.imgsz,
|
88 |
+
str(opt.pretrained).lower() == "true",
|
89 |
+
)
|
90 |
+
cuda = device.type != "cpu"
|
91 |
+
|
92 |
+
# Directories
|
93 |
+
wdir = save_dir / "weights"
|
94 |
+
wdir.mkdir(parents=True, exist_ok=True) # make dir
|
95 |
+
last, best = wdir / "last.pt", wdir / "best.pt"
|
96 |
+
|
97 |
+
# Save run settings
|
98 |
+
yaml_save(save_dir / "opt.yaml", vars(opt))
|
99 |
+
|
100 |
+
# Logger
|
101 |
+
logger = GenericLogger(opt=opt, console_logger=LOGGER) if RANK in {-1, 0} else None
|
102 |
+
|
103 |
+
# Download Dataset
|
104 |
+
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
|
105 |
+
data_dir = data if data.is_dir() else (DATASETS_DIR / data)
|
106 |
+
if not data_dir.is_dir():
|
107 |
+
LOGGER.info(f"\nDataset not found ⚠️, missing path {data_dir}, attempting download...")
|
108 |
+
t = time.time()
|
109 |
+
if str(data) == "imagenet":
|
110 |
+
subprocess.run(["bash", str(ROOT / "data/scripts/get_imagenet.sh")], shell=True, check=True)
|
111 |
+
else:
|
112 |
+
url = f"https://github.com/ultralytics/assets/releases/download/v0.0.0/{data}.zip"
|
113 |
+
download(url, dir=data_dir.parent)
|
114 |
+
s = f"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\n"
|
115 |
+
LOGGER.info(s)
|
116 |
+
|
117 |
+
# Dataloaders
|
118 |
+
nc = len([x for x in (data_dir / "train").glob("*") if x.is_dir()]) # number of classes
|
119 |
+
trainloader = create_classification_dataloader(
|
120 |
+
path=data_dir / "train",
|
121 |
+
imgsz=imgsz,
|
122 |
+
batch_size=bs // WORLD_SIZE,
|
123 |
+
augment=True,
|
124 |
+
cache=opt.cache,
|
125 |
+
rank=LOCAL_RANK,
|
126 |
+
workers=nw,
|
127 |
+
)
|
128 |
+
|
129 |
+
test_dir = data_dir / "test" if (data_dir / "test").exists() else data_dir / "val" # data/test or data/val
|
130 |
+
if RANK in {-1, 0}:
|
131 |
+
testloader = create_classification_dataloader(
|
132 |
+
path=test_dir,
|
133 |
+
imgsz=imgsz,
|
134 |
+
batch_size=bs // WORLD_SIZE * 2,
|
135 |
+
augment=False,
|
136 |
+
cache=opt.cache,
|
137 |
+
rank=-1,
|
138 |
+
workers=nw,
|
139 |
+
)
|
140 |
+
|
141 |
+
# Model
|
142 |
+
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
|
143 |
+
if Path(opt.model).is_file() or opt.model.endswith(".pt"):
|
144 |
+
model = attempt_load(opt.model, device="cpu", fuse=False)
|
145 |
+
elif opt.model in torchvision.models.__dict__: # TorchVision models i.e. resnet50, efficientnet_b0
|
146 |
+
model = torchvision.models.__dict__[opt.model](weights="IMAGENET1K_V1" if pretrained else None)
|
147 |
+
else:
|
148 |
+
m = hub.list("ultralytics/yolov5") # + hub.list('pytorch/vision') # models
|
149 |
+
raise ModuleNotFoundError(f"--model {opt.model} not found. Available models are: \n" + "\n".join(m))
|
150 |
+
if isinstance(model, DetectionModel):
|
151 |
+
LOGGER.warning("WARNING ⚠️ pass YOLOv5 classifier model with '-cls' suffix, i.e. '--model yolov5s-cls.pt'")
|
152 |
+
model = ClassificationModel(model=model, nc=nc, cutoff=opt.cutoff or 10) # convert to classification model
|
153 |
+
reshape_classifier_output(model, nc) # update class count
|
154 |
+
for m in model.modules():
|
155 |
+
if not pretrained and hasattr(m, "reset_parameters"):
|
156 |
+
m.reset_parameters()
|
157 |
+
if isinstance(m, torch.nn.Dropout) and opt.dropout is not None:
|
158 |
+
m.p = opt.dropout # set dropout
|
159 |
+
for p in model.parameters():
|
160 |
+
p.requires_grad = True # for training
|
161 |
+
model = model.to(device)
|
162 |
+
|
163 |
+
# Info
|
164 |
+
if RANK in {-1, 0}:
|
165 |
+
model.names = trainloader.dataset.classes # attach class names
|
166 |
+
model.transforms = testloader.dataset.torch_transforms # attach inference transforms
|
167 |
+
model_info(model)
|
168 |
+
if opt.verbose:
|
169 |
+
LOGGER.info(model)
|
170 |
+
images, labels = next(iter(trainloader))
|
171 |
+
file = imshow_cls(images[:25], labels[:25], names=model.names, f=save_dir / "train_images.jpg")
|
172 |
+
logger.log_images(file, name="Train Examples")
|
173 |
+
logger.log_graph(model, imgsz) # log model
|
174 |
+
|
175 |
+
# Optimizer
|
176 |
+
optimizer = smart_optimizer(model, opt.optimizer, opt.lr0, momentum=0.9, decay=opt.decay)
|
177 |
+
|
178 |
+
# Scheduler
|
179 |
+
lrf = 0.01 # final lr (fraction of lr0)
|
180 |
+
|
181 |
+
# lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - lrf) + lrf # cosine
|
182 |
+
def lf(x):
|
183 |
+
"""Linear learning rate scheduler function, scaling learning rate from initial value to `lrf` over `epochs`."""
|
184 |
+
return (1 - x / epochs) * (1 - lrf) + lrf # linear
|
185 |
+
|
186 |
+
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
|
187 |
+
# scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=lr0, total_steps=epochs, pct_start=0.1,
|
188 |
+
# final_div_factor=1 / 25 / lrf)
|
189 |
+
|
190 |
+
# EMA
|
191 |
+
ema = ModelEMA(model) if RANK in {-1, 0} else None
|
192 |
+
|
193 |
+
# DDP mode
|
194 |
+
if cuda and RANK != -1:
|
195 |
+
model = smart_DDP(model)
|
196 |
+
|
197 |
+
# Train
|
198 |
+
t0 = time.time()
|
199 |
+
criterion = smartCrossEntropyLoss(label_smoothing=opt.label_smoothing) # loss function
|
200 |
+
best_fitness = 0.0
|
201 |
+
scaler = amp.GradScaler(enabled=cuda)
|
202 |
+
val = test_dir.stem # 'val' or 'test'
|
203 |
+
LOGGER.info(
|
204 |
+
f'Image sizes {imgsz} train, {imgsz} test\n'
|
205 |
+
f'Using {nw * WORLD_SIZE} dataloader workers\n'
|
206 |
+
f"Logging results to {colorstr('bold', save_dir)}\n"
|
207 |
+
f'Starting {opt.model} training on {data} dataset with {nc} classes for {epochs} epochs...\n\n'
|
208 |
+
f"{'Epoch':>10}{'GPU_mem':>10}{'train_loss':>12}{f'{val}_loss':>12}{'top1_acc':>12}{'top5_acc':>12}"
|
209 |
+
)
|
210 |
+
for epoch in range(epochs): # loop over the dataset multiple times
|
211 |
+
tloss, vloss, fitness = 0.0, 0.0, 0.0 # train loss, val loss, fitness
|
212 |
+
model.train()
|
213 |
+
if RANK != -1:
|
214 |
+
trainloader.sampler.set_epoch(epoch)
|
215 |
+
pbar = enumerate(trainloader)
|
216 |
+
if RANK in {-1, 0}:
|
217 |
+
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format=TQDM_BAR_FORMAT)
|
218 |
+
for i, (images, labels) in pbar: # progress bar
|
219 |
+
images, labels = images.to(device, non_blocking=True), labels.to(device)
|
220 |
+
|
221 |
+
# Forward
|
222 |
+
with amp.autocast(enabled=cuda): # stability issues when enabled
|
223 |
+
loss = criterion(model(images), labels)
|
224 |
+
|
225 |
+
# Backward
|
226 |
+
scaler.scale(loss).backward()
|
227 |
+
|
228 |
+
# Optimize
|
229 |
+
scaler.unscale_(optimizer) # unscale gradients
|
230 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
|
231 |
+
scaler.step(optimizer)
|
232 |
+
scaler.update()
|
233 |
+
optimizer.zero_grad()
|
234 |
+
if ema:
|
235 |
+
ema.update(model)
|
236 |
+
|
237 |
+
if RANK in {-1, 0}:
|
238 |
+
# Print
|
239 |
+
tloss = (tloss * i + loss.item()) / (i + 1) # update mean losses
|
240 |
+
mem = "%.3gG" % (torch.cuda.memory_reserved() / 1e9 if torch.cuda.is_available() else 0) # (GB)
|
241 |
+
pbar.desc = f"{f'{epoch + 1}/{epochs}':>10}{mem:>10}{tloss:>12.3g}" + " " * 36
|
242 |
+
|
243 |
+
# Test
|
244 |
+
if i == len(pbar) - 1: # last batch
|
245 |
+
top1, top5, vloss = validate.run(
|
246 |
+
model=ema.ema, dataloader=testloader, criterion=criterion, pbar=pbar
|
247 |
+
) # test accuracy, loss
|
248 |
+
fitness = top1 # define fitness as top1 accuracy
|
249 |
+
|
250 |
+
# Scheduler
|
251 |
+
scheduler.step()
|
252 |
+
|
253 |
+
# Log metrics
|
254 |
+
if RANK in {-1, 0}:
|
255 |
+
# Best fitness
|
256 |
+
if fitness > best_fitness:
|
257 |
+
best_fitness = fitness
|
258 |
+
|
259 |
+
# Log
|
260 |
+
metrics = {
|
261 |
+
"train/loss": tloss,
|
262 |
+
f"{val}/loss": vloss,
|
263 |
+
"metrics/accuracy_top1": top1,
|
264 |
+
"metrics/accuracy_top5": top5,
|
265 |
+
"lr/0": optimizer.param_groups[0]["lr"],
|
266 |
+
} # learning rate
|
267 |
+
logger.log_metrics(metrics, epoch)
|
268 |
+
|
269 |
+
# Save model
|
270 |
+
final_epoch = epoch + 1 == epochs
|
271 |
+
if (not opt.nosave) or final_epoch:
|
272 |
+
ckpt = {
|
273 |
+
"epoch": epoch,
|
274 |
+
"best_fitness": best_fitness,
|
275 |
+
"model": deepcopy(ema.ema).half(), # deepcopy(de_parallel(model)).half(),
|
276 |
+
"ema": None, # deepcopy(ema.ema).half(),
|
277 |
+
"updates": ema.updates,
|
278 |
+
"optimizer": None, # optimizer.state_dict(),
|
279 |
+
"opt": vars(opt),
|
280 |
+
"git": GIT_INFO, # {remote, branch, commit} if a git repo
|
281 |
+
"date": datetime.now().isoformat(),
|
282 |
+
}
|
283 |
+
|
284 |
+
# Save last, best and delete
|
285 |
+
torch.save(ckpt, last)
|
286 |
+
if best_fitness == fitness:
|
287 |
+
torch.save(ckpt, best)
|
288 |
+
del ckpt
|
289 |
+
|
290 |
+
# Train complete
|
291 |
+
if RANK in {-1, 0} and final_epoch:
|
292 |
+
LOGGER.info(
|
293 |
+
f'\nTraining complete ({(time.time() - t0) / 3600:.3f} hours)'
|
294 |
+
f"\nResults saved to {colorstr('bold', save_dir)}"
|
295 |
+
f'\nPredict: python classify/predict.py --weights {best} --source im.jpg'
|
296 |
+
f'\nValidate: python classify/val.py --weights {best} --data {data_dir}'
|
297 |
+
f'\nExport: python export.py --weights {best} --include onnx'
|
298 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{best}')"
|
299 |
+
f'\nVisualize: https://netron.app\n'
|
300 |
+
)
|
301 |
+
|
302 |
+
# Plot examples
|
303 |
+
images, labels = (x[:25] for x in next(iter(testloader))) # first 25 images and labels
|
304 |
+
pred = torch.max(ema.ema(images.to(device)), 1)[1]
|
305 |
+
file = imshow_cls(images, labels, pred, de_parallel(model).names, verbose=False, f=save_dir / "test_images.jpg")
|
306 |
+
|
307 |
+
# Log results
|
308 |
+
meta = {"epochs": epochs, "top1_acc": best_fitness, "date": datetime.now().isoformat()}
|
309 |
+
logger.log_images(file, name="Test Examples (true-predicted)", epoch=epoch)
|
310 |
+
logger.log_model(best, epochs, metadata=meta)
|
311 |
+
|
312 |
+
|
313 |
+
def parse_opt(known=False):
|
314 |
+
"""Parses command line arguments for YOLOv5 training including model path, dataset, epochs, and more, returning
|
315 |
+
parsed arguments.
|
316 |
+
"""
|
317 |
+
parser = argparse.ArgumentParser()
|
318 |
+
parser.add_argument("--model", type=str, default="yolov5s-cls.pt", help="initial weights path")
|
319 |
+
parser.add_argument("--data", type=str, default="imagenette160", help="cifar10, cifar100, mnist, imagenet, ...")
|
320 |
+
parser.add_argument("--epochs", type=int, default=10, help="total training epochs")
|
321 |
+
parser.add_argument("--batch-size", type=int, default=64, help="total batch size for all GPUs")
|
322 |
+
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=224, help="train, val image size (pixels)")
|
323 |
+
parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
|
324 |
+
parser.add_argument("--cache", type=str, nargs="?", const="ram", help='--cache images in "ram" (default) or "disk"')
|
325 |
+
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
326 |
+
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
|
327 |
+
parser.add_argument("--project", default=ROOT / "runs/train-cls", help="save to project/name")
|
328 |
+
parser.add_argument("--name", default="exp", help="save to project/name")
|
329 |
+
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
330 |
+
parser.add_argument("--pretrained", nargs="?", const=True, default=True, help="start from i.e. --pretrained False")
|
331 |
+
parser.add_argument("--optimizer", choices=["SGD", "Adam", "AdamW", "RMSProp"], default="Adam", help="optimizer")
|
332 |
+
parser.add_argument("--lr0", type=float, default=0.001, help="initial learning rate")
|
333 |
+
parser.add_argument("--decay", type=float, default=5e-5, help="weight decay")
|
334 |
+
parser.add_argument("--label-smoothing", type=float, default=0.1, help="Label smoothing epsilon")
|
335 |
+
parser.add_argument("--cutoff", type=int, default=None, help="Model layer cutoff index for Classify() head")
|
336 |
+
parser.add_argument("--dropout", type=float, default=None, help="Dropout (fraction)")
|
337 |
+
parser.add_argument("--verbose", action="store_true", help="Verbose mode")
|
338 |
+
parser.add_argument("--seed", type=int, default=0, help="Global training seed")
|
339 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")
|
340 |
+
return parser.parse_known_args()[0] if known else parser.parse_args()
|
341 |
+
|
342 |
+
|
343 |
+
def main(opt):
|
344 |
+
"""Executes YOLOv5 training with given options, handling device setup and DDP mode; includes pre-training checks."""
|
345 |
+
if RANK in {-1, 0}:
|
346 |
+
print_args(vars(opt))
|
347 |
+
check_git_status()
|
348 |
+
check_requirements(ROOT / "requirements.txt")
|
349 |
+
|
350 |
+
# DDP mode
|
351 |
+
device = select_device(opt.device, batch_size=opt.batch_size)
|
352 |
+
if LOCAL_RANK != -1:
|
353 |
+
assert opt.batch_size != -1, "AutoBatch is coming soon for classification, please pass a valid --batch-size"
|
354 |
+
assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE"
|
355 |
+
assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command"
|
356 |
+
torch.cuda.set_device(LOCAL_RANK)
|
357 |
+
device = torch.device("cuda", LOCAL_RANK)
|
358 |
+
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
|
359 |
+
|
360 |
+
# Parameters
|
361 |
+
opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
|
362 |
+
|
363 |
+
# Train
|
364 |
+
train(opt, device)
|
365 |
+
|
366 |
+
|
367 |
+
def run(**kwargs):
|
368 |
+
"""
|
369 |
+
Executes YOLOv5 model training or inference with specified parameters, returning updated options.
|
370 |
+
|
371 |
+
Example: from yolov5 import classify; classify.train.run(data=mnist, imgsz=320, model='yolov5m')
|
372 |
+
"""
|
373 |
+
opt = parse_opt(True)
|
374 |
+
for k, v in kwargs.items():
|
375 |
+
setattr(opt, k, v)
|
376 |
+
main(opt)
|
377 |
+
return opt
|
378 |
+
|
379 |
+
|
380 |
+
if __name__ == "__main__":
|
381 |
+
opt = parse_opt()
|
382 |
+
main(opt)
|
yolov5/classify/tutorial.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
yolov5/classify/val.py
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 (
|
40 |
+
LOGGER,
|
41 |
+
TQDM_BAR_FORMAT,
|
42 |
+
Profile,
|
43 |
+
check_img_size,
|
44 |
+
check_requirements,
|
45 |
+
colorstr,
|
46 |
+
increment_path,
|
47 |
+
print_args,
|
48 |
+
)
|
49 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
50 |
+
|
51 |
+
|
52 |
+
@smart_inference_mode()
|
53 |
+
def run(
|
54 |
+
data=ROOT / "../datasets/mnist", # dataset dir
|
55 |
+
weights=ROOT / "yolov5s-cls.pt", # model.pt path(s)
|
56 |
+
batch_size=128, # batch size
|
57 |
+
imgsz=224, # inference size (pixels)
|
58 |
+
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
59 |
+
workers=8, # max dataloader workers (per RANK in DDP mode)
|
60 |
+
verbose=False, # verbose output
|
61 |
+
project=ROOT / "runs/val-cls", # save to project/name
|
62 |
+
name="exp", # save to project/name
|
63 |
+
exist_ok=False, # existing project/name ok, do not increment
|
64 |
+
half=False, # use FP16 half-precision inference
|
65 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
66 |
+
model=None,
|
67 |
+
dataloader=None,
|
68 |
+
criterion=None,
|
69 |
+
pbar=None,
|
70 |
+
):
|
71 |
+
"""Validates a YOLOv5 classification model on a dataset, computing metrics like top1 and top5 accuracy."""
|
72 |
+
# Initialize/load model and set device
|
73 |
+
training = model is not None
|
74 |
+
if training: # called by train.py
|
75 |
+
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
|
76 |
+
half &= device.type != "cpu" # half precision only supported on CUDA
|
77 |
+
model.half() if half else model.float()
|
78 |
+
else: # called directly
|
79 |
+
device = select_device(device, batch_size=batch_size)
|
80 |
+
|
81 |
+
# Directories
|
82 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
83 |
+
save_dir.mkdir(parents=True, exist_ok=True) # make dir
|
84 |
+
|
85 |
+
# Load model
|
86 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, fp16=half)
|
87 |
+
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
|
88 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
89 |
+
half = model.fp16 # FP16 supported on limited backends with CUDA
|
90 |
+
if engine:
|
91 |
+
batch_size = model.batch_size
|
92 |
+
else:
|
93 |
+
device = model.device
|
94 |
+
if not (pt or jit):
|
95 |
+
batch_size = 1 # export.py models default to batch-size 1
|
96 |
+
LOGGER.info(f"Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models")
|
97 |
+
|
98 |
+
# Dataloader
|
99 |
+
data = Path(data)
|
100 |
+
test_dir = data / "test" if (data / "test").exists() else data / "val" # data/test or data/val
|
101 |
+
dataloader = create_classification_dataloader(
|
102 |
+
path=test_dir, imgsz=imgsz, batch_size=batch_size, augment=False, rank=-1, workers=workers
|
103 |
+
)
|
104 |
+
|
105 |
+
model.eval()
|
106 |
+
pred, targets, loss, dt = [], [], 0, (Profile(device=device), Profile(device=device), Profile(device=device))
|
107 |
+
n = len(dataloader) # number of batches
|
108 |
+
action = "validating" if dataloader.dataset.root.stem == "val" else "testing"
|
109 |
+
desc = f"{pbar.desc[:-36]}{action:>36}" if pbar else f"{action}"
|
110 |
+
bar = tqdm(dataloader, desc, n, not training, bar_format=TQDM_BAR_FORMAT, position=0)
|
111 |
+
with torch.cuda.amp.autocast(enabled=device.type != "cpu"):
|
112 |
+
for images, labels in bar:
|
113 |
+
with dt[0]:
|
114 |
+
images, labels = images.to(device, non_blocking=True), labels.to(device)
|
115 |
+
|
116 |
+
with dt[1]:
|
117 |
+
y = model(images)
|
118 |
+
|
119 |
+
with dt[2]:
|
120 |
+
pred.append(y.argsort(1, descending=True)[:, :5])
|
121 |
+
targets.append(labels)
|
122 |
+
if criterion:
|
123 |
+
loss += criterion(y, labels)
|
124 |
+
|
125 |
+
loss /= n
|
126 |
+
pred, targets = torch.cat(pred), torch.cat(targets)
|
127 |
+
correct = (targets[:, None] == pred).float()
|
128 |
+
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
|
129 |
+
top1, top5 = acc.mean(0).tolist()
|
130 |
+
|
131 |
+
if pbar:
|
132 |
+
pbar.desc = f"{pbar.desc[:-36]}{loss:>12.3g}{top1:>12.3g}{top5:>12.3g}"
|
133 |
+
if verbose: # all classes
|
134 |
+
LOGGER.info(f"{'Class':>24}{'Images':>12}{'top1_acc':>12}{'top5_acc':>12}")
|
135 |
+
LOGGER.info(f"{'all':>24}{targets.shape[0]:>12}{top1:>12.3g}{top5:>12.3g}")
|
136 |
+
for i, c in model.names.items():
|
137 |
+
acc_i = acc[targets == i]
|
138 |
+
top1i, top5i = acc_i.mean(0).tolist()
|
139 |
+
LOGGER.info(f"{c:>24}{acc_i.shape[0]:>12}{top1i:>12.3g}{top5i:>12.3g}")
|
140 |
+
|
141 |
+
# Print results
|
142 |
+
t = tuple(x.t / len(dataloader.dataset.samples) * 1e3 for x in dt) # speeds per image
|
143 |
+
shape = (1, 3, imgsz, imgsz)
|
144 |
+
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms post-process per image at shape {shape}" % t)
|
145 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
|
146 |
+
|
147 |
+
return top1, top5, loss
|
148 |
+
|
149 |
+
|
150 |
+
def parse_opt():
|
151 |
+
"""Parses and returns command line arguments for YOLOv5 model evaluation and inference settings."""
|
152 |
+
parser = argparse.ArgumentParser()
|
153 |
+
parser.add_argument("--data", type=str, default=ROOT / "../datasets/mnist", help="dataset path")
|
154 |
+
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model.pt path(s)")
|
155 |
+
parser.add_argument("--batch-size", type=int, default=128, help="batch size")
|
156 |
+
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=224, help="inference size (pixels)")
|
157 |
+
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
158 |
+
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
|
159 |
+
parser.add_argument("--verbose", nargs="?", const=True, default=True, help="verbose output")
|
160 |
+
parser.add_argument("--project", default=ROOT / "runs/val-cls", help="save to project/name")
|
161 |
+
parser.add_argument("--name", default="exp", help="save to project/name")
|
162 |
+
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
163 |
+
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
164 |
+
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
|
165 |
+
opt = parser.parse_args()
|
166 |
+
print_args(vars(opt))
|
167 |
+
return opt
|
168 |
+
|
169 |
+
|
170 |
+
def main(opt):
|
171 |
+
"""Executes the YOLOv5 model prediction workflow, handling argument parsing and requirement checks."""
|
172 |
+
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
|
173 |
+
run(**vars(opt))
|
174 |
+
|
175 |
+
|
176 |
+
if __name__ == "__main__":
|
177 |
+
opt = parse_opt()
|
178 |
+
main(opt)
|
yolov5/data/Argoverse.yaml
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/Argoverse # dataset root dir
|
11 |
+
train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
|
12 |
+
val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
|
13 |
+
test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: person
|
18 |
+
1: bicycle
|
19 |
+
2: car
|
20 |
+
3: motorcycle
|
21 |
+
4: bus
|
22 |
+
5: truck
|
23 |
+
6: traffic_light
|
24 |
+
7: stop_sign
|
25 |
+
|
26 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
27 |
+
download: |
|
28 |
+
import json
|
29 |
+
|
30 |
+
from tqdm import tqdm
|
31 |
+
from utils.general import download, Path
|
32 |
+
|
33 |
+
|
34 |
+
def argoverse2yolo(set):
|
35 |
+
labels = {}
|
36 |
+
a = json.load(open(set, "rb"))
|
37 |
+
for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
|
38 |
+
img_id = annot['image_id']
|
39 |
+
img_name = a['images'][img_id]['name']
|
40 |
+
img_label_name = f'{img_name[:-3]}txt'
|
41 |
+
|
42 |
+
cls = annot['category_id'] # instance class id
|
43 |
+
x_center, y_center, width, height = annot['bbox']
|
44 |
+
x_center = (x_center + width / 2) / 1920.0 # offset and scale
|
45 |
+
y_center = (y_center + height / 2) / 1200.0 # offset and scale
|
46 |
+
width /= 1920.0 # scale
|
47 |
+
height /= 1200.0 # scale
|
48 |
+
|
49 |
+
img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
|
50 |
+
if not img_dir.exists():
|
51 |
+
img_dir.mkdir(parents=True, exist_ok=True)
|
52 |
+
|
53 |
+
k = str(img_dir / img_label_name)
|
54 |
+
if k not in labels:
|
55 |
+
labels[k] = []
|
56 |
+
labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
|
57 |
+
|
58 |
+
for k in labels:
|
59 |
+
with open(k, "w") as f:
|
60 |
+
f.writelines(labels[k])
|
61 |
+
|
62 |
+
|
63 |
+
# Download
|
64 |
+
dir = Path(yaml['path']) # dataset root dir
|
65 |
+
urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
|
66 |
+
download(urls, dir=dir, delete=False)
|
67 |
+
|
68 |
+
# Convert
|
69 |
+
annotations_dir = 'Argoverse-HD/annotations/'
|
70 |
+
(dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
|
71 |
+
for d in "train.json", "val.json":
|
72 |
+
argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
|
yolov5/data/GlobalWheat2020.yaml
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/GlobalWheat2020 # dataset root dir
|
11 |
+
train: # train images (relative to 'path') 3422 images
|
12 |
+
- images/arvalis_1
|
13 |
+
- images/arvalis_2
|
14 |
+
- images/arvalis_3
|
15 |
+
- images/ethz_1
|
16 |
+
- images/rres_1
|
17 |
+
- images/inrae_1
|
18 |
+
- images/usask_1
|
19 |
+
val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
|
20 |
+
- images/ethz_1
|
21 |
+
test: # test images (optional) 1276 images
|
22 |
+
- images/utokyo_1
|
23 |
+
- images/utokyo_2
|
24 |
+
- images/nau_1
|
25 |
+
- images/uq_1
|
26 |
+
|
27 |
+
# Classes
|
28 |
+
names:
|
29 |
+
0: wheat_head
|
30 |
+
|
31 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
32 |
+
download: |
|
33 |
+
from utils.general import download, Path
|
34 |
+
|
35 |
+
|
36 |
+
# Download
|
37 |
+
dir = Path(yaml['path']) # dataset root dir
|
38 |
+
urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
|
39 |
+
'https://github.com/ultralytics/assets/releases/download/v0.0.0/GlobalWheat2020_labels.zip']
|
40 |
+
download(urls, dir=dir)
|
41 |
+
|
42 |
+
# Make Directories
|
43 |
+
for p in 'annotations', 'images', 'labels':
|
44 |
+
(dir / p).mkdir(parents=True, exist_ok=True)
|
45 |
+
|
46 |
+
# Move
|
47 |
+
for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
|
48 |
+
'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
|
49 |
+
(dir / p).rename(dir / 'images' / p) # move to /images
|
50 |
+
f = (dir / p).with_suffix('.json') # json file
|
51 |
+
if f.exists():
|
52 |
+
f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
|
yolov5/data/ImageNet.yaml
ADDED
@@ -0,0 +1,1020 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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/imagenet # dataset root dir
|
12 |
+
train: train # train images (relative to 'path') 1281167 images
|
13 |
+
val: val # val images (relative to 'path') 50000 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: tench
|
19 |
+
1: goldfish
|
20 |
+
2: great white shark
|
21 |
+
3: tiger shark
|
22 |
+
4: hammerhead shark
|
23 |
+
5: electric ray
|
24 |
+
6: stingray
|
25 |
+
7: cock
|
26 |
+
8: hen
|
27 |
+
9: ostrich
|
28 |
+
10: brambling
|
29 |
+
11: goldfinch
|
30 |
+
12: house finch
|
31 |
+
13: junco
|
32 |
+
14: indigo bunting
|
33 |
+
15: American robin
|
34 |
+
16: bulbul
|
35 |
+
17: jay
|
36 |
+
18: magpie
|
37 |
+
19: chickadee
|
38 |
+
20: American dipper
|
39 |
+
21: kite
|
40 |
+
22: bald eagle
|
41 |
+
23: vulture
|
42 |
+
24: great grey owl
|
43 |
+
25: fire salamander
|
44 |
+
26: smooth newt
|
45 |
+
27: newt
|
46 |
+
28: spotted salamander
|
47 |
+
29: axolotl
|
48 |
+
30: American bullfrog
|
49 |
+
31: tree frog
|
50 |
+
32: tailed frog
|
51 |
+
33: loggerhead sea turtle
|
52 |
+
34: leatherback sea turtle
|
53 |
+
35: mud turtle
|
54 |
+
36: terrapin
|
55 |
+
37: box turtle
|
56 |
+
38: banded gecko
|
57 |
+
39: green iguana
|
58 |
+
40: Carolina anole
|
59 |
+
41: desert grassland whiptail lizard
|
60 |
+
42: agama
|
61 |
+
43: frilled-necked lizard
|
62 |
+
44: alligator lizard
|
63 |
+
45: Gila monster
|
64 |
+
46: European green lizard
|
65 |
+
47: chameleon
|
66 |
+
48: Komodo dragon
|
67 |
+
49: Nile crocodile
|
68 |
+
50: American alligator
|
69 |
+
51: triceratops
|
70 |
+
52: worm snake
|
71 |
+
53: ring-necked snake
|
72 |
+
54: eastern hog-nosed snake
|
73 |
+
55: smooth green snake
|
74 |
+
56: kingsnake
|
75 |
+
57: garter snake
|
76 |
+
58: water snake
|
77 |
+
59: vine snake
|
78 |
+
60: night snake
|
79 |
+
61: boa constrictor
|
80 |
+
62: African rock python
|
81 |
+
63: Indian cobra
|
82 |
+
64: green mamba
|
83 |
+
65: sea snake
|
84 |
+
66: Saharan horned viper
|
85 |
+
67: eastern diamondback rattlesnake
|
86 |
+
68: sidewinder
|
87 |
+
69: trilobite
|
88 |
+
70: harvestman
|
89 |
+
71: scorpion
|
90 |
+
72: yellow garden spider
|
91 |
+
73: barn spider
|
92 |
+
74: European garden spider
|
93 |
+
75: southern black widow
|
94 |
+
76: tarantula
|
95 |
+
77: wolf spider
|
96 |
+
78: tick
|
97 |
+
79: centipede
|
98 |
+
80: black grouse
|
99 |
+
81: ptarmigan
|
100 |
+
82: ruffed grouse
|
101 |
+
83: prairie grouse
|
102 |
+
84: peacock
|
103 |
+
85: quail
|
104 |
+
86: partridge
|
105 |
+
87: grey parrot
|
106 |
+
88: macaw
|
107 |
+
89: sulphur-crested cockatoo
|
108 |
+
90: lorikeet
|
109 |
+
91: coucal
|
110 |
+
92: bee eater
|
111 |
+
93: hornbill
|
112 |
+
94: hummingbird
|
113 |
+
95: jacamar
|
114 |
+
96: toucan
|
115 |
+
97: duck
|
116 |
+
98: red-breasted merganser
|
117 |
+
99: goose
|
118 |
+
100: black swan
|
119 |
+
101: tusker
|
120 |
+
102: echidna
|
121 |
+
103: platypus
|
122 |
+
104: wallaby
|
123 |
+
105: koala
|
124 |
+
106: wombat
|
125 |
+
107: jellyfish
|
126 |
+
108: sea anemone
|
127 |
+
109: brain coral
|
128 |
+
110: flatworm
|
129 |
+
111: nematode
|
130 |
+
112: conch
|
131 |
+
113: snail
|
132 |
+
114: slug
|
133 |
+
115: sea slug
|
134 |
+
116: chiton
|
135 |
+
117: chambered nautilus
|
136 |
+
118: Dungeness crab
|
137 |
+
119: rock crab
|
138 |
+
120: fiddler crab
|
139 |
+
121: red king crab
|
140 |
+
122: American lobster
|
141 |
+
123: spiny lobster
|
142 |
+
124: crayfish
|
143 |
+
125: hermit crab
|
144 |
+
126: isopod
|
145 |
+
127: white stork
|
146 |
+
128: black stork
|
147 |
+
129: spoonbill
|
148 |
+
130: flamingo
|
149 |
+
131: little blue heron
|
150 |
+
132: great egret
|
151 |
+
133: bittern
|
152 |
+
134: crane (bird)
|
153 |
+
135: limpkin
|
154 |
+
136: common gallinule
|
155 |
+
137: American coot
|
156 |
+
138: bustard
|
157 |
+
139: ruddy turnstone
|
158 |
+
140: dunlin
|
159 |
+
141: common redshank
|
160 |
+
142: dowitcher
|
161 |
+
143: oystercatcher
|
162 |
+
144: pelican
|
163 |
+
145: king penguin
|
164 |
+
146: albatross
|
165 |
+
147: grey whale
|
166 |
+
148: killer whale
|
167 |
+
149: dugong
|
168 |
+
150: sea lion
|
169 |
+
151: Chihuahua
|
170 |
+
152: Japanese Chin
|
171 |
+
153: Maltese
|
172 |
+
154: Pekingese
|
173 |
+
155: Shih Tzu
|
174 |
+
156: King Charles Spaniel
|
175 |
+
157: Papillon
|
176 |
+
158: toy terrier
|
177 |
+
159: Rhodesian Ridgeback
|
178 |
+
160: Afghan Hound
|
179 |
+
161: Basset Hound
|
180 |
+
162: Beagle
|
181 |
+
163: Bloodhound
|
182 |
+
164: Bluetick Coonhound
|
183 |
+
165: Black and Tan Coonhound
|
184 |
+
166: Treeing Walker Coonhound
|
185 |
+
167: English foxhound
|
186 |
+
168: Redbone Coonhound
|
187 |
+
169: borzoi
|
188 |
+
170: Irish Wolfhound
|
189 |
+
171: Italian Greyhound
|
190 |
+
172: Whippet
|
191 |
+
173: Ibizan Hound
|
192 |
+
174: Norwegian Elkhound
|
193 |
+
175: Otterhound
|
194 |
+
176: Saluki
|
195 |
+
177: Scottish Deerhound
|
196 |
+
178: Weimaraner
|
197 |
+
179: Staffordshire Bull Terrier
|
198 |
+
180: American Staffordshire Terrier
|
199 |
+
181: Bedlington Terrier
|
200 |
+
182: Border Terrier
|
201 |
+
183: Kerry Blue Terrier
|
202 |
+
184: Irish Terrier
|
203 |
+
185: Norfolk Terrier
|
204 |
+
186: Norwich Terrier
|
205 |
+
187: Yorkshire Terrier
|
206 |
+
188: Wire Fox Terrier
|
207 |
+
189: Lakeland Terrier
|
208 |
+
190: Sealyham Terrier
|
209 |
+
191: Airedale Terrier
|
210 |
+
192: Cairn Terrier
|
211 |
+
193: Australian Terrier
|
212 |
+
194: Dandie Dinmont Terrier
|
213 |
+
195: Boston Terrier
|
214 |
+
196: Miniature Schnauzer
|
215 |
+
197: Giant Schnauzer
|
216 |
+
198: Standard Schnauzer
|
217 |
+
199: Scottish Terrier
|
218 |
+
200: Tibetan Terrier
|
219 |
+
201: Australian Silky Terrier
|
220 |
+
202: Soft-coated Wheaten Terrier
|
221 |
+
203: West Highland White Terrier
|
222 |
+
204: Lhasa Apso
|
223 |
+
205: Flat-Coated Retriever
|
224 |
+
206: Curly-coated Retriever
|
225 |
+
207: Golden Retriever
|
226 |
+
208: Labrador Retriever
|
227 |
+
209: Chesapeake Bay Retriever
|
228 |
+
210: German Shorthaired Pointer
|
229 |
+
211: Vizsla
|
230 |
+
212: English Setter
|
231 |
+
213: Irish Setter
|
232 |
+
214: Gordon Setter
|
233 |
+
215: Brittany
|
234 |
+
216: Clumber Spaniel
|
235 |
+
217: English Springer Spaniel
|
236 |
+
218: Welsh Springer Spaniel
|
237 |
+
219: Cocker Spaniels
|
238 |
+
220: Sussex Spaniel
|
239 |
+
221: Irish Water Spaniel
|
240 |
+
222: Kuvasz
|
241 |
+
223: Schipperke
|
242 |
+
224: Groenendael
|
243 |
+
225: Malinois
|
244 |
+
226: Briard
|
245 |
+
227: Australian Kelpie
|
246 |
+
228: Komondor
|
247 |
+
229: Old English Sheepdog
|
248 |
+
230: Shetland Sheepdog
|
249 |
+
231: collie
|
250 |
+
232: Border Collie
|
251 |
+
233: Bouvier des Flandres
|
252 |
+
234: Rottweiler
|
253 |
+
235: German Shepherd Dog
|
254 |
+
236: Dobermann
|
255 |
+
237: Miniature Pinscher
|
256 |
+
238: Greater Swiss Mountain Dog
|
257 |
+
239: Bernese Mountain Dog
|
258 |
+
240: Appenzeller Sennenhund
|
259 |
+
241: Entlebucher Sennenhund
|
260 |
+
242: Boxer
|
261 |
+
243: Bullmastiff
|
262 |
+
244: Tibetan Mastiff
|
263 |
+
245: French Bulldog
|
264 |
+
246: Great Dane
|
265 |
+
247: St. Bernard
|
266 |
+
248: husky
|
267 |
+
249: Alaskan Malamute
|
268 |
+
250: Siberian Husky
|
269 |
+
251: Dalmatian
|
270 |
+
252: Affenpinscher
|
271 |
+
253: Basenji
|
272 |
+
254: pug
|
273 |
+
255: Leonberger
|
274 |
+
256: Newfoundland
|
275 |
+
257: Pyrenean Mountain Dog
|
276 |
+
258: Samoyed
|
277 |
+
259: Pomeranian
|
278 |
+
260: Chow Chow
|
279 |
+
261: Keeshond
|
280 |
+
262: Griffon Bruxellois
|
281 |
+
263: Pembroke Welsh Corgi
|
282 |
+
264: Cardigan Welsh Corgi
|
283 |
+
265: Toy Poodle
|
284 |
+
266: Miniature Poodle
|
285 |
+
267: Standard Poodle
|
286 |
+
268: Mexican hairless dog
|
287 |
+
269: grey wolf
|
288 |
+
270: Alaskan tundra wolf
|
289 |
+
271: red wolf
|
290 |
+
272: coyote
|
291 |
+
273: dingo
|
292 |
+
274: dhole
|
293 |
+
275: African wild dog
|
294 |
+
276: hyena
|
295 |
+
277: red fox
|
296 |
+
278: kit fox
|
297 |
+
279: Arctic fox
|
298 |
+
280: grey fox
|
299 |
+
281: tabby cat
|
300 |
+
282: tiger cat
|
301 |
+
283: Persian cat
|
302 |
+
284: Siamese cat
|
303 |
+
285: Egyptian Mau
|
304 |
+
286: cougar
|
305 |
+
287: lynx
|
306 |
+
288: leopard
|
307 |
+
289: snow leopard
|
308 |
+
290: jaguar
|
309 |
+
291: lion
|
310 |
+
292: tiger
|
311 |
+
293: cheetah
|
312 |
+
294: brown bear
|
313 |
+
295: American black bear
|
314 |
+
296: polar bear
|
315 |
+
297: sloth bear
|
316 |
+
298: mongoose
|
317 |
+
299: meerkat
|
318 |
+
300: tiger beetle
|
319 |
+
301: ladybug
|
320 |
+
302: ground beetle
|
321 |
+
303: longhorn beetle
|
322 |
+
304: leaf beetle
|
323 |
+
305: dung beetle
|
324 |
+
306: rhinoceros beetle
|
325 |
+
307: weevil
|
326 |
+
308: fly
|
327 |
+
309: bee
|
328 |
+
310: ant
|
329 |
+
311: grasshopper
|
330 |
+
312: cricket
|
331 |
+
313: stick insect
|
332 |
+
314: cockroach
|
333 |
+
315: mantis
|
334 |
+
316: cicada
|
335 |
+
317: leafhopper
|
336 |
+
318: lacewing
|
337 |
+
319: dragonfly
|
338 |
+
320: damselfly
|
339 |
+
321: red admiral
|
340 |
+
322: ringlet
|
341 |
+
323: monarch butterfly
|
342 |
+
324: small white
|
343 |
+
325: sulphur butterfly
|
344 |
+
326: gossamer-winged butterfly
|
345 |
+
327: starfish
|
346 |
+
328: sea urchin
|
347 |
+
329: sea cucumber
|
348 |
+
330: cottontail rabbit
|
349 |
+
331: hare
|
350 |
+
332: Angora rabbit
|
351 |
+
333: hamster
|
352 |
+
334: porcupine
|
353 |
+
335: fox squirrel
|
354 |
+
336: marmot
|
355 |
+
337: beaver
|
356 |
+
338: guinea pig
|
357 |
+
339: common sorrel
|
358 |
+
340: zebra
|
359 |
+
341: pig
|
360 |
+
342: wild boar
|
361 |
+
343: warthog
|
362 |
+
344: hippopotamus
|
363 |
+
345: ox
|
364 |
+
346: water buffalo
|
365 |
+
347: bison
|
366 |
+
348: ram
|
367 |
+
349: bighorn sheep
|
368 |
+
350: Alpine ibex
|
369 |
+
351: hartebeest
|
370 |
+
352: impala
|
371 |
+
353: gazelle
|
372 |
+
354: dromedary
|
373 |
+
355: llama
|
374 |
+
356: weasel
|
375 |
+
357: mink
|
376 |
+
358: European polecat
|
377 |
+
359: black-footed ferret
|
378 |
+
360: otter
|
379 |
+
361: skunk
|
380 |
+
362: badger
|
381 |
+
363: armadillo
|
382 |
+
364: three-toed sloth
|
383 |
+
365: orangutan
|
384 |
+
366: gorilla
|
385 |
+
367: chimpanzee
|
386 |
+
368: gibbon
|
387 |
+
369: siamang
|
388 |
+
370: guenon
|
389 |
+
371: patas monkey
|
390 |
+
372: baboon
|
391 |
+
373: macaque
|
392 |
+
374: langur
|
393 |
+
375: black-and-white colobus
|
394 |
+
376: proboscis monkey
|
395 |
+
377: marmoset
|
396 |
+
378: white-headed capuchin
|
397 |
+
379: howler monkey
|
398 |
+
380: titi
|
399 |
+
381: Geoffroy's spider monkey
|
400 |
+
382: common squirrel monkey
|
401 |
+
383: ring-tailed lemur
|
402 |
+
384: indri
|
403 |
+
385: Asian elephant
|
404 |
+
386: African bush elephant
|
405 |
+
387: red panda
|
406 |
+
388: giant panda
|
407 |
+
389: snoek
|
408 |
+
390: eel
|
409 |
+
391: coho salmon
|
410 |
+
392: rock beauty
|
411 |
+
393: clownfish
|
412 |
+
394: sturgeon
|
413 |
+
395: garfish
|
414 |
+
396: lionfish
|
415 |
+
397: pufferfish
|
416 |
+
398: abacus
|
417 |
+
399: abaya
|
418 |
+
400: academic gown
|
419 |
+
401: accordion
|
420 |
+
402: acoustic guitar
|
421 |
+
403: aircraft carrier
|
422 |
+
404: airliner
|
423 |
+
405: airship
|
424 |
+
406: altar
|
425 |
+
407: ambulance
|
426 |
+
408: amphibious vehicle
|
427 |
+
409: analog clock
|
428 |
+
410: apiary
|
429 |
+
411: apron
|
430 |
+
412: waste container
|
431 |
+
413: assault rifle
|
432 |
+
414: backpack
|
433 |
+
415: bakery
|
434 |
+
416: balance beam
|
435 |
+
417: balloon
|
436 |
+
418: ballpoint pen
|
437 |
+
419: Band-Aid
|
438 |
+
420: banjo
|
439 |
+
421: baluster
|
440 |
+
422: barbell
|
441 |
+
423: barber chair
|
442 |
+
424: barbershop
|
443 |
+
425: barn
|
444 |
+
426: barometer
|
445 |
+
427: barrel
|
446 |
+
428: wheelbarrow
|
447 |
+
429: baseball
|
448 |
+
430: basketball
|
449 |
+
431: bassinet
|
450 |
+
432: bassoon
|
451 |
+
433: swimming cap
|
452 |
+
434: bath towel
|
453 |
+
435: bathtub
|
454 |
+
436: station wagon
|
455 |
+
437: lighthouse
|
456 |
+
438: beaker
|
457 |
+
439: military cap
|
458 |
+
440: beer bottle
|
459 |
+
441: beer glass
|
460 |
+
442: bell-cot
|
461 |
+
443: bib
|
462 |
+
444: tandem bicycle
|
463 |
+
445: bikini
|
464 |
+
446: ring binder
|
465 |
+
447: binoculars
|
466 |
+
448: birdhouse
|
467 |
+
449: boathouse
|
468 |
+
450: bobsleigh
|
469 |
+
451: bolo tie
|
470 |
+
452: poke bonnet
|
471 |
+
453: bookcase
|
472 |
+
454: bookstore
|
473 |
+
455: bottle cap
|
474 |
+
456: bow
|
475 |
+
457: bow tie
|
476 |
+
458: brass
|
477 |
+
459: bra
|
478 |
+
460: breakwater
|
479 |
+
461: breastplate
|
480 |
+
462: broom
|
481 |
+
463: bucket
|
482 |
+
464: buckle
|
483 |
+
465: bulletproof vest
|
484 |
+
466: high-speed train
|
485 |
+
467: butcher shop
|
486 |
+
468: taxicab
|
487 |
+
469: cauldron
|
488 |
+
470: candle
|
489 |
+
471: cannon
|
490 |
+
472: canoe
|
491 |
+
473: can opener
|
492 |
+
474: cardigan
|
493 |
+
475: car mirror
|
494 |
+
476: carousel
|
495 |
+
477: tool kit
|
496 |
+
478: carton
|
497 |
+
479: car wheel
|
498 |
+
480: automated teller machine
|
499 |
+
481: cassette
|
500 |
+
482: cassette player
|
501 |
+
483: castle
|
502 |
+
484: catamaran
|
503 |
+
485: CD player
|
504 |
+
486: cello
|
505 |
+
487: mobile phone
|
506 |
+
488: chain
|
507 |
+
489: chain-link fence
|
508 |
+
490: chain mail
|
509 |
+
491: chainsaw
|
510 |
+
492: chest
|
511 |
+
493: chiffonier
|
512 |
+
494: chime
|
513 |
+
495: china cabinet
|
514 |
+
496: Christmas stocking
|
515 |
+
497: church
|
516 |
+
498: movie theater
|
517 |
+
499: cleaver
|
518 |
+
500: cliff dwelling
|
519 |
+
501: cloak
|
520 |
+
502: clogs
|
521 |
+
503: cocktail shaker
|
522 |
+
504: coffee mug
|
523 |
+
505: coffeemaker
|
524 |
+
506: coil
|
525 |
+
507: combination lock
|
526 |
+
508: computer keyboard
|
527 |
+
509: confectionery store
|
528 |
+
510: container ship
|
529 |
+
511: convertible
|
530 |
+
512: corkscrew
|
531 |
+
513: cornet
|
532 |
+
514: cowboy boot
|
533 |
+
515: cowboy hat
|
534 |
+
516: cradle
|
535 |
+
517: crane (machine)
|
536 |
+
518: crash helmet
|
537 |
+
519: crate
|
538 |
+
520: infant bed
|
539 |
+
521: Crock Pot
|
540 |
+
522: croquet ball
|
541 |
+
523: crutch
|
542 |
+
524: cuirass
|
543 |
+
525: dam
|
544 |
+
526: desk
|
545 |
+
527: desktop computer
|
546 |
+
528: rotary dial telephone
|
547 |
+
529: diaper
|
548 |
+
530: digital clock
|
549 |
+
531: digital watch
|
550 |
+
532: dining table
|
551 |
+
533: dishcloth
|
552 |
+
534: dishwasher
|
553 |
+
535: disc brake
|
554 |
+
536: dock
|
555 |
+
537: dog sled
|
556 |
+
538: dome
|
557 |
+
539: doormat
|
558 |
+
540: drilling rig
|
559 |
+
541: drum
|
560 |
+
542: drumstick
|
561 |
+
543: dumbbell
|
562 |
+
544: Dutch oven
|
563 |
+
545: electric fan
|
564 |
+
546: electric guitar
|
565 |
+
547: electric locomotive
|
566 |
+
548: entertainment center
|
567 |
+
549: envelope
|
568 |
+
550: espresso machine
|
569 |
+
551: face powder
|
570 |
+
552: feather boa
|
571 |
+
553: filing cabinet
|
572 |
+
554: fireboat
|
573 |
+
555: fire engine
|
574 |
+
556: fire screen sheet
|
575 |
+
557: flagpole
|
576 |
+
558: flute
|
577 |
+
559: folding chair
|
578 |
+
560: football helmet
|
579 |
+
561: forklift
|
580 |
+
562: fountain
|
581 |
+
563: fountain pen
|
582 |
+
564: four-poster bed
|
583 |
+
565: freight car
|
584 |
+
566: French horn
|
585 |
+
567: frying pan
|
586 |
+
568: fur coat
|
587 |
+
569: garbage truck
|
588 |
+
570: gas mask
|
589 |
+
571: gas pump
|
590 |
+
572: goblet
|
591 |
+
573: go-kart
|
592 |
+
574: golf ball
|
593 |
+
575: golf cart
|
594 |
+
576: gondola
|
595 |
+
577: gong
|
596 |
+
578: gown
|
597 |
+
579: grand piano
|
598 |
+
580: greenhouse
|
599 |
+
581: grille
|
600 |
+
582: grocery store
|
601 |
+
583: guillotine
|
602 |
+
584: barrette
|
603 |
+
585: hair spray
|
604 |
+
586: half-track
|
605 |
+
587: hammer
|
606 |
+
588: hamper
|
607 |
+
589: hair dryer
|
608 |
+
590: hand-held computer
|
609 |
+
591: handkerchief
|
610 |
+
592: hard disk drive
|
611 |
+
593: harmonica
|
612 |
+
594: harp
|
613 |
+
595: harvester
|
614 |
+
596: hatchet
|
615 |
+
597: holster
|
616 |
+
598: home theater
|
617 |
+
599: honeycomb
|
618 |
+
600: hook
|
619 |
+
601: hoop skirt
|
620 |
+
602: horizontal bar
|
621 |
+
603: horse-drawn vehicle
|
622 |
+
604: hourglass
|
623 |
+
605: iPod
|
624 |
+
606: clothes iron
|
625 |
+
607: jack-o'-lantern
|
626 |
+
608: jeans
|
627 |
+
609: jeep
|
628 |
+
610: T-shirt
|
629 |
+
611: jigsaw puzzle
|
630 |
+
612: pulled rickshaw
|
631 |
+
613: joystick
|
632 |
+
614: kimono
|
633 |
+
615: knee pad
|
634 |
+
616: knot
|
635 |
+
617: lab coat
|
636 |
+
618: ladle
|
637 |
+
619: lampshade
|
638 |
+
620: laptop computer
|
639 |
+
621: lawn mower
|
640 |
+
622: lens cap
|
641 |
+
623: paper knife
|
642 |
+
624: library
|
643 |
+
625: lifeboat
|
644 |
+
626: lighter
|
645 |
+
627: limousine
|
646 |
+
628: ocean liner
|
647 |
+
629: lipstick
|
648 |
+
630: slip-on shoe
|
649 |
+
631: lotion
|
650 |
+
632: speaker
|
651 |
+
633: loupe
|
652 |
+
634: sawmill
|
653 |
+
635: magnetic compass
|
654 |
+
636: mail bag
|
655 |
+
637: mailbox
|
656 |
+
638: tights
|
657 |
+
639: tank suit
|
658 |
+
640: manhole cover
|
659 |
+
641: maraca
|
660 |
+
642: marimba
|
661 |
+
643: mask
|
662 |
+
644: match
|
663 |
+
645: maypole
|
664 |
+
646: maze
|
665 |
+
647: measuring cup
|
666 |
+
648: medicine chest
|
667 |
+
649: megalith
|
668 |
+
650: microphone
|
669 |
+
651: microwave oven
|
670 |
+
652: military uniform
|
671 |
+
653: milk can
|
672 |
+
654: minibus
|
673 |
+
655: miniskirt
|
674 |
+
656: minivan
|
675 |
+
657: missile
|
676 |
+
658: mitten
|
677 |
+
659: mixing bowl
|
678 |
+
660: mobile home
|
679 |
+
661: Model T
|
680 |
+
662: modem
|
681 |
+
663: monastery
|
682 |
+
664: monitor
|
683 |
+
665: moped
|
684 |
+
666: mortar
|
685 |
+
667: square academic cap
|
686 |
+
668: mosque
|
687 |
+
669: mosquito net
|
688 |
+
670: scooter
|
689 |
+
671: mountain bike
|
690 |
+
672: tent
|
691 |
+
673: computer mouse
|
692 |
+
674: mousetrap
|
693 |
+
675: moving van
|
694 |
+
676: muzzle
|
695 |
+
677: nail
|
696 |
+
678: neck brace
|
697 |
+
679: necklace
|
698 |
+
680: nipple
|
699 |
+
681: notebook computer
|
700 |
+
682: obelisk
|
701 |
+
683: oboe
|
702 |
+
684: ocarina
|
703 |
+
685: odometer
|
704 |
+
686: oil filter
|
705 |
+
687: organ
|
706 |
+
688: oscilloscope
|
707 |
+
689: overskirt
|
708 |
+
690: bullock cart
|
709 |
+
691: oxygen mask
|
710 |
+
692: packet
|
711 |
+
693: paddle
|
712 |
+
694: paddle wheel
|
713 |
+
695: padlock
|
714 |
+
696: paintbrush
|
715 |
+
697: pajamas
|
716 |
+
698: palace
|
717 |
+
699: pan flute
|
718 |
+
700: paper towel
|
719 |
+
701: parachute
|
720 |
+
702: parallel bars
|
721 |
+
703: park bench
|
722 |
+
704: parking meter
|
723 |
+
705: passenger car
|
724 |
+
706: patio
|
725 |
+
707: payphone
|
726 |
+
708: pedestal
|
727 |
+
709: pencil case
|
728 |
+
710: pencil sharpener
|
729 |
+
711: perfume
|
730 |
+
712: Petri dish
|
731 |
+
713: photocopier
|
732 |
+
714: plectrum
|
733 |
+
715: Pickelhaube
|
734 |
+
716: picket fence
|
735 |
+
717: pickup truck
|
736 |
+
718: pier
|
737 |
+
719: piggy bank
|
738 |
+
720: pill bottle
|
739 |
+
721: pillow
|
740 |
+
722: ping-pong ball
|
741 |
+
723: pinwheel
|
742 |
+
724: pirate ship
|
743 |
+
725: pitcher
|
744 |
+
726: hand plane
|
745 |
+
727: planetarium
|
746 |
+
728: plastic bag
|
747 |
+
729: plate rack
|
748 |
+
730: plow
|
749 |
+
731: plunger
|
750 |
+
732: Polaroid camera
|
751 |
+
733: pole
|
752 |
+
734: police van
|
753 |
+
735: poncho
|
754 |
+
736: billiard table
|
755 |
+
737: soda bottle
|
756 |
+
738: pot
|
757 |
+
739: potter's wheel
|
758 |
+
740: power drill
|
759 |
+
741: prayer rug
|
760 |
+
742: printer
|
761 |
+
743: prison
|
762 |
+
744: projectile
|
763 |
+
745: projector
|
764 |
+
746: hockey puck
|
765 |
+
747: punching bag
|
766 |
+
748: purse
|
767 |
+
749: quill
|
768 |
+
750: quilt
|
769 |
+
751: race car
|
770 |
+
752: racket
|
771 |
+
753: radiator
|
772 |
+
754: radio
|
773 |
+
755: radio telescope
|
774 |
+
756: rain barrel
|
775 |
+
757: recreational vehicle
|
776 |
+
758: reel
|
777 |
+
759: reflex camera
|
778 |
+
760: refrigerator
|
779 |
+
761: remote control
|
780 |
+
762: restaurant
|
781 |
+
763: revolver
|
782 |
+
764: rifle
|
783 |
+
765: rocking chair
|
784 |
+
766: rotisserie
|
785 |
+
767: eraser
|
786 |
+
768: rugby ball
|
787 |
+
769: ruler
|
788 |
+
770: running shoe
|
789 |
+
771: safe
|
790 |
+
772: safety pin
|
791 |
+
773: salt shaker
|
792 |
+
774: sandal
|
793 |
+
775: sarong
|
794 |
+
776: saxophone
|
795 |
+
777: scabbard
|
796 |
+
778: weighing scale
|
797 |
+
779: school bus
|
798 |
+
780: schooner
|
799 |
+
781: scoreboard
|
800 |
+
782: CRT screen
|
801 |
+
783: screw
|
802 |
+
784: screwdriver
|
803 |
+
785: seat belt
|
804 |
+
786: sewing machine
|
805 |
+
787: shield
|
806 |
+
788: shoe store
|
807 |
+
789: shoji
|
808 |
+
790: shopping basket
|
809 |
+
791: shopping cart
|
810 |
+
792: shovel
|
811 |
+
793: shower cap
|
812 |
+
794: shower curtain
|
813 |
+
795: ski
|
814 |
+
796: ski mask
|
815 |
+
797: sleeping bag
|
816 |
+
798: slide rule
|
817 |
+
799: sliding door
|
818 |
+
800: slot machine
|
819 |
+
801: snorkel
|
820 |
+
802: snowmobile
|
821 |
+
803: snowplow
|
822 |
+
804: soap dispenser
|
823 |
+
805: soccer ball
|
824 |
+
806: sock
|
825 |
+
807: solar thermal collector
|
826 |
+
808: sombrero
|
827 |
+
809: soup bowl
|
828 |
+
810: space bar
|
829 |
+
811: space heater
|
830 |
+
812: space shuttle
|
831 |
+
813: spatula
|
832 |
+
814: motorboat
|
833 |
+
815: spider web
|
834 |
+
816: spindle
|
835 |
+
817: sports car
|
836 |
+
818: spotlight
|
837 |
+
819: stage
|
838 |
+
820: steam locomotive
|
839 |
+
821: through arch bridge
|
840 |
+
822: steel drum
|
841 |
+
823: stethoscope
|
842 |
+
824: scarf
|
843 |
+
825: stone wall
|
844 |
+
826: stopwatch
|
845 |
+
827: stove
|
846 |
+
828: strainer
|
847 |
+
829: tram
|
848 |
+
830: stretcher
|
849 |
+
831: couch
|
850 |
+
832: stupa
|
851 |
+
833: submarine
|
852 |
+
834: suit
|
853 |
+
835: sundial
|
854 |
+
836: sunglass
|
855 |
+
837: sunglasses
|
856 |
+
838: sunscreen
|
857 |
+
839: suspension bridge
|
858 |
+
840: mop
|
859 |
+
841: sweatshirt
|
860 |
+
842: swimsuit
|
861 |
+
843: swing
|
862 |
+
844: switch
|
863 |
+
845: syringe
|
864 |
+
846: table lamp
|
865 |
+
847: tank
|
866 |
+
848: tape player
|
867 |
+
849: teapot
|
868 |
+
850: teddy bear
|
869 |
+
851: television
|
870 |
+
852: tennis ball
|
871 |
+
853: thatched roof
|
872 |
+
854: front curtain
|
873 |
+
855: thimble
|
874 |
+
856: threshing machine
|
875 |
+
857: throne
|
876 |
+
858: tile roof
|
877 |
+
859: toaster
|
878 |
+
860: tobacco shop
|
879 |
+
861: toilet seat
|
880 |
+
862: torch
|
881 |
+
863: totem pole
|
882 |
+
864: tow truck
|
883 |
+
865: toy store
|
884 |
+
866: tractor
|
885 |
+
867: semi-trailer truck
|
886 |
+
868: tray
|
887 |
+
869: trench coat
|
888 |
+
870: tricycle
|
889 |
+
871: trimaran
|
890 |
+
872: tripod
|
891 |
+
873: triumphal arch
|
892 |
+
874: trolleybus
|
893 |
+
875: trombone
|
894 |
+
876: tub
|
895 |
+
877: turnstile
|
896 |
+
878: typewriter keyboard
|
897 |
+
879: umbrella
|
898 |
+
880: unicycle
|
899 |
+
881: upright piano
|
900 |
+
882: vacuum cleaner
|
901 |
+
883: vase
|
902 |
+
884: vault
|
903 |
+
885: velvet
|
904 |
+
886: vending machine
|
905 |
+
887: vestment
|
906 |
+
888: viaduct
|
907 |
+
889: violin
|
908 |
+
890: volleyball
|
909 |
+
891: waffle iron
|
910 |
+
892: wall clock
|
911 |
+
893: wallet
|
912 |
+
894: wardrobe
|
913 |
+
895: military aircraft
|
914 |
+
896: sink
|
915 |
+
897: washing machine
|
916 |
+
898: water bottle
|
917 |
+
899: water jug
|
918 |
+
900: water tower
|
919 |
+
901: whiskey jug
|
920 |
+
902: whistle
|
921 |
+
903: wig
|
922 |
+
904: window screen
|
923 |
+
905: window shade
|
924 |
+
906: Windsor tie
|
925 |
+
907: wine bottle
|
926 |
+
908: wing
|
927 |
+
909: wok
|
928 |
+
910: wooden spoon
|
929 |
+
911: wool
|
930 |
+
912: split-rail fence
|
931 |
+
913: shipwreck
|
932 |
+
914: yawl
|
933 |
+
915: yurt
|
934 |
+
916: website
|
935 |
+
917: comic book
|
936 |
+
918: crossword
|
937 |
+
919: traffic sign
|
938 |
+
920: traffic light
|
939 |
+
921: dust jacket
|
940 |
+
922: menu
|
941 |
+
923: plate
|
942 |
+
924: guacamole
|
943 |
+
925: consomme
|
944 |
+
926: hot pot
|
945 |
+
927: trifle
|
946 |
+
928: ice cream
|
947 |
+
929: ice pop
|
948 |
+
930: baguette
|
949 |
+
931: bagel
|
950 |
+
932: pretzel
|
951 |
+
933: cheeseburger
|
952 |
+
934: hot dog
|
953 |
+
935: mashed potato
|
954 |
+
936: cabbage
|
955 |
+
937: broccoli
|
956 |
+
938: cauliflower
|
957 |
+
939: zucchini
|
958 |
+
940: spaghetti squash
|
959 |
+
941: acorn squash
|
960 |
+
942: butternut squash
|
961 |
+
943: cucumber
|
962 |
+
944: artichoke
|
963 |
+
945: bell pepper
|
964 |
+
946: cardoon
|
965 |
+
947: mushroom
|
966 |
+
948: Granny Smith
|
967 |
+
949: strawberry
|
968 |
+
950: orange
|
969 |
+
951: lemon
|
970 |
+
952: fig
|
971 |
+
953: pineapple
|
972 |
+
954: banana
|
973 |
+
955: jackfruit
|
974 |
+
956: custard apple
|
975 |
+
957: pomegranate
|
976 |
+
958: hay
|
977 |
+
959: carbonara
|
978 |
+
960: chocolate syrup
|
979 |
+
961: dough
|
980 |
+
962: meatloaf
|
981 |
+
963: pizza
|
982 |
+
964: pot pie
|
983 |
+
965: burrito
|
984 |
+
966: red wine
|
985 |
+
967: espresso
|
986 |
+
968: cup
|
987 |
+
969: eggnog
|
988 |
+
970: alp
|
989 |
+
971: bubble
|
990 |
+
972: cliff
|
991 |
+
973: coral reef
|
992 |
+
974: geyser
|
993 |
+
975: lakeshore
|
994 |
+
976: promontory
|
995 |
+
977: shoal
|
996 |
+
978: seashore
|
997 |
+
979: valley
|
998 |
+
980: volcano
|
999 |
+
981: baseball player
|
1000 |
+
982: bridegroom
|
1001 |
+
983: scuba diver
|
1002 |
+
984: rapeseed
|
1003 |
+
985: daisy
|
1004 |
+
986: yellow lady's slipper
|
1005 |
+
987: corn
|
1006 |
+
988: acorn
|
1007 |
+
989: rose hip
|
1008 |
+
990: horse chestnut seed
|
1009 |
+
991: coral fungus
|
1010 |
+
992: agaric
|
1011 |
+
993: gyromitra
|
1012 |
+
994: stinkhorn mushroom
|
1013 |
+
995: earth star
|
1014 |
+
996: hen-of-the-woods
|
1015 |
+
997: bolete
|
1016 |
+
998: ear
|
1017 |
+
999: toilet paper
|
1018 |
+
|
1019 |
+
# Download script/URL (optional)
|
1020 |
+
download: data/scripts/get_imagenet.sh
|
yolov5/data/ImageNet10.yaml
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# └── imagenet10 ← downloads here
|
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/imagenet10 # dataset root dir
|
12 |
+
train: train # train images (relative to 'path') 1281167 images
|
13 |
+
val: val # val images (relative to 'path') 50000 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: tench
|
19 |
+
1: goldfish
|
20 |
+
2: great white shark
|
21 |
+
3: tiger shark
|
22 |
+
4: hammerhead shark
|
23 |
+
5: electric ray
|
24 |
+
6: stingray
|
25 |
+
7: cock
|
26 |
+
8: hen
|
27 |
+
9: ostrich
|
28 |
+
|
29 |
+
# Download script/URL (optional)
|
30 |
+
download: data/scripts/get_imagenet10.sh
|
yolov5/data/ImageNet100.yaml
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# └── imagenet100 ← downloads here
|
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/imagenet100 # dataset root dir
|
12 |
+
train: train # train images (relative to 'path') 1281167 images
|
13 |
+
val: val # val images (relative to 'path') 50000 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: tench
|
19 |
+
1: goldfish
|
20 |
+
2: great white shark
|
21 |
+
3: tiger shark
|
22 |
+
4: hammerhead shark
|
23 |
+
5: electric ray
|
24 |
+
6: stingray
|
25 |
+
7: cock
|
26 |
+
8: hen
|
27 |
+
9: ostrich
|
28 |
+
10: brambling
|
29 |
+
11: goldfinch
|
30 |
+
12: house finch
|
31 |
+
13: junco
|
32 |
+
14: indigo bunting
|
33 |
+
15: American robin
|
34 |
+
16: bulbul
|
35 |
+
17: jay
|
36 |
+
18: magpie
|
37 |
+
19: chickadee
|
38 |
+
20: American dipper
|
39 |
+
21: kite
|
40 |
+
22: bald eagle
|
41 |
+
23: vulture
|
42 |
+
24: great grey owl
|
43 |
+
25: fire salamander
|
44 |
+
26: smooth newt
|
45 |
+
27: newt
|
46 |
+
28: spotted salamander
|
47 |
+
29: axolotl
|
48 |
+
30: American bullfrog
|
49 |
+
31: tree frog
|
50 |
+
32: tailed frog
|
51 |
+
33: loggerhead sea turtle
|
52 |
+
34: leatherback sea turtle
|
53 |
+
35: mud turtle
|
54 |
+
36: terrapin
|
55 |
+
37: box turtle
|
56 |
+
38: banded gecko
|
57 |
+
39: green iguana
|
58 |
+
40: Carolina anole
|
59 |
+
41: desert grassland whiptail lizard
|
60 |
+
42: agama
|
61 |
+
43: frilled-necked lizard
|
62 |
+
44: alligator lizard
|
63 |
+
45: Gila monster
|
64 |
+
46: European green lizard
|
65 |
+
47: chameleon
|
66 |
+
48: Komodo dragon
|
67 |
+
49: Nile crocodile
|
68 |
+
50: American alligator
|
69 |
+
51: triceratops
|
70 |
+
52: worm snake
|
71 |
+
53: ring-necked snake
|
72 |
+
54: eastern hog-nosed snake
|
73 |
+
55: smooth green snake
|
74 |
+
56: kingsnake
|
75 |
+
57: garter snake
|
76 |
+
58: water snake
|
77 |
+
59: vine snake
|
78 |
+
60: night snake
|
79 |
+
61: boa constrictor
|
80 |
+
62: African rock python
|
81 |
+
63: Indian cobra
|
82 |
+
64: green mamba
|
83 |
+
65: sea snake
|
84 |
+
66: Saharan horned viper
|
85 |
+
67: eastern diamondback rattlesnake
|
86 |
+
68: sidewinder
|
87 |
+
69: trilobite
|
88 |
+
70: harvestman
|
89 |
+
71: scorpion
|
90 |
+
72: yellow garden spider
|
91 |
+
73: barn spider
|
92 |
+
74: European garden spider
|
93 |
+
75: southern black widow
|
94 |
+
76: tarantula
|
95 |
+
77: wolf spider
|
96 |
+
78: tick
|
97 |
+
79: centipede
|
98 |
+
80: black grouse
|
99 |
+
81: ptarmigan
|
100 |
+
82: ruffed grouse
|
101 |
+
83: prairie grouse
|
102 |
+
84: peacock
|
103 |
+
85: quail
|
104 |
+
86: partridge
|
105 |
+
87: grey parrot
|
106 |
+
88: macaw
|
107 |
+
89: sulphur-crested cockatoo
|
108 |
+
90: lorikeet
|
109 |
+
91: coucal
|
110 |
+
92: bee eater
|
111 |
+
93: hornbill
|
112 |
+
94: hummingbird
|
113 |
+
95: jacamar
|
114 |
+
96: toucan
|
115 |
+
97: duck
|
116 |
+
98: red-breasted merganser
|
117 |
+
99: goose
|
118 |
+
# Download script/URL (optional)
|
119 |
+
download: data/scripts/get_imagenet100.sh
|
yolov5/data/ImageNet1000.yaml
ADDED
@@ -0,0 +1,1020 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# └── imagenet100 ← downloads here
|
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/imagenet1000 # dataset root dir
|
12 |
+
train: train # train images (relative to 'path') 1281167 images
|
13 |
+
val: val # val images (relative to 'path') 50000 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
names:
|
18 |
+
0: tench
|
19 |
+
1: goldfish
|
20 |
+
2: great white shark
|
21 |
+
3: tiger shark
|
22 |
+
4: hammerhead shark
|
23 |
+
5: electric ray
|
24 |
+
6: stingray
|
25 |
+
7: cock
|
26 |
+
8: hen
|
27 |
+
9: ostrich
|
28 |
+
10: brambling
|
29 |
+
11: goldfinch
|
30 |
+
12: house finch
|
31 |
+
13: junco
|
32 |
+
14: indigo bunting
|
33 |
+
15: American robin
|
34 |
+
16: bulbul
|
35 |
+
17: jay
|
36 |
+
18: magpie
|
37 |
+
19: chickadee
|
38 |
+
20: American dipper
|
39 |
+
21: kite
|
40 |
+
22: bald eagle
|
41 |
+
23: vulture
|
42 |
+
24: great grey owl
|
43 |
+
25: fire salamander
|
44 |
+
26: smooth newt
|
45 |
+
27: newt
|
46 |
+
28: spotted salamander
|
47 |
+
29: axolotl
|
48 |
+
30: American bullfrog
|
49 |
+
31: tree frog
|
50 |
+
32: tailed frog
|
51 |
+
33: loggerhead sea turtle
|
52 |
+
34: leatherback sea turtle
|
53 |
+
35: mud turtle
|
54 |
+
36: terrapin
|
55 |
+
37: box turtle
|
56 |
+
38: banded gecko
|
57 |
+
39: green iguana
|
58 |
+
40: Carolina anole
|
59 |
+
41: desert grassland whiptail lizard
|
60 |
+
42: agama
|
61 |
+
43: frilled-necked lizard
|
62 |
+
44: alligator lizard
|
63 |
+
45: Gila monster
|
64 |
+
46: European green lizard
|
65 |
+
47: chameleon
|
66 |
+
48: Komodo dragon
|
67 |
+
49: Nile crocodile
|
68 |
+
50: American alligator
|
69 |
+
51: triceratops
|
70 |
+
52: worm snake
|
71 |
+
53: ring-necked snake
|
72 |
+
54: eastern hog-nosed snake
|
73 |
+
55: smooth green snake
|
74 |
+
56: kingsnake
|
75 |
+
57: garter snake
|
76 |
+
58: water snake
|
77 |
+
59: vine snake
|
78 |
+
60: night snake
|
79 |
+
61: boa constrictor
|
80 |
+
62: African rock python
|
81 |
+
63: Indian cobra
|
82 |
+
64: green mamba
|
83 |
+
65: sea snake
|
84 |
+
66: Saharan horned viper
|
85 |
+
67: eastern diamondback rattlesnake
|
86 |
+
68: sidewinder
|
87 |
+
69: trilobite
|
88 |
+
70: harvestman
|
89 |
+
71: scorpion
|
90 |
+
72: yellow garden spider
|
91 |
+
73: barn spider
|
92 |
+
74: European garden spider
|
93 |
+
75: southern black widow
|
94 |
+
76: tarantula
|
95 |
+
77: wolf spider
|
96 |
+
78: tick
|
97 |
+
79: centipede
|
98 |
+
80: black grouse
|
99 |
+
81: ptarmigan
|
100 |
+
82: ruffed grouse
|
101 |
+
83: prairie grouse
|
102 |
+
84: peacock
|
103 |
+
85: quail
|
104 |
+
86: partridge
|
105 |
+
87: grey parrot
|
106 |
+
88: macaw
|
107 |
+
89: sulphur-crested cockatoo
|
108 |
+
90: lorikeet
|
109 |
+
91: coucal
|
110 |
+
92: bee eater
|
111 |
+
93: hornbill
|
112 |
+
94: hummingbird
|
113 |
+
95: jacamar
|
114 |
+
96: toucan
|
115 |
+
97: duck
|
116 |
+
98: red-breasted merganser
|
117 |
+
99: goose
|
118 |
+
100: black swan
|
119 |
+
101: tusker
|
120 |
+
102: echidna
|
121 |
+
103: platypus
|
122 |
+
104: wallaby
|
123 |
+
105: koala
|
124 |
+
106: wombat
|
125 |
+
107: jellyfish
|
126 |
+
108: sea anemone
|
127 |
+
109: brain coral
|
128 |
+
110: flatworm
|
129 |
+
111: nematode
|
130 |
+
112: conch
|
131 |
+
113: snail
|
132 |
+
114: slug
|
133 |
+
115: sea slug
|
134 |
+
116: chiton
|
135 |
+
117: chambered nautilus
|
136 |
+
118: Dungeness crab
|
137 |
+
119: rock crab
|
138 |
+
120: fiddler crab
|
139 |
+
121: red king crab
|
140 |
+
122: American lobster
|
141 |
+
123: spiny lobster
|
142 |
+
124: crayfish
|
143 |
+
125: hermit crab
|
144 |
+
126: isopod
|
145 |
+
127: white stork
|
146 |
+
128: black stork
|
147 |
+
129: spoonbill
|
148 |
+
130: flamingo
|
149 |
+
131: little blue heron
|
150 |
+
132: great egret
|
151 |
+
133: bittern
|
152 |
+
134: crane (bird)
|
153 |
+
135: limpkin
|
154 |
+
136: common gallinule
|
155 |
+
137: American coot
|
156 |
+
138: bustard
|
157 |
+
139: ruddy turnstone
|
158 |
+
140: dunlin
|
159 |
+
141: common redshank
|
160 |
+
142: dowitcher
|
161 |
+
143: oystercatcher
|
162 |
+
144: pelican
|
163 |
+
145: king penguin
|
164 |
+
146: albatross
|
165 |
+
147: grey whale
|
166 |
+
148: killer whale
|
167 |
+
149: dugong
|
168 |
+
150: sea lion
|
169 |
+
151: Chihuahua
|
170 |
+
152: Japanese Chin
|
171 |
+
153: Maltese
|
172 |
+
154: Pekingese
|
173 |
+
155: Shih Tzu
|
174 |
+
156: King Charles Spaniel
|
175 |
+
157: Papillon
|
176 |
+
158: toy terrier
|
177 |
+
159: Rhodesian Ridgeback
|
178 |
+
160: Afghan Hound
|
179 |
+
161: Basset Hound
|
180 |
+
162: Beagle
|
181 |
+
163: Bloodhound
|
182 |
+
164: Bluetick Coonhound
|
183 |
+
165: Black and Tan Coonhound
|
184 |
+
166: Treeing Walker Coonhound
|
185 |
+
167: English foxhound
|
186 |
+
168: Redbone Coonhound
|
187 |
+
169: borzoi
|
188 |
+
170: Irish Wolfhound
|
189 |
+
171: Italian Greyhound
|
190 |
+
172: Whippet
|
191 |
+
173: Ibizan Hound
|
192 |
+
174: Norwegian Elkhound
|
193 |
+
175: Otterhound
|
194 |
+
176: Saluki
|
195 |
+
177: Scottish Deerhound
|
196 |
+
178: Weimaraner
|
197 |
+
179: Staffordshire Bull Terrier
|
198 |
+
180: American Staffordshire Terrier
|
199 |
+
181: Bedlington Terrier
|
200 |
+
182: Border Terrier
|
201 |
+
183: Kerry Blue Terrier
|
202 |
+
184: Irish Terrier
|
203 |
+
185: Norfolk Terrier
|
204 |
+
186: Norwich Terrier
|
205 |
+
187: Yorkshire Terrier
|
206 |
+
188: Wire Fox Terrier
|
207 |
+
189: Lakeland Terrier
|
208 |
+
190: Sealyham Terrier
|
209 |
+
191: Airedale Terrier
|
210 |
+
192: Cairn Terrier
|
211 |
+
193: Australian Terrier
|
212 |
+
194: Dandie Dinmont Terrier
|
213 |
+
195: Boston Terrier
|
214 |
+
196: Miniature Schnauzer
|
215 |
+
197: Giant Schnauzer
|
216 |
+
198: Standard Schnauzer
|
217 |
+
199: Scottish Terrier
|
218 |
+
200: Tibetan Terrier
|
219 |
+
201: Australian Silky Terrier
|
220 |
+
202: Soft-coated Wheaten Terrier
|
221 |
+
203: West Highland White Terrier
|
222 |
+
204: Lhasa Apso
|
223 |
+
205: Flat-Coated Retriever
|
224 |
+
206: Curly-coated Retriever
|
225 |
+
207: Golden Retriever
|
226 |
+
208: Labrador Retriever
|
227 |
+
209: Chesapeake Bay Retriever
|
228 |
+
210: German Shorthaired Pointer
|
229 |
+
211: Vizsla
|
230 |
+
212: English Setter
|
231 |
+
213: Irish Setter
|
232 |
+
214: Gordon Setter
|
233 |
+
215: Brittany
|
234 |
+
216: Clumber Spaniel
|
235 |
+
217: English Springer Spaniel
|
236 |
+
218: Welsh Springer Spaniel
|
237 |
+
219: Cocker Spaniels
|
238 |
+
220: Sussex Spaniel
|
239 |
+
221: Irish Water Spaniel
|
240 |
+
222: Kuvasz
|
241 |
+
223: Schipperke
|
242 |
+
224: Groenendael
|
243 |
+
225: Malinois
|
244 |
+
226: Briard
|
245 |
+
227: Australian Kelpie
|
246 |
+
228: Komondor
|
247 |
+
229: Old English Sheepdog
|
248 |
+
230: Shetland Sheepdog
|
249 |
+
231: collie
|
250 |
+
232: Border Collie
|
251 |
+
233: Bouvier des Flandres
|
252 |
+
234: Rottweiler
|
253 |
+
235: German Shepherd Dog
|
254 |
+
236: Dobermann
|
255 |
+
237: Miniature Pinscher
|
256 |
+
238: Greater Swiss Mountain Dog
|
257 |
+
239: Bernese Mountain Dog
|
258 |
+
240: Appenzeller Sennenhund
|
259 |
+
241: Entlebucher Sennenhund
|
260 |
+
242: Boxer
|
261 |
+
243: Bullmastiff
|
262 |
+
244: Tibetan Mastiff
|
263 |
+
245: French Bulldog
|
264 |
+
246: Great Dane
|
265 |
+
247: St. Bernard
|
266 |
+
248: husky
|
267 |
+
249: Alaskan Malamute
|
268 |
+
250: Siberian Husky
|
269 |
+
251: Dalmatian
|
270 |
+
252: Affenpinscher
|
271 |
+
253: Basenji
|
272 |
+
254: pug
|
273 |
+
255: Leonberger
|
274 |
+
256: Newfoundland
|
275 |
+
257: Pyrenean Mountain Dog
|
276 |
+
258: Samoyed
|
277 |
+
259: Pomeranian
|
278 |
+
260: Chow Chow
|
279 |
+
261: Keeshond
|
280 |
+
262: Griffon Bruxellois
|
281 |
+
263: Pembroke Welsh Corgi
|
282 |
+
264: Cardigan Welsh Corgi
|
283 |
+
265: Toy Poodle
|
284 |
+
266: Miniature Poodle
|
285 |
+
267: Standard Poodle
|
286 |
+
268: Mexican hairless dog
|
287 |
+
269: grey wolf
|
288 |
+
270: Alaskan tundra wolf
|
289 |
+
271: red wolf
|
290 |
+
272: coyote
|
291 |
+
273: dingo
|
292 |
+
274: dhole
|
293 |
+
275: African wild dog
|
294 |
+
276: hyena
|
295 |
+
277: red fox
|
296 |
+
278: kit fox
|
297 |
+
279: Arctic fox
|
298 |
+
280: grey fox
|
299 |
+
281: tabby cat
|
300 |
+
282: tiger cat
|
301 |
+
283: Persian cat
|
302 |
+
284: Siamese cat
|
303 |
+
285: Egyptian Mau
|
304 |
+
286: cougar
|
305 |
+
287: lynx
|
306 |
+
288: leopard
|
307 |
+
289: snow leopard
|
308 |
+
290: jaguar
|
309 |
+
291: lion
|
310 |
+
292: tiger
|
311 |
+
293: cheetah
|
312 |
+
294: brown bear
|
313 |
+
295: American black bear
|
314 |
+
296: polar bear
|
315 |
+
297: sloth bear
|
316 |
+
298: mongoose
|
317 |
+
299: meerkat
|
318 |
+
300: tiger beetle
|
319 |
+
301: ladybug
|
320 |
+
302: ground beetle
|
321 |
+
303: longhorn beetle
|
322 |
+
304: leaf beetle
|
323 |
+
305: dung beetle
|
324 |
+
306: rhinoceros beetle
|
325 |
+
307: weevil
|
326 |
+
308: fly
|
327 |
+
309: bee
|
328 |
+
310: ant
|
329 |
+
311: grasshopper
|
330 |
+
312: cricket
|
331 |
+
313: stick insect
|
332 |
+
314: cockroach
|
333 |
+
315: mantis
|
334 |
+
316: cicada
|
335 |
+
317: leafhopper
|
336 |
+
318: lacewing
|
337 |
+
319: dragonfly
|
338 |
+
320: damselfly
|
339 |
+
321: red admiral
|
340 |
+
322: ringlet
|
341 |
+
323: monarch butterfly
|
342 |
+
324: small white
|
343 |
+
325: sulphur butterfly
|
344 |
+
326: gossamer-winged butterfly
|
345 |
+
327: starfish
|
346 |
+
328: sea urchin
|
347 |
+
329: sea cucumber
|
348 |
+
330: cottontail rabbit
|
349 |
+
331: hare
|
350 |
+
332: Angora rabbit
|
351 |
+
333: hamster
|
352 |
+
334: porcupine
|
353 |
+
335: fox squirrel
|
354 |
+
336: marmot
|
355 |
+
337: beaver
|
356 |
+
338: guinea pig
|
357 |
+
339: common sorrel
|
358 |
+
340: zebra
|
359 |
+
341: pig
|
360 |
+
342: wild boar
|
361 |
+
343: warthog
|
362 |
+
344: hippopotamus
|
363 |
+
345: ox
|
364 |
+
346: water buffalo
|
365 |
+
347: bison
|
366 |
+
348: ram
|
367 |
+
349: bighorn sheep
|
368 |
+
350: Alpine ibex
|
369 |
+
351: hartebeest
|
370 |
+
352: impala
|
371 |
+
353: gazelle
|
372 |
+
354: dromedary
|
373 |
+
355: llama
|
374 |
+
356: weasel
|
375 |
+
357: mink
|
376 |
+
358: European polecat
|
377 |
+
359: black-footed ferret
|
378 |
+
360: otter
|
379 |
+
361: skunk
|
380 |
+
362: badger
|
381 |
+
363: armadillo
|
382 |
+
364: three-toed sloth
|
383 |
+
365: orangutan
|
384 |
+
366: gorilla
|
385 |
+
367: chimpanzee
|
386 |
+
368: gibbon
|
387 |
+
369: siamang
|
388 |
+
370: guenon
|
389 |
+
371: patas monkey
|
390 |
+
372: baboon
|
391 |
+
373: macaque
|
392 |
+
374: langur
|
393 |
+
375: black-and-white colobus
|
394 |
+
376: proboscis monkey
|
395 |
+
377: marmoset
|
396 |
+
378: white-headed capuchin
|
397 |
+
379: howler monkey
|
398 |
+
380: titi
|
399 |
+
381: Geoffroy's spider monkey
|
400 |
+
382: common squirrel monkey
|
401 |
+
383: ring-tailed lemur
|
402 |
+
384: indri
|
403 |
+
385: Asian elephant
|
404 |
+
386: African bush elephant
|
405 |
+
387: red panda
|
406 |
+
388: giant panda
|
407 |
+
389: snoek
|
408 |
+
390: eel
|
409 |
+
391: coho salmon
|
410 |
+
392: rock beauty
|
411 |
+
393: clownfish
|
412 |
+
394: sturgeon
|
413 |
+
395: garfish
|
414 |
+
396: lionfish
|
415 |
+
397: pufferfish
|
416 |
+
398: abacus
|
417 |
+
399: abaya
|
418 |
+
400: academic gown
|
419 |
+
401: accordion
|
420 |
+
402: acoustic guitar
|
421 |
+
403: aircraft carrier
|
422 |
+
404: airliner
|
423 |
+
405: airship
|
424 |
+
406: altar
|
425 |
+
407: ambulance
|
426 |
+
408: amphibious vehicle
|
427 |
+
409: analog clock
|
428 |
+
410: apiary
|
429 |
+
411: apron
|
430 |
+
412: waste container
|
431 |
+
413: assault rifle
|
432 |
+
414: backpack
|
433 |
+
415: bakery
|
434 |
+
416: balance beam
|
435 |
+
417: balloon
|
436 |
+
418: ballpoint pen
|
437 |
+
419: Band-Aid
|
438 |
+
420: banjo
|
439 |
+
421: baluster
|
440 |
+
422: barbell
|
441 |
+
423: barber chair
|
442 |
+
424: barbershop
|
443 |
+
425: barn
|
444 |
+
426: barometer
|
445 |
+
427: barrel
|
446 |
+
428: wheelbarrow
|
447 |
+
429: baseball
|
448 |
+
430: basketball
|
449 |
+
431: bassinet
|
450 |
+
432: bassoon
|
451 |
+
433: swimming cap
|
452 |
+
434: bath towel
|
453 |
+
435: bathtub
|
454 |
+
436: station wagon
|
455 |
+
437: lighthouse
|
456 |
+
438: beaker
|
457 |
+
439: military cap
|
458 |
+
440: beer bottle
|
459 |
+
441: beer glass
|
460 |
+
442: bell-cot
|
461 |
+
443: bib
|
462 |
+
444: tandem bicycle
|
463 |
+
445: bikini
|
464 |
+
446: ring binder
|
465 |
+
447: binoculars
|
466 |
+
448: birdhouse
|
467 |
+
449: boathouse
|
468 |
+
450: bobsleigh
|
469 |
+
451: bolo tie
|
470 |
+
452: poke bonnet
|
471 |
+
453: bookcase
|
472 |
+
454: bookstore
|
473 |
+
455: bottle cap
|
474 |
+
456: bow
|
475 |
+
457: bow tie
|
476 |
+
458: brass
|
477 |
+
459: bra
|
478 |
+
460: breakwater
|
479 |
+
461: breastplate
|
480 |
+
462: broom
|
481 |
+
463: bucket
|
482 |
+
464: buckle
|
483 |
+
465: bulletproof vest
|
484 |
+
466: high-speed train
|
485 |
+
467: butcher shop
|
486 |
+
468: taxicab
|
487 |
+
469: cauldron
|
488 |
+
470: candle
|
489 |
+
471: cannon
|
490 |
+
472: canoe
|
491 |
+
473: can opener
|
492 |
+
474: cardigan
|
493 |
+
475: car mirror
|
494 |
+
476: carousel
|
495 |
+
477: tool kit
|
496 |
+
478: carton
|
497 |
+
479: car wheel
|
498 |
+
480: automated teller machine
|
499 |
+
481: cassette
|
500 |
+
482: cassette player
|
501 |
+
483: castle
|
502 |
+
484: catamaran
|
503 |
+
485: CD player
|
504 |
+
486: cello
|
505 |
+
487: mobile phone
|
506 |
+
488: chain
|
507 |
+
489: chain-link fence
|
508 |
+
490: chain mail
|
509 |
+
491: chainsaw
|
510 |
+
492: chest
|
511 |
+
493: chiffonier
|
512 |
+
494: chime
|
513 |
+
495: china cabinet
|
514 |
+
496: Christmas stocking
|
515 |
+
497: church
|
516 |
+
498: movie theater
|
517 |
+
499: cleaver
|
518 |
+
500: cliff dwelling
|
519 |
+
501: cloak
|
520 |
+
502: clogs
|
521 |
+
503: cocktail shaker
|
522 |
+
504: coffee mug
|
523 |
+
505: coffeemaker
|
524 |
+
506: coil
|
525 |
+
507: combination lock
|
526 |
+
508: computer keyboard
|
527 |
+
509: confectionery store
|
528 |
+
510: container ship
|
529 |
+
511: convertible
|
530 |
+
512: corkscrew
|
531 |
+
513: cornet
|
532 |
+
514: cowboy boot
|
533 |
+
515: cowboy hat
|
534 |
+
516: cradle
|
535 |
+
517: crane (machine)
|
536 |
+
518: crash helmet
|
537 |
+
519: crate
|
538 |
+
520: infant bed
|
539 |
+
521: Crock Pot
|
540 |
+
522: croquet ball
|
541 |
+
523: crutch
|
542 |
+
524: cuirass
|
543 |
+
525: dam
|
544 |
+
526: desk
|
545 |
+
527: desktop computer
|
546 |
+
528: rotary dial telephone
|
547 |
+
529: diaper
|
548 |
+
530: digital clock
|
549 |
+
531: digital watch
|
550 |
+
532: dining table
|
551 |
+
533: dishcloth
|
552 |
+
534: dishwasher
|
553 |
+
535: disc brake
|
554 |
+
536: dock
|
555 |
+
537: dog sled
|
556 |
+
538: dome
|
557 |
+
539: doormat
|
558 |
+
540: drilling rig
|
559 |
+
541: drum
|
560 |
+
542: drumstick
|
561 |
+
543: dumbbell
|
562 |
+
544: Dutch oven
|
563 |
+
545: electric fan
|
564 |
+
546: electric guitar
|
565 |
+
547: electric locomotive
|
566 |
+
548: entertainment center
|
567 |
+
549: envelope
|
568 |
+
550: espresso machine
|
569 |
+
551: face powder
|
570 |
+
552: feather boa
|
571 |
+
553: filing cabinet
|
572 |
+
554: fireboat
|
573 |
+
555: fire engine
|
574 |
+
556: fire screen sheet
|
575 |
+
557: flagpole
|
576 |
+
558: flute
|
577 |
+
559: folding chair
|
578 |
+
560: football helmet
|
579 |
+
561: forklift
|
580 |
+
562: fountain
|
581 |
+
563: fountain pen
|
582 |
+
564: four-poster bed
|
583 |
+
565: freight car
|
584 |
+
566: French horn
|
585 |
+
567: frying pan
|
586 |
+
568: fur coat
|
587 |
+
569: garbage truck
|
588 |
+
570: gas mask
|
589 |
+
571: gas pump
|
590 |
+
572: goblet
|
591 |
+
573: go-kart
|
592 |
+
574: golf ball
|
593 |
+
575: golf cart
|
594 |
+
576: gondola
|
595 |
+
577: gong
|
596 |
+
578: gown
|
597 |
+
579: grand piano
|
598 |
+
580: greenhouse
|
599 |
+
581: grille
|
600 |
+
582: grocery store
|
601 |
+
583: guillotine
|
602 |
+
584: barrette
|
603 |
+
585: hair spray
|
604 |
+
586: half-track
|
605 |
+
587: hammer
|
606 |
+
588: hamper
|
607 |
+
589: hair dryer
|
608 |
+
590: hand-held computer
|
609 |
+
591: handkerchief
|
610 |
+
592: hard disk drive
|
611 |
+
593: harmonica
|
612 |
+
594: harp
|
613 |
+
595: harvester
|
614 |
+
596: hatchet
|
615 |
+
597: holster
|
616 |
+
598: home theater
|
617 |
+
599: honeycomb
|
618 |
+
600: hook
|
619 |
+
601: hoop skirt
|
620 |
+
602: horizontal bar
|
621 |
+
603: horse-drawn vehicle
|
622 |
+
604: hourglass
|
623 |
+
605: iPod
|
624 |
+
606: clothes iron
|
625 |
+
607: jack-o'-lantern
|
626 |
+
608: jeans
|
627 |
+
609: jeep
|
628 |
+
610: T-shirt
|
629 |
+
611: jigsaw puzzle
|
630 |
+
612: pulled rickshaw
|
631 |
+
613: joystick
|
632 |
+
614: kimono
|
633 |
+
615: knee pad
|
634 |
+
616: knot
|
635 |
+
617: lab coat
|
636 |
+
618: ladle
|
637 |
+
619: lampshade
|
638 |
+
620: laptop computer
|
639 |
+
621: lawn mower
|
640 |
+
622: lens cap
|
641 |
+
623: paper knife
|
642 |
+
624: library
|
643 |
+
625: lifeboat
|
644 |
+
626: lighter
|
645 |
+
627: limousine
|
646 |
+
628: ocean liner
|
647 |
+
629: lipstick
|
648 |
+
630: slip-on shoe
|
649 |
+
631: lotion
|
650 |
+
632: speaker
|
651 |
+
633: loupe
|
652 |
+
634: sawmill
|
653 |
+
635: magnetic compass
|
654 |
+
636: mail bag
|
655 |
+
637: mailbox
|
656 |
+
638: tights
|
657 |
+
639: tank suit
|
658 |
+
640: manhole cover
|
659 |
+
641: maraca
|
660 |
+
642: marimba
|
661 |
+
643: mask
|
662 |
+
644: match
|
663 |
+
645: maypole
|
664 |
+
646: maze
|
665 |
+
647: measuring cup
|
666 |
+
648: medicine chest
|
667 |
+
649: megalith
|
668 |
+
650: microphone
|
669 |
+
651: microwave oven
|
670 |
+
652: military uniform
|
671 |
+
653: milk can
|
672 |
+
654: minibus
|
673 |
+
655: miniskirt
|
674 |
+
656: minivan
|
675 |
+
657: missile
|
676 |
+
658: mitten
|
677 |
+
659: mixing bowl
|
678 |
+
660: mobile home
|
679 |
+
661: Model T
|
680 |
+
662: modem
|
681 |
+
663: monastery
|
682 |
+
664: monitor
|
683 |
+
665: moped
|
684 |
+
666: mortar
|
685 |
+
667: square academic cap
|
686 |
+
668: mosque
|
687 |
+
669: mosquito net
|
688 |
+
670: scooter
|
689 |
+
671: mountain bike
|
690 |
+
672: tent
|
691 |
+
673: computer mouse
|
692 |
+
674: mousetrap
|
693 |
+
675: moving van
|
694 |
+
676: muzzle
|
695 |
+
677: nail
|
696 |
+
678: neck brace
|
697 |
+
679: necklace
|
698 |
+
680: nipple
|
699 |
+
681: notebook computer
|
700 |
+
682: obelisk
|
701 |
+
683: oboe
|
702 |
+
684: ocarina
|
703 |
+
685: odometer
|
704 |
+
686: oil filter
|
705 |
+
687: organ
|
706 |
+
688: oscilloscope
|
707 |
+
689: overskirt
|
708 |
+
690: bullock cart
|
709 |
+
691: oxygen mask
|
710 |
+
692: packet
|
711 |
+
693: paddle
|
712 |
+
694: paddle wheel
|
713 |
+
695: padlock
|
714 |
+
696: paintbrush
|
715 |
+
697: pajamas
|
716 |
+
698: palace
|
717 |
+
699: pan flute
|
718 |
+
700: paper towel
|
719 |
+
701: parachute
|
720 |
+
702: parallel bars
|
721 |
+
703: park bench
|
722 |
+
704: parking meter
|
723 |
+
705: passenger car
|
724 |
+
706: patio
|
725 |
+
707: payphone
|
726 |
+
708: pedestal
|
727 |
+
709: pencil case
|
728 |
+
710: pencil sharpener
|
729 |
+
711: perfume
|
730 |
+
712: Petri dish
|
731 |
+
713: photocopier
|
732 |
+
714: plectrum
|
733 |
+
715: Pickelhaube
|
734 |
+
716: picket fence
|
735 |
+
717: pickup truck
|
736 |
+
718: pier
|
737 |
+
719: piggy bank
|
738 |
+
720: pill bottle
|
739 |
+
721: pillow
|
740 |
+
722: ping-pong ball
|
741 |
+
723: pinwheel
|
742 |
+
724: pirate ship
|
743 |
+
725: pitcher
|
744 |
+
726: hand plane
|
745 |
+
727: planetarium
|
746 |
+
728: plastic bag
|
747 |
+
729: plate rack
|
748 |
+
730: plow
|
749 |
+
731: plunger
|
750 |
+
732: Polaroid camera
|
751 |
+
733: pole
|
752 |
+
734: police van
|
753 |
+
735: poncho
|
754 |
+
736: billiard table
|
755 |
+
737: soda bottle
|
756 |
+
738: pot
|
757 |
+
739: potter's wheel
|
758 |
+
740: power drill
|
759 |
+
741: prayer rug
|
760 |
+
742: printer
|
761 |
+
743: prison
|
762 |
+
744: projectile
|
763 |
+
745: projector
|
764 |
+
746: hockey puck
|
765 |
+
747: punching bag
|
766 |
+
748: purse
|
767 |
+
749: quill
|
768 |
+
750: quilt
|
769 |
+
751: race car
|
770 |
+
752: racket
|
771 |
+
753: radiator
|
772 |
+
754: radio
|
773 |
+
755: radio telescope
|
774 |
+
756: rain barrel
|
775 |
+
757: recreational vehicle
|
776 |
+
758: reel
|
777 |
+
759: reflex camera
|
778 |
+
760: refrigerator
|
779 |
+
761: remote control
|
780 |
+
762: restaurant
|
781 |
+
763: revolver
|
782 |
+
764: rifle
|
783 |
+
765: rocking chair
|
784 |
+
766: rotisserie
|
785 |
+
767: eraser
|
786 |
+
768: rugby ball
|
787 |
+
769: ruler
|
788 |
+
770: running shoe
|
789 |
+
771: safe
|
790 |
+
772: safety pin
|
791 |
+
773: salt shaker
|
792 |
+
774: sandal
|
793 |
+
775: sarong
|
794 |
+
776: saxophone
|
795 |
+
777: scabbard
|
796 |
+
778: weighing scale
|
797 |
+
779: school bus
|
798 |
+
780: schooner
|
799 |
+
781: scoreboard
|
800 |
+
782: CRT screen
|
801 |
+
783: screw
|
802 |
+
784: screwdriver
|
803 |
+
785: seat belt
|
804 |
+
786: sewing machine
|
805 |
+
787: shield
|
806 |
+
788: shoe store
|
807 |
+
789: shoji
|
808 |
+
790: shopping basket
|
809 |
+
791: shopping cart
|
810 |
+
792: shovel
|
811 |
+
793: shower cap
|
812 |
+
794: shower curtain
|
813 |
+
795: ski
|
814 |
+
796: ski mask
|
815 |
+
797: sleeping bag
|
816 |
+
798: slide rule
|
817 |
+
799: sliding door
|
818 |
+
800: slot machine
|
819 |
+
801: snorkel
|
820 |
+
802: snowmobile
|
821 |
+
803: snowplow
|
822 |
+
804: soap dispenser
|
823 |
+
805: soccer ball
|
824 |
+
806: sock
|
825 |
+
807: solar thermal collector
|
826 |
+
808: sombrero
|
827 |
+
809: soup bowl
|
828 |
+
810: space bar
|
829 |
+
811: space heater
|
830 |
+
812: space shuttle
|
831 |
+
813: spatula
|
832 |
+
814: motorboat
|
833 |
+
815: spider web
|
834 |
+
816: spindle
|
835 |
+
817: sports car
|
836 |
+
818: spotlight
|
837 |
+
819: stage
|
838 |
+
820: steam locomotive
|
839 |
+
821: through arch bridge
|
840 |
+
822: steel drum
|
841 |
+
823: stethoscope
|
842 |
+
824: scarf
|
843 |
+
825: stone wall
|
844 |
+
826: stopwatch
|
845 |
+
827: stove
|
846 |
+
828: strainer
|
847 |
+
829: tram
|
848 |
+
830: stretcher
|
849 |
+
831: couch
|
850 |
+
832: stupa
|
851 |
+
833: submarine
|
852 |
+
834: suit
|
853 |
+
835: sundial
|
854 |
+
836: sunglass
|
855 |
+
837: sunglasses
|
856 |
+
838: sunscreen
|
857 |
+
839: suspension bridge
|
858 |
+
840: mop
|
859 |
+
841: sweatshirt
|
860 |
+
842: swimsuit
|
861 |
+
843: swing
|
862 |
+
844: switch
|
863 |
+
845: syringe
|
864 |
+
846: table lamp
|
865 |
+
847: tank
|
866 |
+
848: tape player
|
867 |
+
849: teapot
|
868 |
+
850: teddy bear
|
869 |
+
851: television
|
870 |
+
852: tennis ball
|
871 |
+
853: thatched roof
|
872 |
+
854: front curtain
|
873 |
+
855: thimble
|
874 |
+
856: threshing machine
|
875 |
+
857: throne
|
876 |
+
858: tile roof
|
877 |
+
859: toaster
|
878 |
+
860: tobacco shop
|
879 |
+
861: toilet seat
|
880 |
+
862: torch
|
881 |
+
863: totem pole
|
882 |
+
864: tow truck
|
883 |
+
865: toy store
|
884 |
+
866: tractor
|
885 |
+
867: semi-trailer truck
|
886 |
+
868: tray
|
887 |
+
869: trench coat
|
888 |
+
870: tricycle
|
889 |
+
871: trimaran
|
890 |
+
872: tripod
|
891 |
+
873: triumphal arch
|
892 |
+
874: trolleybus
|
893 |
+
875: trombone
|
894 |
+
876: tub
|
895 |
+
877: turnstile
|
896 |
+
878: typewriter keyboard
|
897 |
+
879: umbrella
|
898 |
+
880: unicycle
|
899 |
+
881: upright piano
|
900 |
+
882: vacuum cleaner
|
901 |
+
883: vase
|
902 |
+
884: vault
|
903 |
+
885: velvet
|
904 |
+
886: vending machine
|
905 |
+
887: vestment
|
906 |
+
888: viaduct
|
907 |
+
889: violin
|
908 |
+
890: volleyball
|
909 |
+
891: waffle iron
|
910 |
+
892: wall clock
|
911 |
+
893: wallet
|
912 |
+
894: wardrobe
|
913 |
+
895: military aircraft
|
914 |
+
896: sink
|
915 |
+
897: washing machine
|
916 |
+
898: water bottle
|
917 |
+
899: water jug
|
918 |
+
900: water tower
|
919 |
+
901: whiskey jug
|
920 |
+
902: whistle
|
921 |
+
903: wig
|
922 |
+
904: window screen
|
923 |
+
905: window shade
|
924 |
+
906: Windsor tie
|
925 |
+
907: wine bottle
|
926 |
+
908: wing
|
927 |
+
909: wok
|
928 |
+
910: wooden spoon
|
929 |
+
911: wool
|
930 |
+
912: split-rail fence
|
931 |
+
913: shipwreck
|
932 |
+
914: yawl
|
933 |
+
915: yurt
|
934 |
+
916: website
|
935 |
+
917: comic book
|
936 |
+
918: crossword
|
937 |
+
919: traffic sign
|
938 |
+
920: traffic light
|
939 |
+
921: dust jacket
|
940 |
+
922: menu
|
941 |
+
923: plate
|
942 |
+
924: guacamole
|
943 |
+
925: consomme
|
944 |
+
926: hot pot
|
945 |
+
927: trifle
|
946 |
+
928: ice cream
|
947 |
+
929: ice pop
|
948 |
+
930: baguette
|
949 |
+
931: bagel
|
950 |
+
932: pretzel
|
951 |
+
933: cheeseburger
|
952 |
+
934: hot dog
|
953 |
+
935: mashed potato
|
954 |
+
936: cabbage
|
955 |
+
937: broccoli
|
956 |
+
938: cauliflower
|
957 |
+
939: zucchini
|
958 |
+
940: spaghetti squash
|
959 |
+
941: acorn squash
|
960 |
+
942: butternut squash
|
961 |
+
943: cucumber
|
962 |
+
944: artichoke
|
963 |
+
945: bell pepper
|
964 |
+
946: cardoon
|
965 |
+
947: mushroom
|
966 |
+
948: Granny Smith
|
967 |
+
949: strawberry
|
968 |
+
950: orange
|
969 |
+
951: lemon
|
970 |
+
952: fig
|
971 |
+
953: pineapple
|
972 |
+
954: banana
|
973 |
+
955: jackfruit
|
974 |
+
956: custard apple
|
975 |
+
957: pomegranate
|
976 |
+
958: hay
|
977 |
+
959: carbonara
|
978 |
+
960: chocolate syrup
|
979 |
+
961: dough
|
980 |
+
962: meatloaf
|
981 |
+
963: pizza
|
982 |
+
964: pot pie
|
983 |
+
965: burrito
|
984 |
+
966: red wine
|
985 |
+
967: espresso
|
986 |
+
968: cup
|
987 |
+
969: eggnog
|
988 |
+
970: alp
|
989 |
+
971: bubble
|
990 |
+
972: cliff
|
991 |
+
973: coral reef
|
992 |
+
974: geyser
|
993 |
+
975: lakeshore
|
994 |
+
976: promontory
|
995 |
+
977: shoal
|
996 |
+
978: seashore
|
997 |
+
979: valley
|
998 |
+
980: volcano
|
999 |
+
981: baseball player
|
1000 |
+
982: bridegroom
|
1001 |
+
983: scuba diver
|
1002 |
+
984: rapeseed
|
1003 |
+
985: daisy
|
1004 |
+
986: yellow lady's slipper
|
1005 |
+
987: corn
|
1006 |
+
988: acorn
|
1007 |
+
989: rose hip
|
1008 |
+
990: horse chestnut seed
|
1009 |
+
991: coral fungus
|
1010 |
+
992: agaric
|
1011 |
+
993: gyromitra
|
1012 |
+
994: stinkhorn mushroom
|
1013 |
+
995: earth star
|
1014 |
+
996: hen-of-the-woods
|
1015 |
+
997: bolete
|
1016 |
+
998: ear
|
1017 |
+
999: toilet paper
|
1018 |
+
|
1019 |
+
# Download script/URL (optional)
|
1020 |
+
download: data/scripts/get_imagenet1000.sh
|
yolov5/data/Objects365.yaml
ADDED
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/Objects365 # dataset root dir
|
11 |
+
train: images/train # train images (relative to 'path') 1742289 images
|
12 |
+
val: images/val # val images (relative to 'path') 80000 images
|
13 |
+
test: # test images (optional)
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: Person
|
18 |
+
1: Sneakers
|
19 |
+
2: Chair
|
20 |
+
3: Other Shoes
|
21 |
+
4: Hat
|
22 |
+
5: Car
|
23 |
+
6: Lamp
|
24 |
+
7: Glasses
|
25 |
+
8: Bottle
|
26 |
+
9: Desk
|
27 |
+
10: Cup
|
28 |
+
11: Street Lights
|
29 |
+
12: Cabinet/shelf
|
30 |
+
13: Handbag/Satchel
|
31 |
+
14: Bracelet
|
32 |
+
15: Plate
|
33 |
+
16: Picture/Frame
|
34 |
+
17: Helmet
|
35 |
+
18: Book
|
36 |
+
19: Gloves
|
37 |
+
20: Storage box
|
38 |
+
21: Boat
|
39 |
+
22: Leather Shoes
|
40 |
+
23: Flower
|
41 |
+
24: Bench
|
42 |
+
25: Potted Plant
|
43 |
+
26: Bowl/Basin
|
44 |
+
27: Flag
|
45 |
+
28: Pillow
|
46 |
+
29: Boots
|
47 |
+
30: Vase
|
48 |
+
31: Microphone
|
49 |
+
32: Necklace
|
50 |
+
33: Ring
|
51 |
+
34: SUV
|
52 |
+
35: Wine Glass
|
53 |
+
36: Belt
|
54 |
+
37: Monitor/TV
|
55 |
+
38: Backpack
|
56 |
+
39: Umbrella
|
57 |
+
40: Traffic Light
|
58 |
+
41: Speaker
|
59 |
+
42: Watch
|
60 |
+
43: Tie
|
61 |
+
44: Trash bin Can
|
62 |
+
45: Slippers
|
63 |
+
46: Bicycle
|
64 |
+
47: Stool
|
65 |
+
48: Barrel/bucket
|
66 |
+
49: Van
|
67 |
+
50: Couch
|
68 |
+
51: Sandals
|
69 |
+
52: Basket
|
70 |
+
53: Drum
|
71 |
+
54: Pen/Pencil
|
72 |
+
55: Bus
|
73 |
+
56: Wild Bird
|
74 |
+
57: High Heels
|
75 |
+
58: Motorcycle
|
76 |
+
59: Guitar
|
77 |
+
60: Carpet
|
78 |
+
61: Cell Phone
|
79 |
+
62: Bread
|
80 |
+
63: Camera
|
81 |
+
64: Canned
|
82 |
+
65: Truck
|
83 |
+
66: Traffic cone
|
84 |
+
67: Cymbal
|
85 |
+
68: Lifesaver
|
86 |
+
69: Towel
|
87 |
+
70: Stuffed Toy
|
88 |
+
71: Candle
|
89 |
+
72: Sailboat
|
90 |
+
73: Laptop
|
91 |
+
74: Awning
|
92 |
+
75: Bed
|
93 |
+
76: Faucet
|
94 |
+
77: Tent
|
95 |
+
78: Horse
|
96 |
+
79: Mirror
|
97 |
+
80: Power outlet
|
98 |
+
81: Sink
|
99 |
+
82: Apple
|
100 |
+
83: Air Conditioner
|
101 |
+
84: Knife
|
102 |
+
85: Hockey Stick
|
103 |
+
86: Paddle
|
104 |
+
87: Pickup Truck
|
105 |
+
88: Fork
|
106 |
+
89: Traffic Sign
|
107 |
+
90: Balloon
|
108 |
+
91: Tripod
|
109 |
+
92: Dog
|
110 |
+
93: Spoon
|
111 |
+
94: Clock
|
112 |
+
95: Pot
|
113 |
+
96: Cow
|
114 |
+
97: Cake
|
115 |
+
98: Dinning Table
|
116 |
+
99: Sheep
|
117 |
+
100: Hanger
|
118 |
+
101: Blackboard/Whiteboard
|
119 |
+
102: Napkin
|
120 |
+
103: Other Fish
|
121 |
+
104: Orange/Tangerine
|
122 |
+
105: Toiletry
|
123 |
+
106: Keyboard
|
124 |
+
107: Tomato
|
125 |
+
108: Lantern
|
126 |
+
109: Machinery Vehicle
|
127 |
+
110: Fan
|
128 |
+
111: Green Vegetables
|
129 |
+
112: Banana
|
130 |
+
113: Baseball Glove
|
131 |
+
114: Airplane
|
132 |
+
115: Mouse
|
133 |
+
116: Train
|
134 |
+
117: Pumpkin
|
135 |
+
118: Soccer
|
136 |
+
119: Skiboard
|
137 |
+
120: Luggage
|
138 |
+
121: Nightstand
|
139 |
+
122: Tea pot
|
140 |
+
123: Telephone
|
141 |
+
124: Trolley
|
142 |
+
125: Head Phone
|
143 |
+
126: Sports Car
|
144 |
+
127: Stop Sign
|
145 |
+
128: Dessert
|
146 |
+
129: Scooter
|
147 |
+
130: Stroller
|
148 |
+
131: Crane
|
149 |
+
132: Remote
|
150 |
+
133: Refrigerator
|
151 |
+
134: Oven
|
152 |
+
135: Lemon
|
153 |
+
136: Duck
|
154 |
+
137: Baseball Bat
|
155 |
+
138: Surveillance Camera
|
156 |
+
139: Cat
|
157 |
+
140: Jug
|
158 |
+
141: Broccoli
|
159 |
+
142: Piano
|
160 |
+
143: Pizza
|
161 |
+
144: Elephant
|
162 |
+
145: Skateboard
|
163 |
+
146: Surfboard
|
164 |
+
147: Gun
|
165 |
+
148: Skating and Skiing shoes
|
166 |
+
149: Gas stove
|
167 |
+
150: Donut
|
168 |
+
151: Bow Tie
|
169 |
+
152: Carrot
|
170 |
+
153: Toilet
|
171 |
+
154: Kite
|
172 |
+
155: Strawberry
|
173 |
+
156: Other Balls
|
174 |
+
157: Shovel
|
175 |
+
158: Pepper
|
176 |
+
159: Computer Box
|
177 |
+
160: Toilet Paper
|
178 |
+
161: Cleaning Products
|
179 |
+
162: Chopsticks
|
180 |
+
163: Microwave
|
181 |
+
164: Pigeon
|
182 |
+
165: Baseball
|
183 |
+
166: Cutting/chopping Board
|
184 |
+
167: Coffee Table
|
185 |
+
168: Side Table
|
186 |
+
169: Scissors
|
187 |
+
170: Marker
|
188 |
+
171: Pie
|
189 |
+
172: Ladder
|
190 |
+
173: Snowboard
|
191 |
+
174: Cookies
|
192 |
+
175: Radiator
|
193 |
+
176: Fire Hydrant
|
194 |
+
177: Basketball
|
195 |
+
178: Zebra
|
196 |
+
179: Grape
|
197 |
+
180: Giraffe
|
198 |
+
181: Potato
|
199 |
+
182: Sausage
|
200 |
+
183: Tricycle
|
201 |
+
184: Violin
|
202 |
+
185: Egg
|
203 |
+
186: Fire Extinguisher
|
204 |
+
187: Candy
|
205 |
+
188: Fire Truck
|
206 |
+
189: Billiards
|
207 |
+
190: Converter
|
208 |
+
191: Bathtub
|
209 |
+
192: Wheelchair
|
210 |
+
193: Golf Club
|
211 |
+
194: Briefcase
|
212 |
+
195: Cucumber
|
213 |
+
196: Cigar/Cigarette
|
214 |
+
197: Paint Brush
|
215 |
+
198: Pear
|
216 |
+
199: Heavy Truck
|
217 |
+
200: Hamburger
|
218 |
+
201: Extractor
|
219 |
+
202: Extension Cord
|
220 |
+
203: Tong
|
221 |
+
204: Tennis Racket
|
222 |
+
205: Folder
|
223 |
+
206: American Football
|
224 |
+
207: earphone
|
225 |
+
208: Mask
|
226 |
+
209: Kettle
|
227 |
+
210: Tennis
|
228 |
+
211: Ship
|
229 |
+
212: Swing
|
230 |
+
213: Coffee Machine
|
231 |
+
214: Slide
|
232 |
+
215: Carriage
|
233 |
+
216: Onion
|
234 |
+
217: Green beans
|
235 |
+
218: Projector
|
236 |
+
219: Frisbee
|
237 |
+
220: Washing Machine/Drying Machine
|
238 |
+
221: Chicken
|
239 |
+
222: Printer
|
240 |
+
223: Watermelon
|
241 |
+
224: Saxophone
|
242 |
+
225: Tissue
|
243 |
+
226: Toothbrush
|
244 |
+
227: Ice cream
|
245 |
+
228: Hot-air balloon
|
246 |
+
229: Cello
|
247 |
+
230: French Fries
|
248 |
+
231: Scale
|
249 |
+
232: Trophy
|
250 |
+
233: Cabbage
|
251 |
+
234: Hot dog
|
252 |
+
235: Blender
|
253 |
+
236: Peach
|
254 |
+
237: Rice
|
255 |
+
238: Wallet/Purse
|
256 |
+
239: Volleyball
|
257 |
+
240: Deer
|
258 |
+
241: Goose
|
259 |
+
242: Tape
|
260 |
+
243: Tablet
|
261 |
+
244: Cosmetics
|
262 |
+
245: Trumpet
|
263 |
+
246: Pineapple
|
264 |
+
247: Golf Ball
|
265 |
+
248: Ambulance
|
266 |
+
249: Parking meter
|
267 |
+
250: Mango
|
268 |
+
251: Key
|
269 |
+
252: Hurdle
|
270 |
+
253: Fishing Rod
|
271 |
+
254: Medal
|
272 |
+
255: Flute
|
273 |
+
256: Brush
|
274 |
+
257: Penguin
|
275 |
+
258: Megaphone
|
276 |
+
259: Corn
|
277 |
+
260: Lettuce
|
278 |
+
261: Garlic
|
279 |
+
262: Swan
|
280 |
+
263: Helicopter
|
281 |
+
264: Green Onion
|
282 |
+
265: Sandwich
|
283 |
+
266: Nuts
|
284 |
+
267: Speed Limit Sign
|
285 |
+
268: Induction Cooker
|
286 |
+
269: Broom
|
287 |
+
270: Trombone
|
288 |
+
271: Plum
|
289 |
+
272: Rickshaw
|
290 |
+
273: Goldfish
|
291 |
+
274: Kiwi fruit
|
292 |
+
275: Router/modem
|
293 |
+
276: Poker Card
|
294 |
+
277: Toaster
|
295 |
+
278: Shrimp
|
296 |
+
279: Sushi
|
297 |
+
280: Cheese
|
298 |
+
281: Notepaper
|
299 |
+
282: Cherry
|
300 |
+
283: Pliers
|
301 |
+
284: CD
|
302 |
+
285: Pasta
|
303 |
+
286: Hammer
|
304 |
+
287: Cue
|
305 |
+
288: Avocado
|
306 |
+
289: Hamimelon
|
307 |
+
290: Flask
|
308 |
+
291: Mushroom
|
309 |
+
292: Screwdriver
|
310 |
+
293: Soap
|
311 |
+
294: Recorder
|
312 |
+
295: Bear
|
313 |
+
296: Eggplant
|
314 |
+
297: Board Eraser
|
315 |
+
298: Coconut
|
316 |
+
299: Tape Measure/Ruler
|
317 |
+
300: Pig
|
318 |
+
301: Showerhead
|
319 |
+
302: Globe
|
320 |
+
303: Chips
|
321 |
+
304: Steak
|
322 |
+
305: Crosswalk Sign
|
323 |
+
306: Stapler
|
324 |
+
307: Camel
|
325 |
+
308: Formula 1
|
326 |
+
309: Pomegranate
|
327 |
+
310: Dishwasher
|
328 |
+
311: Crab
|
329 |
+
312: Hoverboard
|
330 |
+
313: Meat ball
|
331 |
+
314: Rice Cooker
|
332 |
+
315: Tuba
|
333 |
+
316: Calculator
|
334 |
+
317: Papaya
|
335 |
+
318: Antelope
|
336 |
+
319: Parrot
|
337 |
+
320: Seal
|
338 |
+
321: Butterfly
|
339 |
+
322: Dumbbell
|
340 |
+
323: Donkey
|
341 |
+
324: Lion
|
342 |
+
325: Urinal
|
343 |
+
326: Dolphin
|
344 |
+
327: Electric Drill
|
345 |
+
328: Hair Dryer
|
346 |
+
329: Egg tart
|
347 |
+
330: Jellyfish
|
348 |
+
331: Treadmill
|
349 |
+
332: Lighter
|
350 |
+
333: Grapefruit
|
351 |
+
334: Game board
|
352 |
+
335: Mop
|
353 |
+
336: Radish
|
354 |
+
337: Baozi
|
355 |
+
338: Target
|
356 |
+
339: French
|
357 |
+
340: Spring Rolls
|
358 |
+
341: Monkey
|
359 |
+
342: Rabbit
|
360 |
+
343: Pencil Case
|
361 |
+
344: Yak
|
362 |
+
345: Red Cabbage
|
363 |
+
346: Binoculars
|
364 |
+
347: Asparagus
|
365 |
+
348: Barbell
|
366 |
+
349: Scallop
|
367 |
+
350: Noddles
|
368 |
+
351: Comb
|
369 |
+
352: Dumpling
|
370 |
+
353: Oyster
|
371 |
+
354: Table Tennis paddle
|
372 |
+
355: Cosmetics Brush/Eyeliner Pencil
|
373 |
+
356: Chainsaw
|
374 |
+
357: Eraser
|
375 |
+
358: Lobster
|
376 |
+
359: Durian
|
377 |
+
360: Okra
|
378 |
+
361: Lipstick
|
379 |
+
362: Cosmetics Mirror
|
380 |
+
363: Curling
|
381 |
+
364: Table Tennis
|
382 |
+
|
383 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
384 |
+
download: |
|
385 |
+
from tqdm import tqdm
|
386 |
+
|
387 |
+
from utils.general import Path, check_requirements, download, np, xyxy2xywhn
|
388 |
+
|
389 |
+
check_requirements('pycocotools>=2.0')
|
390 |
+
from pycocotools.coco import COCO
|
391 |
+
|
392 |
+
# Make Directories
|
393 |
+
dir = Path(yaml['path']) # dataset root dir
|
394 |
+
for p in 'images', 'labels':
|
395 |
+
(dir / p).mkdir(parents=True, exist_ok=True)
|
396 |
+
for q in 'train', 'val':
|
397 |
+
(dir / p / q).mkdir(parents=True, exist_ok=True)
|
398 |
+
|
399 |
+
# Train, Val Splits
|
400 |
+
for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:
|
401 |
+
print(f"Processing {split} in {patches} patches ...")
|
402 |
+
images, labels = dir / 'images' / split, dir / 'labels' / split
|
403 |
+
|
404 |
+
# Download
|
405 |
+
url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/"
|
406 |
+
if split == 'train':
|
407 |
+
download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json
|
408 |
+
download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8)
|
409 |
+
elif split == 'val':
|
410 |
+
download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json
|
411 |
+
download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8)
|
412 |
+
download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8)
|
413 |
+
|
414 |
+
# Move
|
415 |
+
for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):
|
416 |
+
f.rename(images / f.name) # move to /images/{split}
|
417 |
+
|
418 |
+
# Labels
|
419 |
+
coco = COCO(dir / f'zhiyuan_objv2_{split}.json')
|
420 |
+
names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
|
421 |
+
for cid, cat in enumerate(names):
|
422 |
+
catIds = coco.getCatIds(catNms=[cat])
|
423 |
+
imgIds = coco.getImgIds(catIds=catIds)
|
424 |
+
for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
|
425 |
+
width, height = im["width"], im["height"]
|
426 |
+
path = Path(im["file_name"]) # image filename
|
427 |
+
try:
|
428 |
+
with open(labels / path.with_suffix('.txt').name, 'a') as file:
|
429 |
+
annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=False)
|
430 |
+
for a in coco.loadAnns(annIds):
|
431 |
+
x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
|
432 |
+
xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4)
|
433 |
+
x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped
|
434 |
+
file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n")
|
435 |
+
except Exception as e:
|
436 |
+
print(e)
|
yolov5/data/SKU-110K.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/SKU-110K # dataset root dir
|
11 |
+
train: train.txt # train images (relative to 'path') 8219 images
|
12 |
+
val: val.txt # val images (relative to 'path') 588 images
|
13 |
+
test: test.txt # test images (optional) 2936 images
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: object
|
18 |
+
|
19 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
20 |
+
download: |
|
21 |
+
import shutil
|
22 |
+
from tqdm import tqdm
|
23 |
+
from utils.general import np, pd, Path, download, xyxy2xywh
|
24 |
+
|
25 |
+
|
26 |
+
# Download
|
27 |
+
dir = Path(yaml['path']) # dataset root dir
|
28 |
+
parent = Path(dir.parent) # download dir
|
29 |
+
urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
|
30 |
+
download(urls, dir=parent, delete=False)
|
31 |
+
|
32 |
+
# Rename directories
|
33 |
+
if dir.exists():
|
34 |
+
shutil.rmtree(dir)
|
35 |
+
(parent / 'SKU110K_fixed').rename(dir) # rename dir
|
36 |
+
(dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
|
37 |
+
|
38 |
+
# Convert labels
|
39 |
+
names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
|
40 |
+
for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
|
41 |
+
x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
|
42 |
+
images, unique_images = x[:, 0], np.unique(x[:, 0])
|
43 |
+
with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
|
44 |
+
f.writelines(f'./images/{s}\n' for s in unique_images)
|
45 |
+
for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
|
46 |
+
cls = 0 # single-class dataset
|
47 |
+
with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
|
48 |
+
for r in x[images == im]:
|
49 |
+
w, h = r[6], r[7] # image width, height
|
50 |
+
xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
|
51 |
+
f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
|
yolov5/data/VOC.yaml
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/VOC
|
11 |
+
train: # train images (relative to 'path') 16551 images
|
12 |
+
- images/train2012
|
13 |
+
- images/train2007
|
14 |
+
- images/val2012
|
15 |
+
- images/val2007
|
16 |
+
val: # val images (relative to 'path') 4952 images
|
17 |
+
- images/test2007
|
18 |
+
test: # test images (optional)
|
19 |
+
- images/test2007
|
20 |
+
|
21 |
+
# Classes
|
22 |
+
names:
|
23 |
+
0: aeroplane
|
24 |
+
1: bicycle
|
25 |
+
2: bird
|
26 |
+
3: boat
|
27 |
+
4: bottle
|
28 |
+
5: bus
|
29 |
+
6: car
|
30 |
+
7: cat
|
31 |
+
8: chair
|
32 |
+
9: cow
|
33 |
+
10: diningtable
|
34 |
+
11: dog
|
35 |
+
12: horse
|
36 |
+
13: motorbike
|
37 |
+
14: person
|
38 |
+
15: pottedplant
|
39 |
+
16: sheep
|
40 |
+
17: sofa
|
41 |
+
18: train
|
42 |
+
19: tvmonitor
|
43 |
+
|
44 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
45 |
+
download: |
|
46 |
+
import xml.etree.ElementTree as ET
|
47 |
+
|
48 |
+
from tqdm import tqdm
|
49 |
+
from utils.general import download, Path
|
50 |
+
|
51 |
+
|
52 |
+
def convert_label(path, lb_path, year, image_id):
|
53 |
+
def convert_box(size, box):
|
54 |
+
dw, dh = 1. / size[0], 1. / size[1]
|
55 |
+
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]
|
56 |
+
return x * dw, y * dh, w * dw, h * dh
|
57 |
+
|
58 |
+
in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
|
59 |
+
out_file = open(lb_path, 'w')
|
60 |
+
tree = ET.parse(in_file)
|
61 |
+
root = tree.getroot()
|
62 |
+
size = root.find('size')
|
63 |
+
w = int(size.find('width').text)
|
64 |
+
h = int(size.find('height').text)
|
65 |
+
|
66 |
+
names = list(yaml['names'].values()) # names list
|
67 |
+
for obj in root.iter('object'):
|
68 |
+
cls = obj.find('name').text
|
69 |
+
if cls in names and int(obj.find('difficult').text) != 1:
|
70 |
+
xmlbox = obj.find('bndbox')
|
71 |
+
bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
|
72 |
+
cls_id = names.index(cls) # class id
|
73 |
+
out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
|
74 |
+
|
75 |
+
|
76 |
+
# Download
|
77 |
+
dir = Path(yaml['path']) # dataset root dir
|
78 |
+
url = 'https://github.com/ultralytics/assets/releases/download/v0.0.0/'
|
79 |
+
urls = [f'{url}VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
|
80 |
+
f'{url}VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
|
81 |
+
f'{url}VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
|
82 |
+
download(urls, dir=dir / 'images', delete=False, curl=True, threads=3)
|
83 |
+
|
84 |
+
# Convert
|
85 |
+
path = dir / 'images/VOCdevkit'
|
86 |
+
for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
|
87 |
+
imgs_path = dir / 'images' / f'{image_set}{year}'
|
88 |
+
lbs_path = dir / 'labels' / f'{image_set}{year}'
|
89 |
+
imgs_path.mkdir(exist_ok=True, parents=True)
|
90 |
+
lbs_path.mkdir(exist_ok=True, parents=True)
|
91 |
+
|
92 |
+
with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:
|
93 |
+
image_ids = f.read().strip().split()
|
94 |
+
for id in tqdm(image_ids, desc=f'{image_set}{year}'):
|
95 |
+
f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
|
96 |
+
lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
|
97 |
+
f.rename(imgs_path / f.name) # move image
|
98 |
+
convert_label(path, lb_path, year, id) # convert labels to YOLO format
|
yolov5/data/VisDrone.yaml
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/VisDrone # dataset root dir
|
11 |
+
train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
|
12 |
+
val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
|
13 |
+
test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: pedestrian
|
18 |
+
1: people
|
19 |
+
2: bicycle
|
20 |
+
3: car
|
21 |
+
4: van
|
22 |
+
5: truck
|
23 |
+
6: tricycle
|
24 |
+
7: awning-tricycle
|
25 |
+
8: bus
|
26 |
+
9: motor
|
27 |
+
|
28 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
29 |
+
download: |
|
30 |
+
from utils.general import download, os, Path
|
31 |
+
|
32 |
+
def visdrone2yolo(dir):
|
33 |
+
from PIL import Image
|
34 |
+
from tqdm import tqdm
|
35 |
+
|
36 |
+
def convert_box(size, box):
|
37 |
+
# Convert VisDrone box to YOLO xywh box
|
38 |
+
dw = 1. / size[0]
|
39 |
+
dh = 1. / size[1]
|
40 |
+
return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
|
41 |
+
|
42 |
+
(dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
|
43 |
+
pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
|
44 |
+
for f in pbar:
|
45 |
+
img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
|
46 |
+
lines = []
|
47 |
+
with open(f, 'r') as file: # read annotation.txt
|
48 |
+
for row in [x.split(',') for x in file.read().strip().splitlines()]:
|
49 |
+
if row[4] == '0': # VisDrone 'ignored regions' class 0
|
50 |
+
continue
|
51 |
+
cls = int(row[5]) - 1
|
52 |
+
box = convert_box(img_size, tuple(map(int, row[:4])))
|
53 |
+
lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
|
54 |
+
with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
|
55 |
+
fl.writelines(lines) # write label.txt
|
56 |
+
|
57 |
+
|
58 |
+
# Download
|
59 |
+
dir = Path(yaml['path']) # dataset root dir
|
60 |
+
urls = ['https://github.com/ultralytics/assets/releases/download/v0.0.0/VisDrone2019-DET-train.zip',
|
61 |
+
'https://github.com/ultralytics/assets/releases/download/v0.0.0/VisDrone2019-DET-val.zip',
|
62 |
+
'https://github.com/ultralytics/assets/releases/download/v0.0.0/VisDrone2019-DET-test-dev.zip',
|
63 |
+
'https://github.com/ultralytics/assets/releases/download/v0.0.0/VisDrone2019-DET-test-challenge.zip']
|
64 |
+
download(urls, dir=dir, curl=True, threads=4)
|
65 |
+
|
66 |
+
# Convert
|
67 |
+
for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
|
68 |
+
visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
|
yolov5/data/coco.yaml
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/coco # dataset root dir
|
11 |
+
train: train2017.txt # train images (relative to 'path') 118287 images
|
12 |
+
val: val2017.txt # val images (relative to 'path') 5000 images
|
13 |
+
test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: person
|
18 |
+
1: bicycle
|
19 |
+
2: car
|
20 |
+
3: motorcycle
|
21 |
+
4: airplane
|
22 |
+
5: bus
|
23 |
+
6: train
|
24 |
+
7: truck
|
25 |
+
8: boat
|
26 |
+
9: traffic light
|
27 |
+
10: fire hydrant
|
28 |
+
11: stop sign
|
29 |
+
12: parking meter
|
30 |
+
13: bench
|
31 |
+
14: bird
|
32 |
+
15: cat
|
33 |
+
16: dog
|
34 |
+
17: horse
|
35 |
+
18: sheep
|
36 |
+
19: cow
|
37 |
+
20: elephant
|
38 |
+
21: bear
|
39 |
+
22: zebra
|
40 |
+
23: giraffe
|
41 |
+
24: backpack
|
42 |
+
25: umbrella
|
43 |
+
26: handbag
|
44 |
+
27: tie
|
45 |
+
28: suitcase
|
46 |
+
29: frisbee
|
47 |
+
30: skis
|
48 |
+
31: snowboard
|
49 |
+
32: sports ball
|
50 |
+
33: kite
|
51 |
+
34: baseball bat
|
52 |
+
35: baseball glove
|
53 |
+
36: skateboard
|
54 |
+
37: surfboard
|
55 |
+
38: tennis racket
|
56 |
+
39: bottle
|
57 |
+
40: wine glass
|
58 |
+
41: cup
|
59 |
+
42: fork
|
60 |
+
43: knife
|
61 |
+
44: spoon
|
62 |
+
45: bowl
|
63 |
+
46: banana
|
64 |
+
47: apple
|
65 |
+
48: sandwich
|
66 |
+
49: orange
|
67 |
+
50: broccoli
|
68 |
+
51: carrot
|
69 |
+
52: hot dog
|
70 |
+
53: pizza
|
71 |
+
54: donut
|
72 |
+
55: cake
|
73 |
+
56: chair
|
74 |
+
57: couch
|
75 |
+
58: potted plant
|
76 |
+
59: bed
|
77 |
+
60: dining table
|
78 |
+
61: toilet
|
79 |
+
62: tv
|
80 |
+
63: laptop
|
81 |
+
64: mouse
|
82 |
+
65: remote
|
83 |
+
66: keyboard
|
84 |
+
67: cell phone
|
85 |
+
68: microwave
|
86 |
+
69: oven
|
87 |
+
70: toaster
|
88 |
+
71: sink
|
89 |
+
72: refrigerator
|
90 |
+
73: book
|
91 |
+
74: clock
|
92 |
+
75: vase
|
93 |
+
76: scissors
|
94 |
+
77: teddy bear
|
95 |
+
78: hair drier
|
96 |
+
79: toothbrush
|
97 |
+
|
98 |
+
# Download script/URL (optional)
|
99 |
+
download: |
|
100 |
+
from utils.general import download, Path
|
101 |
+
|
102 |
+
|
103 |
+
# Download labels
|
104 |
+
segments = False # segment or box labels
|
105 |
+
dir = Path(yaml['path']) # dataset root dir
|
106 |
+
url = 'https://github.com/ultralytics/assets/releases/download/v0.0.0/'
|
107 |
+
urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
|
108 |
+
download(urls, dir=dir.parent)
|
109 |
+
|
110 |
+
# Download data
|
111 |
+
urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
|
112 |
+
'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
|
113 |
+
'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
|
114 |
+
download(urls, dir=dir / 'images', threads=3)
|
yolov5/data/coco128-seg.yaml
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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, ..]
|
10 |
+
path: ../datasets/coco128-seg # dataset root dir
|
11 |
+
train: images/train2017 # train images (relative to 'path') 128 images
|
12 |
+
val: images/train2017 # val images (relative to 'path') 128 images
|
13 |
+
test: # test images (optional)
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: person
|
18 |
+
1: bicycle
|
19 |
+
2: car
|
20 |
+
3: motorcycle
|
21 |
+
4: airplane
|
22 |
+
5: bus
|
23 |
+
6: train
|
24 |
+
7: truck
|
25 |
+
8: boat
|
26 |
+
9: traffic light
|
27 |
+
10: fire hydrant
|
28 |
+
11: stop sign
|
29 |
+
12: parking meter
|
30 |
+
13: bench
|
31 |
+
14: bird
|
32 |
+
15: cat
|
33 |
+
16: dog
|
34 |
+
17: horse
|
35 |
+
18: sheep
|
36 |
+
19: cow
|
37 |
+
20: elephant
|
38 |
+
21: bear
|
39 |
+
22: zebra
|
40 |
+
23: giraffe
|
41 |
+
24: backpack
|
42 |
+
25: umbrella
|
43 |
+
26: handbag
|
44 |
+
27: tie
|
45 |
+
28: suitcase
|
46 |
+
29: frisbee
|
47 |
+
30: skis
|
48 |
+
31: snowboard
|
49 |
+
32: sports ball
|
50 |
+
33: kite
|
51 |
+
34: baseball bat
|
52 |
+
35: baseball glove
|
53 |
+
36: skateboard
|
54 |
+
37: surfboard
|
55 |
+
38: tennis racket
|
56 |
+
39: bottle
|
57 |
+
40: wine glass
|
58 |
+
41: cup
|
59 |
+
42: fork
|
60 |
+
43: knife
|
61 |
+
44: spoon
|
62 |
+
45: bowl
|
63 |
+
46: banana
|
64 |
+
47: apple
|
65 |
+
48: sandwich
|
66 |
+
49: orange
|
67 |
+
50: broccoli
|
68 |
+
51: carrot
|
69 |
+
52: hot dog
|
70 |
+
53: pizza
|
71 |
+
54: donut
|
72 |
+
55: cake
|
73 |
+
56: chair
|
74 |
+
57: couch
|
75 |
+
58: potted plant
|
76 |
+
59: bed
|
77 |
+
60: dining table
|
78 |
+
61: toilet
|
79 |
+
62: tv
|
80 |
+
63: laptop
|
81 |
+
64: mouse
|
82 |
+
65: remote
|
83 |
+
66: keyboard
|
84 |
+
67: cell phone
|
85 |
+
68: microwave
|
86 |
+
69: oven
|
87 |
+
70: toaster
|
88 |
+
71: sink
|
89 |
+
72: refrigerator
|
90 |
+
73: book
|
91 |
+
74: clock
|
92 |
+
75: vase
|
93 |
+
76: scissors
|
94 |
+
77: teddy bear
|
95 |
+
78: hair drier
|
96 |
+
79: toothbrush
|
97 |
+
|
98 |
+
# Download script/URL (optional)
|
99 |
+
download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco128-seg.zip
|
yolov5/data/coco128.yaml
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
2 |
+
# COCO128 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 ← downloads here (7 MB)
|
8 |
+
|
9 |
+
# 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, ..]
|
10 |
+
path: ../datasets/coco128 # dataset root dir
|
11 |
+
train: images/train2017 # train images (relative to 'path') 128 images
|
12 |
+
val: images/train2017 # val images (relative to 'path') 128 images
|
13 |
+
test: # test images (optional)
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: person
|
18 |
+
1: bicycle
|
19 |
+
2: car
|
20 |
+
3: motorcycle
|
21 |
+
4: airplane
|
22 |
+
5: bus
|
23 |
+
6: train
|
24 |
+
7: truck
|
25 |
+
8: boat
|
26 |
+
9: traffic light
|
27 |
+
10: fire hydrant
|
28 |
+
11: stop sign
|
29 |
+
12: parking meter
|
30 |
+
13: bench
|
31 |
+
14: bird
|
32 |
+
15: cat
|
33 |
+
16: dog
|
34 |
+
17: horse
|
35 |
+
18: sheep
|
36 |
+
19: cow
|
37 |
+
20: elephant
|
38 |
+
21: bear
|
39 |
+
22: zebra
|
40 |
+
23: giraffe
|
41 |
+
24: backpack
|
42 |
+
25: umbrella
|
43 |
+
26: handbag
|
44 |
+
27: tie
|
45 |
+
28: suitcase
|
46 |
+
29: frisbee
|
47 |
+
30: skis
|
48 |
+
31: snowboard
|
49 |
+
32: sports ball
|
50 |
+
33: kite
|
51 |
+
34: baseball bat
|
52 |
+
35: baseball glove
|
53 |
+
36: skateboard
|
54 |
+
37: surfboard
|
55 |
+
38: tennis racket
|
56 |
+
39: bottle
|
57 |
+
40: wine glass
|
58 |
+
41: cup
|
59 |
+
42: fork
|
60 |
+
43: knife
|
61 |
+
44: spoon
|
62 |
+
45: bowl
|
63 |
+
46: banana
|
64 |
+
47: apple
|
65 |
+
48: sandwich
|
66 |
+
49: orange
|
67 |
+
50: broccoli
|
68 |
+
51: carrot
|
69 |
+
52: hot dog
|
70 |
+
53: pizza
|
71 |
+
54: donut
|
72 |
+
55: cake
|
73 |
+
56: chair
|
74 |
+
57: couch
|
75 |
+
58: potted plant
|
76 |
+
59: bed
|
77 |
+
60: dining table
|
78 |
+
61: toilet
|
79 |
+
62: tv
|
80 |
+
63: laptop
|
81 |
+
64: mouse
|
82 |
+
65: remote
|
83 |
+
66: keyboard
|
84 |
+
67: cell phone
|
85 |
+
68: microwave
|
86 |
+
69: oven
|
87 |
+
70: toaster
|
88 |
+
71: sink
|
89 |
+
72: refrigerator
|
90 |
+
73: book
|
91 |
+
74: clock
|
92 |
+
75: vase
|
93 |
+
76: scissors
|
94 |
+
77: teddy bear
|
95 |
+
78: hair drier
|
96 |
+
79: toothbrush
|
97 |
+
|
98 |
+
# Download script/URL (optional)
|
99 |
+
download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco128.zip
|
yolov5/data/hyps/hyp.Objects365.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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
|
yolov5/data/hyps/hyp.VOC.yaml
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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
|
yolov5/data/hyps/hyp.no-augmentation.yaml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
2 |
+
# Hyperparameters when using Albumentations frameworks
|
3 |
+
# python train.py --hyp hyp.no-augmentation.yaml
|
4 |
+
# See https://github.com/ultralytics/yolov5/pull/3882 for YOLOv5 + Albumentations Usage examples
|
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 |
+
# this parameters are all zero since we want to use albumentation framework
|
22 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
23 |
+
hsv_h: 0 # image HSV-Hue augmentation (fraction)
|
24 |
+
hsv_s: 0 # image HSV-Saturation augmentation (fraction)
|
25 |
+
hsv_v: 0 # image HSV-Value augmentation (fraction)
|
26 |
+
degrees: 0.0 # image rotation (+/- deg)
|
27 |
+
translate: 0 # image translation (+/- fraction)
|
28 |
+
scale: 0 # image scale (+/- gain)
|
29 |
+
shear: 0 # image shear (+/- deg)
|
30 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
31 |
+
flipud: 0.0 # image flip up-down (probability)
|
32 |
+
fliplr: 0.0 # image flip left-right (probability)
|
33 |
+
mosaic: 0.0 # image mosaic (probability)
|
34 |
+
mixup: 0.0 # image mixup (probability)
|
35 |
+
copy_paste: 0.0 # segment copy-paste (probability)
|
yolov5/data/hyps/hyp.scratch-high.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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)
|
yolov5/data/hyps/hyp.scratch-low.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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)
|
yolov5/data/hyps/hyp.scratch-med.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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)
|
yolov5/data/images/bus.jpg
ADDED
![]() |
yolov5/data/images/zidane.jpg
ADDED
![]() |
yolov5/data/scripts/download_weights.sh
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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 = list('nsmlx') # 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 |
+
seg = [f'{x}-seg' for x in p5] # classification models
|
18 |
+
|
19 |
+
for x in p5 + p6 + cls + seg:
|
20 |
+
attempt_download(f'weights/yolov5{x}.pt')
|
21 |
+
|
22 |
+
EOF
|
yolov5/data/scripts/get_coco.sh
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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' # 46 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
|
yolov5/data/scripts/get_coco128.sh
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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
|
yolov5/data/scripts/get_imagenet.sh
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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
|
yolov5/data/scripts/get_imagenet10.sh
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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/imagenet10' # unzip directory
|
25 |
+
mkdir -p $d && cd $d
|
26 |
+
|
27 |
+
# Download/unzip train
|
28 |
+
wget https://github.com/ultralytics/yolov5/releases/download/v1.0/imagenet10.zip
|
29 |
+
unzip imagenet10.zip && rm imagenet10.zip
|
yolov5/data/scripts/get_imagenet100.sh
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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/imagenet100' # unzip directory
|
25 |
+
mkdir -p $d && cd $d
|
26 |
+
|
27 |
+
# Download/unzip train
|
28 |
+
wget https://github.com/ultralytics/yolov5/releases/download/v1.0/imagenet100.zip
|
29 |
+
unzip imagenet100.zip && rm imagenet100.zip
|
yolov5/data/scripts/get_imagenet1000.sh
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, AGPL-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/imagenet1000' # unzip directory
|
25 |
+
mkdir -p $d && cd $d
|
26 |
+
|
27 |
+
# Download/unzip train
|
28 |
+
wget https://github.com/ultralytics/yolov5/releases/download/v1.0/imagenet1000.zip
|
29 |
+
unzip imagenet1000.zip && rm imagenet1000.zip
|
yolov5/data/xView.yaml
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
# 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/xView # dataset root dir
|
12 |
+
train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images
|
13 |
+
val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images
|
14 |
+
|
15 |
+
# Classes
|
16 |
+
names:
|
17 |
+
0: Fixed-wing Aircraft
|
18 |
+
1: Small Aircraft
|
19 |
+
2: Cargo Plane
|
20 |
+
3: Helicopter
|
21 |
+
4: Passenger Vehicle
|
22 |
+
5: Small Car
|
23 |
+
6: Bus
|
24 |
+
7: Pickup Truck
|
25 |
+
8: Utility Truck
|
26 |
+
9: Truck
|
27 |
+
10: Cargo Truck
|
28 |
+
11: Truck w/Box
|
29 |
+
12: Truck Tractor
|
30 |
+
13: Trailer
|
31 |
+
14: Truck w/Flatbed
|
32 |
+
15: Truck w/Liquid
|
33 |
+
16: Crane Truck
|
34 |
+
17: Railway Vehicle
|
35 |
+
18: Passenger Car
|
36 |
+
19: Cargo Car
|
37 |
+
20: Flat Car
|
38 |
+
21: Tank car
|
39 |
+
22: Locomotive
|
40 |
+
23: Maritime Vessel
|
41 |
+
24: Motorboat
|
42 |
+
25: Sailboat
|
43 |
+
26: Tugboat
|
44 |
+
27: Barge
|
45 |
+
28: Fishing Vessel
|
46 |
+
29: Ferry
|
47 |
+
30: Yacht
|
48 |
+
31: Container Ship
|
49 |
+
32: Oil Tanker
|
50 |
+
33: Engineering Vehicle
|
51 |
+
34: Tower crane
|
52 |
+
35: Container Crane
|
53 |
+
36: Reach Stacker
|
54 |
+
37: Straddle Carrier
|
55 |
+
38: Mobile Crane
|
56 |
+
39: Dump Truck
|
57 |
+
40: Haul Truck
|
58 |
+
41: Scraper/Tractor
|
59 |
+
42: Front loader/Bulldozer
|
60 |
+
43: Excavator
|
61 |
+
44: Cement Mixer
|
62 |
+
45: Ground Grader
|
63 |
+
46: Hut/Tent
|
64 |
+
47: Shed
|
65 |
+
48: Building
|
66 |
+
49: Aircraft Hangar
|
67 |
+
50: Damaged Building
|
68 |
+
51: Facility
|
69 |
+
52: Construction Site
|
70 |
+
53: Vehicle Lot
|
71 |
+
54: Helipad
|
72 |
+
55: Storage Tank
|
73 |
+
56: Shipping container lot
|
74 |
+
57: Shipping Container
|
75 |
+
58: Pylon
|
76 |
+
59: Tower
|
77 |
+
|
78 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
79 |
+
download: |
|
80 |
+
import json
|
81 |
+
import os
|
82 |
+
from pathlib import Path
|
83 |
+
|
84 |
+
import numpy as np
|
85 |
+
from PIL import Image
|
86 |
+
from tqdm import tqdm
|
87 |
+
|
88 |
+
from utils.dataloaders import autosplit
|
89 |
+
from utils.general import download, xyxy2xywhn
|
90 |
+
|
91 |
+
|
92 |
+
def convert_labels(fname=Path('xView/xView_train.geojson')):
|
93 |
+
# Convert xView geoJSON labels to YOLO format
|
94 |
+
path = fname.parent
|
95 |
+
with open(fname) as f:
|
96 |
+
print(f'Loading {fname}...')
|
97 |
+
data = json.load(f)
|
98 |
+
|
99 |
+
# Make dirs
|
100 |
+
labels = Path(path / 'labels' / 'train')
|
101 |
+
os.system(f'rm -rf {labels}')
|
102 |
+
labels.mkdir(parents=True, exist_ok=True)
|
103 |
+
|
104 |
+
# xView classes 11-94 to 0-59
|
105 |
+
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,
|
106 |
+
12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,
|
107 |
+
29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,
|
108 |
+
47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]
|
109 |
+
|
110 |
+
shapes = {}
|
111 |
+
for feature in tqdm(data['features'], desc=f'Converting {fname}'):
|
112 |
+
p = feature['properties']
|
113 |
+
if p['bounds_imcoords']:
|
114 |
+
id = p['image_id']
|
115 |
+
file = path / 'train_images' / id
|
116 |
+
if file.exists(): # 1395.tif missing
|
117 |
+
try:
|
118 |
+
box = np.array([int(num) for num in p['bounds_imcoords'].split(",")])
|
119 |
+
assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'
|
120 |
+
cls = p['type_id']
|
121 |
+
cls = xview_class2index[int(cls)] # xView class to 0-60
|
122 |
+
assert 59 >= cls >= 0, f'incorrect class index {cls}'
|
123 |
+
|
124 |
+
# Write YOLO label
|
125 |
+
if id not in shapes:
|
126 |
+
shapes[id] = Image.open(file).size
|
127 |
+
box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)
|
128 |
+
with open((labels / id).with_suffix('.txt'), 'a') as f:
|
129 |
+
f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt
|
130 |
+
except Exception as e:
|
131 |
+
print(f'WARNING: skipping one label for {file}: {e}')
|
132 |
+
|
133 |
+
|
134 |
+
# Download manually from https://challenge.xviewdataset.org
|
135 |
+
dir = Path(yaml['path']) # dataset root dir
|
136 |
+
# urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels
|
137 |
+
# 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images
|
138 |
+
# 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels)
|
139 |
+
# download(urls, dir=dir, delete=False)
|
140 |
+
|
141 |
+
# Convert labels
|
142 |
+
convert_labels(dir / 'xView_train.geojson')
|
143 |
+
|
144 |
+
# Move images
|
145 |
+
images = Path(dir / 'images')
|
146 |
+
images.mkdir(parents=True, exist_ok=True)
|
147 |
+
Path(dir / 'train_images').rename(dir / 'images' / 'train')
|
148 |
+
Path(dir / 'val_images').rename(dir / 'images' / 'val')
|
149 |
+
|
150 |
+
# Split
|
151 |
+
autosplit(dir / 'images' / 'train')
|
yolov5/detect.py
ADDED
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
2 |
+
"""
|
3 |
+
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
|
4 |
+
|
5 |
+
Usage - sources:
|
6 |
+
$ python detect.py --weights yolov5s.pt --source 0 # webcam
|
7 |
+
img.jpg # image
|
8 |
+
vid.mp4 # video
|
9 |
+
screen # screenshot
|
10 |
+
path/ # directory
|
11 |
+
list.txt # list of images
|
12 |
+
list.streams # list of streams
|
13 |
+
'path/*.jpg' # glob
|
14 |
+
'https://youtu.be/LNwODJXcvt4' # YouTube
|
15 |
+
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
16 |
+
|
17 |
+
Usage - formats:
|
18 |
+
$ python detect.py --weights yolov5s.pt # PyTorch
|
19 |
+
yolov5s.torchscript # TorchScript
|
20 |
+
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
21 |
+
yolov5s_openvino_model # OpenVINO
|
22 |
+
yolov5s.engine # TensorRT
|
23 |
+
yolov5s.mlpackage # CoreML (macOS-only)
|
24 |
+
yolov5s_saved_model # TensorFlow SavedModel
|
25 |
+
yolov5s.pb # TensorFlow GraphDef
|
26 |
+
yolov5s.tflite # TensorFlow Lite
|
27 |
+
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
28 |
+
yolov5s_paddle_model # PaddlePaddle
|
29 |
+
"""
|
30 |
+
|
31 |
+
import argparse
|
32 |
+
import csv
|
33 |
+
import os
|
34 |
+
import platform
|
35 |
+
import sys
|
36 |
+
from pathlib import Path
|
37 |
+
|
38 |
+
import torch
|
39 |
+
|
40 |
+
FILE = Path(__file__).resolve()
|
41 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
42 |
+
if str(ROOT) not in sys.path:
|
43 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
44 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
45 |
+
|
46 |
+
from ultralytics.utils.plotting import Annotator, colors, save_one_box
|
47 |
+
|
48 |
+
from models.common import DetectMultiBackend
|
49 |
+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
|
50 |
+
from utils.general import (
|
51 |
+
LOGGER,
|
52 |
+
Profile,
|
53 |
+
check_file,
|
54 |
+
check_img_size,
|
55 |
+
check_imshow,
|
56 |
+
check_requirements,
|
57 |
+
colorstr,
|
58 |
+
cv2,
|
59 |
+
increment_path,
|
60 |
+
non_max_suppression,
|
61 |
+
print_args,
|
62 |
+
scale_boxes,
|
63 |
+
strip_optimizer,
|
64 |
+
xyxy2xywh,
|
65 |
+
)
|
66 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
67 |
+
|
68 |
+
|
69 |
+
@smart_inference_mode()
|
70 |
+
def run(
|
71 |
+
weights=ROOT / "yolov5s.pt", # model path or triton URL
|
72 |
+
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
|
73 |
+
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
74 |
+
imgsz=(640, 640), # inference size (height, width)
|
75 |
+
conf_thres=0.25, # confidence threshold
|
76 |
+
iou_thres=0.45, # NMS IOU threshold
|
77 |
+
max_det=1000, # maximum detections per image
|
78 |
+
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
79 |
+
view_img=False, # show results
|
80 |
+
save_txt=False, # save results to *.txt
|
81 |
+
save_csv=False, # save results in CSV format
|
82 |
+
save_conf=False, # save confidences in --save-txt labels
|
83 |
+
save_crop=False, # save cropped prediction boxes
|
84 |
+
nosave=False, # do not save images/videos
|
85 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
86 |
+
agnostic_nms=False, # class-agnostic NMS
|
87 |
+
augment=False, # augmented inference
|
88 |
+
visualize=False, # visualize features
|
89 |
+
update=False, # update all models
|
90 |
+
project=ROOT / "runs/detect", # save results to project/name
|
91 |
+
name="exp", # save results to project/name
|
92 |
+
exist_ok=False, # existing project/name ok, do not increment
|
93 |
+
line_thickness=3, # bounding box thickness (pixels)
|
94 |
+
hide_labels=False, # hide labels
|
95 |
+
hide_conf=False, # hide confidences
|
96 |
+
half=False, # use FP16 half-precision inference
|
97 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
98 |
+
vid_stride=1, # video frame-rate stride
|
99 |
+
):
|
100 |
+
"""
|
101 |
+
Runs YOLOv5 detection inference on various sources like images, videos, directories, streams, etc.
|
102 |
+
|
103 |
+
Args:
|
104 |
+
weights (str | Path): Path to the model weights file or a Triton URL. Default is 'yolov5s.pt'.
|
105 |
+
source (str | Path): Input source, which can be a file, directory, URL, glob pattern, screen capture, or webcam
|
106 |
+
index. Default is 'data/images'.
|
107 |
+
data (str | Path): Path to the dataset YAML file. Default is 'data/coco128.yaml'.
|
108 |
+
imgsz (tuple[int, int]): Inference image size as a tuple (height, width). Default is (640, 640).
|
109 |
+
conf_thres (float): Confidence threshold for detections. Default is 0.25.
|
110 |
+
iou_thres (float): Intersection Over Union (IOU) threshold for non-max suppression. Default is 0.45.
|
111 |
+
max_det (int): Maximum number of detections per image. Default is 1000.
|
112 |
+
device (str): CUDA device identifier (e.g., '0' or '0,1,2,3') or 'cpu'. Default is an empty string, which uses the
|
113 |
+
best available device.
|
114 |
+
view_img (bool): If True, display inference results using OpenCV. Default is False.
|
115 |
+
save_txt (bool): If True, save results in a text file. Default is False.
|
116 |
+
save_csv (bool): If True, save results in a CSV file. Default is False.
|
117 |
+
save_conf (bool): If True, include confidence scores in the saved results. Default is False.
|
118 |
+
save_crop (bool): If True, save cropped prediction boxes. Default is False.
|
119 |
+
nosave (bool): If True, do not save inference images or videos. Default is False.
|
120 |
+
classes (list[int]): List of class indices to filter detections by. Default is None.
|
121 |
+
agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False.
|
122 |
+
augment (bool): If True, use augmented inference. Default is False.
|
123 |
+
visualize (bool): If True, visualize feature maps. Default is False.
|
124 |
+
update (bool): If True, update all models' weights. Default is False.
|
125 |
+
project (str | Path): Directory to save results. Default is 'runs/detect'.
|
126 |
+
name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'.
|
127 |
+
exist_ok (bool): If True, existing directories with the same name are reused instead of being incremented. Default is
|
128 |
+
False.
|
129 |
+
line_thickness (int): Thickness of bounding box lines in pixels. Default is 3.
|
130 |
+
hide_labels (bool): If True, do not display labels on bounding boxes. Default is False.
|
131 |
+
hide_conf (bool): If True, do not display confidence scores on bounding boxes. Default is False.
|
132 |
+
half (bool): If True, use FP16 half-precision inference. Default is False.
|
133 |
+
dnn (bool): If True, use OpenCV DNN backend for ONNX inference. Default is False.
|
134 |
+
vid_stride (int): Stride for processing video frames, to skip frames between processing. Default is 1.
|
135 |
+
|
136 |
+
Returns:
|
137 |
+
None
|
138 |
+
|
139 |
+
Examples:
|
140 |
+
```python
|
141 |
+
from ultralytics import run
|
142 |
+
|
143 |
+
# Run inference on an image
|
144 |
+
run(source='data/images/example.jpg', weights='yolov5s.pt', device='0')
|
145 |
+
|
146 |
+
# Run inference on a video with specific confidence threshold
|
147 |
+
run(source='data/videos/example.mp4', weights='yolov5s.pt', conf_thres=0.4, device='0')
|
148 |
+
```
|
149 |
+
"""
|
150 |
+
source = str(source)
|
151 |
+
save_img = not nosave and not source.endswith(".txt") # save inference images
|
152 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
153 |
+
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
|
154 |
+
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
|
155 |
+
screenshot = source.lower().startswith("screen")
|
156 |
+
if is_url and is_file:
|
157 |
+
source = check_file(source) # download
|
158 |
+
|
159 |
+
# Directories
|
160 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
161 |
+
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
162 |
+
|
163 |
+
# Load model
|
164 |
+
device = select_device(device)
|
165 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
166 |
+
stride, names, pt = model.stride, model.names, model.pt
|
167 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
168 |
+
|
169 |
+
# Dataloader
|
170 |
+
bs = 1 # batch_size
|
171 |
+
if webcam:
|
172 |
+
view_img = check_imshow(warn=True)
|
173 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
174 |
+
bs = len(dataset)
|
175 |
+
elif screenshot:
|
176 |
+
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
|
177 |
+
else:
|
178 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
179 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
180 |
+
|
181 |
+
# Run inference
|
182 |
+
model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
|
183 |
+
seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
|
184 |
+
for path, im, im0s, vid_cap, s in dataset:
|
185 |
+
with dt[0]:
|
186 |
+
im = torch.from_numpy(im).to(model.device)
|
187 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
188 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
189 |
+
if len(im.shape) == 3:
|
190 |
+
im = im[None] # expand for batch dim
|
191 |
+
if model.xml and im.shape[0] > 1:
|
192 |
+
ims = torch.chunk(im, im.shape[0], 0)
|
193 |
+
|
194 |
+
# Inference
|
195 |
+
with dt[1]:
|
196 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
197 |
+
if model.xml and im.shape[0] > 1:
|
198 |
+
pred = None
|
199 |
+
for image in ims:
|
200 |
+
if pred is None:
|
201 |
+
pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
|
202 |
+
else:
|
203 |
+
pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
|
204 |
+
pred = [pred, None]
|
205 |
+
else:
|
206 |
+
pred = model(im, augment=augment, visualize=visualize)
|
207 |
+
# NMS
|
208 |
+
with dt[2]:
|
209 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
210 |
+
|
211 |
+
# Second-stage classifier (optional)
|
212 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
213 |
+
|
214 |
+
# Define the path for the CSV file
|
215 |
+
csv_path = save_dir / "predictions.csv"
|
216 |
+
|
217 |
+
# Create or append to the CSV file
|
218 |
+
def write_to_csv(image_name, prediction, confidence):
|
219 |
+
"""Writes prediction data for an image to a CSV file, appending if the file exists."""
|
220 |
+
data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence}
|
221 |
+
with open(csv_path, mode="a", newline="") as f:
|
222 |
+
writer = csv.DictWriter(f, fieldnames=data.keys())
|
223 |
+
if not csv_path.is_file():
|
224 |
+
writer.writeheader()
|
225 |
+
writer.writerow(data)
|
226 |
+
|
227 |
+
# Process predictions
|
228 |
+
for i, det in enumerate(pred): # per image
|
229 |
+
seen += 1
|
230 |
+
if webcam: # batch_size >= 1
|
231 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
232 |
+
s += f"{i}: "
|
233 |
+
else:
|
234 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
|
235 |
+
|
236 |
+
p = Path(p) # to Path
|
237 |
+
save_path = str(save_dir / p.name) # im.jpg
|
238 |
+
txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
|
239 |
+
s += "%gx%g " % im.shape[2:] # print string
|
240 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
241 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
242 |
+
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
243 |
+
if len(det):
|
244 |
+
# Rescale boxes from img_size to im0 size
|
245 |
+
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
|
246 |
+
|
247 |
+
# Print results
|
248 |
+
for c in det[:, 5].unique():
|
249 |
+
n = (det[:, 5] == c).sum() # detections per class
|
250 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
251 |
+
|
252 |
+
# Write results
|
253 |
+
for *xyxy, conf, cls in reversed(det):
|
254 |
+
c = int(cls) # integer class
|
255 |
+
label = names[c] if hide_conf else f"{names[c]}"
|
256 |
+
confidence = float(conf)
|
257 |
+
confidence_str = f"{confidence:.2f}"
|
258 |
+
|
259 |
+
if save_csv:
|
260 |
+
write_to_csv(p.name, label, confidence_str)
|
261 |
+
|
262 |
+
if save_txt: # Write to file
|
263 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
264 |
+
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
265 |
+
with open(f"{txt_path}.txt", "a") as f:
|
266 |
+
f.write(("%g " * len(line)).rstrip() % line + "\n")
|
267 |
+
|
268 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
269 |
+
c = int(cls) # integer class
|
270 |
+
label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}")
|
271 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
272 |
+
if save_crop:
|
273 |
+
save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
|
274 |
+
|
275 |
+
# Stream results
|
276 |
+
im0 = annotator.result()
|
277 |
+
if view_img:
|
278 |
+
if platform.system() == "Linux" and p not in windows:
|
279 |
+
windows.append(p)
|
280 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
281 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
282 |
+
cv2.imshow(str(p), im0)
|
283 |
+
cv2.waitKey(1) # 1 millisecond
|
284 |
+
|
285 |
+
# Save results (image with detections)
|
286 |
+
if save_img:
|
287 |
+
if dataset.mode == "image":
|
288 |
+
cv2.imwrite(save_path, im0)
|
289 |
+
else: # 'video' or 'stream'
|
290 |
+
if vid_path[i] != save_path: # new video
|
291 |
+
vid_path[i] = save_path
|
292 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
293 |
+
vid_writer[i].release() # release previous video writer
|
294 |
+
if vid_cap: # video
|
295 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
296 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
297 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
298 |
+
else: # stream
|
299 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
300 |
+
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
|
301 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
|
302 |
+
vid_writer[i].write(im0)
|
303 |
+
|
304 |
+
# Print time (inference-only)
|
305 |
+
LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
|
306 |
+
|
307 |
+
# Print results
|
308 |
+
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
|
309 |
+
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
|
310 |
+
if save_txt or save_img:
|
311 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
|
312 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
313 |
+
if update:
|
314 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
315 |
+
|
316 |
+
|
317 |
+
def parse_opt():
|
318 |
+
"""
|
319 |
+
Parse command-line arguments for YOLOv5 detection, allowing custom inference options and model configurations.
|
320 |
+
|
321 |
+
Args:
|
322 |
+
--weights (str | list[str], optional): Model path or Triton URL. Defaults to ROOT / 'yolov5s.pt'.
|
323 |
+
--source (str, optional): File/dir/URL/glob/screen/0(webcam). Defaults to ROOT / 'data/images'.
|
324 |
+
--data (str, optional): Dataset YAML path. Provides dataset configuration information.
|
325 |
+
--imgsz (list[int], optional): Inference size (height, width). Defaults to [640].
|
326 |
+
--conf-thres (float, optional): Confidence threshold. Defaults to 0.25.
|
327 |
+
--iou-thres (float, optional): NMS IoU threshold. Defaults to 0.45.
|
328 |
+
--max-det (int, optional): Maximum number of detections per image. Defaults to 1000.
|
329 |
+
--device (str, optional): CUDA device, i.e., '0' or '0,1,2,3' or 'cpu'. Defaults to "".
|
330 |
+
--view-img (bool, optional): Flag to display results. Defaults to False.
|
331 |
+
--save-txt (bool, optional): Flag to save results to *.txt files. Defaults to False.
|
332 |
+
--save-csv (bool, optional): Flag to save results in CSV format. Defaults to False.
|
333 |
+
--save-conf (bool, optional): Flag to save confidences in labels saved via --save-txt. Defaults to False.
|
334 |
+
--save-crop (bool, optional): Flag to save cropped prediction boxes. Defaults to False.
|
335 |
+
--nosave (bool, optional): Flag to prevent saving images/videos. Defaults to False.
|
336 |
+
--classes (list[int], optional): List of classes to filter results by, e.g., '--classes 0 2 3'. Defaults to None.
|
337 |
+
--agnostic-nms (bool, optional): Flag for class-agnostic NMS. Defaults to False.
|
338 |
+
--augment (bool, optional): Flag for augmented inference. Defaults to False.
|
339 |
+
--visualize (bool, optional): Flag for visualizing features. Defaults to False.
|
340 |
+
--update (bool, optional): Flag to update all models in the model directory. Defaults to False.
|
341 |
+
--project (str, optional): Directory to save results. Defaults to ROOT / 'runs/detect'.
|
342 |
+
--name (str, optional): Sub-directory name for saving results within --project. Defaults to 'exp'.
|
343 |
+
--exist-ok (bool, optional): Flag to allow overwriting if the project/name already exists. Defaults to False.
|
344 |
+
--line-thickness (int, optional): Thickness (in pixels) of bounding boxes. Defaults to 3.
|
345 |
+
--hide-labels (bool, optional): Flag to hide labels in the output. Defaults to False.
|
346 |
+
--hide-conf (bool, optional): Flag to hide confidences in the output. Defaults to False.
|
347 |
+
--half (bool, optional): Flag to use FP16 half-precision inference. Defaults to False.
|
348 |
+
--dnn (bool, optional): Flag to use OpenCV DNN for ONNX inference. Defaults to False.
|
349 |
+
--vid-stride (int, optional): Video frame-rate stride, determining the number of frames to skip in between
|
350 |
+
consecutive frames. Defaults to 1.
|
351 |
+
|
352 |
+
Returns:
|
353 |
+
argparse.Namespace: Parsed command-line arguments as an argparse.Namespace object.
|
354 |
+
|
355 |
+
Example:
|
356 |
+
```python
|
357 |
+
from ultralytics import YOLOv5
|
358 |
+
args = YOLOv5.parse_opt()
|
359 |
+
```
|
360 |
+
"""
|
361 |
+
parser = argparse.ArgumentParser()
|
362 |
+
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL")
|
363 |
+
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
|
364 |
+
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
|
365 |
+
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
|
366 |
+
parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold")
|
367 |
+
parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold")
|
368 |
+
parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image")
|
369 |
+
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
370 |
+
parser.add_argument("--view-img", action="store_true", help="show results")
|
371 |
+
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
|
372 |
+
parser.add_argument("--save-csv", action="store_true", help="save results in CSV format")
|
373 |
+
parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels")
|
374 |
+
parser.add_argument("--save-crop", action="store_true", help="save cropped prediction boxes")
|
375 |
+
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
|
376 |
+
parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
|
377 |
+
parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
|
378 |
+
parser.add_argument("--augment", action="store_true", help="augmented inference")
|
379 |
+
parser.add_argument("--visualize", action="store_true", help="visualize features")
|
380 |
+
parser.add_argument("--update", action="store_true", help="update all models")
|
381 |
+
parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name")
|
382 |
+
parser.add_argument("--name", default="exp", help="save results to project/name")
|
383 |
+
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
384 |
+
parser.add_argument("--line-thickness", default=3, type=int, help="bounding box thickness (pixels)")
|
385 |
+
parser.add_argument("--hide-labels", default=False, action="store_true", help="hide labels")
|
386 |
+
parser.add_argument("--hide-conf", default=False, action="store_true", help="hide confidences")
|
387 |
+
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
388 |
+
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
|
389 |
+
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
|
390 |
+
opt = parser.parse_args()
|
391 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
392 |
+
print_args(vars(opt))
|
393 |
+
return opt
|
394 |
+
|
395 |
+
|
396 |
+
def main(opt):
|
397 |
+
"""
|
398 |
+
Executes YOLOv5 model inference based on provided command-line arguments, validating dependencies before running.
|
399 |
+
|
400 |
+
Args:
|
401 |
+
opt (argparse.Namespace): Command-line arguments for YOLOv5 detection. See function `parse_opt` for details.
|
402 |
+
|
403 |
+
Returns:
|
404 |
+
None
|
405 |
+
|
406 |
+
Note:
|
407 |
+
This function performs essential pre-execution checks and initiates the YOLOv5 detection process based on user-specified
|
408 |
+
options. Refer to the usage guide and examples for more information about different sources and formats at:
|
409 |
+
https://github.com/ultralytics/ultralytics
|
410 |
+
|
411 |
+
Example usage:
|
412 |
+
|
413 |
+
```python
|
414 |
+
if __name__ == "__main__":
|
415 |
+
opt = parse_opt()
|
416 |
+
main(opt)
|
417 |
+
```
|
418 |
+
"""
|
419 |
+
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
|
420 |
+
run(**vars(opt))
|
421 |
+
|
422 |
+
|
423 |
+
if __name__ == "__main__":
|
424 |
+
opt = parse_opt()
|
425 |
+
main(opt)
|
yolov5/export.py
ADDED
@@ -0,0 +1,1538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 detect.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 contextlib
|
49 |
+
import json
|
50 |
+
import os
|
51 |
+
import platform
|
52 |
+
import re
|
53 |
+
import subprocess
|
54 |
+
import sys
|
55 |
+
import time
|
56 |
+
import warnings
|
57 |
+
from pathlib import Path
|
58 |
+
|
59 |
+
import pandas as pd
|
60 |
+
import torch
|
61 |
+
from torch.utils.mobile_optimizer import optimize_for_mobile
|
62 |
+
|
63 |
+
FILE = Path(__file__).resolve()
|
64 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
65 |
+
if str(ROOT) not in sys.path:
|
66 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
67 |
+
if platform.system() != "Windows":
|
68 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
69 |
+
|
70 |
+
from models.experimental import attempt_load
|
71 |
+
from models.yolo import ClassificationModel, Detect, DetectionModel, SegmentationModel
|
72 |
+
from utils.dataloaders import LoadImages
|
73 |
+
from utils.general import (
|
74 |
+
LOGGER,
|
75 |
+
Profile,
|
76 |
+
check_dataset,
|
77 |
+
check_img_size,
|
78 |
+
check_requirements,
|
79 |
+
check_version,
|
80 |
+
check_yaml,
|
81 |
+
colorstr,
|
82 |
+
file_size,
|
83 |
+
get_default_args,
|
84 |
+
print_args,
|
85 |
+
url2file,
|
86 |
+
yaml_save,
|
87 |
+
)
|
88 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
89 |
+
|
90 |
+
MACOS = platform.system() == "Darwin" # macOS environment
|
91 |
+
|
92 |
+
|
93 |
+
class iOSModel(torch.nn.Module):
|
94 |
+
def __init__(self, model, im):
|
95 |
+
"""
|
96 |
+
Initializes an iOS compatible model with normalization based on image dimensions.
|
97 |
+
|
98 |
+
Args:
|
99 |
+
model (torch.nn.Module): The PyTorch model to be adapted for iOS compatibility.
|
100 |
+
im (torch.Tensor): An input tensor representing a batch of images with shape (B, C, H, W).
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
None: This method does not return any value.
|
104 |
+
|
105 |
+
Notes:
|
106 |
+
This initializer configures normalization based on the input image dimensions, which is critical for
|
107 |
+
ensuring the model's compatibility and proper functionality on iOS devices. The normalization step
|
108 |
+
involves dividing by the image width if the image is square; otherwise, additional conditions might apply.
|
109 |
+
"""
|
110 |
+
super().__init__()
|
111 |
+
b, c, h, w = im.shape # batch, channel, height, width
|
112 |
+
self.model = model
|
113 |
+
self.nc = model.nc # number of classes
|
114 |
+
if w == h:
|
115 |
+
self.normalize = 1.0 / w
|
116 |
+
else:
|
117 |
+
self.normalize = torch.tensor([1.0 / w, 1.0 / h, 1.0 / w, 1.0 / h]) # broadcast (slower, smaller)
|
118 |
+
# np = model(im)[0].shape[1] # number of points
|
119 |
+
# self.normalize = torch.tensor([1. / w, 1. / h, 1. / w, 1. / h]).expand(np, 4) # explicit (faster, larger)
|
120 |
+
|
121 |
+
def forward(self, x):
|
122 |
+
"""
|
123 |
+
Run a forward pass on the input tensor, returning class confidences and normalized coordinates.
|
124 |
+
|
125 |
+
Args:
|
126 |
+
x (torch.Tensor): Input tensor containing the image data with shape (batch, channels, height, width).
|
127 |
+
|
128 |
+
Returns:
|
129 |
+
torch.Tensor: Concatenated tensor with normalized coordinates (xywh), confidence scores (conf),
|
130 |
+
and class probabilities (cls), having shape (N, 4 + 1 + C), where N is the number of predictions,
|
131 |
+
and C is the number of classes.
|
132 |
+
|
133 |
+
Examples:
|
134 |
+
```python
|
135 |
+
model = iOSModel(pretrained_model, input_image)
|
136 |
+
output = model.forward(torch_input_tensor)
|
137 |
+
```
|
138 |
+
"""
|
139 |
+
xywh, conf, cls = self.model(x)[0].squeeze().split((4, 1, self.nc), 1)
|
140 |
+
return cls * conf, xywh * self.normalize # confidence (3780, 80), coordinates (3780, 4)
|
141 |
+
|
142 |
+
|
143 |
+
def export_formats():
|
144 |
+
"""
|
145 |
+
Returns a DataFrame of supported YOLOv5 model export formats and their properties.
|
146 |
+
|
147 |
+
Returns:
|
148 |
+
pandas.DataFrame: A DataFrame containing supported export formats and their properties. The DataFrame
|
149 |
+
includes columns for format name, CLI argument suffix, file extension or directory name, and boolean flags
|
150 |
+
indicating if the export format supports training and detection.
|
151 |
+
|
152 |
+
Examples:
|
153 |
+
```python
|
154 |
+
formats = export_formats()
|
155 |
+
print(f"Supported export formats:\n{formats}")
|
156 |
+
```
|
157 |
+
|
158 |
+
Notes:
|
159 |
+
The DataFrame contains the following columns:
|
160 |
+
- Format: The name of the model format (e.g., PyTorch, TorchScript, ONNX, etc.).
|
161 |
+
- Include Argument: The argument to use with the export script to include this format.
|
162 |
+
- File Suffix: File extension or directory name associated with the format.
|
163 |
+
- Supports Training: Whether the format supports training.
|
164 |
+
- Supports Detection: Whether the format supports detection.
|
165 |
+
"""
|
166 |
+
x = [
|
167 |
+
["PyTorch", "-", ".pt", True, True],
|
168 |
+
["TorchScript", "torchscript", ".torchscript", True, True],
|
169 |
+
["ONNX", "onnx", ".onnx", True, True],
|
170 |
+
["OpenVINO", "openvino", "_openvino_model", True, False],
|
171 |
+
["TensorRT", "engine", ".engine", False, True],
|
172 |
+
["CoreML", "coreml", ".mlpackage", True, False],
|
173 |
+
["TensorFlow SavedModel", "saved_model", "_saved_model", True, True],
|
174 |
+
["TensorFlow GraphDef", "pb", ".pb", True, True],
|
175 |
+
["TensorFlow Lite", "tflite", ".tflite", True, False],
|
176 |
+
["TensorFlow Edge TPU", "edgetpu", "_edgetpu.tflite", False, False],
|
177 |
+
["TensorFlow.js", "tfjs", "_web_model", False, False],
|
178 |
+
["PaddlePaddle", "paddle", "_paddle_model", True, True],
|
179 |
+
]
|
180 |
+
return pd.DataFrame(x, columns=["Format", "Argument", "Suffix", "CPU", "GPU"])
|
181 |
+
|
182 |
+
|
183 |
+
def try_export(inner_func):
|
184 |
+
"""
|
185 |
+
Log success or failure, execution time, and file size for YOLOv5 model export functions wrapped with @try_export.
|
186 |
+
|
187 |
+
Args:
|
188 |
+
inner_func (Callable): The model export function to be wrapped by the decorator.
|
189 |
+
|
190 |
+
Returns:
|
191 |
+
Callable: The wrapped function that logs execution details. When executed, this wrapper function returns either:
|
192 |
+
- Tuple (str | torch.nn.Module): On success — the file path of the exported model and the model instance.
|
193 |
+
- Tuple (None, None): On failure — None values indicating export failure.
|
194 |
+
|
195 |
+
Examples:
|
196 |
+
```python
|
197 |
+
@try_export
|
198 |
+
def export_onnx(model, filepath):
|
199 |
+
# implementation here
|
200 |
+
pass
|
201 |
+
|
202 |
+
exported_file, exported_model = export_onnx(yolo_model, 'path/to/save/model.onnx')
|
203 |
+
```
|
204 |
+
|
205 |
+
Notes:
|
206 |
+
For additional requirements and model export formats, refer to the
|
207 |
+
[Ultralytics YOLOv5 GitHub repository](https://github.com/ultralytics/ultralytics).
|
208 |
+
"""
|
209 |
+
inner_args = get_default_args(inner_func)
|
210 |
+
|
211 |
+
def outer_func(*args, **kwargs):
|
212 |
+
"""Logs success/failure and execution details of model export functions wrapped with @try_export decorator."""
|
213 |
+
prefix = inner_args["prefix"]
|
214 |
+
try:
|
215 |
+
with Profile() as dt:
|
216 |
+
f, model = inner_func(*args, **kwargs)
|
217 |
+
LOGGER.info(f"{prefix} export success ✅ {dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)")
|
218 |
+
return f, model
|
219 |
+
except Exception as e:
|
220 |
+
LOGGER.info(f"{prefix} export failure ❌ {dt.t:.1f}s: {e}")
|
221 |
+
return None, None
|
222 |
+
|
223 |
+
return outer_func
|
224 |
+
|
225 |
+
|
226 |
+
@try_export
|
227 |
+
def export_torchscript(model, im, file, optimize, prefix=colorstr("TorchScript:")):
|
228 |
+
"""
|
229 |
+
Export a YOLOv5 model to the TorchScript format.
|
230 |
+
|
231 |
+
Args:
|
232 |
+
model (torch.nn.Module): The YOLOv5 model to be exported.
|
233 |
+
im (torch.Tensor): Example input tensor to be used for tracing the TorchScript model.
|
234 |
+
file (Path): File path where the exported TorchScript model will be saved.
|
235 |
+
optimize (bool): If True, applies optimizations for mobile deployment.
|
236 |
+
prefix (str): Optional prefix for log messages. Default is 'TorchScript:'.
|
237 |
+
|
238 |
+
Returns:
|
239 |
+
(str | None, torch.jit.ScriptModule | None): A tuple containing the file path of the exported model
|
240 |
+
(as a string) and the TorchScript model (as a torch.jit.ScriptModule). If the export fails, both elements
|
241 |
+
of the tuple will be None.
|
242 |
+
|
243 |
+
Notes:
|
244 |
+
- This function uses tracing to create the TorchScript model.
|
245 |
+
- Metadata, including the input image shape, model stride, and class names, is saved in an extra file (`config.txt`)
|
246 |
+
within the TorchScript model package.
|
247 |
+
- For mobile optimization, refer to the PyTorch tutorial: https://pytorch.org/tutorials/recipes/mobile_interpreter.html
|
248 |
+
|
249 |
+
Example:
|
250 |
+
```python
|
251 |
+
from pathlib import Path
|
252 |
+
import torch
|
253 |
+
from models.experimental import attempt_load
|
254 |
+
from utils.torch_utils import select_device
|
255 |
+
|
256 |
+
# Load model
|
257 |
+
weights = 'yolov5s.pt'
|
258 |
+
device = select_device('')
|
259 |
+
model = attempt_load(weights, device=device)
|
260 |
+
|
261 |
+
# Example input tensor
|
262 |
+
im = torch.zeros(1, 3, 640, 640).to(device)
|
263 |
+
|
264 |
+
# Export model
|
265 |
+
file = Path('yolov5s.torchscript')
|
266 |
+
export_torchscript(model, im, file, optimize=False)
|
267 |
+
```
|
268 |
+
"""
|
269 |
+
LOGGER.info(f"\n{prefix} starting export with torch {torch.__version__}...")
|
270 |
+
f = file.with_suffix(".torchscript")
|
271 |
+
|
272 |
+
ts = torch.jit.trace(model, im, strict=False)
|
273 |
+
d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
|
274 |
+
extra_files = {"config.txt": json.dumps(d)} # torch._C.ExtraFilesMap()
|
275 |
+
if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
|
276 |
+
optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
|
277 |
+
else:
|
278 |
+
ts.save(str(f), _extra_files=extra_files)
|
279 |
+
return f, None
|
280 |
+
|
281 |
+
|
282 |
+
@try_export
|
283 |
+
def export_onnx(model, im, file, opset, dynamic, simplify, prefix=colorstr("ONNX:")):
|
284 |
+
"""
|
285 |
+
Export a YOLOv5 model to ONNX format with dynamic axes support and optional model simplification.
|
286 |
+
|
287 |
+
Args:
|
288 |
+
model (torch.nn.Module): The YOLOv5 model to be exported.
|
289 |
+
im (torch.Tensor): A sample input tensor for model tracing, usually the shape is (1, 3, height, width).
|
290 |
+
file (pathlib.Path | str): The output file path where the ONNX model will be saved.
|
291 |
+
opset (int): The ONNX opset version to use for export.
|
292 |
+
dynamic (bool): If True, enables dynamic axes for batch, height, and width dimensions.
|
293 |
+
simplify (bool): If True, applies ONNX model simplification for optimization.
|
294 |
+
prefix (str): A prefix string for logging messages, defaults to 'ONNX:'.
|
295 |
+
|
296 |
+
Returns:
|
297 |
+
tuple[pathlib.Path | str, None]: The path to the saved ONNX model file and None (consistent with decorator).
|
298 |
+
|
299 |
+
Raises:
|
300 |
+
ImportError: If required libraries for export (e.g., 'onnx', 'onnx-simplifier') are not installed.
|
301 |
+
AssertionError: If the simplification check fails.
|
302 |
+
|
303 |
+
Notes:
|
304 |
+
The required packages for this function can be installed via:
|
305 |
+
```
|
306 |
+
pip install onnx onnx-simplifier onnxruntime onnxruntime-gpu
|
307 |
+
```
|
308 |
+
|
309 |
+
Example:
|
310 |
+
```python
|
311 |
+
from pathlib import Path
|
312 |
+
import torch
|
313 |
+
from models.experimental import attempt_load
|
314 |
+
from utils.torch_utils import select_device
|
315 |
+
|
316 |
+
# Load model
|
317 |
+
weights = 'yolov5s.pt'
|
318 |
+
device = select_device('')
|
319 |
+
model = attempt_load(weights, map_location=device)
|
320 |
+
|
321 |
+
# Example input tensor
|
322 |
+
im = torch.zeros(1, 3, 640, 640).to(device)
|
323 |
+
|
324 |
+
# Export model
|
325 |
+
file_path = Path('yolov5s.onnx')
|
326 |
+
export_onnx(model, im, file_path, opset=12, dynamic=True, simplify=True)
|
327 |
+
```
|
328 |
+
"""
|
329 |
+
check_requirements("onnx>=1.12.0")
|
330 |
+
import onnx
|
331 |
+
|
332 |
+
LOGGER.info(f"\n{prefix} starting export with onnx {onnx.__version__}...")
|
333 |
+
f = str(file.with_suffix(".onnx"))
|
334 |
+
|
335 |
+
output_names = ["output0", "output1"] if isinstance(model, SegmentationModel) else ["output0"]
|
336 |
+
if dynamic:
|
337 |
+
dynamic = {"images": {0: "batch", 2: "height", 3: "width"}} # shape(1,3,640,640)
|
338 |
+
if isinstance(model, SegmentationModel):
|
339 |
+
dynamic["output0"] = {0: "batch", 1: "anchors"} # shape(1,25200,85)
|
340 |
+
dynamic["output1"] = {0: "batch", 2: "mask_height", 3: "mask_width"} # shape(1,32,160,160)
|
341 |
+
elif isinstance(model, DetectionModel):
|
342 |
+
dynamic["output0"] = {0: "batch", 1: "anchors"} # shape(1,25200,85)
|
343 |
+
|
344 |
+
torch.onnx.export(
|
345 |
+
model.cpu() if dynamic else model, # --dynamic only compatible with cpu
|
346 |
+
im.cpu() if dynamic else im,
|
347 |
+
f,
|
348 |
+
verbose=False,
|
349 |
+
opset_version=opset,
|
350 |
+
do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
|
351 |
+
input_names=["images"],
|
352 |
+
output_names=output_names,
|
353 |
+
dynamic_axes=dynamic or None,
|
354 |
+
)
|
355 |
+
|
356 |
+
# Checks
|
357 |
+
model_onnx = onnx.load(f) # load onnx model
|
358 |
+
onnx.checker.check_model(model_onnx) # check onnx model
|
359 |
+
|
360 |
+
# Metadata
|
361 |
+
d = {"stride": int(max(model.stride)), "names": model.names}
|
362 |
+
for k, v in d.items():
|
363 |
+
meta = model_onnx.metadata_props.add()
|
364 |
+
meta.key, meta.value = k, str(v)
|
365 |
+
onnx.save(model_onnx, f)
|
366 |
+
|
367 |
+
# Simplify
|
368 |
+
if simplify:
|
369 |
+
try:
|
370 |
+
cuda = torch.cuda.is_available()
|
371 |
+
check_requirements(("onnxruntime-gpu" if cuda else "onnxruntime", "onnx-simplifier>=0.4.1"))
|
372 |
+
import onnxsim
|
373 |
+
|
374 |
+
LOGGER.info(f"{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...")
|
375 |
+
model_onnx, check = onnxsim.simplify(model_onnx)
|
376 |
+
assert check, "assert check failed"
|
377 |
+
onnx.save(model_onnx, f)
|
378 |
+
except Exception as e:
|
379 |
+
LOGGER.info(f"{prefix} simplifier failure: {e}")
|
380 |
+
return f, model_onnx
|
381 |
+
|
382 |
+
|
383 |
+
@try_export
|
384 |
+
def export_openvino(file, metadata, half, int8, data, prefix=colorstr("OpenVINO:")):
|
385 |
+
"""
|
386 |
+
Export a YOLOv5 model to OpenVINO format with optional FP16 and INT8 quantization.
|
387 |
+
|
388 |
+
Args:
|
389 |
+
file (Path): Path to the output file where the OpenVINO model will be saved.
|
390 |
+
metadata (dict): Dictionary including model metadata such as names and strides.
|
391 |
+
half (bool): If True, export the model with FP16 precision.
|
392 |
+
int8 (bool): If True, export the model with INT8 quantization.
|
393 |
+
data (str): Path to the dataset YAML file required for INT8 quantization.
|
394 |
+
prefix (str): Prefix string for logging purposes (default is "OpenVINO:").
|
395 |
+
|
396 |
+
Returns:
|
397 |
+
(str, openvino.runtime.Model | None): The OpenVINO model file path and openvino.runtime.Model object if export is
|
398 |
+
successful; otherwise, None.
|
399 |
+
|
400 |
+
Notes:
|
401 |
+
- Requires `openvino-dev` package version 2023.0 or higher. Install with:
|
402 |
+
`$ pip install openvino-dev>=2023.0`
|
403 |
+
- For INT8 quantization, also requires `nncf` library version 2.5.0 or higher. Install with:
|
404 |
+
`$ pip install nncf>=2.5.0`
|
405 |
+
|
406 |
+
Examples:
|
407 |
+
```python
|
408 |
+
from pathlib import Path
|
409 |
+
from ultralytics import YOLOv5
|
410 |
+
|
411 |
+
model = YOLOv5('yolov5s.pt')
|
412 |
+
export_openvino(Path('yolov5s.onnx'), metadata={'names': model.names, 'stride': model.stride}, half=True,
|
413 |
+
int8=False, data='data.yaml')
|
414 |
+
```
|
415 |
+
|
416 |
+
This will export the YOLOv5 model to OpenVINO with FP16 precision but without INT8 quantization, saving it to
|
417 |
+
the specified file path.
|
418 |
+
"""
|
419 |
+
check_requirements("openvino-dev>=2023.0") # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
420 |
+
import openvino.runtime as ov # noqa
|
421 |
+
from openvino.tools import mo # noqa
|
422 |
+
|
423 |
+
LOGGER.info(f"\n{prefix} starting export with openvino {ov.__version__}...")
|
424 |
+
f = str(file).replace(file.suffix, f"_{'int8_' if int8 else ''}openvino_model{os.sep}")
|
425 |
+
f_onnx = file.with_suffix(".onnx")
|
426 |
+
f_ov = str(Path(f) / file.with_suffix(".xml").name)
|
427 |
+
|
428 |
+
ov_model = mo.convert_model(f_onnx, model_name=file.stem, framework="onnx", compress_to_fp16=half) # export
|
429 |
+
|
430 |
+
if int8:
|
431 |
+
check_requirements("nncf>=2.5.0") # requires at least version 2.5.0 to use the post-training quantization
|
432 |
+
import nncf
|
433 |
+
import numpy as np
|
434 |
+
|
435 |
+
from utils.dataloaders import create_dataloader
|
436 |
+
|
437 |
+
def gen_dataloader(yaml_path, task="train", imgsz=640, workers=4):
|
438 |
+
"""Generates a DataLoader for model training or validation based on the given YAML dataset configuration."""
|
439 |
+
data_yaml = check_yaml(yaml_path)
|
440 |
+
data = check_dataset(data_yaml)
|
441 |
+
dataloader = create_dataloader(
|
442 |
+
data[task], imgsz=imgsz, batch_size=1, stride=32, pad=0.5, single_cls=False, rect=False, workers=workers
|
443 |
+
)[0]
|
444 |
+
return dataloader
|
445 |
+
|
446 |
+
# noqa: F811
|
447 |
+
|
448 |
+
def transform_fn(data_item):
|
449 |
+
"""
|
450 |
+
Quantization transform function.
|
451 |
+
|
452 |
+
Extracts and preprocess input data from dataloader item for quantization.
|
453 |
+
Parameters:
|
454 |
+
data_item: Tuple with data item produced by DataLoader during iteration
|
455 |
+
Returns:
|
456 |
+
input_tensor: Input data for quantization
|
457 |
+
"""
|
458 |
+
assert data_item[0].dtype == torch.uint8, "input image must be uint8 for the quantization preprocessing"
|
459 |
+
|
460 |
+
img = data_item[0].numpy().astype(np.float32) # uint8 to fp16/32
|
461 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
462 |
+
return np.expand_dims(img, 0) if img.ndim == 3 else img
|
463 |
+
|
464 |
+
ds = gen_dataloader(data)
|
465 |
+
quantization_dataset = nncf.Dataset(ds, transform_fn)
|
466 |
+
ov_model = nncf.quantize(ov_model, quantization_dataset, preset=nncf.QuantizationPreset.MIXED)
|
467 |
+
|
468 |
+
ov.serialize(ov_model, f_ov) # save
|
469 |
+
yaml_save(Path(f) / file.with_suffix(".yaml").name, metadata) # add metadata.yaml
|
470 |
+
return f, None
|
471 |
+
|
472 |
+
|
473 |
+
@try_export
|
474 |
+
def export_paddle(model, im, file, metadata, prefix=colorstr("PaddlePaddle:")):
|
475 |
+
"""
|
476 |
+
Export a YOLOv5 PyTorch model to PaddlePaddle format using X2Paddle, saving the converted model and metadata.
|
477 |
+
|
478 |
+
Args:
|
479 |
+
model (torch.nn.Module): The YOLOv5 model to be exported.
|
480 |
+
im (torch.Tensor): Input tensor used for model tracing during export.
|
481 |
+
file (pathlib.Path): Path to the source file to be converted.
|
482 |
+
metadata (dict): Additional metadata to be saved alongside the model.
|
483 |
+
prefix (str): Prefix for logging information.
|
484 |
+
|
485 |
+
Returns:
|
486 |
+
tuple (str, None): A tuple where the first element is the path to the saved PaddlePaddle model, and the
|
487 |
+
second element is None.
|
488 |
+
|
489 |
+
Examples:
|
490 |
+
```python
|
491 |
+
from pathlib import Path
|
492 |
+
import torch
|
493 |
+
|
494 |
+
# Assume 'model' is a pre-trained YOLOv5 model and 'im' is an example input tensor
|
495 |
+
model = ... # Load your model here
|
496 |
+
im = torch.randn((1, 3, 640, 640)) # Dummy input tensor for tracing
|
497 |
+
file = Path("yolov5s.pt")
|
498 |
+
metadata = {"stride": 32, "names": ["person", "bicycle", "car", "motorbike"]}
|
499 |
+
|
500 |
+
export_paddle(model=model, im=im, file=file, metadata=metadata)
|
501 |
+
```
|
502 |
+
|
503 |
+
Notes:
|
504 |
+
Ensure that `paddlepaddle` and `x2paddle` are installed, as these are required for the export function. You can
|
505 |
+
install them via pip:
|
506 |
+
```
|
507 |
+
$ pip install paddlepaddle x2paddle
|
508 |
+
```
|
509 |
+
"""
|
510 |
+
check_requirements(("paddlepaddle", "x2paddle"))
|
511 |
+
import x2paddle
|
512 |
+
from x2paddle.convert import pytorch2paddle
|
513 |
+
|
514 |
+
LOGGER.info(f"\n{prefix} starting export with X2Paddle {x2paddle.__version__}...")
|
515 |
+
f = str(file).replace(".pt", f"_paddle_model{os.sep}")
|
516 |
+
|
517 |
+
pytorch2paddle(module=model, save_dir=f, jit_type="trace", input_examples=[im]) # export
|
518 |
+
yaml_save(Path(f) / file.with_suffix(".yaml").name, metadata) # add metadata.yaml
|
519 |
+
return f, None
|
520 |
+
|
521 |
+
|
522 |
+
@try_export
|
523 |
+
def export_coreml(model, im, file, int8, half, nms, mlmodel, prefix=colorstr("CoreML:")):
|
524 |
+
"""
|
525 |
+
Export a YOLOv5 model to CoreML format with optional NMS, INT8, and FP16 support.
|
526 |
+
|
527 |
+
Args:
|
528 |
+
model (torch.nn.Module): The YOLOv5 model to be exported.
|
529 |
+
im (torch.Tensor): Example input tensor to trace the model.
|
530 |
+
file (pathlib.Path): Path object where the CoreML model will be saved.
|
531 |
+
int8 (bool): Flag indicating whether to use INT8 quantization (default is False).
|
532 |
+
half (bool): Flag indicating whether to use FP16 quantization (default is False).
|
533 |
+
nms (bool): Flag indicating whether to include Non-Maximum Suppression (default is False).
|
534 |
+
mlmodel (bool): Flag indicating whether to export as older *.mlmodel format (default is False).
|
535 |
+
prefix (str): Prefix string for logging purposes (default is 'CoreML:').
|
536 |
+
|
537 |
+
Returns:
|
538 |
+
tuple[pathlib.Path | None, None]: The path to the saved CoreML model file, or (None, None) if there is an error.
|
539 |
+
|
540 |
+
Notes:
|
541 |
+
The exported CoreML model will be saved with a .mlmodel extension.
|
542 |
+
Quantization is supported only on macOS.
|
543 |
+
|
544 |
+
Example:
|
545 |
+
```python
|
546 |
+
from pathlib import Path
|
547 |
+
import torch
|
548 |
+
from models.yolo import Model
|
549 |
+
model = Model(cfg, ch=3, nc=80)
|
550 |
+
im = torch.randn(1, 3, 640, 640)
|
551 |
+
file = Path("yolov5s_coreml")
|
552 |
+
export_coreml(model, im, file, int8=False, half=False, nms=True, mlmodel=False)
|
553 |
+
```
|
554 |
+
"""
|
555 |
+
check_requirements("coremltools")
|
556 |
+
import coremltools as ct
|
557 |
+
|
558 |
+
LOGGER.info(f"\n{prefix} starting export with coremltools {ct.__version__}...")
|
559 |
+
if mlmodel:
|
560 |
+
f = file.with_suffix(".mlmodel")
|
561 |
+
convert_to = "neuralnetwork"
|
562 |
+
precision = None
|
563 |
+
else:
|
564 |
+
f = file.with_suffix(".mlpackage")
|
565 |
+
convert_to = "mlprogram"
|
566 |
+
if half:
|
567 |
+
precision = ct.precision.FLOAT16
|
568 |
+
else:
|
569 |
+
precision = ct.precision.FLOAT32
|
570 |
+
|
571 |
+
if nms:
|
572 |
+
model = iOSModel(model, im)
|
573 |
+
ts = torch.jit.trace(model, im, strict=False) # TorchScript model
|
574 |
+
ct_model = ct.convert(
|
575 |
+
ts,
|
576 |
+
inputs=[ct.ImageType("image", shape=im.shape, scale=1 / 255, bias=[0, 0, 0])],
|
577 |
+
convert_to=convert_to,
|
578 |
+
compute_precision=precision,
|
579 |
+
)
|
580 |
+
bits, mode = (8, "kmeans") if int8 else (16, "linear") if half else (32, None)
|
581 |
+
if bits < 32:
|
582 |
+
if mlmodel:
|
583 |
+
with warnings.catch_warnings():
|
584 |
+
warnings.filterwarnings(
|
585 |
+
"ignore", category=DeprecationWarning
|
586 |
+
) # suppress numpy==1.20 float warning, fixed in coremltools==7.0
|
587 |
+
ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
|
588 |
+
elif bits == 8:
|
589 |
+
op_config = ct.optimize.coreml.OpPalettizerConfig(mode=mode, nbits=bits, weight_threshold=512)
|
590 |
+
config = ct.optimize.coreml.OptimizationConfig(global_config=op_config)
|
591 |
+
ct_model = ct.optimize.coreml.palettize_weights(ct_model, config)
|
592 |
+
ct_model.save(f)
|
593 |
+
return f, ct_model
|
594 |
+
|
595 |
+
|
596 |
+
@try_export
|
597 |
+
def export_engine(model, im, file, half, dynamic, simplify, workspace=4, verbose=False, prefix=colorstr("TensorRT:")):
|
598 |
+
"""
|
599 |
+
Export a YOLOv5 model to TensorRT engine format, requiring GPU and TensorRT>=7.0.0.
|
600 |
+
|
601 |
+
Args:
|
602 |
+
model (torch.nn.Module): YOLOv5 model to be exported.
|
603 |
+
im (torch.Tensor): Input tensor of shape (B, C, H, W).
|
604 |
+
file (pathlib.Path): Path to save the exported model.
|
605 |
+
half (bool): Set to True to export with FP16 precision.
|
606 |
+
dynamic (bool): Set to True to enable dynamic input shapes.
|
607 |
+
simplify (bool): Set to True to simplify the model during export.
|
608 |
+
workspace (int): Workspace size in GB (default is 4).
|
609 |
+
verbose (bool): Set to True for verbose logging output.
|
610 |
+
prefix (str): Log message prefix.
|
611 |
+
|
612 |
+
Returns:
|
613 |
+
(pathlib.Path, None): Tuple containing the path to the exported model and None.
|
614 |
+
|
615 |
+
Raises:
|
616 |
+
AssertionError: If executed on CPU instead of GPU.
|
617 |
+
RuntimeError: If there is a failure in parsing the ONNX file.
|
618 |
+
|
619 |
+
Example:
|
620 |
+
```python
|
621 |
+
from ultralytics import YOLOv5
|
622 |
+
import torch
|
623 |
+
from pathlib import Path
|
624 |
+
|
625 |
+
model = YOLOv5('yolov5s.pt') # Load a pre-trained YOLOv5 model
|
626 |
+
input_tensor = torch.randn(1, 3, 640, 640).cuda() # example input tensor on GPU
|
627 |
+
export_path = Path('yolov5s.engine') # export destination
|
628 |
+
|
629 |
+
export_engine(model.model, input_tensor, export_path, half=True, dynamic=True, simplify=True, workspace=8, verbose=True)
|
630 |
+
```
|
631 |
+
"""
|
632 |
+
assert im.device.type != "cpu", "export running on CPU but must be on GPU, i.e. `python export.py --device 0`"
|
633 |
+
try:
|
634 |
+
import tensorrt as trt
|
635 |
+
except Exception:
|
636 |
+
if platform.system() == "Linux":
|
637 |
+
check_requirements("nvidia-tensorrt", cmds="-U --index-url https://pypi.ngc.nvidia.com")
|
638 |
+
import tensorrt as trt
|
639 |
+
|
640 |
+
if trt.__version__[0] == "7": # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
|
641 |
+
grid = model.model[-1].anchor_grid
|
642 |
+
model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
|
643 |
+
export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
|
644 |
+
model.model[-1].anchor_grid = grid
|
645 |
+
else: # TensorRT >= 8
|
646 |
+
check_version(trt.__version__, "8.0.0", hard=True) # require tensorrt>=8.0.0
|
647 |
+
export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
|
648 |
+
onnx = file.with_suffix(".onnx")
|
649 |
+
|
650 |
+
LOGGER.info(f"\n{prefix} starting export with TensorRT {trt.__version__}...")
|
651 |
+
is_trt10 = int(trt.__version__.split(".")[0]) >= 10 # is TensorRT >= 10
|
652 |
+
assert onnx.exists(), f"failed to export ONNX file: {onnx}"
|
653 |
+
f = file.with_suffix(".engine") # TensorRT engine file
|
654 |
+
logger = trt.Logger(trt.Logger.INFO)
|
655 |
+
if verbose:
|
656 |
+
logger.min_severity = trt.Logger.Severity.VERBOSE
|
657 |
+
|
658 |
+
builder = trt.Builder(logger)
|
659 |
+
config = builder.create_builder_config()
|
660 |
+
if is_trt10:
|
661 |
+
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30)
|
662 |
+
else: # TensorRT versions 7, 8
|
663 |
+
config.max_workspace_size = workspace * 1 << 30
|
664 |
+
flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
|
665 |
+
network = builder.create_network(flag)
|
666 |
+
parser = trt.OnnxParser(network, logger)
|
667 |
+
if not parser.parse_from_file(str(onnx)):
|
668 |
+
raise RuntimeError(f"failed to load ONNX file: {onnx}")
|
669 |
+
|
670 |
+
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
671 |
+
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
672 |
+
for inp in inputs:
|
673 |
+
LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
|
674 |
+
for out in outputs:
|
675 |
+
LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
|
676 |
+
|
677 |
+
if dynamic:
|
678 |
+
if im.shape[0] <= 1:
|
679 |
+
LOGGER.warning(f"{prefix} WARNING ⚠️ --dynamic model requires maximum --batch-size argument")
|
680 |
+
profile = builder.create_optimization_profile()
|
681 |
+
for inp in inputs:
|
682 |
+
profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape)
|
683 |
+
config.add_optimization_profile(profile)
|
684 |
+
|
685 |
+
LOGGER.info(f"{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine as {f}")
|
686 |
+
if builder.platform_has_fast_fp16 and half:
|
687 |
+
config.set_flag(trt.BuilderFlag.FP16)
|
688 |
+
|
689 |
+
build = builder.build_serialized_network if is_trt10 else builder.build_engine
|
690 |
+
with build(network, config) as engine, open(f, "wb") as t:
|
691 |
+
t.write(engine if is_trt10 else engine.serialize())
|
692 |
+
return f, None
|
693 |
+
|
694 |
+
|
695 |
+
@try_export
|
696 |
+
def export_saved_model(
|
697 |
+
model,
|
698 |
+
im,
|
699 |
+
file,
|
700 |
+
dynamic,
|
701 |
+
tf_nms=False,
|
702 |
+
agnostic_nms=False,
|
703 |
+
topk_per_class=100,
|
704 |
+
topk_all=100,
|
705 |
+
iou_thres=0.45,
|
706 |
+
conf_thres=0.25,
|
707 |
+
keras=False,
|
708 |
+
prefix=colorstr("TensorFlow SavedModel:"),
|
709 |
+
):
|
710 |
+
"""
|
711 |
+
Export a YOLOv5 model to the TensorFlow SavedModel format, supporting dynamic axes and non-maximum suppression
|
712 |
+
(NMS).
|
713 |
+
|
714 |
+
Args:
|
715 |
+
model (torch.nn.Module): The PyTorch model to convert.
|
716 |
+
im (torch.Tensor): Sample input tensor with shape (B, C, H, W) for tracing.
|
717 |
+
file (pathlib.Path): File path to save the exported model.
|
718 |
+
dynamic (bool): Flag to indicate whether dynamic axes should be used.
|
719 |
+
tf_nms (bool, optional): Enable TensorFlow non-maximum suppression (NMS). Default is False.
|
720 |
+
agnostic_nms (bool, optional): Enable class-agnostic NMS. Default is False.
|
721 |
+
topk_per_class (int, optional): Top K detections per class to keep before applying NMS. Default is 100.
|
722 |
+
topk_all (int, optional): Top K detections across all classes to keep before applying NMS. Default is 100.
|
723 |
+
iou_thres (float, optional): IoU threshold for NMS. Default is 0.45.
|
724 |
+
conf_thres (float, optional): Confidence threshold for detections. Default is 0.25.
|
725 |
+
keras (bool, optional): Save the model in Keras format if True. Default is False.
|
726 |
+
prefix (str, optional): Prefix for logging messages. Default is "TensorFlow SavedModel:".
|
727 |
+
|
728 |
+
Returns:
|
729 |
+
tuple[str, tf.keras.Model | None]: A tuple containing the path to the saved model folder and the Keras model instance,
|
730 |
+
or None if TensorFlow export fails.
|
731 |
+
|
732 |
+
Notes:
|
733 |
+
- The method supports TensorFlow versions up to 2.15.1.
|
734 |
+
- TensorFlow NMS may not be supported in older TensorFlow versions.
|
735 |
+
- If the TensorFlow version exceeds 2.13.1, it might cause issues when exporting to TFLite.
|
736 |
+
Refer to: https://github.com/ultralytics/yolov5/issues/12489
|
737 |
+
|
738 |
+
Example:
|
739 |
+
```python
|
740 |
+
model, im = ... # Initialize your PyTorch model and input tensor
|
741 |
+
export_saved_model(model, im, Path("yolov5_saved_model"), dynamic=True)
|
742 |
+
```
|
743 |
+
"""
|
744 |
+
# YOLOv5 TensorFlow SavedModel export
|
745 |
+
try:
|
746 |
+
import tensorflow as tf
|
747 |
+
except Exception:
|
748 |
+
check_requirements(f"tensorflow{'' if torch.cuda.is_available() else '-macos' if MACOS else '-cpu'}<=2.15.1")
|
749 |
+
|
750 |
+
import tensorflow as tf
|
751 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
752 |
+
|
753 |
+
from models.tf import TFModel
|
754 |
+
|
755 |
+
LOGGER.info(f"\n{prefix} starting export with tensorflow {tf.__version__}...")
|
756 |
+
if tf.__version__ > "2.13.1":
|
757 |
+
helper_url = "https://github.com/ultralytics/yolov5/issues/12489"
|
758 |
+
LOGGER.info(
|
759 |
+
f"WARNING ⚠️ using Tensorflow {tf.__version__} > 2.13.1 might cause issue when exporting the model to tflite {helper_url}"
|
760 |
+
) # handling issue https://github.com/ultralytics/yolov5/issues/12489
|
761 |
+
f = str(file).replace(".pt", "_saved_model")
|
762 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
763 |
+
|
764 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
765 |
+
im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
|
766 |
+
_ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
767 |
+
inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
|
768 |
+
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
769 |
+
keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
|
770 |
+
keras_model.trainable = False
|
771 |
+
keras_model.summary()
|
772 |
+
if keras:
|
773 |
+
keras_model.save(f, save_format="tf")
|
774 |
+
else:
|
775 |
+
spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
|
776 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
777 |
+
m = m.get_concrete_function(spec)
|
778 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
779 |
+
tfm = tf.Module()
|
780 |
+
tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x), [spec])
|
781 |
+
tfm.__call__(im)
|
782 |
+
tf.saved_model.save(
|
783 |
+
tfm,
|
784 |
+
f,
|
785 |
+
options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
|
786 |
+
if check_version(tf.__version__, "2.6")
|
787 |
+
else tf.saved_model.SaveOptions(),
|
788 |
+
)
|
789 |
+
return f, keras_model
|
790 |
+
|
791 |
+
|
792 |
+
@try_export
|
793 |
+
def export_pb(keras_model, file, prefix=colorstr("TensorFlow GraphDef:")):
|
794 |
+
"""
|
795 |
+
Export YOLOv5 model to TensorFlow GraphDef (*.pb) format.
|
796 |
+
|
797 |
+
Args:
|
798 |
+
keras_model (tf.keras.Model): The Keras model to be converted.
|
799 |
+
file (Path): The output file path where the GraphDef will be saved.
|
800 |
+
prefix (str): Optional prefix string; defaults to a colored string indicating TensorFlow GraphDef export status.
|
801 |
+
|
802 |
+
Returns:
|
803 |
+
Tuple[Path, None]: The file path where the GraphDef model was saved and a None placeholder.
|
804 |
+
|
805 |
+
Notes:
|
806 |
+
For more details, refer to the guide on frozen graphs: https://github.com/leimao/Frozen_Graph_TensorFlow
|
807 |
+
|
808 |
+
Example:
|
809 |
+
```python
|
810 |
+
from pathlib import Path
|
811 |
+
keras_model = ... # assume an existing Keras model
|
812 |
+
file = Path("model.pb")
|
813 |
+
export_pb(keras_model, file)
|
814 |
+
```
|
815 |
+
"""
|
816 |
+
import tensorflow as tf
|
817 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
818 |
+
|
819 |
+
LOGGER.info(f"\n{prefix} starting export with tensorflow {tf.__version__}...")
|
820 |
+
f = file.with_suffix(".pb")
|
821 |
+
|
822 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
823 |
+
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
|
824 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
825 |
+
frozen_func.graph.as_graph_def()
|
826 |
+
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
|
827 |
+
return f, None
|
828 |
+
|
829 |
+
|
830 |
+
@try_export
|
831 |
+
def export_tflite(
|
832 |
+
keras_model, im, file, int8, per_tensor, data, nms, agnostic_nms, prefix=colorstr("TensorFlow Lite:")
|
833 |
+
):
|
834 |
+
# YOLOv5 TensorFlow Lite export
|
835 |
+
"""
|
836 |
+
Export a YOLOv5 model to TensorFlow Lite format with optional INT8 quantization and NMS support.
|
837 |
+
|
838 |
+
Args:
|
839 |
+
keras_model (tf.keras.Model): The Keras model to be exported.
|
840 |
+
im (torch.Tensor): An input image tensor for normalization and model tracing.
|
841 |
+
file (Path): The file path to save the TensorFlow Lite model.
|
842 |
+
int8 (bool): Enables INT8 quantization if True.
|
843 |
+
per_tensor (bool): If True, disables per-channel quantization.
|
844 |
+
data (str): Path to the dataset for representative dataset generation in INT8 quantization.
|
845 |
+
nms (bool): Enables Non-Maximum Suppression (NMS) if True.
|
846 |
+
agnostic_nms (bool): Enables class-agnostic NMS if True.
|
847 |
+
prefix (str): Prefix for log messages.
|
848 |
+
|
849 |
+
Returns:
|
850 |
+
(str | None, tflite.Model | None): The file path of the exported TFLite model and the TFLite model instance, or None
|
851 |
+
if the export failed.
|
852 |
+
|
853 |
+
Example:
|
854 |
+
```python
|
855 |
+
from pathlib import Path
|
856 |
+
import torch
|
857 |
+
import tensorflow as tf
|
858 |
+
|
859 |
+
# Load a Keras model wrapping a YOLOv5 model
|
860 |
+
keras_model = tf.keras.models.load_model('path/to/keras_model.h5')
|
861 |
+
|
862 |
+
# Example input tensor
|
863 |
+
im = torch.zeros(1, 3, 640, 640)
|
864 |
+
|
865 |
+
# Export the model
|
866 |
+
export_tflite(keras_model, im, Path('model.tflite'), int8=True, per_tensor=False, data='data/coco.yaml',
|
867 |
+
nms=True, agnostic_nms=False)
|
868 |
+
```
|
869 |
+
|
870 |
+
Notes:
|
871 |
+
- Ensure TensorFlow and TensorFlow Lite dependencies are installed.
|
872 |
+
- INT8 quantization requires a representative dataset to achieve optimal accuracy.
|
873 |
+
- TensorFlow Lite models are suitable for efficient inference on mobile and edge devices.
|
874 |
+
"""
|
875 |
+
import tensorflow as tf
|
876 |
+
|
877 |
+
LOGGER.info(f"\n{prefix} starting export with tensorflow {tf.__version__}...")
|
878 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
879 |
+
f = str(file).replace(".pt", "-fp16.tflite")
|
880 |
+
|
881 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
|
882 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
|
883 |
+
converter.target_spec.supported_types = [tf.float16]
|
884 |
+
converter.optimizations = [tf.lite.Optimize.DEFAULT]
|
885 |
+
if int8:
|
886 |
+
from models.tf import representative_dataset_gen
|
887 |
+
|
888 |
+
dataset = LoadImages(check_dataset(check_yaml(data))["train"], img_size=imgsz, auto=False)
|
889 |
+
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
|
890 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
891 |
+
converter.target_spec.supported_types = []
|
892 |
+
converter.inference_input_type = tf.uint8 # or tf.int8
|
893 |
+
converter.inference_output_type = tf.uint8 # or tf.int8
|
894 |
+
converter.experimental_new_quantizer = True
|
895 |
+
if per_tensor:
|
896 |
+
converter._experimental_disable_per_channel = True
|
897 |
+
f = str(file).replace(".pt", "-int8.tflite")
|
898 |
+
if nms or agnostic_nms:
|
899 |
+
converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
|
900 |
+
|
901 |
+
tflite_model = converter.convert()
|
902 |
+
open(f, "wb").write(tflite_model)
|
903 |
+
return f, None
|
904 |
+
|
905 |
+
|
906 |
+
@try_export
|
907 |
+
def export_edgetpu(file, prefix=colorstr("Edge TPU:")):
|
908 |
+
"""
|
909 |
+
Exports a YOLOv5 model to Edge TPU compatible TFLite format; requires Linux and Edge TPU compiler.
|
910 |
+
|
911 |
+
Args:
|
912 |
+
file (Path): Path to the YOLOv5 model file to be exported (.pt format).
|
913 |
+
prefix (str, optional): Prefix for logging messages. Defaults to colorstr("Edge TPU:").
|
914 |
+
|
915 |
+
Returns:
|
916 |
+
tuple[Path, None]: Path to the exported Edge TPU compatible TFLite model, None.
|
917 |
+
|
918 |
+
Raises:
|
919 |
+
AssertionError: If the system is not Linux.
|
920 |
+
subprocess.CalledProcessError: If any subprocess call to install or run the Edge TPU compiler fails.
|
921 |
+
|
922 |
+
Notes:
|
923 |
+
To use this function, ensure you have the Edge TPU compiler installed on your Linux system. You can find
|
924 |
+
installation instructions here: https://coral.ai/docs/edgetpu/compiler/.
|
925 |
+
|
926 |
+
Example:
|
927 |
+
```python
|
928 |
+
from pathlib import Path
|
929 |
+
file = Path('yolov5s.pt')
|
930 |
+
export_edgetpu(file)
|
931 |
+
```
|
932 |
+
"""
|
933 |
+
cmd = "edgetpu_compiler --version"
|
934 |
+
help_url = "https://coral.ai/docs/edgetpu/compiler/"
|
935 |
+
assert platform.system() == "Linux", f"export only supported on Linux. See {help_url}"
|
936 |
+
if subprocess.run(f"{cmd} > /dev/null 2>&1", shell=True).returncode != 0:
|
937 |
+
LOGGER.info(f"\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}")
|
938 |
+
sudo = subprocess.run("sudo --version >/dev/null", shell=True).returncode == 0 # sudo installed on system
|
939 |
+
for c in (
|
940 |
+
"curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -",
|
941 |
+
'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
|
942 |
+
"sudo apt-get update",
|
943 |
+
"sudo apt-get install edgetpu-compiler",
|
944 |
+
):
|
945 |
+
subprocess.run(c if sudo else c.replace("sudo ", ""), shell=True, check=True)
|
946 |
+
ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
|
947 |
+
|
948 |
+
LOGGER.info(f"\n{prefix} starting export with Edge TPU compiler {ver}...")
|
949 |
+
f = str(file).replace(".pt", "-int8_edgetpu.tflite") # Edge TPU model
|
950 |
+
f_tfl = str(file).replace(".pt", "-int8.tflite") # TFLite model
|
951 |
+
|
952 |
+
subprocess.run(
|
953 |
+
[
|
954 |
+
"edgetpu_compiler",
|
955 |
+
"-s",
|
956 |
+
"-d",
|
957 |
+
"-k",
|
958 |
+
"10",
|
959 |
+
"--out_dir",
|
960 |
+
str(file.parent),
|
961 |
+
f_tfl,
|
962 |
+
],
|
963 |
+
check=True,
|
964 |
+
)
|
965 |
+
return f, None
|
966 |
+
|
967 |
+
|
968 |
+
@try_export
|
969 |
+
def export_tfjs(file, int8, prefix=colorstr("TensorFlow.js:")):
|
970 |
+
"""
|
971 |
+
Convert a YOLOv5 model to TensorFlow.js format with optional uint8 quantization.
|
972 |
+
|
973 |
+
Args:
|
974 |
+
file (Path): Path to the YOLOv5 model file to be converted, typically having a ".pt" or ".onnx" extension.
|
975 |
+
int8 (bool): If True, applies uint8 quantization during the conversion process.
|
976 |
+
prefix (str): Optional prefix for logging messages, default is 'TensorFlow.js:' with color formatting.
|
977 |
+
|
978 |
+
Returns:
|
979 |
+
(str, None): Tuple containing the output directory path as a string and None.
|
980 |
+
|
981 |
+
Notes:
|
982 |
+
- This function requires the `tensorflowjs` package. Install it using:
|
983 |
+
```shell
|
984 |
+
pip install tensorflowjs
|
985 |
+
```
|
986 |
+
- The converted TensorFlow.js model will be saved in a directory with the "_web_model" suffix appended to the original file name.
|
987 |
+
- The conversion involves running shell commands that invoke the TensorFlow.js converter tool.
|
988 |
+
|
989 |
+
Example:
|
990 |
+
```python
|
991 |
+
from pathlib import Path
|
992 |
+
file = Path('yolov5.onnx')
|
993 |
+
export_tfjs(file, int8=False)
|
994 |
+
```
|
995 |
+
"""
|
996 |
+
check_requirements("tensorflowjs")
|
997 |
+
import tensorflowjs as tfjs
|
998 |
+
|
999 |
+
LOGGER.info(f"\n{prefix} starting export with tensorflowjs {tfjs.__version__}...")
|
1000 |
+
f = str(file).replace(".pt", "_web_model") # js dir
|
1001 |
+
f_pb = file.with_suffix(".pb") # *.pb path
|
1002 |
+
f_json = f"{f}/model.json" # *.json path
|
1003 |
+
|
1004 |
+
args = [
|
1005 |
+
"tensorflowjs_converter",
|
1006 |
+
"--input_format=tf_frozen_model",
|
1007 |
+
"--quantize_uint8" if int8 else "",
|
1008 |
+
"--output_node_names=Identity,Identity_1,Identity_2,Identity_3",
|
1009 |
+
str(f_pb),
|
1010 |
+
f,
|
1011 |
+
]
|
1012 |
+
subprocess.run([arg for arg in args if arg], check=True)
|
1013 |
+
|
1014 |
+
json = Path(f_json).read_text()
|
1015 |
+
with open(f_json, "w") as j: # sort JSON Identity_* in ascending order
|
1016 |
+
subst = re.sub(
|
1017 |
+
r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
|
1018 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
1019 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
1020 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}}}',
|
1021 |
+
r'{"outputs": {"Identity": {"name": "Identity"}, '
|
1022 |
+
r'"Identity_1": {"name": "Identity_1"}, '
|
1023 |
+
r'"Identity_2": {"name": "Identity_2"}, '
|
1024 |
+
r'"Identity_3": {"name": "Identity_3"}}}',
|
1025 |
+
json,
|
1026 |
+
)
|
1027 |
+
j.write(subst)
|
1028 |
+
return f, None
|
1029 |
+
|
1030 |
+
|
1031 |
+
def add_tflite_metadata(file, metadata, num_outputs):
|
1032 |
+
"""
|
1033 |
+
Adds metadata to a TensorFlow Lite (TFLite) model file, supporting multiple outputs according to TensorFlow
|
1034 |
+
guidelines.
|
1035 |
+
|
1036 |
+
Args:
|
1037 |
+
file (str): Path to the TFLite model file to which metadata will be added.
|
1038 |
+
metadata (dict): Metadata information to be added to the model, structured as required by the TFLite metadata schema.
|
1039 |
+
Common keys include "name", "description", "version", "author", and "license".
|
1040 |
+
num_outputs (int): Number of output tensors the model has, used to configure the metadata properly.
|
1041 |
+
|
1042 |
+
Returns:
|
1043 |
+
None
|
1044 |
+
|
1045 |
+
Example:
|
1046 |
+
```python
|
1047 |
+
metadata = {
|
1048 |
+
"name": "yolov5",
|
1049 |
+
"description": "YOLOv5 object detection model",
|
1050 |
+
"version": "1.0",
|
1051 |
+
"author": "Ultralytics",
|
1052 |
+
"license": "Apache License 2.0"
|
1053 |
+
}
|
1054 |
+
add_tflite_metadata("model.tflite", metadata, num_outputs=4)
|
1055 |
+
```
|
1056 |
+
|
1057 |
+
Note:
|
1058 |
+
TFLite metadata can include information such as model name, version, author, and other relevant details.
|
1059 |
+
For more details on the structure of the metadata, refer to TensorFlow Lite
|
1060 |
+
[metadata guidelines](https://www.tensorflow.org/lite/models/convert/metadata).
|
1061 |
+
"""
|
1062 |
+
with contextlib.suppress(ImportError):
|
1063 |
+
# check_requirements('tflite_support')
|
1064 |
+
from tflite_support import flatbuffers
|
1065 |
+
from tflite_support import metadata as _metadata
|
1066 |
+
from tflite_support import metadata_schema_py_generated as _metadata_fb
|
1067 |
+
|
1068 |
+
tmp_file = Path("/tmp/meta.txt")
|
1069 |
+
with open(tmp_file, "w") as meta_f:
|
1070 |
+
meta_f.write(str(metadata))
|
1071 |
+
|
1072 |
+
model_meta = _metadata_fb.ModelMetadataT()
|
1073 |
+
label_file = _metadata_fb.AssociatedFileT()
|
1074 |
+
label_file.name = tmp_file.name
|
1075 |
+
model_meta.associatedFiles = [label_file]
|
1076 |
+
|
1077 |
+
subgraph = _metadata_fb.SubGraphMetadataT()
|
1078 |
+
subgraph.inputTensorMetadata = [_metadata_fb.TensorMetadataT()]
|
1079 |
+
subgraph.outputTensorMetadata = [_metadata_fb.TensorMetadataT()] * num_outputs
|
1080 |
+
model_meta.subgraphMetadata = [subgraph]
|
1081 |
+
|
1082 |
+
b = flatbuffers.Builder(0)
|
1083 |
+
b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)
|
1084 |
+
metadata_buf = b.Output()
|
1085 |
+
|
1086 |
+
populator = _metadata.MetadataPopulator.with_model_file(file)
|
1087 |
+
populator.load_metadata_buffer(metadata_buf)
|
1088 |
+
populator.load_associated_files([str(tmp_file)])
|
1089 |
+
populator.populate()
|
1090 |
+
tmp_file.unlink()
|
1091 |
+
|
1092 |
+
|
1093 |
+
def pipeline_coreml(model, im, file, names, y, mlmodel, prefix=colorstr("CoreML Pipeline:")):
|
1094 |
+
"""
|
1095 |
+
Convert a PyTorch YOLOv5 model to CoreML format with Non-Maximum Suppression (NMS), handling different input/output
|
1096 |
+
shapes, and saving the model.
|
1097 |
+
|
1098 |
+
Args:
|
1099 |
+
model (torch.nn.Module): The YOLOv5 PyTorch model to be converted.
|
1100 |
+
im (torch.Tensor): Example input tensor with shape (N, C, H, W), where N is the batch size, C is the number of channels,
|
1101 |
+
H is the height, and W is the width.
|
1102 |
+
file (Path): Path to save the converted CoreML model.
|
1103 |
+
names (dict[int, str]): Dictionary mapping class indices to class names.
|
1104 |
+
y (torch.Tensor): Output tensor from the PyTorch model's forward pass.
|
1105 |
+
mlmodel (bool): Flag indicating whether to export as older *.mlmodel format (default is False).
|
1106 |
+
prefix (str): Custom prefix for logging messages.
|
1107 |
+
|
1108 |
+
Returns:
|
1109 |
+
(Path): Path to the saved CoreML model (.mlmodel).
|
1110 |
+
|
1111 |
+
Raises:
|
1112 |
+
AssertionError: If the number of class names does not match the number of classes in the model.
|
1113 |
+
|
1114 |
+
Notes:
|
1115 |
+
- This function requires `coremltools` to be installed.
|
1116 |
+
- Running this function on a non-macOS environment might not support some features.
|
1117 |
+
- Flexible input shapes and additional NMS options can be customized within the function.
|
1118 |
+
|
1119 |
+
Examples:
|
1120 |
+
```python
|
1121 |
+
from pathlib import Path
|
1122 |
+
import torch
|
1123 |
+
|
1124 |
+
model = torch.load('yolov5s.pt') # Load YOLOv5 model
|
1125 |
+
im = torch.zeros((1, 3, 640, 640)) # Example input tensor
|
1126 |
+
|
1127 |
+
names = {0: "person", 1: "bicycle", 2: "car", ...} # Define class names
|
1128 |
+
|
1129 |
+
y = model(im) # Perform forward pass to get model output
|
1130 |
+
|
1131 |
+
output_file = Path('yolov5s.mlmodel') # Convert to CoreML
|
1132 |
+
pipeline_coreml(model, im, output_file, names, y)
|
1133 |
+
```
|
1134 |
+
"""
|
1135 |
+
import coremltools as ct
|
1136 |
+
from PIL import Image
|
1137 |
+
|
1138 |
+
if mlmodel:
|
1139 |
+
f = file.with_suffix(".mlmodel") # filename
|
1140 |
+
else:
|
1141 |
+
f = file.with_suffix(".mlpackage") # filename
|
1142 |
+
|
1143 |
+
print(f"{prefix} starting pipeline with coremltools {ct.__version__}...")
|
1144 |
+
batch_size, ch, h, w = list(im.shape) # BCHW
|
1145 |
+
t = time.time()
|
1146 |
+
|
1147 |
+
# YOLOv5 Output shapes
|
1148 |
+
spec = model.get_spec()
|
1149 |
+
out0, out1 = iter(spec.description.output)
|
1150 |
+
if platform.system() == "Darwin":
|
1151 |
+
img = Image.new("RGB", (w, h)) # img(192 width, 320 height)
|
1152 |
+
# img = torch.zeros((*opt.img_size, 3)).numpy() # img size(320,192,3) iDetection
|
1153 |
+
out = model.predict({"image": img})
|
1154 |
+
out0_shape, out1_shape = out[out0.name].shape, out[out1.name].shape
|
1155 |
+
else: # linux and windows can not run model.predict(), get sizes from pytorch output y
|
1156 |
+
s = tuple(y[0].shape)
|
1157 |
+
out0_shape, out1_shape = (s[1], s[2] - 5), (s[1], 4) # (3780, 80), (3780, 4)
|
1158 |
+
|
1159 |
+
# Checks
|
1160 |
+
nx, ny = spec.description.input[0].type.imageType.width, spec.description.input[0].type.imageType.height
|
1161 |
+
na, nc = out0_shape
|
1162 |
+
# na, nc = out0.type.multiArrayType.shape # number anchors, classes
|
1163 |
+
assert len(names) == nc, f"{len(names)} names found for nc={nc}" # check
|
1164 |
+
|
1165 |
+
# Define output shapes (missing)
|
1166 |
+
out0.type.multiArrayType.shape[:] = out0_shape # (3780, 80)
|
1167 |
+
out1.type.multiArrayType.shape[:] = out1_shape # (3780, 4)
|
1168 |
+
# spec.neuralNetwork.preprocessing[0].featureName = '0'
|
1169 |
+
|
1170 |
+
# Flexible input shapes
|
1171 |
+
# from coremltools.models.neural_network import flexible_shape_utils
|
1172 |
+
# s = [] # shapes
|
1173 |
+
# s.append(flexible_shape_utils.NeuralNetworkImageSize(320, 192))
|
1174 |
+
# s.append(flexible_shape_utils.NeuralNetworkImageSize(640, 384)) # (height, width)
|
1175 |
+
# flexible_shape_utils.add_enumerated_image_sizes(spec, feature_name='image', sizes=s)
|
1176 |
+
# r = flexible_shape_utils.NeuralNetworkImageSizeRange() # shape ranges
|
1177 |
+
# r.add_height_range((192, 640))
|
1178 |
+
# r.add_width_range((192, 640))
|
1179 |
+
# flexible_shape_utils.update_image_size_range(spec, feature_name='image', size_range=r)
|
1180 |
+
|
1181 |
+
# Print
|
1182 |
+
print(spec.description)
|
1183 |
+
|
1184 |
+
# Model from spec
|
1185 |
+
weights_dir = None
|
1186 |
+
if mlmodel:
|
1187 |
+
weights_dir = None
|
1188 |
+
else:
|
1189 |
+
weights_dir = str(f / "Data/com.apple.CoreML/weights")
|
1190 |
+
model = ct.models.MLModel(spec, weights_dir=weights_dir)
|
1191 |
+
|
1192 |
+
# 3. Create NMS protobuf
|
1193 |
+
nms_spec = ct.proto.Model_pb2.Model()
|
1194 |
+
nms_spec.specificationVersion = 5
|
1195 |
+
for i in range(2):
|
1196 |
+
decoder_output = model._spec.description.output[i].SerializeToString()
|
1197 |
+
nms_spec.description.input.add()
|
1198 |
+
nms_spec.description.input[i].ParseFromString(decoder_output)
|
1199 |
+
nms_spec.description.output.add()
|
1200 |
+
nms_spec.description.output[i].ParseFromString(decoder_output)
|
1201 |
+
|
1202 |
+
nms_spec.description.output[0].name = "confidence"
|
1203 |
+
nms_spec.description.output[1].name = "coordinates"
|
1204 |
+
|
1205 |
+
output_sizes = [nc, 4]
|
1206 |
+
for i in range(2):
|
1207 |
+
ma_type = nms_spec.description.output[i].type.multiArrayType
|
1208 |
+
ma_type.shapeRange.sizeRanges.add()
|
1209 |
+
ma_type.shapeRange.sizeRanges[0].lowerBound = 0
|
1210 |
+
ma_type.shapeRange.sizeRanges[0].upperBound = -1
|
1211 |
+
ma_type.shapeRange.sizeRanges.add()
|
1212 |
+
ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i]
|
1213 |
+
ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i]
|
1214 |
+
del ma_type.shape[:]
|
1215 |
+
|
1216 |
+
nms = nms_spec.nonMaximumSuppression
|
1217 |
+
nms.confidenceInputFeatureName = out0.name # 1x507x80
|
1218 |
+
nms.coordinatesInputFeatureName = out1.name # 1x507x4
|
1219 |
+
nms.confidenceOutputFeatureName = "confidence"
|
1220 |
+
nms.coordinatesOutputFeatureName = "coordinates"
|
1221 |
+
nms.iouThresholdInputFeatureName = "iouThreshold"
|
1222 |
+
nms.confidenceThresholdInputFeatureName = "confidenceThreshold"
|
1223 |
+
nms.iouThreshold = 0.45
|
1224 |
+
nms.confidenceThreshold = 0.25
|
1225 |
+
nms.pickTop.perClass = True
|
1226 |
+
nms.stringClassLabels.vector.extend(names.values())
|
1227 |
+
nms_model = ct.models.MLModel(nms_spec)
|
1228 |
+
|
1229 |
+
# 4. Pipeline models together
|
1230 |
+
pipeline = ct.models.pipeline.Pipeline(
|
1231 |
+
input_features=[
|
1232 |
+
("image", ct.models.datatypes.Array(3, ny, nx)),
|
1233 |
+
("iouThreshold", ct.models.datatypes.Double()),
|
1234 |
+
("confidenceThreshold", ct.models.datatypes.Double()),
|
1235 |
+
],
|
1236 |
+
output_features=["confidence", "coordinates"],
|
1237 |
+
)
|
1238 |
+
pipeline.add_model(model)
|
1239 |
+
pipeline.add_model(nms_model)
|
1240 |
+
|
1241 |
+
# Correct datatypes
|
1242 |
+
pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString())
|
1243 |
+
pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString())
|
1244 |
+
pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString())
|
1245 |
+
|
1246 |
+
# Update metadata
|
1247 |
+
pipeline.spec.specificationVersion = 5
|
1248 |
+
pipeline.spec.description.metadata.versionString = "https://github.com/ultralytics/yolov5"
|
1249 |
+
pipeline.spec.description.metadata.shortDescription = "https://github.com/ultralytics/yolov5"
|
1250 |
+
pipeline.spec.description.metadata.author = "[email protected]"
|
1251 |
+
pipeline.spec.description.metadata.license = "https://github.com/ultralytics/yolov5/blob/master/LICENSE"
|
1252 |
+
pipeline.spec.description.metadata.userDefined.update(
|
1253 |
+
{
|
1254 |
+
"classes": ",".join(names.values()),
|
1255 |
+
"iou_threshold": str(nms.iouThreshold),
|
1256 |
+
"confidence_threshold": str(nms.confidenceThreshold),
|
1257 |
+
}
|
1258 |
+
)
|
1259 |
+
|
1260 |
+
# Save the model
|
1261 |
+
model = ct.models.MLModel(pipeline.spec, weights_dir=weights_dir)
|
1262 |
+
model.input_description["image"] = "Input image"
|
1263 |
+
model.input_description["iouThreshold"] = f"(optional) IOU Threshold override (default: {nms.iouThreshold})"
|
1264 |
+
model.input_description["confidenceThreshold"] = (
|
1265 |
+
f"(optional) Confidence Threshold override (default: {nms.confidenceThreshold})"
|
1266 |
+
)
|
1267 |
+
model.output_description["confidence"] = 'Boxes × Class confidence (see user-defined metadata "classes")'
|
1268 |
+
model.output_description["coordinates"] = "Boxes × [x, y, width, height] (relative to image size)"
|
1269 |
+
model.save(f) # pipelined
|
1270 |
+
print(f"{prefix} pipeline success ({time.time() - t:.2f}s), saved as {f} ({file_size(f):.1f} MB)")
|
1271 |
+
|
1272 |
+
|
1273 |
+
@smart_inference_mode()
|
1274 |
+
def run(
|
1275 |
+
data=ROOT / "data/coco128.yaml", # 'dataset.yaml path'
|
1276 |
+
weights=ROOT / "yolov5s.pt", # weights path
|
1277 |
+
imgsz=(640, 640), # image (height, width)
|
1278 |
+
batch_size=1, # batch size
|
1279 |
+
device="cpu", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
1280 |
+
include=("torchscript", "onnx"), # include formats
|
1281 |
+
half=False, # FP16 half-precision export
|
1282 |
+
inplace=False, # set YOLOv5 Detect() inplace=True
|
1283 |
+
keras=False, # use Keras
|
1284 |
+
optimize=False, # TorchScript: optimize for mobile
|
1285 |
+
int8=False, # CoreML/TF INT8 quantization
|
1286 |
+
per_tensor=False, # TF per tensor quantization
|
1287 |
+
dynamic=False, # ONNX/TF/TensorRT: dynamic axes
|
1288 |
+
simplify=False, # ONNX: simplify model
|
1289 |
+
mlmodel=False, # CoreML: Export in *.mlmodel format
|
1290 |
+
opset=12, # ONNX: opset version
|
1291 |
+
verbose=False, # TensorRT: verbose log
|
1292 |
+
workspace=4, # TensorRT: workspace size (GB)
|
1293 |
+
nms=False, # TF: add NMS to model
|
1294 |
+
agnostic_nms=False, # TF: add agnostic NMS to model
|
1295 |
+
topk_per_class=100, # TF.js NMS: topk per class to keep
|
1296 |
+
topk_all=100, # TF.js NMS: topk for all classes to keep
|
1297 |
+
iou_thres=0.45, # TF.js NMS: IoU threshold
|
1298 |
+
conf_thres=0.25, # TF.js NMS: confidence threshold
|
1299 |
+
):
|
1300 |
+
"""
|
1301 |
+
Exports a YOLOv5 model to specified formats including ONNX, TensorRT, CoreML, and TensorFlow.
|
1302 |
+
|
1303 |
+
Args:
|
1304 |
+
data (str | Path): Path to the dataset YAML configuration file. Default is 'data/coco128.yaml'.
|
1305 |
+
weights (str | Path): Path to the pretrained model weights file. Default is 'yolov5s.pt'.
|
1306 |
+
imgsz (tuple): Image size as (height, width). Default is (640, 640).
|
1307 |
+
batch_size (int): Batch size for exporting the model. Default is 1.
|
1308 |
+
device (str): Device to run the export on, e.g., '0' for GPU, 'cpu' for CPU. Default is 'cpu'.
|
1309 |
+
include (tuple): Formats to include in the export. Default is ('torchscript', 'onnx').
|
1310 |
+
half (bool): Flag to export model with FP16 half-precision. Default is False.
|
1311 |
+
inplace (bool): Set the YOLOv5 Detect() module inplace=True. Default is False.
|
1312 |
+
keras (bool): Flag to use Keras for TensorFlow SavedModel export. Default is False.
|
1313 |
+
optimize (bool): Optimize TorchScript model for mobile deployment. Default is False.
|
1314 |
+
int8 (bool): Apply INT8 quantization for CoreML or TensorFlow models. Default is False.
|
1315 |
+
per_tensor (bool): Apply per tensor quantization for TensorFlow models. Default is False.
|
1316 |
+
dynamic (bool): Enable dynamic axes for ONNX, TensorFlow, or TensorRT exports. Default is False.
|
1317 |
+
simplify (bool): Simplify the ONNX model during export. Default is False.
|
1318 |
+
opset (int): ONNX opset version. Default is 12.
|
1319 |
+
verbose (bool): Enable verbose logging for TensorRT export. Default is False.
|
1320 |
+
workspace (int): TensorRT workspace size in GB. Default is 4.
|
1321 |
+
nms (bool): Add non-maximum suppression (NMS) to the TensorFlow model. Default is False.
|
1322 |
+
agnostic_nms (bool): Add class-agnostic NMS to the TensorFlow model. Default is False.
|
1323 |
+
topk_per_class (int): Top-K boxes per class to keep for TensorFlow.js NMS. Default is 100.
|
1324 |
+
topk_all (int): Top-K boxes for all classes to keep for TensorFlow.js NMS. Default is 100.
|
1325 |
+
iou_thres (float): IoU threshold for NMS. Default is 0.45.
|
1326 |
+
conf_thres (float): Confidence threshold for NMS. Default is 0.25.
|
1327 |
+
mlmodel (bool): Flag to use *.mlmodel for CoreML export. Default is False.
|
1328 |
+
|
1329 |
+
Returns:
|
1330 |
+
None
|
1331 |
+
|
1332 |
+
Notes:
|
1333 |
+
- Model export is based on the specified formats in the 'include' argument.
|
1334 |
+
- Be cautious of combinations where certain flags are mutually exclusive, such as `--half` and `--dynamic`.
|
1335 |
+
|
1336 |
+
Example:
|
1337 |
+
```python
|
1338 |
+
run(
|
1339 |
+
data="data/coco128.yaml",
|
1340 |
+
weights="yolov5s.pt",
|
1341 |
+
imgsz=(640, 640),
|
1342 |
+
batch_size=1,
|
1343 |
+
device="cpu",
|
1344 |
+
include=("torchscript", "onnx"),
|
1345 |
+
half=False,
|
1346 |
+
inplace=False,
|
1347 |
+
keras=False,
|
1348 |
+
optimize=False,
|
1349 |
+
int8=False,
|
1350 |
+
per_tensor=False,
|
1351 |
+
dynamic=False,
|
1352 |
+
simplify=False,
|
1353 |
+
opset=12,
|
1354 |
+
verbose=False,
|
1355 |
+
mlmodel=False,
|
1356 |
+
workspace=4,
|
1357 |
+
nms=False,
|
1358 |
+
agnostic_nms=False,
|
1359 |
+
topk_per_class=100,
|
1360 |
+
topk_all=100,
|
1361 |
+
iou_thres=0.45,
|
1362 |
+
conf_thres=0.25,
|
1363 |
+
)
|
1364 |
+
```
|
1365 |
+
"""
|
1366 |
+
t = time.time()
|
1367 |
+
include = [x.lower() for x in include] # to lowercase
|
1368 |
+
fmts = tuple(export_formats()["Argument"][1:]) # --include arguments
|
1369 |
+
flags = [x in include for x in fmts]
|
1370 |
+
assert sum(flags) == len(include), f"ERROR: Invalid --include {include}, valid --include arguments are {fmts}"
|
1371 |
+
jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle = flags # export booleans
|
1372 |
+
file = Path(url2file(weights) if str(weights).startswith(("http:/", "https:/")) else weights) # PyTorch weights
|
1373 |
+
|
1374 |
+
# Load PyTorch model
|
1375 |
+
device = select_device(device)
|
1376 |
+
if half:
|
1377 |
+
assert device.type != "cpu" or coreml, "--half only compatible with GPU export, i.e. use --device 0"
|
1378 |
+
assert not dynamic, "--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both"
|
1379 |
+
model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
|
1380 |
+
|
1381 |
+
# Checks
|
1382 |
+
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
|
1383 |
+
if optimize:
|
1384 |
+
assert device.type == "cpu", "--optimize not compatible with cuda devices, i.e. use --device cpu"
|
1385 |
+
|
1386 |
+
# Input
|
1387 |
+
gs = int(max(model.stride)) # grid size (max stride)
|
1388 |
+
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
|
1389 |
+
im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
|
1390 |
+
|
1391 |
+
# Update model
|
1392 |
+
model.eval()
|
1393 |
+
for k, m in model.named_modules():
|
1394 |
+
if isinstance(m, Detect):
|
1395 |
+
m.inplace = inplace
|
1396 |
+
m.dynamic = dynamic
|
1397 |
+
m.export = True
|
1398 |
+
|
1399 |
+
for _ in range(2):
|
1400 |
+
y = model(im) # dry runs
|
1401 |
+
if half and not coreml:
|
1402 |
+
im, model = im.half(), model.half() # to FP16
|
1403 |
+
shape = tuple((y[0] if isinstance(y, tuple) else y).shape) # model output shape
|
1404 |
+
metadata = {"stride": int(max(model.stride)), "names": model.names} # model metadata
|
1405 |
+
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
|
1406 |
+
|
1407 |
+
# Exports
|
1408 |
+
f = [""] * len(fmts) # exported filenames
|
1409 |
+
warnings.filterwarnings(action="ignore", category=torch.jit.TracerWarning) # suppress TracerWarning
|
1410 |
+
if jit: # TorchScript
|
1411 |
+
f[0], _ = export_torchscript(model, im, file, optimize)
|
1412 |
+
if engine: # TensorRT required before ONNX
|
1413 |
+
f[1], _ = export_engine(model, im, file, half, dynamic, simplify, workspace, verbose)
|
1414 |
+
if onnx or xml: # OpenVINO requires ONNX
|
1415 |
+
f[2], _ = export_onnx(model, im, file, opset, dynamic, simplify)
|
1416 |
+
if xml: # OpenVINO
|
1417 |
+
f[3], _ = export_openvino(file, metadata, half, int8, data)
|
1418 |
+
if coreml: # CoreML
|
1419 |
+
f[4], ct_model = export_coreml(model, im, file, int8, half, nms, mlmodel)
|
1420 |
+
if nms:
|
1421 |
+
pipeline_coreml(ct_model, im, file, model.names, y, mlmodel)
|
1422 |
+
if any((saved_model, pb, tflite, edgetpu, tfjs)): # TensorFlow formats
|
1423 |
+
assert not tflite or not tfjs, "TFLite and TF.js models must be exported separately, please pass only one type."
|
1424 |
+
assert not isinstance(model, ClassificationModel), "ClassificationModel export to TF formats not yet supported."
|
1425 |
+
f[5], s_model = export_saved_model(
|
1426 |
+
model.cpu(),
|
1427 |
+
im,
|
1428 |
+
file,
|
1429 |
+
dynamic,
|
1430 |
+
tf_nms=nms or agnostic_nms or tfjs,
|
1431 |
+
agnostic_nms=agnostic_nms or tfjs,
|
1432 |
+
topk_per_class=topk_per_class,
|
1433 |
+
topk_all=topk_all,
|
1434 |
+
iou_thres=iou_thres,
|
1435 |
+
conf_thres=conf_thres,
|
1436 |
+
keras=keras,
|
1437 |
+
)
|
1438 |
+
if pb or tfjs: # pb prerequisite to tfjs
|
1439 |
+
f[6], _ = export_pb(s_model, file)
|
1440 |
+
if tflite or edgetpu:
|
1441 |
+
f[7], _ = export_tflite(
|
1442 |
+
s_model, im, file, int8 or edgetpu, per_tensor, data=data, nms=nms, agnostic_nms=agnostic_nms
|
1443 |
+
)
|
1444 |
+
if edgetpu:
|
1445 |
+
f[8], _ = export_edgetpu(file)
|
1446 |
+
add_tflite_metadata(f[8] or f[7], metadata, num_outputs=len(s_model.outputs))
|
1447 |
+
if tfjs:
|
1448 |
+
f[9], _ = export_tfjs(file, int8)
|
1449 |
+
if paddle: # PaddlePaddle
|
1450 |
+
f[10], _ = export_paddle(model, im, file, metadata)
|
1451 |
+
|
1452 |
+
# Finish
|
1453 |
+
f = [str(x) for x in f if x] # filter out '' and None
|
1454 |
+
if any(f):
|
1455 |
+
cls, det, seg = (isinstance(model, x) for x in (ClassificationModel, DetectionModel, SegmentationModel)) # type
|
1456 |
+
det &= not seg # segmentation models inherit from SegmentationModel(DetectionModel)
|
1457 |
+
dir = Path("segment" if seg else "classify" if cls else "")
|
1458 |
+
h = "--half" if half else "" # --half FP16 inference arg
|
1459 |
+
s = (
|
1460 |
+
"# WARNING ⚠️ ClassificationModel not yet supported for PyTorch Hub AutoShape inference"
|
1461 |
+
if cls
|
1462 |
+
else "# WARNING ⚠️ SegmentationModel not yet supported for PyTorch Hub AutoShape inference"
|
1463 |
+
if seg
|
1464 |
+
else ""
|
1465 |
+
)
|
1466 |
+
LOGGER.info(
|
1467 |
+
f'\nExport complete ({time.time() - t:.1f}s)'
|
1468 |
+
f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
|
1469 |
+
f"\nDetect: python {dir / ('detect.py' if det else 'predict.py')} --weights {f[-1]} {h}"
|
1470 |
+
f"\nValidate: python {dir / 'val.py'} --weights {f[-1]} {h}"
|
1471 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}') {s}"
|
1472 |
+
f'\nVisualize: https://netron.app'
|
1473 |
+
)
|
1474 |
+
return f # return list of exported files/dirs
|
1475 |
+
|
1476 |
+
|
1477 |
+
def parse_opt(known=False):
|
1478 |
+
"""
|
1479 |
+
Parse command-line options for YOLOv5 model export configurations.
|
1480 |
+
|
1481 |
+
Args:
|
1482 |
+
known (bool): If True, uses `argparse.ArgumentParser.parse_known_args`; otherwise, uses `argparse.ArgumentParser.parse_args`.
|
1483 |
+
Default is False.
|
1484 |
+
|
1485 |
+
Returns:
|
1486 |
+
argparse.Namespace: Object containing parsed command-line arguments.
|
1487 |
+
|
1488 |
+
Example:
|
1489 |
+
```python
|
1490 |
+
opts = parse_opt()
|
1491 |
+
print(opts.data)
|
1492 |
+
print(opts.weights)
|
1493 |
+
```
|
1494 |
+
"""
|
1495 |
+
parser = argparse.ArgumentParser()
|
1496 |
+
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
|
1497 |
+
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model.pt path(s)")
|
1498 |
+
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640, 640], help="image (h, w)")
|
1499 |
+
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
|
1500 |
+
parser.add_argument("--device", default="cpu", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
1501 |
+
parser.add_argument("--half", action="store_true", help="FP16 half-precision export")
|
1502 |
+
parser.add_argument("--inplace", action="store_true", help="set YOLOv5 Detect() inplace=True")
|
1503 |
+
parser.add_argument("--keras", action="store_true", help="TF: use Keras")
|
1504 |
+
parser.add_argument("--optimize", action="store_true", help="TorchScript: optimize for mobile")
|
1505 |
+
parser.add_argument("--int8", action="store_true", help="CoreML/TF/OpenVINO INT8 quantization")
|
1506 |
+
parser.add_argument("--per-tensor", action="store_true", help="TF per-tensor quantization")
|
1507 |
+
parser.add_argument("--dynamic", action="store_true", help="ONNX/TF/TensorRT: dynamic axes")
|
1508 |
+
parser.add_argument("--simplify", action="store_true", help="ONNX: simplify model")
|
1509 |
+
parser.add_argument("--mlmodel", action="store_true", help="CoreML: Export in *.mlmodel format")
|
1510 |
+
parser.add_argument("--opset", type=int, default=17, help="ONNX: opset version")
|
1511 |
+
parser.add_argument("--verbose", action="store_true", help="TensorRT: verbose log")
|
1512 |
+
parser.add_argument("--workspace", type=int, default=4, help="TensorRT: workspace size (GB)")
|
1513 |
+
parser.add_argument("--nms", action="store_true", help="TF: add NMS to model")
|
1514 |
+
parser.add_argument("--agnostic-nms", action="store_true", help="TF: add agnostic NMS to model")
|
1515 |
+
parser.add_argument("--topk-per-class", type=int, default=100, help="TF.js NMS: topk per class to keep")
|
1516 |
+
parser.add_argument("--topk-all", type=int, default=100, help="TF.js NMS: topk for all classes to keep")
|
1517 |
+
parser.add_argument("--iou-thres", type=float, default=0.45, help="TF.js NMS: IoU threshold")
|
1518 |
+
parser.add_argument("--conf-thres", type=float, default=0.25, help="TF.js NMS: confidence threshold")
|
1519 |
+
parser.add_argument(
|
1520 |
+
"--include",
|
1521 |
+
nargs="+",
|
1522 |
+
default=["torchscript"],
|
1523 |
+
help="torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle",
|
1524 |
+
)
|
1525 |
+
opt = parser.parse_known_args()[0] if known else parser.parse_args()
|
1526 |
+
print_args(vars(opt))
|
1527 |
+
return opt
|
1528 |
+
|
1529 |
+
|
1530 |
+
def main(opt):
|
1531 |
+
"""Run(**vars(opt)) # Execute the run function with parsed options."""
|
1532 |
+
for opt.weights in opt.weights if isinstance(opt.weights, list) else [opt.weights]:
|
1533 |
+
run(**vars(opt))
|
1534 |
+
|
1535 |
+
|
1536 |
+
if __name__ == "__main__":
|
1537 |
+
opt = parse_opt()
|
1538 |
+
main(opt)
|
yolov5/hubconf.py
ADDED
@@ -0,0 +1,510 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
"""
|
18 |
+
Creates or loads a YOLOv5 model, with options for pretrained weights and model customization.
|
19 |
+
|
20 |
+
Args:
|
21 |
+
name (str): Model name (e.g., 'yolov5s') or path to the model checkpoint (e.g., 'path/to/best.pt').
|
22 |
+
pretrained (bool, optional): If True, loads pretrained weights into the model. Defaults to True.
|
23 |
+
channels (int, optional): Number of input channels the model expects. Defaults to 3.
|
24 |
+
classes (int, optional): Number of classes the model is expected to detect. Defaults to 80.
|
25 |
+
autoshape (bool, optional): If True, applies the YOLOv5 .autoshape() wrapper for various input formats. Defaults to True.
|
26 |
+
verbose (bool, optional): If True, prints detailed information during the model creation/loading process. Defaults to True.
|
27 |
+
device (str | torch.device | None, optional): Device to use for model parameters (e.g., 'cpu', 'cuda'). If None, selects
|
28 |
+
the best available device. Defaults to None.
|
29 |
+
|
30 |
+
Returns:
|
31 |
+
(DetectMultiBackend | AutoShape): The loaded YOLOv5 model, potentially wrapped with AutoShape if specified.
|
32 |
+
|
33 |
+
Examples:
|
34 |
+
```python
|
35 |
+
import torch
|
36 |
+
from ultralytics import _create
|
37 |
+
|
38 |
+
# Load an official YOLOv5s model with pretrained weights
|
39 |
+
model = _create('yolov5s')
|
40 |
+
|
41 |
+
# Load a custom model from a local checkpoint
|
42 |
+
model = _create('path/to/custom_model.pt', pretrained=False)
|
43 |
+
|
44 |
+
# Load a model with specific input channels and classes
|
45 |
+
model = _create('yolov5s', channels=1, classes=10)
|
46 |
+
```
|
47 |
+
|
48 |
+
Notes:
|
49 |
+
For more information on model loading and customization, visit the
|
50 |
+
[YOLOv5 PyTorch Hub Documentation](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading).
|
51 |
+
"""
|
52 |
+
from pathlib import Path
|
53 |
+
|
54 |
+
from models.common import AutoShape, DetectMultiBackend
|
55 |
+
from models.experimental import attempt_load
|
56 |
+
from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
|
57 |
+
from utils.downloads import attempt_download
|
58 |
+
from utils.general import LOGGER, ROOT, check_requirements, intersect_dicts, logging
|
59 |
+
from utils.torch_utils import select_device
|
60 |
+
|
61 |
+
if not verbose:
|
62 |
+
LOGGER.setLevel(logging.WARNING)
|
63 |
+
check_requirements(ROOT / "requirements.txt", exclude=("opencv-python", "tensorboard", "thop"))
|
64 |
+
name = Path(name)
|
65 |
+
path = name.with_suffix(".pt") if name.suffix == "" and not name.is_dir() else name # checkpoint path
|
66 |
+
try:
|
67 |
+
device = select_device(device)
|
68 |
+
if pretrained and channels == 3 and classes == 80:
|
69 |
+
try:
|
70 |
+
model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
|
71 |
+
if autoshape:
|
72 |
+
if model.pt and isinstance(model.model, ClassificationModel):
|
73 |
+
LOGGER.warning(
|
74 |
+
"WARNING ⚠️ YOLOv5 ClassificationModel is not yet AutoShape compatible. "
|
75 |
+
"You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224)."
|
76 |
+
)
|
77 |
+
elif model.pt and isinstance(model.model, SegmentationModel):
|
78 |
+
LOGGER.warning(
|
79 |
+
"WARNING ⚠️ YOLOv5 SegmentationModel is not yet AutoShape compatible. "
|
80 |
+
"You will not be able to run inference with this model."
|
81 |
+
)
|
82 |
+
else:
|
83 |
+
model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
|
84 |
+
except Exception:
|
85 |
+
model = attempt_load(path, device=device, fuse=False) # arbitrary model
|
86 |
+
else:
|
87 |
+
cfg = list((Path(__file__).parent / "models").rglob(f"{path.stem}.yaml"))[0] # model.yaml path
|
88 |
+
model = DetectionModel(cfg, channels, classes) # create model
|
89 |
+
if pretrained:
|
90 |
+
ckpt = torch.load(attempt_download(path), map_location=device) # load
|
91 |
+
csd = ckpt["model"].float().state_dict() # checkpoint state_dict as FP32
|
92 |
+
csd = intersect_dicts(csd, model.state_dict(), exclude=["anchors"]) # intersect
|
93 |
+
model.load_state_dict(csd, strict=False) # load
|
94 |
+
if len(ckpt["model"].names) == classes:
|
95 |
+
model.names = ckpt["model"].names # set class names attribute
|
96 |
+
if not verbose:
|
97 |
+
LOGGER.setLevel(logging.INFO) # reset to default
|
98 |
+
return model.to(device)
|
99 |
+
|
100 |
+
except Exception as e:
|
101 |
+
help_url = "https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading"
|
102 |
+
s = f"{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help."
|
103 |
+
raise Exception(s) from e
|
104 |
+
|
105 |
+
|
106 |
+
def custom(path="path/to/model.pt", autoshape=True, _verbose=True, device=None):
|
107 |
+
"""
|
108 |
+
Loads a custom or local YOLOv5 model from a given path with optional autoshaping and device specification.
|
109 |
+
|
110 |
+
Args:
|
111 |
+
path (str): Path to the custom model file (e.g., 'path/to/model.pt').
|
112 |
+
autoshape (bool): Apply YOLOv5 .autoshape() wrapper to model if True, enabling compatibility with various input
|
113 |
+
types (default is True).
|
114 |
+
_verbose (bool): If True, prints all informational messages to the screen; otherwise, operates silently
|
115 |
+
(default is True).
|
116 |
+
device (str | torch.device | None): Device to load the model on, e.g., 'cpu', 'cuda', torch.device('cuda:0'), etc.
|
117 |
+
(default is None, which automatically selects the best available device).
|
118 |
+
|
119 |
+
Returns:
|
120 |
+
torch.nn.Module: A YOLOv5 model loaded with the specified parameters.
|
121 |
+
|
122 |
+
Notes:
|
123 |
+
For more details on loading models from PyTorch Hub:
|
124 |
+
https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading
|
125 |
+
|
126 |
+
Examples:
|
127 |
+
```python
|
128 |
+
# Load model from a given path with autoshape enabled on the best available device
|
129 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt')
|
130 |
+
|
131 |
+
# Load model from a local path without autoshape on the CPU device
|
132 |
+
model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local', autoshape=False, device='cpu')
|
133 |
+
```
|
134 |
+
"""
|
135 |
+
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
|
136 |
+
|
137 |
+
|
138 |
+
def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
139 |
+
"""
|
140 |
+
Instantiates the YOLOv5-nano model with options for pretraining, input channels, class count, autoshaping,
|
141 |
+
verbosity, and device.
|
142 |
+
|
143 |
+
Args:
|
144 |
+
pretrained (bool): If True, loads pretrained weights into the model. Defaults to True.
|
145 |
+
channels (int): Number of input channels for the model. Defaults to 3.
|
146 |
+
classes (int): Number of classes for object detection. Defaults to 80.
|
147 |
+
autoshape (bool): If True, applies the YOLOv5 .autoshape() wrapper to the model for various formats (file/URI/PIL/
|
148 |
+
cv2/np) and non-maximum suppression (NMS) during inference. Defaults to True.
|
149 |
+
_verbose (bool): If True, prints detailed information to the screen. Defaults to True.
|
150 |
+
device (str | torch.device | None): Specifies the device to use for model computation. If None, uses the best device
|
151 |
+
available (i.e., GPU if available, otherwise CPU). Defaults to None.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
DetectionModel | ClassificationModel | SegmentationModel: The instantiated YOLOv5-nano model, potentially with
|
155 |
+
pretrained weights and autoshaping applied.
|
156 |
+
|
157 |
+
Notes:
|
158 |
+
For further details on loading models from PyTorch Hub, refer to [PyTorch Hub models](https://pytorch.org/hub/
|
159 |
+
ultralytics_yolov5).
|
160 |
+
|
161 |
+
Examples:
|
162 |
+
```python
|
163 |
+
import torch
|
164 |
+
from ultralytics import yolov5n
|
165 |
+
|
166 |
+
# Load the YOLOv5-nano model with defaults
|
167 |
+
model = yolov5n()
|
168 |
+
|
169 |
+
# Load the YOLOv5-nano model with a specific device
|
170 |
+
model = yolov5n(device='cuda')
|
171 |
+
```
|
172 |
+
"""
|
173 |
+
return _create("yolov5n", pretrained, channels, classes, autoshape, _verbose, device)
|
174 |
+
|
175 |
+
|
176 |
+
def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
177 |
+
"""
|
178 |
+
Create a YOLOv5-small (yolov5s) model with options for pretraining, input channels, class count, autoshaping,
|
179 |
+
verbosity, and device configuration.
|
180 |
+
|
181 |
+
Args:
|
182 |
+
pretrained (bool, optional): Flag to load pretrained weights into the model. Defaults to True.
|
183 |
+
channels (int, optional): Number of input channels. Defaults to 3.
|
184 |
+
classes (int, optional): Number of model classes. Defaults to 80.
|
185 |
+
autoshape (bool, optional): Whether to wrap the model with YOLOv5's .autoshape() for handling various input formats.
|
186 |
+
Defaults to True.
|
187 |
+
_verbose (bool, optional): Flag to print detailed information regarding model loading. Defaults to True.
|
188 |
+
device (str | torch.device | None, optional): Device to use for model computation, can be 'cpu', 'cuda', or
|
189 |
+
torch.device instances. If None, automatically selects the best available device. Defaults to None.
|
190 |
+
|
191 |
+
Returns:
|
192 |
+
torch.nn.Module: The YOLOv5-small model configured and loaded according to the specified parameters.
|
193 |
+
|
194 |
+
Example:
|
195 |
+
```python
|
196 |
+
import torch
|
197 |
+
|
198 |
+
# Load the official YOLOv5-small model with pretrained weights
|
199 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
|
200 |
+
|
201 |
+
# Load the YOLOv5-small model from a specific branch
|
202 |
+
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s')
|
203 |
+
|
204 |
+
# Load a custom YOLOv5-small model from a local checkpoint
|
205 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt')
|
206 |
+
|
207 |
+
# Load a local YOLOv5-small model specifying source as local repository
|
208 |
+
model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local')
|
209 |
+
```
|
210 |
+
|
211 |
+
Notes:
|
212 |
+
For more details on model loading and customization, visit
|
213 |
+
the [YOLOv5 PyTorch Hub Documentation](https://pytorch.org/hub/ultralytics_yolov5).
|
214 |
+
"""
|
215 |
+
return _create("yolov5s", pretrained, channels, classes, autoshape, _verbose, device)
|
216 |
+
|
217 |
+
|
218 |
+
def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
219 |
+
"""
|
220 |
+
Instantiates the YOLOv5-medium model with customizable pretraining, channel count, class count, autoshaping,
|
221 |
+
verbosity, and device.
|
222 |
+
|
223 |
+
Args:
|
224 |
+
pretrained (bool, optional): Whether to load pretrained weights into the model. Default is True.
|
225 |
+
channels (int, optional): Number of input channels. Default is 3.
|
226 |
+
classes (int, optional): Number of model classes. Default is 80.
|
227 |
+
autoshape (bool, optional): Apply YOLOv5 .autoshape() wrapper to the model for handling various input formats.
|
228 |
+
Default is True.
|
229 |
+
_verbose (bool, optional): Whether to print detailed information to the screen. Default is True.
|
230 |
+
device (str | torch.device | None, optional): Device specification to use for model parameters (e.g., 'cpu', 'cuda').
|
231 |
+
Default is None.
|
232 |
+
|
233 |
+
Returns:
|
234 |
+
torch.nn.Module: The instantiated YOLOv5-medium model.
|
235 |
+
|
236 |
+
Usage Example:
|
237 |
+
```python
|
238 |
+
import torch
|
239 |
+
|
240 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5m') # Load YOLOv5-medium from Ultralytics repository
|
241 |
+
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5m') # Load from the master branch
|
242 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5m.pt') # Load a custom/local YOLOv5-medium model
|
243 |
+
model = torch.hub.load('.', 'custom', 'yolov5m.pt', source='local') # Load from a local repository
|
244 |
+
```
|
245 |
+
|
246 |
+
For more information, visit https://pytorch.org/hub/ultralytics_yolov5.
|
247 |
+
"""
|
248 |
+
return _create("yolov5m", pretrained, channels, classes, autoshape, _verbose, device)
|
249 |
+
|
250 |
+
|
251 |
+
def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
252 |
+
"""
|
253 |
+
Creates YOLOv5-large model with options for pretraining, channels, classes, autoshaping, verbosity, and device
|
254 |
+
selection.
|
255 |
+
|
256 |
+
Args:
|
257 |
+
pretrained (bool): Load pretrained weights into the model. Default is True.
|
258 |
+
channels (int): Number of input channels. Default is 3.
|
259 |
+
classes (int): Number of model classes. Default is 80.
|
260 |
+
autoshape (bool): Apply YOLOv5 .autoshape() wrapper to model. Default is True.
|
261 |
+
_verbose (bool): Print all information to screen. Default is True.
|
262 |
+
device (str | torch.device | None): Device to use for model parameters, e.g., 'cpu', 'cuda', or a torch.device instance.
|
263 |
+
Default is None.
|
264 |
+
|
265 |
+
Returns:
|
266 |
+
YOLOv5 model (torch.nn.Module): The YOLOv5-large model instantiated with specified configurations and possibly
|
267 |
+
pretrained weights.
|
268 |
+
|
269 |
+
Examples:
|
270 |
+
```python
|
271 |
+
import torch
|
272 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5l')
|
273 |
+
```
|
274 |
+
|
275 |
+
Notes:
|
276 |
+
For additional details, refer to the PyTorch Hub models documentation:
|
277 |
+
https://pytorch.org/hub/ultralytics_yolov5
|
278 |
+
"""
|
279 |
+
return _create("yolov5l", pretrained, channels, classes, autoshape, _verbose, device)
|
280 |
+
|
281 |
+
|
282 |
+
def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
283 |
+
"""
|
284 |
+
Perform object detection using the YOLOv5-xlarge model with options for pretraining, input channels, class count,
|
285 |
+
autoshaping, verbosity, and device specification.
|
286 |
+
|
287 |
+
Args:
|
288 |
+
pretrained (bool): If True, loads pretrained weights into the model. Defaults to True.
|
289 |
+
channels (int): Number of input channels for the model. Defaults to 3.
|
290 |
+
classes (int): Number of model classes for object detection. Defaults to 80.
|
291 |
+
autoshape (bool): If True, applies the YOLOv5 .autoshape() wrapper for handling different input formats. Defaults to
|
292 |
+
True.
|
293 |
+
_verbose (bool): If True, prints detailed information during model loading. Defaults to True.
|
294 |
+
device (str | torch.device | None): Device specification for computing the model, e.g., 'cpu', 'cuda:0', torch.device('cuda').
|
295 |
+
Defaults to None.
|
296 |
+
|
297 |
+
Returns:
|
298 |
+
torch.nn.Module: The YOLOv5-xlarge model loaded with the specified parameters, optionally with pretrained weights and
|
299 |
+
autoshaping applied.
|
300 |
+
|
301 |
+
Example:
|
302 |
+
```python
|
303 |
+
import torch
|
304 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5x')
|
305 |
+
```
|
306 |
+
|
307 |
+
For additional details, refer to the official YOLOv5 PyTorch Hub models documentation:
|
308 |
+
https://pytorch.org/hub/ultralytics_yolov5
|
309 |
+
"""
|
310 |
+
return _create("yolov5x", pretrained, channels, classes, autoshape, _verbose, device)
|
311 |
+
|
312 |
+
|
313 |
+
def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
314 |
+
"""
|
315 |
+
Creates YOLOv5-nano-P6 model with options for pretraining, channels, classes, autoshaping, verbosity, and device.
|
316 |
+
|
317 |
+
Args:
|
318 |
+
pretrained (bool, optional): If True, loads pretrained weights into the model. Default is True.
|
319 |
+
channels (int, optional): Number of input channels. Default is 3.
|
320 |
+
classes (int, optional): Number of model classes. Default is 80.
|
321 |
+
autoshape (bool, optional): If True, applies the YOLOv5 .autoshape() wrapper to the model. Default is True.
|
322 |
+
_verbose (bool, optional): If True, prints all information to screen. Default is True.
|
323 |
+
device (str | torch.device | None, optional): Device to use for model parameters. Can be 'cpu', 'cuda', or None.
|
324 |
+
Default is None.
|
325 |
+
|
326 |
+
Returns:
|
327 |
+
torch.nn.Module: YOLOv5-nano-P6 model loaded with the specified configurations.
|
328 |
+
|
329 |
+
Example:
|
330 |
+
```python
|
331 |
+
import torch
|
332 |
+
model = yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device='cuda')
|
333 |
+
```
|
334 |
+
|
335 |
+
Notes:
|
336 |
+
For more information on PyTorch Hub models, visit: https://pytorch.org/hub/ultralytics_yolov5
|
337 |
+
"""
|
338 |
+
return _create("yolov5n6", pretrained, channels, classes, autoshape, _verbose, device)
|
339 |
+
|
340 |
+
|
341 |
+
def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
342 |
+
"""
|
343 |
+
Instantiate the YOLOv5-small-P6 model with options for pretraining, input channels, number of classes, autoshaping,
|
344 |
+
verbosity, and device selection.
|
345 |
+
|
346 |
+
Args:
|
347 |
+
pretrained (bool): If True, loads pretrained weights. Default is True.
|
348 |
+
channels (int): Number of input channels. Default is 3.
|
349 |
+
classes (int): Number of object detection classes. Default is 80.
|
350 |
+
autoshape (bool): If True, applies YOLOv5 .autoshape() wrapper to the model, allowing for varied input formats.
|
351 |
+
Default is True.
|
352 |
+
_verbose (bool): If True, prints detailed information during model loading. Default is True.
|
353 |
+
device (str | torch.device | None): Device specification for model parameters (e.g., 'cpu', 'cuda', or torch.device).
|
354 |
+
Default is None, which selects an available device automatically.
|
355 |
+
|
356 |
+
Returns:
|
357 |
+
torch.nn.Module: The YOLOv5-small-P6 model instance.
|
358 |
+
|
359 |
+
Usage:
|
360 |
+
```python
|
361 |
+
import torch
|
362 |
+
|
363 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s6')
|
364 |
+
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s6') # load from a specific branch
|
365 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', 'path/to/yolov5s6.pt') # custom/local model
|
366 |
+
model = torch.hub.load('.', 'custom', 'path/to/yolov5s6.pt', source='local') # local repo model
|
367 |
+
```
|
368 |
+
|
369 |
+
Notes:
|
370 |
+
- For more information, refer to the PyTorch Hub models documentation at https://pytorch.org/hub/ultralytics_yolov5
|
371 |
+
|
372 |
+
Raises:
|
373 |
+
Exception: If there is an error during model creation or loading, with a suggestion to visit the YOLOv5
|
374 |
+
tutorials for help.
|
375 |
+
"""
|
376 |
+
return _create("yolov5s6", pretrained, channels, classes, autoshape, _verbose, device)
|
377 |
+
|
378 |
+
|
379 |
+
def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
380 |
+
"""
|
381 |
+
Create YOLOv5-medium-P6 model with options for pretraining, channel count, class count, autoshaping, verbosity, and
|
382 |
+
device.
|
383 |
+
|
384 |
+
Args:
|
385 |
+
pretrained (bool): If True, loads pretrained weights. Default is True.
|
386 |
+
channels (int): Number of input channels. Default is 3.
|
387 |
+
classes (int): Number of model classes. Default is 80.
|
388 |
+
autoshape (bool): Apply YOLOv5 .autoshape() wrapper to the model for file/URI/PIL/cv2/np inputs and NMS.
|
389 |
+
Default is True.
|
390 |
+
_verbose (bool): If True, prints detailed information to the screen. Default is True.
|
391 |
+
device (str | torch.device | None): Device to use for model parameters. Default is None, which uses the
|
392 |
+
best available device.
|
393 |
+
|
394 |
+
Returns:
|
395 |
+
torch.nn.Module: The YOLOv5-medium-P6 model.
|
396 |
+
|
397 |
+
Refer to the PyTorch Hub models documentation: https://pytorch.org/hub/ultralytics_yolov5 for additional details.
|
398 |
+
|
399 |
+
Example:
|
400 |
+
```python
|
401 |
+
import torch
|
402 |
+
|
403 |
+
# Load YOLOv5-medium-P6 model
|
404 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5m6')
|
405 |
+
```
|
406 |
+
|
407 |
+
Notes:
|
408 |
+
- The model can be loaded with pre-trained weights for better performance on specific tasks.
|
409 |
+
- The autoshape feature simplifies input handling by allowing various popular data formats.
|
410 |
+
"""
|
411 |
+
return _create("yolov5m6", pretrained, channels, classes, autoshape, _verbose, device)
|
412 |
+
|
413 |
+
|
414 |
+
def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
415 |
+
"""
|
416 |
+
Instantiate the YOLOv5-large-P6 model with options for pretraining, channel and class counts, autoshaping,
|
417 |
+
verbosity, and device selection.
|
418 |
+
|
419 |
+
Args:
|
420 |
+
pretrained (bool, optional): If True, load pretrained weights into the model. Default is True.
|
421 |
+
channels (int, optional): Number of input channels. Default is 3.
|
422 |
+
classes (int, optional): Number of model classes. Default is 80.
|
423 |
+
autoshape (bool, optional): If True, apply YOLOv5 .autoshape() wrapper to the model for input flexibility. Default is True.
|
424 |
+
_verbose (bool, optional): If True, print all information to the screen. Default is True.
|
425 |
+
device (str | torch.device | None, optional): Device to use for model parameters, e.g., 'cpu', 'cuda', or torch.device.
|
426 |
+
If None, automatically selects the best available device. Default is None.
|
427 |
+
|
428 |
+
Returns:
|
429 |
+
torch.nn.Module: The instantiated YOLOv5-large-P6 model.
|
430 |
+
|
431 |
+
Example:
|
432 |
+
```python
|
433 |
+
import torch
|
434 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5l6') # official model
|
435 |
+
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5l6') # from specific branch
|
436 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', 'path/to/yolov5l6.pt') # custom/local model
|
437 |
+
model = torch.hub.load('.', 'custom', 'path/to/yolov5l6.pt', source='local') # local repository
|
438 |
+
```
|
439 |
+
|
440 |
+
Note:
|
441 |
+
Refer to [PyTorch Hub Documentation](https://pytorch.org/hub/ultralytics_yolov5) for additional usage instructions.
|
442 |
+
"""
|
443 |
+
return _create("yolov5l6", pretrained, channels, classes, autoshape, _verbose, device)
|
444 |
+
|
445 |
+
|
446 |
+
def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
447 |
+
"""
|
448 |
+
Creates the YOLOv5-xlarge-P6 model with options for pretraining, number of input channels, class count, autoshaping,
|
449 |
+
verbosity, and device selection.
|
450 |
+
|
451 |
+
Args:
|
452 |
+
pretrained (bool): If True, loads pretrained weights into the model. Default is True.
|
453 |
+
channels (int): Number of input channels. Default is 3.
|
454 |
+
classes (int): Number of model classes. Default is 80.
|
455 |
+
autoshape (bool): If True, applies YOLOv5 .autoshape() wrapper to the model. Default is True.
|
456 |
+
_verbose (bool): If True, prints all information to the screen. Default is True.
|
457 |
+
device (str | torch.device | None): Device to use for model parameters, can be a string, torch.device object, or
|
458 |
+
None for default device selection. Default is None.
|
459 |
+
|
460 |
+
Returns:
|
461 |
+
torch.nn.Module: The instantiated YOLOv5-xlarge-P6 model.
|
462 |
+
|
463 |
+
Example:
|
464 |
+
```python
|
465 |
+
import torch
|
466 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5x6') # load the YOLOv5-xlarge-P6 model
|
467 |
+
```
|
468 |
+
|
469 |
+
Note:
|
470 |
+
For more information on YOLOv5 models, visit the official documentation:
|
471 |
+
https://docs.ultralytics.com/yolov5
|
472 |
+
"""
|
473 |
+
return _create("yolov5x6", pretrained, channels, classes, autoshape, _verbose, device)
|
474 |
+
|
475 |
+
|
476 |
+
if __name__ == "__main__":
|
477 |
+
import argparse
|
478 |
+
from pathlib import Path
|
479 |
+
|
480 |
+
import numpy as np
|
481 |
+
from PIL import Image
|
482 |
+
|
483 |
+
from utils.general import cv2, print_args
|
484 |
+
|
485 |
+
# Argparser
|
486 |
+
parser = argparse.ArgumentParser()
|
487 |
+
parser.add_argument("--model", type=str, default="yolov5s", help="model name")
|
488 |
+
opt = parser.parse_args()
|
489 |
+
print_args(vars(opt))
|
490 |
+
|
491 |
+
# Model
|
492 |
+
model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
|
493 |
+
# model = custom(path='path/to/model.pt') # custom
|
494 |
+
|
495 |
+
# Images
|
496 |
+
imgs = [
|
497 |
+
"data/images/zidane.jpg", # filename
|
498 |
+
Path("data/images/zidane.jpg"), # Path
|
499 |
+
"https://ultralytics.com/images/zidane.jpg", # URI
|
500 |
+
cv2.imread("data/images/bus.jpg")[:, :, ::-1], # OpenCV
|
501 |
+
Image.open("data/images/bus.jpg"), # PIL
|
502 |
+
np.zeros((320, 640, 3)),
|
503 |
+
] # numpy
|
504 |
+
|
505 |
+
# Inference
|
506 |
+
results = model(imgs, size=320) # batched inference
|
507 |
+
|
508 |
+
# Results
|
509 |
+
results.print()
|
510 |
+
results.save()
|
yolov5/models/__init__.py
ADDED
File without changes
|
yolov5/models/common.py
ADDED
@@ -0,0 +1,1083 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
2 |
+
"""Common modules."""
|
3 |
+
|
4 |
+
import ast
|
5 |
+
import contextlib
|
6 |
+
import json
|
7 |
+
import math
|
8 |
+
import platform
|
9 |
+
import warnings
|
10 |
+
import zipfile
|
11 |
+
from collections import OrderedDict, namedtuple
|
12 |
+
from copy import copy
|
13 |
+
from pathlib import Path
|
14 |
+
from urllib.parse import urlparse
|
15 |
+
|
16 |
+
import cv2
|
17 |
+
import numpy as np
|
18 |
+
import pandas as pd
|
19 |
+
import requests
|
20 |
+
import torch
|
21 |
+
import torch.nn as nn
|
22 |
+
from PIL import Image
|
23 |
+
from torch.cuda import amp
|
24 |
+
|
25 |
+
# Import 'ultralytics' package or install if missing
|
26 |
+
try:
|
27 |
+
import ultralytics
|
28 |
+
|
29 |
+
assert hasattr(ultralytics, "__version__") # verify package is not directory
|
30 |
+
except (ImportError, AssertionError):
|
31 |
+
import os
|
32 |
+
|
33 |
+
os.system("pip install -U ultralytics")
|
34 |
+
import ultralytics
|
35 |
+
|
36 |
+
from ultralytics.utils.plotting import Annotator, colors, save_one_box
|
37 |
+
|
38 |
+
from utils import TryExcept
|
39 |
+
from utils.dataloaders import exif_transpose, letterbox
|
40 |
+
from utils.general import (
|
41 |
+
LOGGER,
|
42 |
+
ROOT,
|
43 |
+
Profile,
|
44 |
+
check_requirements,
|
45 |
+
check_suffix,
|
46 |
+
check_version,
|
47 |
+
colorstr,
|
48 |
+
increment_path,
|
49 |
+
is_jupyter,
|
50 |
+
make_divisible,
|
51 |
+
non_max_suppression,
|
52 |
+
scale_boxes,
|
53 |
+
xywh2xyxy,
|
54 |
+
xyxy2xywh,
|
55 |
+
yaml_load,
|
56 |
+
)
|
57 |
+
from utils.torch_utils import copy_attr, smart_inference_mode
|
58 |
+
|
59 |
+
|
60 |
+
def autopad(k, p=None, d=1):
|
61 |
+
"""
|
62 |
+
Pads kernel to 'same' output shape, adjusting for optional dilation; returns padding size.
|
63 |
+
|
64 |
+
`k`: kernel, `p`: padding, `d`: dilation.
|
65 |
+
"""
|
66 |
+
if d > 1:
|
67 |
+
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
|
68 |
+
if p is None:
|
69 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
70 |
+
return p
|
71 |
+
|
72 |
+
|
73 |
+
class Conv(nn.Module):
|
74 |
+
# Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
|
75 |
+
default_act = nn.SiLU() # default activation
|
76 |
+
|
77 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
|
78 |
+
"""Initializes a standard convolution layer with optional batch normalization and activation."""
|
79 |
+
super().__init__()
|
80 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
|
81 |
+
self.bn = nn.BatchNorm2d(c2)
|
82 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
83 |
+
|
84 |
+
def forward(self, x):
|
85 |
+
"""Applies a convolution followed by batch normalization and an activation function to the input tensor `x`."""
|
86 |
+
return self.act(self.bn(self.conv(x)))
|
87 |
+
|
88 |
+
def forward_fuse(self, x):
|
89 |
+
"""Applies a fused convolution and activation function to the input tensor `x`."""
|
90 |
+
return self.act(self.conv(x))
|
91 |
+
|
92 |
+
|
93 |
+
class DWConv(Conv):
|
94 |
+
# Depth-wise convolution
|
95 |
+
def __init__(self, c1, c2, k=1, s=1, d=1, act=True):
|
96 |
+
"""Initializes a depth-wise convolution layer with optional activation; args: input channels (c1), output
|
97 |
+
channels (c2), kernel size (k), stride (s), dilation (d), and activation flag (act).
|
98 |
+
"""
|
99 |
+
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
|
100 |
+
|
101 |
+
|
102 |
+
class DWConvTranspose2d(nn.ConvTranspose2d):
|
103 |
+
# Depth-wise transpose convolution
|
104 |
+
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0):
|
105 |
+
"""Initializes a depth-wise transpose convolutional layer for YOLOv5; args: input channels (c1), output channels
|
106 |
+
(c2), kernel size (k), stride (s), input padding (p1), output padding (p2).
|
107 |
+
"""
|
108 |
+
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
|
109 |
+
|
110 |
+
|
111 |
+
class TransformerLayer(nn.Module):
|
112 |
+
# Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
|
113 |
+
def __init__(self, c, num_heads):
|
114 |
+
"""
|
115 |
+
Initializes a transformer layer, sans LayerNorm for performance, with multihead attention and linear layers.
|
116 |
+
|
117 |
+
See as described in https://arxiv.org/abs/2010.11929.
|
118 |
+
"""
|
119 |
+
super().__init__()
|
120 |
+
self.q = nn.Linear(c, c, bias=False)
|
121 |
+
self.k = nn.Linear(c, c, bias=False)
|
122 |
+
self.v = nn.Linear(c, c, bias=False)
|
123 |
+
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
|
124 |
+
self.fc1 = nn.Linear(c, c, bias=False)
|
125 |
+
self.fc2 = nn.Linear(c, c, bias=False)
|
126 |
+
|
127 |
+
def forward(self, x):
|
128 |
+
"""Performs forward pass using MultiheadAttention and two linear transformations with residual connections."""
|
129 |
+
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
|
130 |
+
x = self.fc2(self.fc1(x)) + x
|
131 |
+
return x
|
132 |
+
|
133 |
+
|
134 |
+
class TransformerBlock(nn.Module):
|
135 |
+
# Vision Transformer https://arxiv.org/abs/2010.11929
|
136 |
+
def __init__(self, c1, c2, num_heads, num_layers):
|
137 |
+
"""Initializes a Transformer block for vision tasks, adapting dimensions if necessary and stacking specified
|
138 |
+
layers.
|
139 |
+
"""
|
140 |
+
super().__init__()
|
141 |
+
self.conv = None
|
142 |
+
if c1 != c2:
|
143 |
+
self.conv = Conv(c1, c2)
|
144 |
+
self.linear = nn.Linear(c2, c2) # learnable position embedding
|
145 |
+
self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
|
146 |
+
self.c2 = c2
|
147 |
+
|
148 |
+
def forward(self, x):
|
149 |
+
"""Processes input through an optional convolution, followed by Transformer layers and position embeddings for
|
150 |
+
object detection.
|
151 |
+
"""
|
152 |
+
if self.conv is not None:
|
153 |
+
x = self.conv(x)
|
154 |
+
b, _, w, h = x.shape
|
155 |
+
p = x.flatten(2).permute(2, 0, 1)
|
156 |
+
return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
|
157 |
+
|
158 |
+
|
159 |
+
class Bottleneck(nn.Module):
|
160 |
+
# Standard bottleneck
|
161 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):
|
162 |
+
"""Initializes a standard bottleneck layer with optional shortcut and group convolution, supporting channel
|
163 |
+
expansion.
|
164 |
+
"""
|
165 |
+
super().__init__()
|
166 |
+
c_ = int(c2 * e) # hidden channels
|
167 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
168 |
+
self.cv2 = Conv(c_, c2, 3, 1, g=g)
|
169 |
+
self.add = shortcut and c1 == c2
|
170 |
+
|
171 |
+
def forward(self, x):
|
172 |
+
"""Processes input through two convolutions, optionally adds shortcut if channel dimensions match; input is a
|
173 |
+
tensor.
|
174 |
+
"""
|
175 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
176 |
+
|
177 |
+
|
178 |
+
class BottleneckCSP(nn.Module):
|
179 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
180 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
181 |
+
"""Initializes CSP bottleneck with optional shortcuts; args: ch_in, ch_out, number of repeats, shortcut bool,
|
182 |
+
groups, expansion.
|
183 |
+
"""
|
184 |
+
super().__init__()
|
185 |
+
c_ = int(c2 * e) # hidden channels
|
186 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
187 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
188 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
189 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
190 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
191 |
+
self.act = nn.SiLU()
|
192 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
193 |
+
|
194 |
+
def forward(self, x):
|
195 |
+
"""Performs forward pass by applying layers, activation, and concatenation on input x, returning feature-
|
196 |
+
enhanced output.
|
197 |
+
"""
|
198 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
199 |
+
y2 = self.cv2(x)
|
200 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
|
201 |
+
|
202 |
+
|
203 |
+
class CrossConv(nn.Module):
|
204 |
+
# Cross Convolution Downsample
|
205 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
|
206 |
+
"""
|
207 |
+
Initializes CrossConv with downsampling, expanding, and optionally shortcutting; `c1` input, `c2` output
|
208 |
+
channels.
|
209 |
+
|
210 |
+
Inputs are ch_in, ch_out, kernel, stride, groups, expansion, shortcut.
|
211 |
+
"""
|
212 |
+
super().__init__()
|
213 |
+
c_ = int(c2 * e) # hidden channels
|
214 |
+
self.cv1 = Conv(c1, c_, (1, k), (1, s))
|
215 |
+
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
|
216 |
+
self.add = shortcut and c1 == c2
|
217 |
+
|
218 |
+
def forward(self, x):
|
219 |
+
"""Performs feature sampling, expanding, and applies shortcut if channels match; expects `x` input tensor."""
|
220 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
221 |
+
|
222 |
+
|
223 |
+
class C3(nn.Module):
|
224 |
+
# CSP Bottleneck with 3 convolutions
|
225 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
226 |
+
"""Initializes C3 module with options for channel count, bottleneck repetition, shortcut usage, group
|
227 |
+
convolutions, and expansion.
|
228 |
+
"""
|
229 |
+
super().__init__()
|
230 |
+
c_ = int(c2 * e) # hidden channels
|
231 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
232 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
233 |
+
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
|
234 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
235 |
+
|
236 |
+
def forward(self, x):
|
237 |
+
"""Performs forward propagation using concatenated outputs from two convolutions and a Bottleneck sequence."""
|
238 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
239 |
+
|
240 |
+
|
241 |
+
class C3x(C3):
|
242 |
+
# C3 module with cross-convolutions
|
243 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
244 |
+
"""Initializes C3x module with cross-convolutions, extending C3 with customizable channel dimensions, groups,
|
245 |
+
and expansion.
|
246 |
+
"""
|
247 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
248 |
+
c_ = int(c2 * e)
|
249 |
+
self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
|
250 |
+
|
251 |
+
|
252 |
+
class C3TR(C3):
|
253 |
+
# C3 module with TransformerBlock()
|
254 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
255 |
+
"""Initializes C3 module with TransformerBlock for enhanced feature extraction, accepts channel sizes, shortcut
|
256 |
+
config, group, and expansion.
|
257 |
+
"""
|
258 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
259 |
+
c_ = int(c2 * e)
|
260 |
+
self.m = TransformerBlock(c_, c_, 4, n)
|
261 |
+
|
262 |
+
|
263 |
+
class C3SPP(C3):
|
264 |
+
# C3 module with SPP()
|
265 |
+
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
|
266 |
+
"""Initializes a C3 module with SPP layer for advanced spatial feature extraction, given channel sizes, kernel
|
267 |
+
sizes, shortcut, group, and expansion ratio.
|
268 |
+
"""
|
269 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
270 |
+
c_ = int(c2 * e)
|
271 |
+
self.m = SPP(c_, c_, k)
|
272 |
+
|
273 |
+
|
274 |
+
class C3Ghost(C3):
|
275 |
+
# C3 module with GhostBottleneck()
|
276 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
277 |
+
"""Initializes YOLOv5's C3 module with Ghost Bottlenecks for efficient feature extraction."""
|
278 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
279 |
+
c_ = int(c2 * e) # hidden channels
|
280 |
+
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
|
281 |
+
|
282 |
+
|
283 |
+
class SPP(nn.Module):
|
284 |
+
# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
|
285 |
+
def __init__(self, c1, c2, k=(5, 9, 13)):
|
286 |
+
"""Initializes SPP layer with Spatial Pyramid Pooling, ref: https://arxiv.org/abs/1406.4729, args: c1 (input channels), c2 (output channels), k (kernel sizes)."""
|
287 |
+
super().__init__()
|
288 |
+
c_ = c1 // 2 # hidden channels
|
289 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
290 |
+
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
291 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
292 |
+
|
293 |
+
def forward(self, x):
|
294 |
+
"""Applies convolution and max pooling layers to the input tensor `x`, concatenates results, and returns output
|
295 |
+
tensor.
|
296 |
+
"""
|
297 |
+
x = self.cv1(x)
|
298 |
+
with warnings.catch_warnings():
|
299 |
+
warnings.simplefilter("ignore") # suppress torch 1.9.0 max_pool2d() warning
|
300 |
+
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
301 |
+
|
302 |
+
|
303 |
+
class SPPF(nn.Module):
|
304 |
+
# Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
|
305 |
+
def __init__(self, c1, c2, k=5):
|
306 |
+
"""
|
307 |
+
Initializes YOLOv5 SPPF layer with given channels and kernel size for YOLOv5 model, combining convolution and
|
308 |
+
max pooling.
|
309 |
+
|
310 |
+
Equivalent to SPP(k=(5, 9, 13)).
|
311 |
+
"""
|
312 |
+
super().__init__()
|
313 |
+
c_ = c1 // 2 # hidden channels
|
314 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
315 |
+
self.cv2 = Conv(c_ * 4, c2, 1, 1)
|
316 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
|
317 |
+
|
318 |
+
def forward(self, x):
|
319 |
+
"""Processes input through a series of convolutions and max pooling operations for feature extraction."""
|
320 |
+
x = self.cv1(x)
|
321 |
+
with warnings.catch_warnings():
|
322 |
+
warnings.simplefilter("ignore") # suppress torch 1.9.0 max_pool2d() warning
|
323 |
+
y1 = self.m(x)
|
324 |
+
y2 = self.m(y1)
|
325 |
+
return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
|
326 |
+
|
327 |
+
|
328 |
+
class Focus(nn.Module):
|
329 |
+
# Focus wh information into c-space
|
330 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
|
331 |
+
"""Initializes Focus module to concentrate width-height info into channel space with configurable convolution
|
332 |
+
parameters.
|
333 |
+
"""
|
334 |
+
super().__init__()
|
335 |
+
self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
|
336 |
+
# self.contract = Contract(gain=2)
|
337 |
+
|
338 |
+
def forward(self, x):
|
339 |
+
"""Processes input through Focus mechanism, reshaping (b,c,w,h) to (b,4c,w/2,h/2) then applies convolution."""
|
340 |
+
return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
|
341 |
+
# return self.conv(self.contract(x))
|
342 |
+
|
343 |
+
|
344 |
+
class GhostConv(nn.Module):
|
345 |
+
# Ghost Convolution https://github.com/huawei-noah/ghostnet
|
346 |
+
def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
|
347 |
+
"""Initializes GhostConv with in/out channels, kernel size, stride, groups, and activation; halves out channels
|
348 |
+
for efficiency.
|
349 |
+
"""
|
350 |
+
super().__init__()
|
351 |
+
c_ = c2 // 2 # hidden channels
|
352 |
+
self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
|
353 |
+
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
|
354 |
+
|
355 |
+
def forward(self, x):
|
356 |
+
"""Performs forward pass, concatenating outputs of two convolutions on input `x`: shape (B,C,H,W)."""
|
357 |
+
y = self.cv1(x)
|
358 |
+
return torch.cat((y, self.cv2(y)), 1)
|
359 |
+
|
360 |
+
|
361 |
+
class GhostBottleneck(nn.Module):
|
362 |
+
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
|
363 |
+
def __init__(self, c1, c2, k=3, s=1):
|
364 |
+
"""Initializes GhostBottleneck with ch_in `c1`, ch_out `c2`, kernel size `k`, stride `s`; see https://github.com/huawei-noah/ghostnet."""
|
365 |
+
super().__init__()
|
366 |
+
c_ = c2 // 2
|
367 |
+
self.conv = nn.Sequential(
|
368 |
+
GhostConv(c1, c_, 1, 1), # pw
|
369 |
+
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
|
370 |
+
GhostConv(c_, c2, 1, 1, act=False),
|
371 |
+
) # pw-linear
|
372 |
+
self.shortcut = (
|
373 |
+
nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
|
374 |
+
)
|
375 |
+
|
376 |
+
def forward(self, x):
|
377 |
+
"""Processes input through conv and shortcut layers, returning their summed output."""
|
378 |
+
return self.conv(x) + self.shortcut(x)
|
379 |
+
|
380 |
+
|
381 |
+
class Contract(nn.Module):
|
382 |
+
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
|
383 |
+
def __init__(self, gain=2):
|
384 |
+
"""Initializes a layer to contract spatial dimensions (width-height) into channels, e.g., input shape
|
385 |
+
(1,64,80,80) to (1,256,40,40).
|
386 |
+
"""
|
387 |
+
super().__init__()
|
388 |
+
self.gain = gain
|
389 |
+
|
390 |
+
def forward(self, x):
|
391 |
+
"""Processes input tensor to expand channel dimensions by contracting spatial dimensions, yielding output shape
|
392 |
+
`(b, c*s*s, h//s, w//s)`.
|
393 |
+
"""
|
394 |
+
b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
|
395 |
+
s = self.gain
|
396 |
+
x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
|
397 |
+
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
|
398 |
+
return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
|
399 |
+
|
400 |
+
|
401 |
+
class Expand(nn.Module):
|
402 |
+
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
|
403 |
+
def __init__(self, gain=2):
|
404 |
+
"""
|
405 |
+
Initializes the Expand module to increase spatial dimensions by redistributing channels, with an optional gain
|
406 |
+
factor.
|
407 |
+
|
408 |
+
Example: x(1,64,80,80) to x(1,16,160,160).
|
409 |
+
"""
|
410 |
+
super().__init__()
|
411 |
+
self.gain = gain
|
412 |
+
|
413 |
+
def forward(self, x):
|
414 |
+
"""Processes input tensor x to expand spatial dimensions by redistributing channels, requiring C / gain^2 ==
|
415 |
+
0.
|
416 |
+
"""
|
417 |
+
b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
|
418 |
+
s = self.gain
|
419 |
+
x = x.view(b, s, s, c // s**2, h, w) # x(1,2,2,16,80,80)
|
420 |
+
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
|
421 |
+
return x.view(b, c // s**2, h * s, w * s) # x(1,16,160,160)
|
422 |
+
|
423 |
+
|
424 |
+
class Concat(nn.Module):
|
425 |
+
# Concatenate a list of tensors along dimension
|
426 |
+
def __init__(self, dimension=1):
|
427 |
+
"""Initializes a Concat module to concatenate tensors along a specified dimension."""
|
428 |
+
super().__init__()
|
429 |
+
self.d = dimension
|
430 |
+
|
431 |
+
def forward(self, x):
|
432 |
+
"""Concatenates a list of tensors along a specified dimension; `x` is a list of tensors, `dimension` is an
|
433 |
+
int.
|
434 |
+
"""
|
435 |
+
return torch.cat(x, self.d)
|
436 |
+
|
437 |
+
|
438 |
+
class DetectMultiBackend(nn.Module):
|
439 |
+
# YOLOv5 MultiBackend class for python inference on various backends
|
440 |
+
def __init__(self, weights="yolov5s.pt", device=torch.device("cpu"), dnn=False, data=None, fp16=False, fuse=True):
|
441 |
+
"""Initializes DetectMultiBackend with support for various inference backends, including PyTorch and ONNX."""
|
442 |
+
# PyTorch: weights = *.pt
|
443 |
+
# TorchScript: *.torchscript
|
444 |
+
# ONNX Runtime: *.onnx
|
445 |
+
# ONNX OpenCV DNN: *.onnx --dnn
|
446 |
+
# OpenVINO: *_openvino_model
|
447 |
+
# CoreML: *.mlpackage
|
448 |
+
# TensorRT: *.engine
|
449 |
+
# TensorFlow SavedModel: *_saved_model
|
450 |
+
# TensorFlow GraphDef: *.pb
|
451 |
+
# TensorFlow Lite: *.tflite
|
452 |
+
# TensorFlow Edge TPU: *_edgetpu.tflite
|
453 |
+
# PaddlePaddle: *_paddle_model
|
454 |
+
from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
|
455 |
+
|
456 |
+
super().__init__()
|
457 |
+
w = str(weights[0] if isinstance(weights, list) else weights)
|
458 |
+
pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)
|
459 |
+
fp16 &= pt or jit or onnx or engine or triton # FP16
|
460 |
+
nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)
|
461 |
+
stride = 32 # default stride
|
462 |
+
cuda = torch.cuda.is_available() and device.type != "cpu" # use CUDA
|
463 |
+
if not (pt or triton):
|
464 |
+
w = attempt_download(w) # download if not local
|
465 |
+
|
466 |
+
if pt: # PyTorch
|
467 |
+
model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
|
468 |
+
stride = max(int(model.stride.max()), 32) # model stride
|
469 |
+
names = model.module.names if hasattr(model, "module") else model.names # get class names
|
470 |
+
model.half() if fp16 else model.float()
|
471 |
+
self.model = model # explicitly assign for to(), cpu(), cuda(), half()
|
472 |
+
elif jit: # TorchScript
|
473 |
+
LOGGER.info(f"Loading {w} for TorchScript inference...")
|
474 |
+
extra_files = {"config.txt": ""} # model metadata
|
475 |
+
model = torch.jit.load(w, _extra_files=extra_files, map_location=device)
|
476 |
+
model.half() if fp16 else model.float()
|
477 |
+
if extra_files["config.txt"]: # load metadata dict
|
478 |
+
d = json.loads(
|
479 |
+
extra_files["config.txt"],
|
480 |
+
object_hook=lambda d: {int(k) if k.isdigit() else k: v for k, v in d.items()},
|
481 |
+
)
|
482 |
+
stride, names = int(d["stride"]), d["names"]
|
483 |
+
elif dnn: # ONNX OpenCV DNN
|
484 |
+
LOGGER.info(f"Loading {w} for ONNX OpenCV DNN inference...")
|
485 |
+
check_requirements("opencv-python>=4.5.4")
|
486 |
+
net = cv2.dnn.readNetFromONNX(w)
|
487 |
+
elif onnx: # ONNX Runtime
|
488 |
+
LOGGER.info(f"Loading {w} for ONNX Runtime inference...")
|
489 |
+
check_requirements(("onnx", "onnxruntime-gpu" if cuda else "onnxruntime"))
|
490 |
+
import onnxruntime
|
491 |
+
|
492 |
+
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] if cuda else ["CPUExecutionProvider"]
|
493 |
+
session = onnxruntime.InferenceSession(w, providers=providers)
|
494 |
+
output_names = [x.name for x in session.get_outputs()]
|
495 |
+
meta = session.get_modelmeta().custom_metadata_map # metadata
|
496 |
+
if "stride" in meta:
|
497 |
+
stride, names = int(meta["stride"]), eval(meta["names"])
|
498 |
+
elif xml: # OpenVINO
|
499 |
+
LOGGER.info(f"Loading {w} for OpenVINO inference...")
|
500 |
+
check_requirements("openvino>=2023.0") # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
501 |
+
from openvino.runtime import Core, Layout, get_batch
|
502 |
+
|
503 |
+
core = Core()
|
504 |
+
if not Path(w).is_file(): # if not *.xml
|
505 |
+
w = next(Path(w).glob("*.xml")) # get *.xml file from *_openvino_model dir
|
506 |
+
ov_model = core.read_model(model=w, weights=Path(w).with_suffix(".bin"))
|
507 |
+
if ov_model.get_parameters()[0].get_layout().empty:
|
508 |
+
ov_model.get_parameters()[0].set_layout(Layout("NCHW"))
|
509 |
+
batch_dim = get_batch(ov_model)
|
510 |
+
if batch_dim.is_static:
|
511 |
+
batch_size = batch_dim.get_length()
|
512 |
+
ov_compiled_model = core.compile_model(ov_model, device_name="AUTO") # AUTO selects best available device
|
513 |
+
stride, names = self._load_metadata(Path(w).with_suffix(".yaml")) # load metadata
|
514 |
+
elif engine: # TensorRT
|
515 |
+
LOGGER.info(f"Loading {w} for TensorRT inference...")
|
516 |
+
import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
|
517 |
+
|
518 |
+
check_version(trt.__version__, "7.0.0", hard=True) # require tensorrt>=7.0.0
|
519 |
+
if device.type == "cpu":
|
520 |
+
device = torch.device("cuda:0")
|
521 |
+
Binding = namedtuple("Binding", ("name", "dtype", "shape", "data", "ptr"))
|
522 |
+
logger = trt.Logger(trt.Logger.INFO)
|
523 |
+
with open(w, "rb") as f, trt.Runtime(logger) as runtime:
|
524 |
+
model = runtime.deserialize_cuda_engine(f.read())
|
525 |
+
context = model.create_execution_context()
|
526 |
+
bindings = OrderedDict()
|
527 |
+
output_names = []
|
528 |
+
fp16 = False # default updated below
|
529 |
+
dynamic = False
|
530 |
+
is_trt10 = not hasattr(model, "num_bindings")
|
531 |
+
num = range(model.num_io_tensors) if is_trt10 else range(model.num_bindings)
|
532 |
+
for i in num:
|
533 |
+
if is_trt10:
|
534 |
+
name = model.get_tensor_name(i)
|
535 |
+
dtype = trt.nptype(model.get_tensor_dtype(name))
|
536 |
+
is_input = model.get_tensor_mode(name) == trt.TensorIOMode.INPUT
|
537 |
+
if is_input:
|
538 |
+
if -1 in tuple(model.get_tensor_shape(name)): # dynamic
|
539 |
+
dynamic = True
|
540 |
+
context.set_input_shape(name, tuple(model.get_profile_shape(name, 0)[2]))
|
541 |
+
if dtype == np.float16:
|
542 |
+
fp16 = True
|
543 |
+
else: # output
|
544 |
+
output_names.append(name)
|
545 |
+
shape = tuple(context.get_tensor_shape(name))
|
546 |
+
else:
|
547 |
+
name = model.get_binding_name(i)
|
548 |
+
dtype = trt.nptype(model.get_binding_dtype(i))
|
549 |
+
if model.binding_is_input(i):
|
550 |
+
if -1 in tuple(model.get_binding_shape(i)): # dynamic
|
551 |
+
dynamic = True
|
552 |
+
context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))
|
553 |
+
if dtype == np.float16:
|
554 |
+
fp16 = True
|
555 |
+
else: # output
|
556 |
+
output_names.append(name)
|
557 |
+
shape = tuple(context.get_binding_shape(i))
|
558 |
+
im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)
|
559 |
+
bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))
|
560 |
+
binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
|
561 |
+
batch_size = bindings["images"].shape[0] # if dynamic, this is instead max batch size
|
562 |
+
elif coreml: # CoreML
|
563 |
+
LOGGER.info(f"Loading {w} for CoreML inference...")
|
564 |
+
import coremltools as ct
|
565 |
+
|
566 |
+
model = ct.models.MLModel(w)
|
567 |
+
elif saved_model: # TF SavedModel
|
568 |
+
LOGGER.info(f"Loading {w} for TensorFlow SavedModel inference...")
|
569 |
+
import tensorflow as tf
|
570 |
+
|
571 |
+
keras = False # assume TF1 saved_model
|
572 |
+
model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
|
573 |
+
elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
|
574 |
+
LOGGER.info(f"Loading {w} for TensorFlow GraphDef inference...")
|
575 |
+
import tensorflow as tf
|
576 |
+
|
577 |
+
def wrap_frozen_graph(gd, inputs, outputs):
|
578 |
+
"""Wraps a TensorFlow GraphDef for inference, returning a pruned function."""
|
579 |
+
x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
|
580 |
+
ge = x.graph.as_graph_element
|
581 |
+
return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
|
582 |
+
|
583 |
+
def gd_outputs(gd):
|
584 |
+
"""Generates a sorted list of graph outputs excluding NoOp nodes and inputs, formatted as '<name>:0'."""
|
585 |
+
name_list, input_list = [], []
|
586 |
+
for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef
|
587 |
+
name_list.append(node.name)
|
588 |
+
input_list.extend(node.input)
|
589 |
+
return sorted(f"{x}:0" for x in list(set(name_list) - set(input_list)) if not x.startswith("NoOp"))
|
590 |
+
|
591 |
+
gd = tf.Graph().as_graph_def() # TF GraphDef
|
592 |
+
with open(w, "rb") as f:
|
593 |
+
gd.ParseFromString(f.read())
|
594 |
+
frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs=gd_outputs(gd))
|
595 |
+
elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
|
596 |
+
try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
|
597 |
+
from tflite_runtime.interpreter import Interpreter, load_delegate
|
598 |
+
except ImportError:
|
599 |
+
import tensorflow as tf
|
600 |
+
|
601 |
+
Interpreter, load_delegate = (
|
602 |
+
tf.lite.Interpreter,
|
603 |
+
tf.lite.experimental.load_delegate,
|
604 |
+
)
|
605 |
+
if edgetpu: # TF Edge TPU https://coral.ai/software/#edgetpu-runtime
|
606 |
+
LOGGER.info(f"Loading {w} for TensorFlow Lite Edge TPU inference...")
|
607 |
+
delegate = {"Linux": "libedgetpu.so.1", "Darwin": "libedgetpu.1.dylib", "Windows": "edgetpu.dll"}[
|
608 |
+
platform.system()
|
609 |
+
]
|
610 |
+
interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
|
611 |
+
else: # TFLite
|
612 |
+
LOGGER.info(f"Loading {w} for TensorFlow Lite inference...")
|
613 |
+
interpreter = Interpreter(model_path=w) # load TFLite model
|
614 |
+
interpreter.allocate_tensors() # allocate
|
615 |
+
input_details = interpreter.get_input_details() # inputs
|
616 |
+
output_details = interpreter.get_output_details() # outputs
|
617 |
+
# load metadata
|
618 |
+
with contextlib.suppress(zipfile.BadZipFile):
|
619 |
+
with zipfile.ZipFile(w, "r") as model:
|
620 |
+
meta_file = model.namelist()[0]
|
621 |
+
meta = ast.literal_eval(model.read(meta_file).decode("utf-8"))
|
622 |
+
stride, names = int(meta["stride"]), meta["names"]
|
623 |
+
elif tfjs: # TF.js
|
624 |
+
raise NotImplementedError("ERROR: YOLOv5 TF.js inference is not supported")
|
625 |
+
elif paddle: # PaddlePaddle
|
626 |
+
LOGGER.info(f"Loading {w} for PaddlePaddle inference...")
|
627 |
+
check_requirements("paddlepaddle-gpu" if cuda else "paddlepaddle")
|
628 |
+
import paddle.inference as pdi
|
629 |
+
|
630 |
+
if not Path(w).is_file(): # if not *.pdmodel
|
631 |
+
w = next(Path(w).rglob("*.pdmodel")) # get *.pdmodel file from *_paddle_model dir
|
632 |
+
weights = Path(w).with_suffix(".pdiparams")
|
633 |
+
config = pdi.Config(str(w), str(weights))
|
634 |
+
if cuda:
|
635 |
+
config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)
|
636 |
+
predictor = pdi.create_predictor(config)
|
637 |
+
input_handle = predictor.get_input_handle(predictor.get_input_names()[0])
|
638 |
+
output_names = predictor.get_output_names()
|
639 |
+
elif triton: # NVIDIA Triton Inference Server
|
640 |
+
LOGGER.info(f"Using {w} as Triton Inference Server...")
|
641 |
+
check_requirements("tritonclient[all]")
|
642 |
+
from utils.triton import TritonRemoteModel
|
643 |
+
|
644 |
+
model = TritonRemoteModel(url=w)
|
645 |
+
nhwc = model.runtime.startswith("tensorflow")
|
646 |
+
else:
|
647 |
+
raise NotImplementedError(f"ERROR: {w} is not a supported format")
|
648 |
+
|
649 |
+
# class names
|
650 |
+
if "names" not in locals():
|
651 |
+
names = yaml_load(data)["names"] if data else {i: f"class{i}" for i in range(999)}
|
652 |
+
if names[0] == "n01440764" and len(names) == 1000: # ImageNet
|
653 |
+
names = yaml_load(ROOT / "data/ImageNet.yaml")["names"] # human-readable names
|
654 |
+
|
655 |
+
self.__dict__.update(locals()) # assign all variables to self
|
656 |
+
|
657 |
+
def forward(self, im, augment=False, visualize=False):
|
658 |
+
"""Performs YOLOv5 inference on input images with options for augmentation and visualization."""
|
659 |
+
b, ch, h, w = im.shape # batch, channel, height, width
|
660 |
+
if self.fp16 and im.dtype != torch.float16:
|
661 |
+
im = im.half() # to FP16
|
662 |
+
if self.nhwc:
|
663 |
+
im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)
|
664 |
+
|
665 |
+
if self.pt: # PyTorch
|
666 |
+
y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
|
667 |
+
elif self.jit: # TorchScript
|
668 |
+
y = self.model(im)
|
669 |
+
elif self.dnn: # ONNX OpenCV DNN
|
670 |
+
im = im.cpu().numpy() # torch to numpy
|
671 |
+
self.net.setInput(im)
|
672 |
+
y = self.net.forward()
|
673 |
+
elif self.onnx: # ONNX Runtime
|
674 |
+
im = im.cpu().numpy() # torch to numpy
|
675 |
+
y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})
|
676 |
+
elif self.xml: # OpenVINO
|
677 |
+
im = im.cpu().numpy() # FP32
|
678 |
+
y = list(self.ov_compiled_model(im).values())
|
679 |
+
elif self.engine: # TensorRT
|
680 |
+
if self.dynamic and im.shape != self.bindings["images"].shape:
|
681 |
+
i = self.model.get_binding_index("images")
|
682 |
+
self.context.set_binding_shape(i, im.shape) # reshape if dynamic
|
683 |
+
self.bindings["images"] = self.bindings["images"]._replace(shape=im.shape)
|
684 |
+
for name in self.output_names:
|
685 |
+
i = self.model.get_binding_index(name)
|
686 |
+
self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))
|
687 |
+
s = self.bindings["images"].shape
|
688 |
+
assert im.shape == s, f"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}"
|
689 |
+
self.binding_addrs["images"] = int(im.data_ptr())
|
690 |
+
self.context.execute_v2(list(self.binding_addrs.values()))
|
691 |
+
y = [self.bindings[x].data for x in sorted(self.output_names)]
|
692 |
+
elif self.coreml: # CoreML
|
693 |
+
im = im.cpu().numpy()
|
694 |
+
im = Image.fromarray((im[0] * 255).astype("uint8"))
|
695 |
+
# im = im.resize((192, 320), Image.BILINEAR)
|
696 |
+
y = self.model.predict({"image": im}) # coordinates are xywh normalized
|
697 |
+
if "confidence" in y:
|
698 |
+
box = xywh2xyxy(y["coordinates"] * [[w, h, w, h]]) # xyxy pixels
|
699 |
+
conf, cls = y["confidence"].max(1), y["confidence"].argmax(1).astype(np.float)
|
700 |
+
y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
|
701 |
+
else:
|
702 |
+
y = list(reversed(y.values())) # reversed for segmentation models (pred, proto)
|
703 |
+
elif self.paddle: # PaddlePaddle
|
704 |
+
im = im.cpu().numpy().astype(np.float32)
|
705 |
+
self.input_handle.copy_from_cpu(im)
|
706 |
+
self.predictor.run()
|
707 |
+
y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]
|
708 |
+
elif self.triton: # NVIDIA Triton Inference Server
|
709 |
+
y = self.model(im)
|
710 |
+
else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
|
711 |
+
im = im.cpu().numpy()
|
712 |
+
if self.saved_model: # SavedModel
|
713 |
+
y = self.model(im, training=False) if self.keras else self.model(im)
|
714 |
+
elif self.pb: # GraphDef
|
715 |
+
y = self.frozen_func(x=self.tf.constant(im))
|
716 |
+
else: # Lite or Edge TPU
|
717 |
+
input = self.input_details[0]
|
718 |
+
int8 = input["dtype"] == np.uint8 # is TFLite quantized uint8 model
|
719 |
+
if int8:
|
720 |
+
scale, zero_point = input["quantization"]
|
721 |
+
im = (im / scale + zero_point).astype(np.uint8) # de-scale
|
722 |
+
self.interpreter.set_tensor(input["index"], im)
|
723 |
+
self.interpreter.invoke()
|
724 |
+
y = []
|
725 |
+
for output in self.output_details:
|
726 |
+
x = self.interpreter.get_tensor(output["index"])
|
727 |
+
if int8:
|
728 |
+
scale, zero_point = output["quantization"]
|
729 |
+
x = (x.astype(np.float32) - zero_point) * scale # re-scale
|
730 |
+
y.append(x)
|
731 |
+
y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]
|
732 |
+
y[0][..., :4] *= [w, h, w, h] # xywh normalized to pixels
|
733 |
+
|
734 |
+
if isinstance(y, (list, tuple)):
|
735 |
+
return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]
|
736 |
+
else:
|
737 |
+
return self.from_numpy(y)
|
738 |
+
|
739 |
+
def from_numpy(self, x):
|
740 |
+
"""Converts a NumPy array to a torch tensor, maintaining device compatibility."""
|
741 |
+
return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x
|
742 |
+
|
743 |
+
def warmup(self, imgsz=(1, 3, 640, 640)):
|
744 |
+
"""Performs a single inference warmup to initialize model weights, accepting an `imgsz` tuple for image size."""
|
745 |
+
warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton
|
746 |
+
if any(warmup_types) and (self.device.type != "cpu" or self.triton):
|
747 |
+
im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
|
748 |
+
for _ in range(2 if self.jit else 1): #
|
749 |
+
self.forward(im) # warmup
|
750 |
+
|
751 |
+
@staticmethod
|
752 |
+
def _model_type(p="path/to/model.pt"):
|
753 |
+
"""
|
754 |
+
Determines model type from file path or URL, supporting various export formats.
|
755 |
+
|
756 |
+
Example: path='path/to/model.onnx' -> type=onnx
|
757 |
+
"""
|
758 |
+
# types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]
|
759 |
+
from export import export_formats
|
760 |
+
from utils.downloads import is_url
|
761 |
+
|
762 |
+
sf = list(export_formats().Suffix) # export suffixes
|
763 |
+
if not is_url(p, check=False):
|
764 |
+
check_suffix(p, sf) # checks
|
765 |
+
url = urlparse(p) # if url may be Triton inference server
|
766 |
+
types = [s in Path(p).name for s in sf]
|
767 |
+
types[8] &= not types[9] # tflite &= not edgetpu
|
768 |
+
triton = not any(types) and all([any(s in url.scheme for s in ["http", "grpc"]), url.netloc])
|
769 |
+
return types + [triton]
|
770 |
+
|
771 |
+
@staticmethod
|
772 |
+
def _load_metadata(f=Path("path/to/meta.yaml")):
|
773 |
+
"""Loads metadata from a YAML file, returning strides and names if the file exists, otherwise `None`."""
|
774 |
+
if f.exists():
|
775 |
+
d = yaml_load(f)
|
776 |
+
return d["stride"], d["names"] # assign stride, names
|
777 |
+
return None, None
|
778 |
+
|
779 |
+
|
780 |
+
class AutoShape(nn.Module):
|
781 |
+
# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
|
782 |
+
conf = 0.25 # NMS confidence threshold
|
783 |
+
iou = 0.45 # NMS IoU threshold
|
784 |
+
agnostic = False # NMS class-agnostic
|
785 |
+
multi_label = False # NMS multiple labels per box
|
786 |
+
classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
|
787 |
+
max_det = 1000 # maximum number of detections per image
|
788 |
+
amp = False # Automatic Mixed Precision (AMP) inference
|
789 |
+
|
790 |
+
def __init__(self, model, verbose=True):
|
791 |
+
"""Initializes YOLOv5 model for inference, setting up attributes and preparing model for evaluation."""
|
792 |
+
super().__init__()
|
793 |
+
if verbose:
|
794 |
+
LOGGER.info("Adding AutoShape... ")
|
795 |
+
copy_attr(self, model, include=("yaml", "nc", "hyp", "names", "stride", "abc"), exclude=()) # copy attributes
|
796 |
+
self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
|
797 |
+
self.pt = not self.dmb or model.pt # PyTorch model
|
798 |
+
self.model = model.eval()
|
799 |
+
if self.pt:
|
800 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
801 |
+
m.inplace = False # Detect.inplace=False for safe multithread inference
|
802 |
+
m.export = True # do not output loss values
|
803 |
+
|
804 |
+
def _apply(self, fn):
|
805 |
+
"""
|
806 |
+
Applies to(), cpu(), cuda(), half() etc.
|
807 |
+
|
808 |
+
to model tensors excluding parameters or registered buffers.
|
809 |
+
"""
|
810 |
+
self = super()._apply(fn)
|
811 |
+
if self.pt:
|
812 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
813 |
+
m.stride = fn(m.stride)
|
814 |
+
m.grid = list(map(fn, m.grid))
|
815 |
+
if isinstance(m.anchor_grid, list):
|
816 |
+
m.anchor_grid = list(map(fn, m.anchor_grid))
|
817 |
+
return self
|
818 |
+
|
819 |
+
@smart_inference_mode()
|
820 |
+
def forward(self, ims, size=640, augment=False, profile=False):
|
821 |
+
"""
|
822 |
+
Performs inference on inputs with optional augment & profiling.
|
823 |
+
|
824 |
+
Supports various formats including file, URI, OpenCV, PIL, numpy, torch.
|
825 |
+
"""
|
826 |
+
# For size(height=640, width=1280), RGB images example inputs are:
|
827 |
+
# file: ims = 'data/images/zidane.jpg' # str or PosixPath
|
828 |
+
# URI: = 'https://ultralytics.com/images/zidane.jpg'
|
829 |
+
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
|
830 |
+
# PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
|
831 |
+
# numpy: = np.zeros((640,1280,3)) # HWC
|
832 |
+
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
|
833 |
+
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
|
834 |
+
|
835 |
+
dt = (Profile(), Profile(), Profile())
|
836 |
+
with dt[0]:
|
837 |
+
if isinstance(size, int): # expand
|
838 |
+
size = (size, size)
|
839 |
+
p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) # param
|
840 |
+
autocast = self.amp and (p.device.type != "cpu") # Automatic Mixed Precision (AMP) inference
|
841 |
+
if isinstance(ims, torch.Tensor): # torch
|
842 |
+
with amp.autocast(autocast):
|
843 |
+
return self.model(ims.to(p.device).type_as(p), augment=augment) # inference
|
844 |
+
|
845 |
+
# Pre-process
|
846 |
+
n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of images
|
847 |
+
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
|
848 |
+
for i, im in enumerate(ims):
|
849 |
+
f = f"image{i}" # filename
|
850 |
+
if isinstance(im, (str, Path)): # filename or uri
|
851 |
+
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith("http") else im), im
|
852 |
+
im = np.asarray(exif_transpose(im))
|
853 |
+
elif isinstance(im, Image.Image): # PIL Image
|
854 |
+
im, f = np.asarray(exif_transpose(im)), getattr(im, "filename", f) or f
|
855 |
+
files.append(Path(f).with_suffix(".jpg").name)
|
856 |
+
if im.shape[0] < 5: # image in CHW
|
857 |
+
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
|
858 |
+
im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch input
|
859 |
+
s = im.shape[:2] # HWC
|
860 |
+
shape0.append(s) # image shape
|
861 |
+
g = max(size) / max(s) # gain
|
862 |
+
shape1.append([int(y * g) for y in s])
|
863 |
+
ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
|
864 |
+
shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] # inf shape
|
865 |
+
x = [letterbox(im, shape1, auto=False)[0] for im in ims] # pad
|
866 |
+
x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
|
867 |
+
x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
|
868 |
+
|
869 |
+
with amp.autocast(autocast):
|
870 |
+
# Inference
|
871 |
+
with dt[1]:
|
872 |
+
y = self.model(x, augment=augment) # forward
|
873 |
+
|
874 |
+
# Post-process
|
875 |
+
with dt[2]:
|
876 |
+
y = non_max_suppression(
|
877 |
+
y if self.dmb else y[0],
|
878 |
+
self.conf,
|
879 |
+
self.iou,
|
880 |
+
self.classes,
|
881 |
+
self.agnostic,
|
882 |
+
self.multi_label,
|
883 |
+
max_det=self.max_det,
|
884 |
+
) # NMS
|
885 |
+
for i in range(n):
|
886 |
+
scale_boxes(shape1, y[i][:, :4], shape0[i])
|
887 |
+
|
888 |
+
return Detections(ims, y, files, dt, self.names, x.shape)
|
889 |
+
|
890 |
+
|
891 |
+
class Detections:
|
892 |
+
# YOLOv5 detections class for inference results
|
893 |
+
def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
|
894 |
+
"""Initializes the YOLOv5 Detections class with image info, predictions, filenames, timing and normalization."""
|
895 |
+
super().__init__()
|
896 |
+
d = pred[0].device # device
|
897 |
+
gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] # normalizations
|
898 |
+
self.ims = ims # list of images as numpy arrays
|
899 |
+
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
|
900 |
+
self.names = names # class names
|
901 |
+
self.files = files # image filenames
|
902 |
+
self.times = times # profiling times
|
903 |
+
self.xyxy = pred # xyxy pixels
|
904 |
+
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
|
905 |
+
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
|
906 |
+
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
|
907 |
+
self.n = len(self.pred) # number of images (batch size)
|
908 |
+
self.t = tuple(x.t / self.n * 1e3 for x in times) # timestamps (ms)
|
909 |
+
self.s = tuple(shape) # inference BCHW shape
|
910 |
+
|
911 |
+
def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path("")):
|
912 |
+
"""Executes model predictions, displaying and/or saving outputs with optional crops and labels."""
|
913 |
+
s, crops = "", []
|
914 |
+
for i, (im, pred) in enumerate(zip(self.ims, self.pred)):
|
915 |
+
s += f"\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} " # string
|
916 |
+
if pred.shape[0]:
|
917 |
+
for c in pred[:, -1].unique():
|
918 |
+
n = (pred[:, -1] == c).sum() # detections per class
|
919 |
+
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
|
920 |
+
s = s.rstrip(", ")
|
921 |
+
if show or save or render or crop:
|
922 |
+
annotator = Annotator(im, example=str(self.names))
|
923 |
+
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
|
924 |
+
label = f"{self.names[int(cls)]} {conf:.2f}"
|
925 |
+
if crop:
|
926 |
+
file = save_dir / "crops" / self.names[int(cls)] / self.files[i] if save else None
|
927 |
+
crops.append(
|
928 |
+
{
|
929 |
+
"box": box,
|
930 |
+
"conf": conf,
|
931 |
+
"cls": cls,
|
932 |
+
"label": label,
|
933 |
+
"im": save_one_box(box, im, file=file, save=save),
|
934 |
+
}
|
935 |
+
)
|
936 |
+
else: # all others
|
937 |
+
annotator.box_label(box, label if labels else "", color=colors(cls))
|
938 |
+
im = annotator.im
|
939 |
+
else:
|
940 |
+
s += "(no detections)"
|
941 |
+
|
942 |
+
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
|
943 |
+
if show:
|
944 |
+
if is_jupyter():
|
945 |
+
from IPython.display import display
|
946 |
+
|
947 |
+
display(im)
|
948 |
+
else:
|
949 |
+
im.show(self.files[i])
|
950 |
+
if save:
|
951 |
+
f = self.files[i]
|
952 |
+
im.save(save_dir / f) # save
|
953 |
+
if i == self.n - 1:
|
954 |
+
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
|
955 |
+
if render:
|
956 |
+
self.ims[i] = np.asarray(im)
|
957 |
+
if pprint:
|
958 |
+
s = s.lstrip("\n")
|
959 |
+
return f"{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}" % self.t
|
960 |
+
if crop:
|
961 |
+
if save:
|
962 |
+
LOGGER.info(f"Saved results to {save_dir}\n")
|
963 |
+
return crops
|
964 |
+
|
965 |
+
@TryExcept("Showing images is not supported in this environment")
|
966 |
+
def show(self, labels=True):
|
967 |
+
"""
|
968 |
+
Displays detection results with optional labels.
|
969 |
+
|
970 |
+
Usage: show(labels=True)
|
971 |
+
"""
|
972 |
+
self._run(show=True, labels=labels) # show results
|
973 |
+
|
974 |
+
def save(self, labels=True, save_dir="runs/detect/exp", exist_ok=False):
|
975 |
+
"""
|
976 |
+
Saves detection results with optional labels to a specified directory.
|
977 |
+
|
978 |
+
Usage: save(labels=True, save_dir='runs/detect/exp', exist_ok=False)
|
979 |
+
"""
|
980 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) # increment save_dir
|
981 |
+
self._run(save=True, labels=labels, save_dir=save_dir) # save results
|
982 |
+
|
983 |
+
def crop(self, save=True, save_dir="runs/detect/exp", exist_ok=False):
|
984 |
+
"""
|
985 |
+
Crops detection results, optionally saves them to a directory.
|
986 |
+
|
987 |
+
Args: save (bool), save_dir (str), exist_ok (bool).
|
988 |
+
"""
|
989 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
|
990 |
+
return self._run(crop=True, save=save, save_dir=save_dir) # crop results
|
991 |
+
|
992 |
+
def render(self, labels=True):
|
993 |
+
"""Renders detection results with optional labels on images; args: labels (bool) indicating label inclusion."""
|
994 |
+
self._run(render=True, labels=labels) # render results
|
995 |
+
return self.ims
|
996 |
+
|
997 |
+
def pandas(self):
|
998 |
+
"""
|
999 |
+
Returns detections as pandas DataFrames for various box formats (xyxy, xyxyn, xywh, xywhn).
|
1000 |
+
|
1001 |
+
Example: print(results.pandas().xyxy[0]).
|
1002 |
+
"""
|
1003 |
+
new = copy(self) # return copy
|
1004 |
+
ca = "xmin", "ymin", "xmax", "ymax", "confidence", "class", "name" # xyxy columns
|
1005 |
+
cb = "xcenter", "ycenter", "width", "height", "confidence", "class", "name" # xywh columns
|
1006 |
+
for k, c in zip(["xyxy", "xyxyn", "xywh", "xywhn"], [ca, ca, cb, cb]):
|
1007 |
+
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
|
1008 |
+
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
|
1009 |
+
return new
|
1010 |
+
|
1011 |
+
def tolist(self):
|
1012 |
+
"""
|
1013 |
+
Converts a Detections object into a list of individual detection results for iteration.
|
1014 |
+
|
1015 |
+
Example: for result in results.tolist():
|
1016 |
+
"""
|
1017 |
+
r = range(self.n) # iterable
|
1018 |
+
return [
|
1019 |
+
Detections(
|
1020 |
+
[self.ims[i]],
|
1021 |
+
[self.pred[i]],
|
1022 |
+
[self.files[i]],
|
1023 |
+
self.times,
|
1024 |
+
self.names,
|
1025 |
+
self.s,
|
1026 |
+
)
|
1027 |
+
for i in r
|
1028 |
+
]
|
1029 |
+
|
1030 |
+
def print(self):
|
1031 |
+
"""Logs the string representation of the current object's state via the LOGGER."""
|
1032 |
+
LOGGER.info(self.__str__())
|
1033 |
+
|
1034 |
+
def __len__(self):
|
1035 |
+
"""Returns the number of results stored, overrides the default len(results)."""
|
1036 |
+
return self.n
|
1037 |
+
|
1038 |
+
def __str__(self):
|
1039 |
+
"""Returns a string representation of the model's results, suitable for printing, overrides default
|
1040 |
+
print(results).
|
1041 |
+
"""
|
1042 |
+
return self._run(pprint=True) # print results
|
1043 |
+
|
1044 |
+
def __repr__(self):
|
1045 |
+
"""Returns a string representation of the YOLOv5 object, including its class and formatted results."""
|
1046 |
+
return f"YOLOv5 {self.__class__} instance\n" + self.__str__()
|
1047 |
+
|
1048 |
+
|
1049 |
+
class Proto(nn.Module):
|
1050 |
+
# YOLOv5 mask Proto module for segmentation models
|
1051 |
+
def __init__(self, c1, c_=256, c2=32):
|
1052 |
+
"""Initializes YOLOv5 Proto module for segmentation with input, proto, and mask channels configuration."""
|
1053 |
+
super().__init__()
|
1054 |
+
self.cv1 = Conv(c1, c_, k=3)
|
1055 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
|
1056 |
+
self.cv2 = Conv(c_, c_, k=3)
|
1057 |
+
self.cv3 = Conv(c_, c2)
|
1058 |
+
|
1059 |
+
def forward(self, x):
|
1060 |
+
"""Performs a forward pass using convolutional layers and upsampling on input tensor `x`."""
|
1061 |
+
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
|
1062 |
+
|
1063 |
+
|
1064 |
+
class Classify(nn.Module):
|
1065 |
+
# YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
1066 |
+
def __init__(
|
1067 |
+
self, c1, c2, k=1, s=1, p=None, g=1, dropout_p=0.0
|
1068 |
+
): # ch_in, ch_out, kernel, stride, padding, groups, dropout probability
|
1069 |
+
"""Initializes YOLOv5 classification head with convolution, pooling, and dropout layers for input to output
|
1070 |
+
channel transformation.
|
1071 |
+
"""
|
1072 |
+
super().__init__()
|
1073 |
+
c_ = 1280 # efficientnet_b0 size
|
1074 |
+
self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
|
1075 |
+
self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
|
1076 |
+
self.drop = nn.Dropout(p=dropout_p, inplace=True)
|
1077 |
+
self.linear = nn.Linear(c_, c2) # to x(b,c2)
|
1078 |
+
|
1079 |
+
def forward(self, x):
|
1080 |
+
"""Processes input through conv, pool, drop, and linear layers; supports list concatenation input."""
|
1081 |
+
if isinstance(x, list):
|
1082 |
+
x = torch.cat(x, 1)
|
1083 |
+
return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
|
yolov5/models/experimental.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
2 |
+
"""Experimental modules."""
|
3 |
+
|
4 |
+
import math
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
|
10 |
+
from utils.downloads import attempt_download
|
11 |
+
|
12 |
+
|
13 |
+
class Sum(nn.Module):
|
14 |
+
"""Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070."""
|
15 |
+
|
16 |
+
def __init__(self, n, weight=False):
|
17 |
+
"""Initializes a module to sum outputs of layers with number of inputs `n` and optional weighting, supporting 2+
|
18 |
+
inputs.
|
19 |
+
"""
|
20 |
+
super().__init__()
|
21 |
+
self.weight = weight # apply weights boolean
|
22 |
+
self.iter = range(n - 1) # iter object
|
23 |
+
if weight:
|
24 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
25 |
+
|
26 |
+
def forward(self, x):
|
27 |
+
"""Processes input through a customizable weighted sum of `n` inputs, optionally applying learned weights."""
|
28 |
+
y = x[0] # no weight
|
29 |
+
if self.weight:
|
30 |
+
w = torch.sigmoid(self.w) * 2
|
31 |
+
for i in self.iter:
|
32 |
+
y = y + x[i + 1] * w[i]
|
33 |
+
else:
|
34 |
+
for i in self.iter:
|
35 |
+
y = y + x[i + 1]
|
36 |
+
return y
|
37 |
+
|
38 |
+
|
39 |
+
class MixConv2d(nn.Module):
|
40 |
+
"""Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595."""
|
41 |
+
|
42 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
|
43 |
+
"""Initializes MixConv2d with mixed depth-wise convolutional layers, taking input and output channels (c1, c2),
|
44 |
+
kernel sizes (k), stride (s), and channel distribution strategy (equal_ch).
|
45 |
+
"""
|
46 |
+
super().__init__()
|
47 |
+
n = len(k) # number of convolutions
|
48 |
+
if equal_ch: # equal c_ per group
|
49 |
+
i = torch.linspace(0, n - 1e-6, c2).floor() # c2 indices
|
50 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
51 |
+
else: # equal weight.numel() per group
|
52 |
+
b = [c2] + [0] * n
|
53 |
+
a = np.eye(n + 1, n, k=-1)
|
54 |
+
a -= np.roll(a, 1, axis=1)
|
55 |
+
a *= np.array(k) ** 2
|
56 |
+
a[0] = 1
|
57 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
58 |
+
|
59 |
+
self.m = nn.ModuleList(
|
60 |
+
[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]
|
61 |
+
)
|
62 |
+
self.bn = nn.BatchNorm2d(c2)
|
63 |
+
self.act = nn.SiLU()
|
64 |
+
|
65 |
+
def forward(self, x):
|
66 |
+
"""Performs forward pass by applying SiLU activation on batch-normalized concatenated convolutional layer
|
67 |
+
outputs.
|
68 |
+
"""
|
69 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
70 |
+
|
71 |
+
|
72 |
+
class Ensemble(nn.ModuleList):
|
73 |
+
"""Ensemble of models."""
|
74 |
+
|
75 |
+
def __init__(self):
|
76 |
+
"""Initializes an ensemble of models to be used for aggregated predictions."""
|
77 |
+
super().__init__()
|
78 |
+
|
79 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
80 |
+
"""Performs forward pass aggregating outputs from an ensemble of models.."""
|
81 |
+
y = [module(x, augment, profile, visualize)[0] for module in self]
|
82 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
83 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
84 |
+
y = torch.cat(y, 1) # nms ensemble
|
85 |
+
return y, None # inference, train output
|
86 |
+
|
87 |
+
|
88 |
+
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
89 |
+
"""
|
90 |
+
Loads and fuses an ensemble or single YOLOv5 model from weights, handling device placement and model adjustments.
|
91 |
+
|
92 |
+
Example inputs: weights=[a,b,c] or a single model weights=[a] or weights=a.
|
93 |
+
"""
|
94 |
+
from models.yolo import Detect, Model
|
95 |
+
|
96 |
+
model = Ensemble()
|
97 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
98 |
+
ckpt = torch.load(attempt_download(w), map_location="cpu") # load
|
99 |
+
ckpt = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
|
100 |
+
|
101 |
+
# Model compatibility updates
|
102 |
+
if not hasattr(ckpt, "stride"):
|
103 |
+
ckpt.stride = torch.tensor([32.0])
|
104 |
+
if hasattr(ckpt, "names") and isinstance(ckpt.names, (list, tuple)):
|
105 |
+
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
|
106 |
+
|
107 |
+
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, "fuse") else ckpt.eval()) # model in eval mode
|
108 |
+
|
109 |
+
# Module updates
|
110 |
+
for m in model.modules():
|
111 |
+
t = type(m)
|
112 |
+
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
113 |
+
m.inplace = inplace
|
114 |
+
if t is Detect and not isinstance(m.anchor_grid, list):
|
115 |
+
delattr(m, "anchor_grid")
|
116 |
+
setattr(m, "anchor_grid", [torch.zeros(1)] * m.nl)
|
117 |
+
elif t is nn.Upsample and not hasattr(m, "recompute_scale_factor"):
|
118 |
+
m.recompute_scale_factor = None # torch 1.11.0 compatibility
|
119 |
+
|
120 |
+
# Return model
|
121 |
+
if len(model) == 1:
|
122 |
+
return model[-1]
|
123 |
+
|
124 |
+
# Return detection ensemble
|
125 |
+
print(f"Ensemble created with {weights}\n")
|
126 |
+
for k in "names", "nc", "yaml":
|
127 |
+
setattr(model, k, getattr(model[0], k))
|
128 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
129 |
+
assert all(model[0].nc == m.nc for m in model), f"Models have different class counts: {[m.nc for m in model]}"
|
130 |
+
return model
|
yolov5/models/hub/anchors.yaml
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
2 |
+
# Default anchors for COCO data
|
3 |
+
|
4 |
+
# P5 -------------------------------------------------------------------------------------------------------------------
|
5 |
+
# P5-640:
|
6 |
+
anchors_p5_640:
|
7 |
+
- [10, 13, 16, 30, 33, 23] # P3/8
|
8 |
+
- [30, 61, 62, 45, 59, 119] # P4/16
|
9 |
+
- [116, 90, 156, 198, 373, 326] # P5/32
|
10 |
+
|
11 |
+
# P6 -------------------------------------------------------------------------------------------------------------------
|
12 |
+
# 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
|
13 |
+
anchors_p6_640:
|
14 |
+
- [9, 11, 21, 19, 17, 41] # P3/8
|
15 |
+
- [43, 32, 39, 70, 86, 64] # P4/16
|
16 |
+
- [65, 131, 134, 130, 120, 265] # P5/32
|
17 |
+
- [282, 180, 247, 354, 512, 387] # P6/64
|
18 |
+
|
19 |
+
# 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
|
20 |
+
anchors_p6_1280:
|
21 |
+
- [19, 27, 44, 40, 38, 94] # P3/8
|
22 |
+
- [96, 68, 86, 152, 180, 137] # P4/16
|
23 |
+
- [140, 301, 303, 264, 238, 542] # P5/32
|
24 |
+
- [436, 615, 739, 380, 925, 792] # P6/64
|
25 |
+
|
26 |
+
# 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
|
27 |
+
anchors_p6_1920:
|
28 |
+
- [28, 41, 67, 59, 57, 141] # P3/8
|
29 |
+
- [144, 103, 129, 227, 270, 205] # P4/16
|
30 |
+
- [209, 452, 455, 396, 358, 812] # P5/32
|
31 |
+
- [653, 922, 1109, 570, 1387, 1187] # P6/64
|
32 |
+
|
33 |
+
# P7 -------------------------------------------------------------------------------------------------------------------
|
34 |
+
# 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
|
35 |
+
anchors_p7_640:
|
36 |
+
- [11, 11, 13, 30, 29, 20] # P3/8
|
37 |
+
- [30, 46, 61, 38, 39, 92] # P4/16
|
38 |
+
- [78, 80, 146, 66, 79, 163] # P5/32
|
39 |
+
- [149, 150, 321, 143, 157, 303] # P6/64
|
40 |
+
- [257, 402, 359, 290, 524, 372] # P7/128
|
41 |
+
|
42 |
+
# 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
|
43 |
+
anchors_p7_1280:
|
44 |
+
- [19, 22, 54, 36, 32, 77] # P3/8
|
45 |
+
- [70, 83, 138, 71, 75, 173] # P4/16
|
46 |
+
- [165, 159, 148, 334, 375, 151] # P5/32
|
47 |
+
- [334, 317, 251, 626, 499, 474] # P6/64
|
48 |
+
- [750, 326, 534, 814, 1079, 818] # P7/128
|
49 |
+
|
50 |
+
# 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
|
51 |
+
anchors_p7_1920:
|
52 |
+
- [29, 34, 81, 55, 47, 115] # P3/8
|
53 |
+
- [105, 124, 207, 107, 113, 259] # P4/16
|
54 |
+
- [247, 238, 222, 500, 563, 227] # P5/32
|
55 |
+
- [501, 476, 376, 939, 749, 711] # P6/64
|
56 |
+
- [1126, 489, 801, 1222, 1618, 1227] # P7/128
|
yolov5/models/hub/yolov3-spp.yaml
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultralytics YOLOv5 🚀, AGPL-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 |
+
[
|
16 |
+
[-1, 1, Conv, [32, 3, 1]], # 0
|
17 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
18 |
+
[-1, 1, Bottleneck, [64]],
|
19 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
20 |
+
[-1, 2, Bottleneck, [128]],
|
21 |
+
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
22 |
+
[-1, 8, Bottleneck, [256]],
|
23 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
24 |
+
[-1, 8, Bottleneck, [512]],
|
25 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
26 |
+
[-1, 4, Bottleneck, [1024]], # 10
|
27 |
+
]
|
28 |
+
|
29 |
+
# YOLOv3-SPP head
|
30 |
+
head: [
|
31 |
+
[-1, 1, Bottleneck, [1024, False]],
|
32 |
+
[-1, 1, SPP, [512, [5, 9, 13]]],
|
33 |
+
[-1, 1, Conv, [1024, 3, 1]],
|
34 |
+
[-1, 1, Conv, [512, 1, 1]],
|
35 |
+
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
36 |
+
|
37 |
+
[-2, 1, Conv, [256, 1, 1]],
|
38 |
+
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
39 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
40 |
+
[-1, 1, Bottleneck, [512, False]],
|
41 |
+
[-1, 1, Bottleneck, [512, False]],
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
44 |
+
|
45 |
+
[-2, 1, Conv, [128, 1, 1]],
|
46 |
+
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
47 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
48 |
+
[-1, 1, Bottleneck, [256, False]],
|
49 |
+
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
50 |
+
|
51 |
+
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
52 |
+
]
|