glenn-jocher commited on
Commit
1e84a23
·
0 Parent(s):

initial commit

Browse files
.dockerignore ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ !data/samples/zidane.jpg
12
+ !data/samples/bus.jpg
13
+ **/results*.txt
14
+ *.jpg
15
+
16
+ # Neural Network weights -----------------------------------------------------------------------------------------------
17
+ **/*.weights
18
+ **/*.pt
19
+ **/*.onnx
20
+ **/*.mlmodel
21
+ **/darknet53.conv.74
22
+ **/yolov3-tiny.conv.15
23
+
24
+
25
+ # Below Copied From .gitignore -----------------------------------------------------------------------------------------
26
+ # Below Copied From .gitignore -----------------------------------------------------------------------------------------
27
+
28
+
29
+ # GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
30
+ # Byte-compiled / optimized / DLL files
31
+ __pycache__/
32
+ *.py[cod]
33
+ *$py.class
34
+
35
+ # C extensions
36
+ *.so
37
+
38
+ # Distribution / packaging
39
+ .Python
40
+ env/
41
+ build/
42
+ develop-eggs/
43
+ dist/
44
+ downloads/
45
+ eggs/
46
+ .eggs/
47
+ lib/
48
+ lib64/
49
+ parts/
50
+ sdist/
51
+ var/
52
+ wheels/
53
+ *.egg-info/
54
+ .installed.cfg
55
+ *.egg
56
+
57
+ # PyInstaller
58
+ # Usually these files are written by a python script from a template
59
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
60
+ *.manifest
61
+ *.spec
62
+
63
+ # Installer logs
64
+ pip-log.txt
65
+ pip-delete-this-directory.txt
66
+
67
+ # Unit test / coverage reports
68
+ htmlcov/
69
+ .tox/
70
+ .coverage
71
+ .coverage.*
72
+ .cache
73
+ nosetests.xml
74
+ coverage.xml
75
+ *.cover
76
+ .hypothesis/
77
+
78
+ # Translations
79
+ *.mo
80
+ *.pot
81
+
82
+ # Django stuff:
83
+ *.log
84
+ local_settings.py
85
+
86
+ # Flask stuff:
87
+ instance/
88
+ .webassets-cache
89
+
90
+ # Scrapy stuff:
91
+ .scrapy
92
+
93
+ # Sphinx documentation
94
+ docs/_build/
95
+
96
+ # PyBuilder
97
+ target/
98
+
99
+ # Jupyter Notebook
100
+ .ipynb_checkpoints
101
+
102
+ # pyenv
103
+ .python-version
104
+
105
+ # celery beat schedule file
106
+ celerybeat-schedule
107
+
108
+ # SageMath parsed files
109
+ *.sage.py
110
+
111
+ # dotenv
112
+ .env
113
+
114
+ # virtualenv
115
+ .venv
116
+ venv/
117
+ ENV/
118
+
119
+ # Spyder project settings
120
+ .spyderproject
121
+ .spyproject
122
+
123
+ # Rope project settings
124
+ .ropeproject
125
+
126
+ # mkdocs documentation
127
+ /site
128
+
129
+ # mypy
130
+ .mypy_cache/
131
+
132
+
133
+ # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
134
+
135
+ # General
136
+ .DS_Store
137
+ .AppleDouble
138
+ .LSOverride
139
+
140
+ # Icon must end with two \r
141
+ Icon
142
+ Icon?
143
+
144
+ # Thumbnails
145
+ ._*
146
+
147
+ # Files that might appear in the root of a volume
148
+ .DocumentRevisions-V100
149
+ .fseventsd
150
+ .Spotlight-V100
151
+ .TemporaryItems
152
+ .Trashes
153
+ .VolumeIcon.icns
154
+ .com.apple.timemachine.donotpresent
155
+
156
+ # Directories potentially created on remote AFP share
157
+ .AppleDB
158
+ .AppleDesktop
159
+ Network Trash Folder
160
+ Temporary Items
161
+ .apdisk
162
+
163
+
164
+ # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
165
+ # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
166
+ # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
167
+
168
+ # User-specific stuff:
169
+ .idea/*
170
+ .idea/**/workspace.xml
171
+ .idea/**/tasks.xml
172
+ .idea/dictionaries
173
+ .html # Bokeh Plots
174
+ .pg # TensorFlow Frozen Graphs
175
+ .avi # videos
176
+
177
+ # Sensitive or high-churn files:
178
+ .idea/**/dataSources/
179
+ .idea/**/dataSources.ids
180
+ .idea/**/dataSources.local.xml
181
+ .idea/**/sqlDataSources.xml
182
+ .idea/**/dynamic.xml
183
+ .idea/**/uiDesigner.xml
184
+
185
+ # Gradle:
186
+ .idea/**/gradle.xml
187
+ .idea/**/libraries
188
+
189
+ # CMake
190
+ cmake-build-debug/
191
+ cmake-build-release/
192
+
193
+ # Mongo Explorer plugin:
194
+ .idea/**/mongoSettings.xml
195
+
196
+ ## File-based project format:
197
+ *.iws
198
+
199
+ ## Plugin-specific files:
200
+
201
+ # IntelliJ
202
+ out/
203
+
204
+ # mpeltonen/sbt-idea plugin
205
+ .idea_modules/
206
+
207
+ # JIRA plugin
208
+ atlassian-ide-plugin.xml
209
+
210
+ # Cursive Clojure plugin
211
+ .idea/replstate.xml
212
+
213
+ # Crashlytics plugin (for Android Studio and IntelliJ)
214
+ com_crashlytics_export_strings.xml
215
+ crashlytics.properties
216
+ crashlytics-build.properties
217
+ fabric.properties
.github/ISSUE_TEMPLATE/--bug-report.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: "\U0001F41BBug report"
3
+ about: Create a report to help us improve
4
+ title: ''
5
+ labels: bug
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ Before submitting a bug report, please ensure that you are using the latest versions of:
11
+ - Python
12
+ - PyTorch
13
+ - This repository (run `git fetch && git status -uno` to check and `git pull` to update)
14
+
15
+ **Your issue must be reproducible on a public dataset (i.e COCO) using the latest version of the repository, and you must supply code to reproduce, or we can not help you.**
16
+
17
+ If this is a custom training question we suggest you include your `train*.jpg`, `test*.jpg` and `results.png` figures.
18
+
19
+
20
+ ## 🐛 Bug
21
+ A clear and concise description of what the bug is.
22
+
23
+ ## To Reproduce
24
+ **REQUIRED**: Code to reproduce your issue below
25
+ ```
26
+ python train.py ...
27
+ ```
28
+
29
+
30
+ ## Expected behavior
31
+ A clear and concise description of what you expected to happen.
32
+
33
+ ## Environment
34
+ If applicable, add screenshots to help explain your problem.
35
+
36
+ - OS: [e.g. Ubuntu]
37
+ - GPU [e.g. 2080 Ti]
38
+
39
+
40
+ ## Additional context
41
+ Add any other context about the problem here.
.github/ISSUE_TEMPLATE/--feature-request.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: "\U0001F680Feature request"
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: enhancement
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ ## 🚀 Feature
11
+ <!-- A clear and concise description of the feature proposal -->
12
+
13
+ ## Motivation
14
+
15
+ <!-- Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too -->
16
+
17
+ ## Pitch
18
+
19
+ <!-- A clear and concise description of what you want to happen. -->
20
+
21
+ ## Alternatives
22
+
23
+ <!-- A clear and concise description of any alternative solutions or features you've considered, if any. -->
24
+
25
+ ## Additional context
26
+
27
+ <!-- Add any other context or screenshots about the feature request here. -->
.github/workflows/greetings.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Greetings
2
+
3
+ on: [pull_request, issues]
4
+
5
+ jobs:
6
+ greeting:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/first-interaction@v1
10
+ with:
11
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
12
+ pr-message: 'Hello @${{ github.actor }}, thank you for submitting a PR! We will respond as soon as possible.'
13
+ issue-message: >
14
+ Hello @${{ github.actor }}, thank you for your interest in our work! Please visit our [Custom Training Tutorial](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) to get started, and see our [Google Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/tutorial.ipynb), [Docker Image](https://hub.docker.com/r/ultralytics/yolov5), and [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) for example environments.
15
+
16
+ If this is a bug report, please provide screenshots and **minimum viable code to reproduce your issue**, otherwise we can not help you.
17
+
18
+ If this is a custom model or data training question, please note that Ultralytics does **not** provide free personal support. As a leader in vision ML and AI, we do offer professional consulting, from simple expert advice up to delivery of fully customized, end-to-end production solutions for our clients, such as:
19
+ - **Cloud-based AI** surveillance systems operating on **hundreds of HD video streams in realtime.**
20
+ - **Edge AI** integrated into custom iOS and Android apps for realtime **30 FPS video inference.**
21
+ - **Custom data training**, hyperparameter evolution, and model exportation to any destination.
22
+
23
+ To discuss your business requirements in greater detail please visit us at https://www.ultralytics.com.
.github/workflows/stale.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Close stale issues
2
+ on:
3
+ schedule:
4
+ - cron: "0 0 * * *"
5
+
6
+ jobs:
7
+ stale:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - uses: actions/stale@v1
11
+ with:
12
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
13
+ stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove Stale label or comment or this will be closed in 5 days.'
14
+ stale-pr-message: 'This pull request is stale because it has been open 30 days with no activity. Remove Stale label or comment or this will be closed in 5 days.'
15
+ days-before-stale: 30
16
+ days-before-close: 5
17
+ exempt-issue-label: 'tutorial'
.gitignore ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repo-specific GitIgnore ----------------------------------------------------------------------------------------------
2
+ *.jpg
3
+ *.jpeg
4
+ *.png
5
+ *.bmp
6
+ *.tif
7
+ *.tiff
8
+ *.heic
9
+ *.JPG
10
+ *.JPEG
11
+ *.PNG
12
+ *.BMP
13
+ *.TIF
14
+ *.TIFF
15
+ *.HEIC
16
+ *.mp4
17
+ *.mov
18
+ *.MOV
19
+ *.avi
20
+ *.data
21
+ *.json
22
+
23
+ *.cfg
24
+ !cfg/yolov3*.cfg
25
+
26
+ storage.googleapis.com
27
+ runs/*
28
+ data/*
29
+ !data/samples/zidane.jpg
30
+ !data/samples/bus.jpg
31
+ !data/coco.names
32
+ !data/coco_paper.names
33
+ !data/coco.data
34
+ !data/coco_*.data
35
+ !data/coco_*.txt
36
+ !data/trainvalno5k.shapes
37
+ !data/*.sh
38
+
39
+ pycocotools/*
40
+ results*.txt
41
+ gcp_test*.sh
42
+
43
+ # MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
44
+ *.m~
45
+ *.mat
46
+ !targets*.mat
47
+
48
+ # Neural Network weights -----------------------------------------------------------------------------------------------
49
+ *.weights
50
+ *.pt
51
+ *.onnx
52
+ *.mlmodel
53
+ darknet53.conv.74
54
+ yolov3-tiny.conv.15
55
+
56
+ # GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
57
+ # Byte-compiled / optimized / DLL files
58
+ __pycache__/
59
+ *.py[cod]
60
+ *$py.class
61
+
62
+ # C extensions
63
+ *.so
64
+
65
+ # Distribution / packaging
66
+ .Python
67
+ env/
68
+ build/
69
+ develop-eggs/
70
+ dist/
71
+ downloads/
72
+ eggs/
73
+ .eggs/
74
+ lib/
75
+ lib64/
76
+ parts/
77
+ sdist/
78
+ var/
79
+ wheels/
80
+ *.egg-info/
81
+ .installed.cfg
82
+ *.egg
83
+
84
+ # PyInstaller
85
+ # Usually these files are written by a python script from a template
86
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
87
+ *.manifest
88
+ *.spec
89
+
90
+ # Installer logs
91
+ pip-log.txt
92
+ pip-delete-this-directory.txt
93
+
94
+ # Unit test / coverage reports
95
+ htmlcov/
96
+ .tox/
97
+ .coverage
98
+ .coverage.*
99
+ .cache
100
+ nosetests.xml
101
+ coverage.xml
102
+ *.cover
103
+ .hypothesis/
104
+
105
+ # Translations
106
+ *.mo
107
+ *.pot
108
+
109
+ # Django stuff:
110
+ *.log
111
+ local_settings.py
112
+
113
+ # Flask stuff:
114
+ instance/
115
+ .webassets-cache
116
+
117
+ # Scrapy stuff:
118
+ .scrapy
119
+
120
+ # Sphinx documentation
121
+ docs/_build/
122
+
123
+ # PyBuilder
124
+ target/
125
+
126
+ # Jupyter Notebook
127
+ .ipynb_checkpoints
128
+
129
+ # pyenv
130
+ .python-version
131
+
132
+ # celery beat schedule file
133
+ celerybeat-schedule
134
+
135
+ # SageMath parsed files
136
+ *.sage.py
137
+
138
+ # dotenv
139
+ .env
140
+
141
+ # virtualenv
142
+ .venv
143
+ venv/
144
+ ENV/
145
+
146
+ # Spyder project settings
147
+ .spyderproject
148
+ .spyproject
149
+
150
+ # Rope project settings
151
+ .ropeproject
152
+
153
+ # mkdocs documentation
154
+ /site
155
+
156
+ # mypy
157
+ .mypy_cache/
158
+
159
+
160
+ # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
161
+
162
+ # General
163
+ .DS_Store
164
+ .AppleDouble
165
+ .LSOverride
166
+
167
+ # Icon must end with two \r
168
+ Icon
169
+ Icon?
170
+
171
+ # Thumbnails
172
+ ._*
173
+
174
+ # Files that might appear in the root of a volume
175
+ .DocumentRevisions-V100
176
+ .fseventsd
177
+ .Spotlight-V100
178
+ .TemporaryItems
179
+ .Trashes
180
+ .VolumeIcon.icns
181
+ .com.apple.timemachine.donotpresent
182
+
183
+ # Directories potentially created on remote AFP share
184
+ .AppleDB
185
+ .AppleDesktop
186
+ Network Trash Folder
187
+ Temporary Items
188
+ .apdisk
189
+
190
+
191
+ # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
192
+ # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
193
+ # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
194
+
195
+ # User-specific stuff:
196
+ .idea/*
197
+ .idea/**/workspace.xml
198
+ .idea/**/tasks.xml
199
+ .idea/dictionaries
200
+ .html # Bokeh Plots
201
+ .pg # TensorFlow Frozen Graphs
202
+ .avi # videos
203
+
204
+ # Sensitive or high-churn files:
205
+ .idea/**/dataSources/
206
+ .idea/**/dataSources.ids
207
+ .idea/**/dataSources.local.xml
208
+ .idea/**/sqlDataSources.xml
209
+ .idea/**/dynamic.xml
210
+ .idea/**/uiDesigner.xml
211
+
212
+ # Gradle:
213
+ .idea/**/gradle.xml
214
+ .idea/**/libraries
215
+
216
+ # CMake
217
+ cmake-build-debug/
218
+ cmake-build-release/
219
+
220
+ # Mongo Explorer plugin:
221
+ .idea/**/mongoSettings.xml
222
+
223
+ ## File-based project format:
224
+ *.iws
225
+
226
+ ## Plugin-specific files:
227
+
228
+ # IntelliJ
229
+ out/
230
+
231
+ # mpeltonen/sbt-idea plugin
232
+ .idea_modules/
233
+
234
+ # JIRA plugin
235
+ atlassian-ide-plugin.xml
236
+
237
+ # Cursive Clojure plugin
238
+ .idea/replstate.xml
239
+
240
+ # Crashlytics plugin (for Android Studio and IntelliJ)
241
+ com_crashlytics_export_strings.xml
242
+ crashlytics.properties
243
+ crashlytics-build.properties
244
+ fabric.properties
Dockerfile ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
2
+ FROM nvcr.io/nvidia/pytorch:20.03-py3
3
+
4
+ # Install dependencies (pip or conda)
5
+ RUN pip install -U gsutil thop
6
+ # RUN pip install -U -r requirements.txt
7
+
8
+ # Create working directory
9
+ RUN mkdir -p /usr/src/app
10
+ WORKDIR /usr/src/app
11
+
12
+ # Copy contents
13
+ COPY . /usr/src/app
14
+
15
+ # Copy weights
16
+ #RUN python3 -c "from models import *; \
17
+ #attempt_download('weights/yolov5s.pt'); \
18
+ #attempt_download('weights/yolov5m.pt'); \
19
+ #attempt_download('weights/yolov5l.pt')"
20
+
21
+
22
+ # --------------------------------------------------- Extras Below ---------------------------------------------------
23
+
24
+ # Build and Push
25
+ # t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t
26
+
27
+ # Pull and Run
28
+ # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host $t bash
29
+
30
+ # Pull and Run with local directory access
31
+ # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t bash
32
+
33
+ # Kill all
34
+ # sudo docker kill "$(sudo docker ps -q)"
35
+
36
+ # Kill all image-based
37
+ # sudo docker kill $(sudo docker ps -a -q --filter ancestor=ultralytics/yolov5:latest)
38
+
39
+ # Run bash for loop
40
+ # sudo docker run --gpus all --ipc=host ultralytics/yolov5:latest while true; do python3 train.py --evolve; done
41
+
42
+ # Bash in running container
43
+ # sudo docker container exec -it 97919ad657de /bin/bash
44
+
45
+ # Bash last stopped container
46
+ # python -c "from utils.utils import *; create_backbone('weights/best.pt')" && gsutil cp weights/backbone.pt gs://ult/coco/yolov5s.pt
47
+
48
+ # Clean up
49
+ # docker system prune -a --volumes
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <http://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
README.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <a href="https://apps.apple.com/app/id1452689527" target="_blank">
2
+ <img src="https://user-images.githubusercontent.com/26833433/82944393-f7644d80-9f4f-11ea-8b87-1a5b04f555f1.jpg" width="1000"></a>
3
+ &nbsp
4
+
5
+ This repository represents Ultralytics open-source research into future object detection methods, and incorporates our lessons learned and best practices evolved over training thousands of models on custom client datasets with our previous YOLO repository https://github.com/ultralytics/yolov3. **All code and models are under active development, and are subject to modification or deletion without notice.** Use at your own risk.
6
+
7
+ Updates:
8
+ - **May 27, 2020**: Public release of repo. yolov3-spp (this repo) is SOTA among all known yolo implementations, yolov5 family will be undergoing architecture research and development over Q2/Q3 2020 to increase performance. Updates may include CSP bottlenecks from yolov4, as well as PANet or BiFPN head features.
9
+ - **May 24, 2020**: Training yolov5s/x and yolov3-spp. yolov5m/l suffered early overfitting and also code 137 early docker terminations, cause unknown. yolov5l underperforms yolov3-spp due to earlier overfitting, cause unknown.
10
+ - **April 1, 2020**: Begin development of a 100% pytorch scaleable yolov3/4-based group of future models, in small, medium, large and extra large sizes, collectively known as yolov5. Models will be defined by new user-friendly yaml-based configuration files for ease of construction and modification. Datasets will likewise use yaml configuration files. New training platform will be simpler use, harder to break, and more robust to training a wider variety of custom dataset.
11
+
12
+
13
+ ## Ultralytics Professional Support
14
+
15
+ Ultralytics is a U.S.-based particle physics and AI startup with over 6 years of expertise supporting government, academic and business clients. We offer a wide range of vision AI services, spanning from simple expert advice up to delivery of fully customized, end-to-end production solutions, including:
16
+ - **Cloud-based AI** surveillance systems operating on **hundreds of HD video streams in realtime.**
17
+ - **Edge AI** integrated into custom iOS and Android apps for realtime **30 FPS video inference.**
18
+ - **Custom data training**, hyperparameter evolution, and model exportation to any destination.
19
+
20
+ For business inquiries and professional support requests please visit us at https://www.ultralytics.com.
21
+
22
+
23
+ ## Pretrained Checkpoints
24
+
25
+ | Model | AP<sup>val</sup> | AP<sup>test</sup> | AP<sub>50</sub> | Latency<sub>GPU</sub> | FPS<sub>GPU</sub> | | params | FLOPs |
26
+ |---------- |------ |------ |------ | -------- | ------| ------ |------ | :------: |
27
+ | YOLOv5-s ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 33.1 | 33.0 | 53.3 | **3.3ms** | **303** | | 7.0B | 14.0
28
+ | YOLOv5-m ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 41.5 | 41.5 | 61.5 | 5.5ms | 182 | | 25.2B | 50.2
29
+ | YOLOv5-l ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 44.2 | 44.5 | 64.3 | 9.7ms | 103 | | 61.8B | 123.1
30
+ | YOLOv5-x ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | **47.1** | **47.2** | **66.7** | 15.8ms | 63 | | 123.1B | 245.7
31
+ | YOLOv3-SPP ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 45.5 | 45.4 | 65.2 | 8.9ms | 112 | | 63.0B | 118.0
32
+
33
+ ** AP<sup>test</sup> denotes COCO [test-dev2017](http://cocodataset.org/#upload) server results, all other AP results in the table denote val2017 accuracy.
34
+ ** All accuracy numbers are for single-model single-scale without ensemble or test-time augmentation. Reproduce by `python test.py --img-size 736 --conf_thres 0.001`
35
+ ** Latency<sub>GPU</sub> measures end-to-end latency per image averaged over 5000 COCO val2017 images using a V100 GPU and includes image preprocessing, inference, postprocessing and NMS. Average NMS time included in this chart is 1.6ms/image. Reproduce by `python test.py --img-size 640 --conf_thres 0.1 --batch-size 16`
36
+ ** All checkpoints are trained to 300 epochs with default settings and hyperparameters (no autoaugmentation).
37
+
38
+
39
+ ## Requirements
40
+
41
+ Python 3.7 or later with all `requirements.txt` dependencies installed, including `torch >= 1.5`. To install run:
42
+ ```bash
43
+ $ pip install -U -r requirements.txt
44
+ ```
45
+
46
+
47
+ ## Tutorials
48
+
49
+ * [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data)
50
+ * [Google Colab Notebook](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) with training, testing and testing examples
51
+ * [GCP Quickstart](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
52
+ * [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart)
53
+
54
+
55
+ ## Inference
56
+
57
+ Inference can be run on most common media formats. Model [checkpoints](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) are downloaded automatically if available. Results are saved to `./inference/output`.
58
+ ```bash
59
+ $ python detect.py --source file.jpg # image
60
+ file.mp4 # video
61
+ ./dir # directory
62
+ 0 # webcam
63
+ rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream
64
+ http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream
65
+ ```
66
+
67
+ To run inference on examples in the `./inference/images` folder:
68
+
69
+ ```bash
70
+ $ python detect.py --source ./inference/images/ --weights yolov5s.pt --conf 0.4
71
+
72
+ Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.4, device='', fourcc='mp4v', half=False, img_size=640, iou_thres=0.5, output='inference/output', save_txt=False, source='./inference/images/', view_img=False, weights='yolov5s.pt')
73
+ Using CUDA device0 _CudaDeviceProperties(name='Tesla P100-PCIE-16GB', total_memory=16280MB)
74
+
75
+ Downloading https://drive.google.com/uc?export=download&id=1R5T6rIyy3lLwgFXNms8whc-387H0tMQO as yolov5s.pt... Done (2.6s)
76
+
77
+ image 1/2 inference/images/bus.jpg: 640x512 3 persons, 1 buss, Done. (0.009s)
78
+ image 2/2 inference/images/zidane.jpg: 384x640 2 persons, 2 ties, Done. (0.009s)
79
+ Results saved to /content/yolov5/inference/output
80
+ ```
81
+
82
+ <img src="https://user-images.githubusercontent.com/26833433/83082816-59e54880-a039-11ea-8abe-ab90cc1ec4b0.jpeg" width="500">
83
+
84
+
85
+ ## Reproduce Our Training
86
+
87
+ Run commands below. Training takes a few days for yolov5s, to a few weeks for yolov5x on a 2080Ti GPU.
88
+ ```bash
89
+ $ python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 16
90
+ ```
91
+ <img src="https://user-images.githubusercontent.com/26833433/82960433-5a191180-9f6f-11ea-85cc-c49dbd1555e1.png" width="900">
92
+
93
+
94
+ ## Reproduce Our Environment
95
+
96
+ To access an up-to-date working environment (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled), consider a:
97
+
98
+ - **GCP** Deep Learning VM with $300 free credit offer: See our [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
99
+ - **Google Colab Notebook** with 12 hours of free GPU time: [Google Colab Notebook](https://colab.sandbox.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb)
100
+ - **Docker Image** from https://hub.docker.com/r/ultralytics/yolov5. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart)
101
+
102
+
103
+ ## Citation
104
+
105
+ [![DOI](https://zenodo.org/badge/146165888.svg)](https://zenodo.org/badge/latestdoi/146165888)
106
+
107
+
108
+ ## Contact
109
+
110
+ **Issues should be raised directly in the repository.** For business inquiries or professional support requests please visit us at https://www.ultralytics.com.
data/coco.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # COCO 2017 dataset http://cocodataset.org
2
+ # Download command: bash yolov5/data/get_coco2017.sh
3
+ # Train command: python train.py --data ./data/coco.yaml
4
+ # Dataset should be placed next to yolov5 folder:
5
+ # /parent_folder
6
+ # /coco
7
+ # /yolov5
8
+
9
+
10
+ # train and val datasets (image directory or *.txt file with image paths)
11
+ train: ../coco/train2017.txt # 118k images
12
+ val: ../coco/val2017.txt # 5k images
13
+ test: ../coco/test-dev2017.txt # 20k images for submission to https://competitions.codalab.org/competitions/20794
14
+
15
+ # number of classes
16
+ nc: 80
17
+
18
+ # class names
19
+ names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
20
+ 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
21
+ 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
22
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
23
+ 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
24
+ 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
25
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
26
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
27
+ 'hair drier', 'toothbrush']
28
+
29
+ # Print classes
30
+ # with open('data/coco.yaml') as f:
31
+ # d = yaml.load(f, Loader=yaml.FullLoader) # dict
32
+ # for i, x in enumerate(d['names']):
33
+ # print(i, x)
data/coco128.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # COCO 2017 dataset http://cocodataset.org - first 128 training images
2
+ # Download command: python -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')"
3
+ # Train command: python train.py --data ./data/coco128.yaml
4
+ # Dataset should be placed next to yolov5 folder:
5
+ # /parent_folder
6
+ # /coco128
7
+ # /yolov5
8
+
9
+
10
+ # train and val datasets (image directory or *.txt file with image paths)
11
+ train: ../coco128/images/train2017/
12
+ val: ../coco128/images/train2017/
13
+
14
+ # number of classes
15
+ nc: 80
16
+
17
+ # class names
18
+ names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
19
+ 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
20
+ 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
21
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
22
+ 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
23
+ 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
24
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
25
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
26
+ 'hair drier', 'toothbrush']
data/get_coco2017.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Zip coco folder
3
+ # zip -r coco.zip coco
4
+ # tar -czvf coco.tar.gz coco
5
+
6
+ # Download labels from Google Drive, accepting presented query
7
+ filename="coco2017labels.zip"
8
+ fileid="1cXZR_ckHki6nddOmcysCuuJFM--T-Q6L"
9
+ curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null
10
+ curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename}
11
+ rm ./cookie
12
+
13
+ # Unzip labels
14
+ unzip -q ${filename} # for coco.zip
15
+ # tar -xzf ${filename} # for coco.tar.gz
16
+ rm ${filename}
17
+
18
+ # Download and unzip images
19
+ cd coco/images
20
+ f="train2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 19G, 118k images
21
+ f="val2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 1G, 5k images
22
+ # f="test2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 7G, 41k images
23
+
24
+ # cd out
25
+ cd ../..
detect.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from utils.datasets import *
4
+ from utils.utils import *
5
+
6
+ ONNX_EXPORT = False
7
+
8
+
9
+ def detect(save_img=False):
10
+ imgsz = (320, 192) if ONNX_EXPORT else opt.img_size # (320, 192) or (416, 256) or (608, 352) for (height, width)
11
+ out, source, weights, half, view_img, save_txt = opt.output, opt.source, opt.weights, opt.half, opt.view_img, opt.save_txt
12
+ webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt')
13
+
14
+ # Initialize
15
+ device = torch_utils.select_device(device='cpu' if ONNX_EXPORT else opt.device)
16
+ if os.path.exists(out):
17
+ shutil.rmtree(out) # delete output folder
18
+ os.makedirs(out) # make new output folder
19
+
20
+ # Load model
21
+ google_utils.attempt_download(weights)
22
+ model = torch.load(weights, map_location=device)['model']
23
+ # torch.save(torch.load(weights, map_location=device), weights) # update model if SourceChangeWarning
24
+
25
+ # Second-stage classifier
26
+ classify = False
27
+ if classify:
28
+ modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
29
+ modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
30
+ modelc.to(device).eval()
31
+
32
+ # Eval mode
33
+ model.to(device).eval()
34
+
35
+ # Fuse Conv2d + BatchNorm2d layers
36
+ # model.fuse()
37
+
38
+ # Export mode
39
+ if ONNX_EXPORT:
40
+ model.fuse()
41
+ img = torch.zeros((1, 3) + imgsz) # (1, 3, 320, 192)
42
+ f = opt.weights.replace(opt.weights.split('.')[-1], 'onnx') # *.onnx filename
43
+ torch.onnx.export(model, img, f, verbose=False, opset_version=11)
44
+
45
+ # Validate exported model
46
+ import onnx
47
+ model = onnx.load(f) # Load the ONNX model
48
+ onnx.checker.check_model(model) # Check that the IR is well formed
49
+ print(onnx.helper.printable_graph(model.graph)) # Print a human readable representation of the graph
50
+ return
51
+
52
+ # Half precision
53
+ half = half and device.type != 'cpu' # half precision only supported on CUDA
54
+ if half:
55
+ model.half()
56
+
57
+ # Set Dataloader
58
+ vid_path, vid_writer = None, None
59
+ if webcam:
60
+ view_img = True
61
+ torch.backends.cudnn.benchmark = True # set True to speed up constant image size inference
62
+ dataset = LoadStreams(source, img_size=imgsz)
63
+ else:
64
+ save_img = True
65
+ dataset = LoadImages(source, img_size=imgsz)
66
+
67
+ # Get names and colors
68
+ names = model.names
69
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
70
+
71
+ # Run inference
72
+ t0 = time.time()
73
+ img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
74
+ _ = model(img.half() if half else img.float()) if device.type != 'cpu' else None # run once
75
+ for path, img, im0s, vid_cap in dataset:
76
+ img = torch.from_numpy(img).to(device)
77
+ img = img.half() if half else img.float() # uint8 to fp16/32
78
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
79
+ if img.ndimension() == 3:
80
+ img = img.unsqueeze(0)
81
+
82
+ # Inference
83
+ t1 = torch_utils.time_synchronized()
84
+ pred = model(img, augment=opt.augment)[0]
85
+ t2 = torch_utils.time_synchronized()
86
+
87
+ # to float
88
+ if half:
89
+ pred = pred.float()
90
+
91
+ # Apply NMS
92
+ pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres,
93
+ multi_label=False, classes=opt.classes, agnostic=opt.agnostic_nms)
94
+
95
+ # Apply Classifier
96
+ if classify:
97
+ pred = apply_classifier(pred, modelc, img, im0s)
98
+
99
+ # Process detections
100
+ for i, det in enumerate(pred): # detections per image
101
+ if webcam: # batch_size >= 1
102
+ p, s, im0 = path[i], '%g: ' % i, im0s[i]
103
+ else:
104
+ p, s, im0 = path, '', im0s
105
+
106
+ save_path = str(Path(out) / Path(p).name)
107
+ s += '%gx%g ' % img.shape[2:] # print string
108
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] #  normalization gain whwh
109
+ if det is not None and len(det):
110
+ # Rescale boxes from img_size to im0 size
111
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
112
+
113
+ # Print results
114
+ for c in det[:, -1].unique():
115
+ n = (det[:, -1] == c).sum() # detections per class
116
+ s += '%g %ss, ' % (n, names[int(c)]) # add to string
117
+
118
+ # Write results
119
+ for *xyxy, conf, cls in det:
120
+ if save_txt: # Write to file
121
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
122
+ with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file:
123
+ file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
124
+
125
+ if save_img or view_img: # Add bbox to image
126
+ label = '%s %.2f' % (names[int(cls)], conf)
127
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
128
+
129
+ # Print time (inference + NMS)
130
+ print('%sDone. (%.3fs)' % (s, t2 - t1))
131
+
132
+ # Stream results
133
+ if view_img:
134
+ cv2.imshow(p, im0)
135
+ if cv2.waitKey(1) == ord('q'): # q to quit
136
+ raise StopIteration
137
+
138
+ # Save results (image with detections)
139
+ if save_img:
140
+ if dataset.mode == 'images':
141
+ cv2.imwrite(save_path, im0)
142
+ else:
143
+ if vid_path != save_path: # new video
144
+ vid_path = save_path
145
+ if isinstance(vid_writer, cv2.VideoWriter):
146
+ vid_writer.release() # release previous video writer
147
+
148
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
149
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
150
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
151
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h))
152
+ vid_writer.write(im0)
153
+
154
+ if save_txt or save_img:
155
+ print('Results saved to %s' % os.getcwd() + os.sep + out)
156
+ if platform == 'darwin': # MacOS
157
+ os.system('open ' + save_path)
158
+
159
+ print('Done. (%.3fs)' % (time.time() - t0))
160
+
161
+
162
+ if __name__ == '__main__':
163
+ parser = argparse.ArgumentParser()
164
+ parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
165
+ parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
166
+ parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
167
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
168
+ parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
169
+ parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
170
+ parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)')
171
+ parser.add_argument('--half', action='store_true', help='half precision FP16 inference')
172
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
173
+ parser.add_argument('--view-img', action='store_true', help='display results')
174
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
175
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class')
176
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
177
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
178
+ opt = parser.parse_args()
179
+ print(opt)
180
+
181
+ with torch.no_grad():
182
+ detect()
inference/images/bus.jpg ADDED
inference/images/zidane.jpg ADDED
models/common.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains modules common to various models
2
+
3
+
4
+ import torch.nn.functional as F
5
+
6
+ from utils.utils import *
7
+
8
+
9
+ def DWConv(c1, c2, k=1, s=1, act=True): # depthwise convolution
10
+ return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
11
+
12
+
13
+ class Conv(nn.Module): # standard convolution
14
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
15
+ super(Conv, self).__init__()
16
+ self.conv = nn.Conv2d(c1, c2, k, s, k // 2, groups=g, bias=False)
17
+ self.bn = nn.BatchNorm2d(c2)
18
+ self.act = nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity()
19
+
20
+ def forward(self, x):
21
+ return self.act(self.bn(self.conv(x)))
22
+
23
+
24
+ class Bottleneck(nn.Module):
25
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
26
+ super(Bottleneck, self).__init__()
27
+ c_ = int(c2 * e) # hidden channels
28
+ self.cv1 = Conv(c1, c_, 1, 1)
29
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
30
+ self.add = shortcut and c1 == c2
31
+
32
+ def forward(self, x):
33
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
34
+
35
+
36
+ class BottleneckLight(nn.Module):
37
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
38
+ super(BottleneckLight, self).__init__()
39
+ c_ = int(c2 * e) # hidden channels
40
+ self.cv1 = Conv(c1, c_, 1, 1)
41
+ self.cv2 = nn.Conv2d(c_, c2, 3, 1, 3 // 2, groups=g, bias=False)
42
+ self.bn = nn.BatchNorm2d(c2)
43
+ self.act = nn.LeakyReLU(0.1, inplace=True)
44
+ self.add = shortcut and c1 == c2
45
+
46
+ def forward(self, x):
47
+ return self.act(self.bn(x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))))
48
+
49
+
50
+ class BottleneckCSP(nn.Module):
51
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
52
+ super(BottleneckCSP, self).__init__()
53
+ c_ = int(c2 * e) # hidden channels
54
+ self.cv1 = Conv(c1, c_, 1, 1)
55
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
56
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
57
+ self.cv4 = Conv(c2, c2, 1, 1)
58
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
59
+ self.act = nn.LeakyReLU(0.1, inplace=True)
60
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
61
+
62
+ def forward(self, x):
63
+ y1 = self.cv3(self.m(self.cv1(x)))
64
+ y2 = self.cv2(x)
65
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
66
+
67
+
68
+ class BottleneckCSPF(nn.Module):
69
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
70
+ super(BottleneckCSPF, self).__init__()
71
+ c_ = int(c2 * e) # hidden channels
72
+ self.cv1 = Conv(c1, c_, 1, 1)
73
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
74
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
75
+ self.cv4 = Conv(c2, c2, 1, 1)
76
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
77
+ self.act = nn.LeakyReLU(0.1, inplace=True)
78
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
79
+
80
+ def forward(self, x):
81
+ y1 = self.cv3(self.m(self.cv1(x)))
82
+ y2 = self.cv2(x)
83
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
84
+
85
+
86
+ class Narrow(nn.Module):
87
+ def __init__(self, c1, c2, shortcut=True, g=1): # ch_in, ch_out, shortcut, groups
88
+ super(Narrow, self).__init__()
89
+ c_ = c2 // 2 # hidden channels
90
+ self.cv1 = Conv(c1, c_, 1, 1)
91
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
92
+ self.add = shortcut and c1 == c2
93
+
94
+ def forward(self, x):
95
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
96
+
97
+
98
+ class Origami(nn.Module): # 5-side layering
99
+ def forward(self, x):
100
+ y = F.pad(x, [1, 1, 1, 1])
101
+ return torch.cat([x, y[..., :-2, 1:-1], y[..., 1:-1, :-2], y[..., 2:, 1:-1], y[..., 1:-1, 2:]], 1)
102
+
103
+
104
+ class ConvPlus(nn.Module): # standard convolution
105
+ def __init__(self, c1, c2, k=3, s=1, g=1, bias=True): # ch_in, ch_out, kernel, stride, groups
106
+ super(ConvPlus, self).__init__()
107
+ self.cv1 = nn.Conv2d(c1, c2, (k, 1), s, (k // 2, 0), groups=g, bias=bias)
108
+ self.cv2 = nn.Conv2d(c1, c2, (1, k), s, (0, k // 2), groups=g, bias=bias)
109
+
110
+ def forward(self, x):
111
+ return self.cv1(x) + self.cv2(x)
112
+
113
+
114
+ class SPP(nn.Module): # Spatial pyramid pooling layer used in YOLOv3-SPP
115
+ def __init__(self, c1, c2, k=(5, 9, 13)):
116
+ super(SPP, self).__init__()
117
+ c_ = c1 // 2 # hidden channels
118
+ self.cv1 = Conv(c1, c_, 1, 1)
119
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
120
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
121
+
122
+ def forward(self, x):
123
+ x = self.cv1(x)
124
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
125
+
126
+
127
+ class Flatten(nn.Module):
128
+ # Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions
129
+ def forward(self, x):
130
+ return x.view(x.size(0), -1)
131
+
132
+
133
+ class Focus(nn.Module):
134
+ # Focus wh information into c-space
135
+ def __init__(self, c1, c2, k=1):
136
+ super(Focus, self).__init__()
137
+ self.conv = Conv(c1 * 4, c2, k, 1)
138
+
139
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
140
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
141
+
142
+
143
+ class Concat(nn.Module):
144
+ # Concatenate a list of tensors along dimension
145
+ def __init__(self, dimension=1):
146
+ super(Concat, self).__init__()
147
+ self.d = dimension
148
+
149
+ def forward(self, x):
150
+ return torch.cat(x, self.d)
151
+
152
+
153
+ class MixConv2d(nn.Module):
154
+ # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
155
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
156
+ super(MixConv2d, self).__init__()
157
+ groups = len(k)
158
+ if equal_ch: # equal c_ per group
159
+ i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
160
+ c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
161
+ else: # equal weight.numel() per group
162
+ b = [c2] + [0] * groups
163
+ a = np.eye(groups + 1, groups, k=-1)
164
+ a -= np.roll(a, 1, axis=1)
165
+ a *= np.array(k) ** 2
166
+ a[0] = 1
167
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
168
+
169
+ self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
170
+ self.bn = nn.BatchNorm2d(c2)
171
+ self.act = nn.LeakyReLU(0.1, inplace=True)
172
+
173
+ def forward(self, x):
174
+ return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
models/experimental.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from models.common import *
2
+
3
+
4
+ class Sum(nn.Module):
5
+ # weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
6
+ def __init__(self, n, weight=False): # n: number of inputs
7
+ super(Sum, self).__init__()
8
+ self.weight = weight # apply weights boolean
9
+ self.iter = range(n - 1) # iter object
10
+ if weight:
11
+ self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
12
+
13
+ def forward(self, x):
14
+ y = x[0] # no weight
15
+ if self.weight:
16
+ w = torch.sigmoid(self.w) * 2
17
+ for i in self.iter:
18
+ y = y + x[i + 1] * w[i]
19
+ else:
20
+ for i in self.iter:
21
+ y = y + x[i + 1]
22
+ return y
23
+
24
+
25
+ class GhostConv(nn.Module):
26
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
27
+ super(GhostConv, self).__init__()
28
+ c_ = c2 // 2 # hidden channels
29
+ self.cv1 = Conv(c1, c_, k, s, g, act)
30
+ self.cv2 = Conv(c_, c_, 5, 1, c_, act)
31
+
32
+ def forward(self, x):
33
+ y = self.cv1(x)
34
+ return torch.cat([y, self.cv2(y)], 1)
35
+
36
+
37
+ class GhostBottleneck(nn.Module):
38
+ def __init__(self, c1, c2, k, s):
39
+ super(GhostBottleneck, self).__init__()
40
+ c_ = c2 // 2
41
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
42
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
43
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
44
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
45
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
46
+
47
+ def forward(self, x):
48
+ return self.conv(x) + self.shortcut(x)
models/yolo.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import yaml
4
+
5
+ from models.common import *
6
+
7
+
8
+ class Detect(nn.Module):
9
+ def __init__(self, nc=80, anchors=()): # detection layer
10
+ super(Detect, self).__init__()
11
+ self.stride = None # strides computed during build
12
+ self.nc = nc # number of classes
13
+ self.no = nc + 5 # number of outputs per anchor
14
+ self.nl = len(anchors) # number of detection layers
15
+ self.na = len(anchors[0]) // 2 # number of anchors
16
+ self.grid = [torch.zeros(1)] * self.nl # init grid
17
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
18
+ self.register_buffer('anchors', a) # shape(nl,na,2)
19
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
20
+ self.export = False # onnx export
21
+
22
+ def forward(self, x):
23
+ x = x.copy()
24
+ z = [] # inference output
25
+ self.training |= self.export
26
+ for i in range(self.nl):
27
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
28
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
29
+
30
+ if not self.training: # inference
31
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
32
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
33
+
34
+ y = x[i].sigmoid()
35
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
36
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
37
+ z.append(y.view(bs, -1, self.no))
38
+
39
+ return x if self.training else (torch.cat(z, 1), x)
40
+
41
+ @staticmethod
42
+ def _make_grid(nx=20, ny=20):
43
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
44
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
45
+
46
+
47
+ class Model(nn.Module):
48
+ def __init__(self, model_yaml='yolov5s.yaml'): # cfg, number of classes, depth-width gains
49
+ super(Model, self).__init__()
50
+ with open(model_yaml) as f:
51
+ self.md = yaml.load(f, Loader=yaml.FullLoader) # model dict
52
+
53
+ # Define model
54
+ self.model, self.save, ch = parse_model(self.md, ch=[3]) # model, savelist, ch_out
55
+ # print([x.shape for x in self.forward(torch.zeros(1, 3, 64, 64))])
56
+
57
+ # Build strides, anchors
58
+ m = self.model[-1] # Detect()
59
+ m.stride = torch.tensor([64 / x.shape[-2] for x in self.forward(torch.zeros(1, 3, 64, 64))]) # forward
60
+ m.anchors /= m.stride.view(-1, 1, 1)
61
+ self.stride = m.stride
62
+
63
+ # Init weights, biases
64
+ torch_utils.initialize_weights(self)
65
+ self._initialize_biases() # only run once
66
+ torch_utils.model_info(self)
67
+ print('')
68
+
69
+ def forward(self, x, augment=False, profile=False):
70
+ y, ts = [], 0 # outputs
71
+ for m in self.model:
72
+ if m.f != -1: # if not from previous layer
73
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
74
+
75
+ if profile:
76
+ import thop
77
+ o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS
78
+ t = torch_utils.time_synchronized()
79
+ for _ in range(10):
80
+ _ = m(x)
81
+ dt = torch_utils.time_synchronized() - t
82
+ ts += dt
83
+ print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt * 100, m.type))
84
+
85
+ x = m(x) # run
86
+ y.append(x if m.i in self.save else None) # save output
87
+
88
+ if profile:
89
+ print(ts * 100)
90
+ return x
91
+
92
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
93
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
94
+ m = self.model[-1] # Detect() module
95
+ for f, s in zip(m.f, m.stride): #  from
96
+ mi = self.model[f % m.i]
97
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
98
+ b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
99
+ b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
100
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
101
+
102
+ def _print_biases(self):
103
+ m = self.model[-1] # Detect() module
104
+ for f in sorted([x % m.i for x in m.f]): #  from
105
+ b = self.model[f].bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
106
+ print(('%g Conv2d.bias:' + '%10.3g' * 6) % (f, *b[:5].mean(1).tolist(), b[5:].mean()))
107
+
108
+
109
+ def parse_model(md, ch): # model_dict, input_channels(3)
110
+ print('\n%3s%15s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
111
+ anchors, nc, gd, gw = md['anchors'], md['nc'], md['depth_multiple'], md['width_multiple']
112
+ na = (len(anchors[0]) // 2) # number of anchors
113
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
114
+
115
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
116
+ for i, (f, n, m, args) in enumerate(md['backbone'] + md['head']): # from, number, module, args
117
+ m = eval(m) if isinstance(m, str) else m # eval strings
118
+ for j, a in enumerate(args):
119
+ try:
120
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
121
+ except:
122
+ pass
123
+
124
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
125
+ if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, ConvPlus, BottleneckCSP, BottleneckCSPF, BottleneckLight]:
126
+ c1, c2 = ch[f], args[0]
127
+
128
+ # Normal
129
+ # if i > 0 and args[0] != no: # channel expansion factor
130
+ # ex = 1.75 # exponential (default 2.0)
131
+ # e = math.log(c2 / ch[1]) / math.log(2)
132
+ # c2 = int(ch[1] * ex ** e)
133
+ # if m != Focus:
134
+ c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
135
+
136
+ # Experimental
137
+ # if i > 0 and args[0] != no: # channel expansion factor
138
+ # ex = 1 + gw # exponential (default 2.0)
139
+ # ch1 = 32 # ch[1]
140
+ # e = math.log(c2 / ch1) / math.log(2) # level 1-n
141
+ # c2 = int(ch1 * ex ** e)
142
+ # if m != Focus:
143
+ # c2 = make_divisible(c2, 8) if c2 != no else c2
144
+
145
+ args = [c1, c2, *args[1:]]
146
+ if m in [BottleneckCSP, BottleneckCSPF]:
147
+ args += [n]
148
+ n = 1
149
+ elif m is nn.BatchNorm2d:
150
+ args = [ch[f]]
151
+ elif m is Concat:
152
+ c2 = sum([ch[x] for x in f])
153
+ elif m is Origami:
154
+ c2 = ch[f] * 5
155
+ elif m is Detect:
156
+ f = f or list(reversed([(-1 if j == i else j - 1) for j, x in enumerate(ch) if x == no]))
157
+ else:
158
+ c2 = ch[f]
159
+
160
+ m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
161
+ t = str(m)[8:-2].replace('__main__.', '') # module type
162
+ np = sum([x.numel() for x in m_.parameters()]) # number params
163
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
164
+ print('%3s%15s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
165
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
166
+ layers.append(m_)
167
+ ch.append(c2)
168
+ return nn.Sequential(*layers), sorted(save), ch
169
+
170
+
171
+ if __name__ == '__main__':
172
+ parser = argparse.ArgumentParser()
173
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
174
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
175
+ opt = parser.parse_args()
176
+ opt.cfg = glob.glob('./**/' + opt.cfg, recursive=True)[0] # find file
177
+ device = torch_utils.select_device(opt.device)
178
+
179
+ # Create model
180
+ model = Model(opt.cfg).to(device)
181
+ model.train()
182
+
183
+ # Profile
184
+ # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
185
+ # y = model(img, profile=True)
186
+ # print([y[0].shape] + [x.shape for x in y[1]])
187
+
188
+ # ONNX export
189
+ # model.model[-1].export = True
190
+ # torch.onnx.export(model, img, f.replace('.yaml', '.onnx'), verbose=True, opset_version=11)
191
+
192
+ # Tensorboard
193
+ # from torch.utils.tensorboard import SummaryWriter
194
+ # tb_writer = SummaryWriter()
195
+ # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
196
+ # tb_writer.add_graph(model.model, img) # add model to tensorboard
197
+ # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
models/yolov3-spp.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # expand model depth
4
+ width_multiple: 1.0 # expand layer channels
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # darknet53 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [32, 3, 1]], # 0
16
+ [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17
+ [-1, 1, Bottleneck, [64]],
18
+ [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19
+ [-1, 2, Bottleneck, [128]],
20
+ [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21
+ [-1, 8, Bottleneck, [256]],
22
+ [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23
+ [-1, 8, Bottleneck, [512]],
24
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25
+ [-1, 4, Bottleneck, [1024]], # 10
26
+ ]
27
+
28
+ # yolov3-spp head
29
+ # na = len(anchors[0])
30
+ head:
31
+ [[-1, 1, Bottleneck, [1024, False]], # 11
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]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 16 (P5/32-large)
37
+
38
+ [-3, 1, Conv, [256, 1, 1]],
39
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
40
+ [[-1, 8], 1, Concat, [1]], # cat backbone P4
41
+ [-1, 1, Bottleneck, [512, False]],
42
+ [-1, 1, Bottleneck, [512, False]],
43
+ [-1, 1, Conv, [256, 1, 1]],
44
+ [-1, 1, Conv, [512, 3, 1]],
45
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 24 (P4/16-medium)
46
+
47
+ [-3, 1, Conv, [128, 1, 1]],
48
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
49
+ [[-1, 6], 1, Concat, [1]], # cat backbone P3
50
+ [-1, 1, Bottleneck, [256, False]],
51
+ [-1, 2, Bottleneck, [256, False]],
52
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 30 (P3/8-small)
53
+
54
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
55
+ ]
models/yolov3-spp_csp.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # expand model depth
4
+ width_multiple: 1.0 # expand layer channels
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # darknet53 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [32, 3, 1]], # 0
16
+ [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17
+ [-1, 1, BottleneckCSP, [64]],
18
+ [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19
+ [-1, 2, BottleneckCSP, [128]],
20
+ [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21
+ [-1, 8, BottleneckCSP, [256]],
22
+ [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23
+ [-1, 8, BottleneckCSP, [512]],
24
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25
+ [-1, 4, BottleneckCSP, [1024]], # 10
26
+ ]
27
+
28
+ # yolov3-spp head
29
+ # na = len(anchors[0])
30
+ head:
31
+ [[-1, 1, Bottleneck, [1024, False]], # 11
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]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 16 (P5/32-large)
37
+
38
+ [-3, 1, Conv, [256, 1, 1]],
39
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
40
+ [[-1, 8], 1, Concat, [1]], # cat backbone P4
41
+ [-1, 1, Bottleneck, [512, False]],
42
+ [-1, 1, Bottleneck, [512, False]],
43
+ [-1, 1, Conv, [256, 1, 1]],
44
+ [-1, 1, Conv, [512, 3, 1]],
45
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 24 (P4/16-medium)
46
+
47
+ [-3, 1, Conv, [128, 1, 1]],
48
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
49
+ [[-1, 6], 1, Concat, [1]], # cat backbone P3
50
+ [-1, 1, Bottleneck, [256, False]],
51
+ [-1, 2, Bottleneck, [256, False]],
52
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 30 (P3/8-small)
53
+
54
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
55
+ ]
models/yolov5l.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, Bottleneck, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, Bottleneck, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, Bottleneck, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, Bottleneck, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, Bottleneck, [1024, False]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, Bottleneck, [512, False]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, Bottleneck, [256, False]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
models/yolov5m.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.67 # model depth multiple
4
+ width_multiple: 0.75 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, Bottleneck, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, Bottleneck, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, Bottleneck, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, Bottleneck, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, Bottleneck, [1024, False]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, Bottleneck, [512, False]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, Bottleneck, [256, False]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
46
+
models/yolov5s.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.33 # model depth multiple
4
+ width_multiple: 0.50 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, Bottleneck, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, Bottleneck, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, Bottleneck, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, Bottleneck, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, Bottleneck, [1024, False]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, Bottleneck, [512, False]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, Bottleneck, [256, False]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
models/yolov5s_csp.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.33 # model depth multiple
4
+ width_multiple: 0.50 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, Bottleneck, [1024, False]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, Bottleneck, [512, False]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, Bottleneck, [256, False]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
46
+
models/yolov5s_csp1.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.33 # model depth multiple
4
+ width_multiple: 0.50 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 6, BottleneckCSP, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, Bottleneck, [1024, False]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, Bottleneck, [512, False]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, Bottleneck, [256, False]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
46
+
models/yolov5s_csp2.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.33 # model depth multiple
4
+ width_multiple: 0.50 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 6, BottleneckCSP, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, BottleneckCSPF, [1024]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, BottleneckCSPF, [512]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, BottleneckCSPF, [256]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
46
+
models/yolov5x.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.33 # model depth multiple
4
+ width_multiple: 1.25 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # yolov5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 1-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 2-P2/4
17
+ [-1, 3, Bottleneck, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 4-P3/8
19
+ [-1, 9, Bottleneck, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 6-P4/16
21
+ [-1, 9, Bottleneck, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, Bottleneck, [1024]], # 10
25
+ ]
26
+
27
+ # yolov5 head
28
+ head:
29
+ [[-1, 3, Bottleneck, [1024]], # 11
30
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large)
31
+
32
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
34
+ [-1, 1, Conv, [512, 1, 1]],
35
+ [-1, 3, Bottleneck, [512, False]],
36
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium)
37
+
38
+ [-2, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
40
+ [-1, 1, Conv, [256, 1, 1]],
41
+ [-1, 3, Bottleneck, [256, False]],
42
+ [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small)
43
+
44
+ [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
requirements.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pip install -U -r requirements.txt
2
+ numpy==1.17
3
+ opencv-python
4
+ torch >= 1.5
5
+ matplotlib
6
+ pycocotools
7
+ tqdm
8
+ pillow
9
+ tensorboard
10
+ pyyaml
11
+
12
+
13
+ # Nvidia Apex (optional) for mixed precision training --------------------------
14
+ # git clone https://github.com/NVIDIA/apex && cd apex && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" . --user && cd .. && rm -rf apex
15
+
16
+ # Conda commands (in place of pip) ---------------------------------------------
17
+ # conda update -yn base -c defaults conda
18
+ # conda install -yc anaconda numpy opencv matplotlib tqdm pillow ipython
19
+ # conda install -yc conda-forge scikit-image pycocotools tensorboard
20
+ # conda install -yc spyder-ide spyder-line-profiler
21
+ # conda install -yc pytorch pytorch torchvision
22
+ # conda install -yc conda-forge protobuf numpy && pip install onnx # https://github.com/onnx/onnx#linux-and-macos
test.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ import yaml
5
+ from torch.utils.data import DataLoader
6
+
7
+ from utils.datasets import *
8
+ from utils.utils import *
9
+
10
+
11
+ def test(data,
12
+ weights=None,
13
+ batch_size=16,
14
+ imgsz=640,
15
+ conf_thres=0.001,
16
+ iou_thres=0.6, # for nms
17
+ save_json=False,
18
+ single_cls=False,
19
+ augment=False,
20
+ model=None,
21
+ dataloader=None,
22
+ multi_label=True,
23
+ verbose=False): # 0 fast, 1 accurate
24
+ # Initialize/load model and set device
25
+ if model is None:
26
+ device = torch_utils.select_device(opt.device, batch_size=batch_size)
27
+
28
+ # Remove previous
29
+ for f in glob.glob('test_batch*.jpg'):
30
+ os.remove(f)
31
+
32
+ # Load model
33
+ google_utils.attempt_download(weights)
34
+ model = torch.load(weights, map_location=device)['model']
35
+ torch_utils.model_info(model)
36
+
37
+ # Fuse
38
+ # model.fuse()
39
+ model.to(device)
40
+
41
+ if device.type != 'cpu' and torch.cuda.device_count() > 1:
42
+ model = nn.DataParallel(model)
43
+
44
+ training = False
45
+ else: # called by train.py
46
+ device = next(model.parameters()).device # get model device
47
+ training = True
48
+
49
+ # Configure run
50
+ with open(data) as f:
51
+ data = yaml.load(f, Loader=yaml.FullLoader) # model dict
52
+ nc = 1 if single_cls else int(data['nc']) # number of classes
53
+ iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for [email protected]:0.95
54
+ # iouv = iouv[0].view(1) # comment for [email protected]:0.95
55
+ niou = iouv.numel()
56
+
57
+ # Dataloader
58
+ if dataloader is None:
59
+ path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images
60
+ dataset = LoadImagesAndLabels(path, imgsz, batch_size, rect=True, single_cls=opt.single_cls)
61
+ batch_size = min(batch_size, len(dataset))
62
+ dataloader = DataLoader(dataset,
63
+ batch_size=batch_size,
64
+ num_workers=min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]),
65
+ pin_memory=True,
66
+ collate_fn=dataset.collate_fn)
67
+
68
+ seen = 0
69
+ model.eval()
70
+ _ = model(torch.zeros((1, 3, imgsz, imgsz), device=device)) if device.type != 'cpu' else None # run once
71
+ coco91class = coco80_to_coco91_class()
72
+ s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', '[email protected]', '[email protected]:.95')
73
+ p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
74
+ loss = torch.zeros(3, device=device)
75
+ jdict, stats, ap, ap_class = [], [], [], []
76
+ for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
77
+ imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0
78
+ targets = targets.to(device)
79
+ nb, _, height, width = imgs.shape # batch size, channels, height, width
80
+ whwh = torch.Tensor([width, height, width, height]).to(device)
81
+
82
+ # Disable gradients
83
+ with torch.no_grad():
84
+ # Run model
85
+ t = torch_utils.time_synchronized()
86
+ inf_out, train_out = model(imgs, augment=augment) # inference and training outputs
87
+ t0 += torch_utils.time_synchronized() - t
88
+
89
+ # Compute loss
90
+ if training: # if model has loss hyperparameters
91
+ loss += compute_loss(train_out, targets, model)[1][:3] # GIoU, obj, cls
92
+
93
+ # Run NMS
94
+ t = torch_utils.time_synchronized()
95
+ output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, multi_label=multi_label)
96
+ t1 += torch_utils.time_synchronized() - t
97
+
98
+ # Statistics per image
99
+ for si, pred in enumerate(output):
100
+ labels = targets[targets[:, 0] == si, 1:]
101
+ nl = len(labels)
102
+ tcls = labels[:, 0].tolist() if nl else [] # target class
103
+ seen += 1
104
+
105
+ if pred is None:
106
+ if nl:
107
+ stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
108
+ continue
109
+
110
+ # Append to text file
111
+ # with open('test.txt', 'a') as file:
112
+ # [file.write('%11.5g' * 7 % tuple(x) + '\n') for x in pred]
113
+
114
+ # Clip boxes to image bounds
115
+ clip_coords(pred, (height, width))
116
+
117
+ # Append to pycocotools JSON dictionary
118
+ if save_json:
119
+ # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
120
+ image_id = int(Path(paths[si]).stem.split('_')[-1])
121
+ box = pred[:, :4].clone() # xyxy
122
+ scale_coords(imgs[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
123
+ box = xyxy2xywh(box) # xywh
124
+ box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
125
+ for p, b in zip(pred.tolist(), box.tolist()):
126
+ jdict.append({'image_id': image_id,
127
+ 'category_id': coco91class[int(p[5])],
128
+ 'bbox': [round(x, 3) for x in b],
129
+ 'score': round(p[4], 5)})
130
+
131
+ # Assign all predictions as incorrect
132
+ correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
133
+ if nl:
134
+ detected = [] # target indices
135
+ tcls_tensor = labels[:, 0]
136
+
137
+ # target boxes
138
+ tbox = xywh2xyxy(labels[:, 1:5]) * whwh
139
+
140
+ # Per target class
141
+ for cls in torch.unique(tcls_tensor):
142
+ ti = (cls == tcls_tensor).nonzero().view(-1) # prediction indices
143
+ pi = (cls == pred[:, 5]).nonzero().view(-1) # target indices
144
+
145
+ # Search for detections
146
+ if pi.shape[0]:
147
+ # Prediction to target ious
148
+ ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices
149
+
150
+ # Append detections
151
+ for j in (ious > iouv[0]).nonzero():
152
+ d = ti[i[j]] # detected target
153
+ if d not in detected:
154
+ detected.append(d)
155
+ correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
156
+ if len(detected) == nl: # all targets already located in image
157
+ break
158
+
159
+ # Append statistics (correct, conf, pcls, tcls)
160
+ stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
161
+
162
+ # Plot images
163
+ if batch_i < 1:
164
+ f = 'test_batch%g_gt.jpg' % batch_i # filename
165
+ plot_images(imgs, targets, paths, f, model.names) # ground truth
166
+ f = 'test_batch%g_pred.jpg' % batch_i
167
+ plot_images(imgs, output_to_target(output, width, height), paths, f, model.names) # predictions
168
+
169
+ # Compute statistics
170
+ stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
171
+ if len(stats):
172
+ p, r, ap, f1, ap_class = ap_per_class(*stats)
173
+ p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, [email protected], [email protected]:0.95]
174
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
175
+ nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
176
+ else:
177
+ nt = torch.zeros(1)
178
+
179
+ # Print results
180
+ pf = '%20s' + '%12.3g' * 6 # print format
181
+ print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
182
+
183
+ # Print results per class
184
+ if verbose and nc > 1 and len(stats):
185
+ for i, c in enumerate(ap_class):
186
+ print(pf % (model.names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
187
+
188
+ # Print speeds
189
+ t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
190
+ if not training:
191
+ print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
192
+
193
+ # Save JSON
194
+ if save_json and map50 and len(jdict):
195
+ imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataloader.dataset.img_files]
196
+ f = 'detections_val2017_%s_results.json' % \
197
+ (weights.split(os.sep)[-1].replace('.pt', '') if weights else '') # filename
198
+ print('\nCOCO mAP with pycocotools... saving %s...' % f)
199
+ with open(f, 'w') as file:
200
+ json.dump(jdict, file)
201
+
202
+ try:
203
+ from pycocotools.coco import COCO
204
+ from pycocotools.cocoeval import COCOeval
205
+
206
+ # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
207
+ cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api
208
+ cocoDt = cocoGt.loadRes(f) # initialize COCO pred api
209
+
210
+ cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
211
+ cocoEval.params.imgIds = imgIds # [:32] # only evaluate these images
212
+ cocoEval.evaluate()
213
+ cocoEval.accumulate()
214
+ cocoEval.summarize()
215
+ map, map50 = cocoEval.stats[:2] # update to pycocotools results ([email protected]:0.95, [email protected])
216
+ except:
217
+ print('WARNING: pycocotools must be installed with numpy==1.17 to run correctly. '
218
+ 'See https://github.com/cocodataset/cocoapi/issues/356')
219
+
220
+ # Return results
221
+ maps = np.zeros(nc) + map
222
+ for i, c in enumerate(ap_class):
223
+ maps[c] = ap[i]
224
+ return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
225
+
226
+
227
+ if __name__ == '__main__':
228
+ parser = argparse.ArgumentParser(prog='test.py')
229
+ parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
230
+ parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path')
231
+ parser.add_argument('--batch-size', type=int, default=16, help='size of each image batch')
232
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
233
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
234
+ parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS')
235
+ parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
236
+ parser.add_argument('--task', default='val', help="'val', 'test', 'study'")
237
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
238
+ parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
239
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
240
+ parser.add_argument('--verbose', action='store_true', help='report mAP by class')
241
+ opt = parser.parse_args()
242
+ opt.save_json = opt.save_json or opt.data.endswith(os.sep + 'coco.yaml')
243
+ opt.data = glob.glob('./**/' + opt.data, recursive=True)[0] # find file
244
+ print(opt)
245
+
246
+ # task = 'val', 'test', 'study'
247
+ if opt.task == 'val': # (default) run normally
248
+ test(opt.data,
249
+ opt.weights,
250
+ opt.batch_size,
251
+ opt.img_size,
252
+ opt.conf_thres,
253
+ opt.iou_thres,
254
+ opt.save_json,
255
+ opt.single_cls,
256
+ opt.augment)
257
+
258
+ elif opt.task == 'study': # run over a range of settings and save/plot
259
+ for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolovl.p5', 'yolov5x.pt', 'yolov3-spp.pt']:
260
+ f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to
261
+ x = list(range(256, 1024, 32)) # x axis
262
+ y = [] # y axis
263
+ for i in x: # img-size
264
+ print('\nRunning %s point %s...' % (f, i))
265
+ r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json)
266
+ y.append(r + t) # results and times
267
+ np.savetxt(f, y, fmt='%10.4g') # save
268
+ plot_study_txt(f, x) # plot
train.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import torch.distributed as dist
4
+ import torch.nn.functional as F
5
+ import torch.optim as optim
6
+ import torch.optim.lr_scheduler as lr_scheduler
7
+ import yaml
8
+ from torch.utils.tensorboard import SummaryWriter
9
+
10
+ import test # import test.py to get mAP after each epoch
11
+ from models.yolo import Model
12
+ from utils.datasets import *
13
+ from utils.utils import *
14
+
15
+ mixed_precision = True
16
+ try: # Mixed precision training https://github.com/NVIDIA/apex
17
+ from apex import amp
18
+ except:
19
+ print('Apex recommended for faster mixed precision training: https://github.com/NVIDIA/apex')
20
+ mixed_precision = False # not installed
21
+
22
+ wdir = 'weights' + os.sep # weights dir
23
+ last = wdir + 'last.pt'
24
+ best = wdir + 'best.pt'
25
+ results_file = 'results.txt'
26
+
27
+ # Hyperparameters
28
+ hyp = {'lr0': 0.01, # initial learning rate (SGD=1E-2, Adam=1E-3)
29
+ 'momentum': 0.937, # SGD momentum
30
+ 'weight_decay': 5e-4, # optimizer weight decay
31
+ 'giou': 0.05, # giou loss gain
32
+ 'cls': 0.58, # cls loss gain
33
+ 'cls_pw': 1.0, # cls BCELoss positive_weight
34
+ 'obj': 1.0, # obj loss gain (*=img_size/320 if img_size != 320)
35
+ 'obj_pw': 1.0, # obj BCELoss positive_weight
36
+ 'iou_t': 0.20, # iou training threshold
37
+ 'anchor_t': 4.0, # anchor-multiple threshold
38
+ 'fl_gamma': 0.0, # focal loss gamma (efficientDet default is gamma=1.5)
39
+ 'hsv_h': 0.014, # image HSV-Hue augmentation (fraction)
40
+ 'hsv_s': 0.68, # image HSV-Saturation augmentation (fraction)
41
+ 'hsv_v': 0.36, # image HSV-Value augmentation (fraction)
42
+ 'degrees': 0.0, # image rotation (+/- deg)
43
+ 'translate': 0.0, # image translation (+/- fraction)
44
+ 'scale': 0.5, # image scale (+/- gain)
45
+ 'shear': 0.0} # image shear (+/- deg)
46
+ print(hyp)
47
+
48
+ # Overwrite hyp with hyp*.txt (optional)
49
+ f = glob.glob('hyp*.txt')
50
+ if f:
51
+ print('Using %s' % f[0])
52
+ for k, v in zip(hyp.keys(), np.loadtxt(f[0])):
53
+ hyp[k] = v
54
+
55
+ # Print focal loss if gamma > 0
56
+ if hyp['fl_gamma']:
57
+ print('Using FocalLoss(gamma=%g)' % hyp['fl_gamma'])
58
+
59
+
60
+ def train(hyp):
61
+ epochs = opt.epochs # 300
62
+ batch_size = opt.batch_size # 64
63
+ weights = opt.weights # initial training weights
64
+
65
+ # Configure
66
+ init_seeds()
67
+ with open(opt.data) as f:
68
+ data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
69
+ train_path = data_dict['train']
70
+ test_path = data_dict['val']
71
+ nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes
72
+
73
+ # Remove previous results
74
+ for f in glob.glob('*_batch*.jpg') + glob.glob(results_file):
75
+ os.remove(f)
76
+
77
+ # Create model
78
+ model = Model(opt.cfg).to(device)
79
+
80
+ # Image sizes
81
+ gs = int(max(model.stride)) # grid size (max stride)
82
+ if any(x % gs != 0 for x in opt.img_size):
83
+ print('WARNING: --img-size %g,%g must be multiple of %s max stride %g' % (*opt.img_size, opt.cfg, gs))
84
+ imgsz, imgsz_test = [make_divisible(x, gs) for x in opt.img_size] # image sizes (train, test)
85
+
86
+ # Optimizer
87
+ nbs = 64 # nominal batch size
88
+ accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
89
+ hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
90
+ pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
91
+ for k, v in model.named_parameters():
92
+ if v.requires_grad:
93
+ if '.bias' in k:
94
+ pg2.append(v) # biases
95
+ elif '.weight' in k and '.bn' not in k:
96
+ pg1.append(v) # apply weight decay
97
+ else:
98
+ pg0.append(v) # all else
99
+
100
+ optimizer = optim.Adam(pg0, lr=hyp['lr0']) if opt.adam else \
101
+ optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
102
+ optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
103
+ optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
104
+ print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
105
+ del pg0, pg1, pg2
106
+
107
+ # Load Model
108
+ google_utils.attempt_download(weights)
109
+ start_epoch, best_fitness = 0, 0.0
110
+ if weights.endswith('.pt'): # pytorch format
111
+ chkpt = torch.load(weights, map_location=device)
112
+
113
+ # load model
114
+ try:
115
+ chkpt['model'] = \
116
+ {k: v for k, v in chkpt['model'].state_dict().items() if model.state_dict()[k].numel() == v.numel()}
117
+ model.load_state_dict(chkpt['model'], strict=False)
118
+ except KeyError as e:
119
+ s = "%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s." \
120
+ % (opt.weights, opt.cfg, opt.weights)
121
+ raise KeyError(s) from e
122
+
123
+ # load optimizer
124
+ if chkpt['optimizer'] is not None:
125
+ optimizer.load_state_dict(chkpt['optimizer'])
126
+ best_fitness = chkpt['best_fitness']
127
+
128
+ # load results
129
+ if chkpt.get('training_results') is not None:
130
+ with open(results_file, 'w') as file:
131
+ file.write(chkpt['training_results']) # write results.txt
132
+
133
+ start_epoch = chkpt['epoch'] + 1
134
+ del chkpt
135
+
136
+ # Mixed precision training https://github.com/NVIDIA/apex
137
+ if mixed_precision:
138
+ model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0)
139
+
140
+ # Scheduler https://arxiv.org/pdf/1812.01187.pdf
141
+ lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.9 + 0.1 # cosine
142
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
143
+ scheduler.last_epoch = start_epoch - 1 # do not move
144
+ # https://discuss.pytorch.org/t/a-problem-occured-when-resuming-an-optimizer/28822
145
+ # plot_lr_scheduler(optimizer, scheduler, epochs)
146
+
147
+ # Initialize distributed training
148
+ if device.type != 'cpu' and torch.cuda.device_count() > 1 and torch.distributed.is_available():
149
+ dist.init_process_group(backend='nccl', # distributed backend
150
+ init_method='tcp://127.0.0.1:9999', # init method
151
+ world_size=1, # number of nodes
152
+ rank=0) # node rank
153
+ model = torch.nn.parallel.DistributedDataParallel(model)
154
+
155
+ # Dataset
156
+ dataset = LoadImagesAndLabels(train_path, imgsz, batch_size,
157
+ augment=True,
158
+ hyp=hyp, # augmentation hyperparameters
159
+ rect=opt.rect, # rectangular training
160
+ cache_images=opt.cache_images,
161
+ single_cls=opt.single_cls)
162
+ mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
163
+ assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Correct your labels or your model.' % (mlc, nc, opt.cfg)
164
+
165
+ # Dataloader
166
+ batch_size = min(batch_size, len(dataset))
167
+ nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers
168
+ dataloader = torch.utils.data.DataLoader(dataset,
169
+ batch_size=batch_size,
170
+ num_workers=nw,
171
+ shuffle=not opt.rect, # Shuffle=True unless rectangular training is used
172
+ pin_memory=True,
173
+ collate_fn=dataset.collate_fn)
174
+
175
+ # Testloader
176
+ testloader = torch.utils.data.DataLoader(LoadImagesAndLabels(test_path, imgsz_test, batch_size,
177
+ hyp=hyp,
178
+ rect=True,
179
+ cache_images=opt.cache_images,
180
+ single_cls=opt.single_cls),
181
+ batch_size=batch_size,
182
+ num_workers=nw,
183
+ pin_memory=True,
184
+ collate_fn=dataset.collate_fn)
185
+
186
+ # Model parameters
187
+ hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset
188
+ model.nc = nc # attach number of classes to model
189
+ model.hyp = hyp # attach hyperparameters to model
190
+ model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou)
191
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
192
+ model.names = data_dict['names']
193
+
194
+ # class frequency
195
+ labels = np.concatenate(dataset.labels, 0)
196
+ c = torch.tensor(labels[:, 0]) # classes
197
+ # cf = torch.bincount(c.long(), minlength=nc) + 1.
198
+ # model._initialize_biases(cf.to(device))
199
+ plot_labels(labels)
200
+ tb_writer.add_histogram('classes', c, 0)
201
+
202
+ # Exponential moving average
203
+ ema = torch_utils.ModelEMA(model)
204
+
205
+ # Start training
206
+ t0 = time.time()
207
+ nb = len(dataloader) # number of batches
208
+ n_burn = max(3 * nb, 1e3) # burn-in iterations, max(3 epochs, 1k iterations)
209
+ maps = np.zeros(nc) # mAP per class
210
+ results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
211
+ print('Image sizes %g train, %g test' % (imgsz, imgsz_test))
212
+ print('Using %g dataloader workers' % nw)
213
+ print('Starting training for %g epochs...' % epochs)
214
+ # torch.autograd.set_detect_anomaly(True)
215
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
216
+ model.train()
217
+
218
+ # Update image weights (optional)
219
+ if dataset.image_weights:
220
+ w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
221
+ image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
222
+ dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n) # rand weighted idx
223
+
224
+ mloss = torch.zeros(4, device=device) # mean losses
225
+ print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
226
+ pbar = tqdm(enumerate(dataloader), total=nb) # progress bar
227
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
228
+ ni = i + nb * epoch # number integrated batches (since train start)
229
+ imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0
230
+
231
+ # Burn-in
232
+ if ni <= n_burn:
233
+ xi = [0, n_burn] # x interp
234
+ # model.gr = np.interp(ni, xi, [0.0, 1.0]) # giou loss ratio (obj_loss = 1.0 or giou)
235
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
236
+ for j, x in enumerate(optimizer.param_groups):
237
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
238
+ x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
239
+ if 'momentum' in x:
240
+ x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']])
241
+
242
+ # Multi-scale
243
+ if True:
244
+ imgsz = random.randrange(640, 640 + gs) // gs * gs
245
+ sf = imgsz / max(imgs.shape[2:]) # scale factor
246
+ if sf != 1:
247
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
248
+ imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
249
+
250
+ # Forward
251
+ pred = model(imgs)
252
+
253
+ # Loss
254
+ loss, loss_items = compute_loss(pred, targets.to(device), model)
255
+ if not torch.isfinite(loss):
256
+ print('WARNING: non-finite loss, ending training ', loss_items)
257
+ return results
258
+
259
+ # Backward
260
+ if mixed_precision:
261
+ with amp.scale_loss(loss, optimizer) as scaled_loss:
262
+ scaled_loss.backward()
263
+ else:
264
+ loss.backward()
265
+
266
+ # Optimize
267
+ if ni % accumulate == 0:
268
+ optimizer.step()
269
+ optimizer.zero_grad()
270
+ ema.update(model)
271
+
272
+ # Print
273
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
274
+ mem = '%.3gG' % (torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0) # (GB)
275
+ s = ('%10s' * 2 + '%10.4g' * 6) % ('%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgsz)
276
+ pbar.set_description(s)
277
+
278
+ # Plot
279
+ if ni < 3:
280
+ f = 'train_batch%g.jpg' % i # filename
281
+ res = plot_images(images=imgs, targets=targets, paths=paths, fname=f)
282
+ if tb_writer:
283
+ tb_writer.add_image(f, res, dataformats='HWC', global_step=epoch)
284
+ # tb_writer.add_graph(model, imgs) # add model to tensorboard
285
+
286
+ # end batch ------------------------------------------------------------------------------------------------
287
+
288
+ # Scheduler
289
+ scheduler.step()
290
+
291
+ # mAP
292
+ ema.update_attr(model)
293
+ final_epoch = epoch + 1 == epochs
294
+ if not opt.notest or final_epoch: # Calculate mAP
295
+ results, maps, times = test.test(opt.data,
296
+ batch_size=batch_size,
297
+ imgsz=imgsz_test,
298
+ save_json=final_epoch and opt.data.endswith(os.sep + 'coco.yaml'),
299
+ model=ema.ema,
300
+ single_cls=opt.single_cls,
301
+ dataloader=testloader,
302
+ multi_label=ni > n_burn)
303
+
304
+ # Write
305
+ with open(results_file, 'a') as f:
306
+ f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
307
+ if len(opt.name) and opt.bucket:
308
+ os.system('gsutil cp results.txt gs://%s/results/results%s.txt' % (opt.bucket, opt.name))
309
+
310
+ # Tensorboard
311
+ if tb_writer:
312
+ tags = ['train/giou_loss', 'train/obj_loss', 'train/cls_loss',
313
+ 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/F1',
314
+ 'val/giou_loss', 'val/obj_loss', 'val/cls_loss']
315
+ for x, tag in zip(list(mloss[:-1]) + list(results), tags):
316
+ tb_writer.add_scalar(tag, x, epoch)
317
+
318
+ # Update best mAP
319
+ fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1]
320
+ if fi > best_fitness:
321
+ best_fitness = fi
322
+
323
+ # Save model
324
+ save = (not opt.nosave) or (final_epoch and not opt.evolve)
325
+ if save:
326
+ with open(results_file, 'r') as f: # create checkpoint
327
+ chkpt = {'epoch': epoch,
328
+ 'best_fitness': best_fitness,
329
+ 'training_results': f.read(),
330
+ 'model': ema.ema.module if hasattr(model, 'module') else ema.ema,
331
+ 'optimizer': None if final_epoch else optimizer.state_dict()}
332
+
333
+ # Save last, best and delete
334
+ torch.save(chkpt, last)
335
+ if (best_fitness == fi) and not final_epoch:
336
+ torch.save(chkpt, best)
337
+ del chkpt
338
+
339
+ # end epoch ----------------------------------------------------------------------------------------------------
340
+ # end training
341
+
342
+ n = opt.name
343
+ if len(n):
344
+ n = '_' + n if not n.isnumeric() else n
345
+ fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n
346
+ for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]):
347
+ if os.path.exists(f1):
348
+ os.rename(f1, f2) # rename
349
+ ispt = f2.endswith('.pt') # is *.pt
350
+ strip_optimizer(f2) if ispt else None # strip optimizer
351
+ os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload
352
+
353
+ if not opt.evolve:
354
+ plot_results() # save as results.png
355
+ print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
356
+ dist.destroy_process_group() if torch.cuda.device_count() > 1 else None
357
+ torch.cuda.empty_cache()
358
+ return results
359
+
360
+
361
+ if __name__ == '__main__':
362
+ parser = argparse.ArgumentParser()
363
+ parser.add_argument('--epochs', type=int, default=300)
364
+ parser.add_argument('--batch-size', type=int, default=16)
365
+ parser.add_argument('--cfg', type=str, default='models/yolov5s.yaml', help='*.cfg path')
366
+ parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
367
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes')
368
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
369
+ parser.add_argument('--resume', action='store_true', help='resume training from last.pt')
370
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
371
+ parser.add_argument('--notest', action='store_true', help='only test final epoch')
372
+ parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
373
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
374
+ parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
375
+ parser.add_argument('--weights', type=str, default='', help='initial weights path')
376
+ parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
377
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
378
+ parser.add_argument('--adam', action='store_true', help='use adam optimizer')
379
+ parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
380
+ opt = parser.parse_args()
381
+ opt.weights = last if opt.resume else opt.weights
382
+ opt.cfg = glob.glob('./**/' + opt.cfg, recursive=True)[0] # find file
383
+ opt.data = glob.glob('./**/' + opt.data, recursive=True)[0] # find file
384
+ print(opt)
385
+ opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
386
+ device = torch_utils.select_device(opt.device, apex=mixed_precision, batch_size=opt.batch_size)
387
+ # check_git_status()
388
+ if device.type == 'cpu':
389
+ mixed_precision = False
390
+
391
+ # Train
392
+ if not opt.evolve:
393
+ tb_writer = SummaryWriter(comment=opt.name)
394
+ print('Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/')
395
+ train(hyp)
396
+
397
+ # Evolve hyperparameters (optional)
398
+ else:
399
+ tb_writer = None
400
+ opt.notest, opt.nosave = True, True # only test/save final epoch
401
+ if opt.bucket:
402
+ os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
403
+
404
+ for _ in range(10): # generations to evolve
405
+ if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate
406
+ # Select parent(s)
407
+ parent = 'single' # parent selection method: 'single' or 'weighted'
408
+ x = np.loadtxt('evolve.txt', ndmin=2)
409
+ n = min(5, len(x)) # number of previous results to consider
410
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
411
+ w = fitness(x) - fitness(x).min() # weights
412
+ if parent == 'single' or len(x) == 1:
413
+ # x = x[random.randint(0, n - 1)] # random selection
414
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
415
+ elif parent == 'weighted':
416
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
417
+
418
+ # Mutate
419
+ mp, s = 0.9, 0.2 # mutation probability, sigma
420
+ npr = np.random
421
+ npr.seed(int(time.time()))
422
+ g = np.array([1, 1, 1, 1, 1, 1, 1, 0, .1, 1, 0, 1, 1, 1, 1, 1, 1, 1]) # gains
423
+ ng = len(g)
424
+ v = np.ones(ng)
425
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
426
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
427
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
428
+ hyp[k] = x[i + 7] * v[i] # mutate
429
+
430
+ # Clip to limits
431
+ keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale', 'fl_gamma']
432
+ limits = [(1e-5, 1e-2), (0.00, 0.70), (0.60, 0.98), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9), (0, 3)]
433
+ for k, v in zip(keys, limits):
434
+ hyp[k] = np.clip(hyp[k], v[0], v[1])
435
+
436
+ # Train mutation
437
+ results = train(hyp.copy())
438
+
439
+ # Write mutation results
440
+ print_mutation(hyp, results, opt.bucket)
441
+
442
+ # Plot results
443
+ # plot_evolution_results(hyp)
tutorial.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
utils/__init__.py ADDED
File without changes
utils/activations.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.functional as F
3
+ import torch.nn as nn
4
+
5
+
6
+ # Swish ------------------------------------------------------------------------
7
+ class SwishImplementation(torch.autograd.Function):
8
+ @staticmethod
9
+ def forward(ctx, x):
10
+ ctx.save_for_backward(x)
11
+ return x * torch.sigmoid(x)
12
+
13
+ @staticmethod
14
+ def backward(ctx, grad_output):
15
+ x = ctx.saved_tensors[0]
16
+ sx = torch.sigmoid(x)
17
+ return grad_output * (sx * (1 + x * (1 - sx)))
18
+
19
+
20
+ class MemoryEfficientSwish(nn.Module):
21
+ @staticmethod
22
+ def forward(x):
23
+ return SwishImplementation.apply(x)
24
+
25
+
26
+ class HardSwish(nn.Module): # https://arxiv.org/pdf/1905.02244.pdf
27
+ @staticmethod
28
+ def forward(x):
29
+ return x * F.hardtanh(x + 3, 0., 6., True) / 6.
30
+
31
+
32
+ class Swish(nn.Module):
33
+ @staticmethod
34
+ def forward(x):
35
+ return x * torch.sigmoid(x)
36
+
37
+
38
+ # Mish ------------------------------------------------------------------------
39
+ class MishImplementation(torch.autograd.Function):
40
+ @staticmethod
41
+ def forward(ctx, x):
42
+ ctx.save_for_backward(x)
43
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
44
+
45
+ @staticmethod
46
+ def backward(ctx, grad_output):
47
+ x = ctx.saved_tensors[0]
48
+ sx = torch.sigmoid(x)
49
+ fx = F.softplus(x).tanh()
50
+ return grad_output * (fx + x * sx * (1 - fx * fx))
51
+
52
+
53
+ class MemoryEfficientMish(nn.Module):
54
+ @staticmethod
55
+ def forward(x):
56
+ return MishImplementation.apply(x)
57
+
58
+
59
+ class Mish(nn.Module): # https://github.com/digantamisra98/Mish
60
+ @staticmethod
61
+ def forward(x):
62
+ return x * F.softplus(x).tanh()
utils/datasets.py ADDED
@@ -0,0 +1,842 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import math
3
+ import os
4
+ import random
5
+ import shutil
6
+ import time
7
+ from pathlib import Path
8
+ from threading import Thread
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import torch
13
+ from PIL import Image, ExifTags
14
+ from torch.utils.data import Dataset
15
+ from tqdm import tqdm
16
+
17
+ from utils.utils import xyxy2xywh, xywh2xyxy
18
+
19
+ help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
20
+ img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.dng']
21
+ vid_formats = ['.mov', '.avi', '.mp4']
22
+
23
+ # Get orientation exif tag
24
+ for orientation in ExifTags.TAGS.keys():
25
+ if ExifTags.TAGS[orientation] == 'Orientation':
26
+ break
27
+
28
+
29
+ def exif_size(img):
30
+ # Returns exif-corrected PIL size
31
+ s = img.size # (width, height)
32
+ try:
33
+ rotation = dict(img._getexif().items())[orientation]
34
+ if rotation == 6: # rotation 270
35
+ s = (s[1], s[0])
36
+ elif rotation == 8: # rotation 90
37
+ s = (s[1], s[0])
38
+ except:
39
+ pass
40
+
41
+ return s
42
+
43
+
44
+ class LoadImages: # for inference
45
+ def __init__(self, path, img_size=416):
46
+ path = str(Path(path)) # os-agnostic
47
+ files = []
48
+ if os.path.isdir(path):
49
+ files = sorted(glob.glob(os.path.join(path, '*.*')))
50
+ elif os.path.isfile(path):
51
+ files = [path]
52
+
53
+ images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
54
+ videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats]
55
+ nI, nV = len(images), len(videos)
56
+
57
+ self.img_size = img_size
58
+ self.files = images + videos
59
+ self.nF = nI + nV # number of files
60
+ self.video_flag = [False] * nI + [True] * nV
61
+ self.mode = 'images'
62
+ if any(videos):
63
+ self.new_video(videos[0]) # new video
64
+ else:
65
+ self.cap = None
66
+ assert self.nF > 0, 'No images or videos found in ' + path
67
+
68
+ def __iter__(self):
69
+ self.count = 0
70
+ return self
71
+
72
+ def __next__(self):
73
+ if self.count == self.nF:
74
+ raise StopIteration
75
+ path = self.files[self.count]
76
+
77
+ if self.video_flag[self.count]:
78
+ # Read video
79
+ self.mode = 'video'
80
+ ret_val, img0 = self.cap.read()
81
+ if not ret_val:
82
+ self.count += 1
83
+ self.cap.release()
84
+ if self.count == self.nF: # last video
85
+ raise StopIteration
86
+ else:
87
+ path = self.files[self.count]
88
+ self.new_video(path)
89
+ ret_val, img0 = self.cap.read()
90
+
91
+ self.frame += 1
92
+ print('video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nF, self.frame, self.nframes, path), end='')
93
+
94
+ else:
95
+ # Read image
96
+ self.count += 1
97
+ img0 = cv2.imread(path) # BGR
98
+ assert img0 is not None, 'Image Not Found ' + path
99
+ print('image %g/%g %s: ' % (self.count, self.nF, path), end='')
100
+
101
+ # Padded resize
102
+ img = letterbox(img0, new_shape=self.img_size)[0]
103
+
104
+ # Convert
105
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
106
+ img = np.ascontiguousarray(img)
107
+
108
+ # cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image
109
+ return path, img, img0, self.cap
110
+
111
+ def new_video(self, path):
112
+ self.frame = 0
113
+ self.cap = cv2.VideoCapture(path)
114
+ self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
115
+
116
+ def __len__(self):
117
+ return self.nF # number of files
118
+
119
+
120
+ class LoadWebcam: # for inference
121
+ def __init__(self, pipe=0, img_size=416):
122
+ self.img_size = img_size
123
+
124
+ if pipe == '0':
125
+ pipe = 0 # local camera
126
+ # pipe = 'rtsp://192.168.1.64/1' # IP camera
127
+ # pipe = 'rtsp://username:[email protected]/1' # IP camera with login
128
+ # pipe = 'rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa' # IP traffic camera
129
+ # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
130
+
131
+ # https://answers.opencv.org/question/215996/changing-gstreamer-pipeline-to-opencv-in-pythonsolved/
132
+ # pipe = '"rtspsrc location="rtsp://username:[email protected]/1" latency=10 ! appsink' # GStreamer
133
+
134
+ # https://answers.opencv.org/question/200787/video-acceleration-gstremer-pipeline-in-videocapture/
135
+ # https://stackoverflow.com/questions/54095699/install-gstreamer-support-for-opencv-python-package # install help
136
+ # pipe = "rtspsrc location=rtsp://root:[email protected]:554/axis-media/media.amp?videocodec=h264&resolution=3840x2160 protocols=GST_RTSP_LOWER_TRANS_TCP ! rtph264depay ! queue ! vaapih264dec ! videoconvert ! appsink" # GStreamer
137
+
138
+ self.pipe = pipe
139
+ self.cap = cv2.VideoCapture(pipe) # video capture object
140
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
141
+
142
+ def __iter__(self):
143
+ self.count = -1
144
+ return self
145
+
146
+ def __next__(self):
147
+ self.count += 1
148
+ if cv2.waitKey(1) == ord('q'): # q to quit
149
+ self.cap.release()
150
+ cv2.destroyAllWindows()
151
+ raise StopIteration
152
+
153
+ # Read frame
154
+ if self.pipe == 0: # local camera
155
+ ret_val, img0 = self.cap.read()
156
+ img0 = cv2.flip(img0, 1) # flip left-right
157
+ else: # IP camera
158
+ n = 0
159
+ while True:
160
+ n += 1
161
+ self.cap.grab()
162
+ if n % 30 == 0: # skip frames
163
+ ret_val, img0 = self.cap.retrieve()
164
+ if ret_val:
165
+ break
166
+
167
+ # Print
168
+ assert ret_val, 'Camera Error %s' % self.pipe
169
+ img_path = 'webcam.jpg'
170
+ print('webcam %g: ' % self.count, end='')
171
+
172
+ # Padded resize
173
+ img = letterbox(img0, new_shape=self.img_size)[0]
174
+
175
+ # Convert
176
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
177
+ img = np.ascontiguousarray(img)
178
+
179
+ return img_path, img, img0, None
180
+
181
+ def __len__(self):
182
+ return 0
183
+
184
+
185
+ class LoadStreams: # multiple IP or RTSP cameras
186
+ def __init__(self, sources='streams.txt', img_size=416):
187
+ self.mode = 'images'
188
+ self.img_size = img_size
189
+
190
+ if os.path.isfile(sources):
191
+ with open(sources, 'r') as f:
192
+ sources = [x.strip() for x in f.read().splitlines() if len(x.strip())]
193
+ else:
194
+ sources = [sources]
195
+
196
+ n = len(sources)
197
+ self.imgs = [None] * n
198
+ self.sources = sources
199
+ for i, s in enumerate(sources):
200
+ # Start the thread to read frames from the video stream
201
+ print('%g/%g: %s... ' % (i + 1, n, s), end='')
202
+ cap = cv2.VideoCapture(0 if s == '0' else s)
203
+ assert cap.isOpened(), 'Failed to open %s' % s
204
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
205
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
206
+ fps = cap.get(cv2.CAP_PROP_FPS) % 100
207
+ _, self.imgs[i] = cap.read() # guarantee first frame
208
+ thread = Thread(target=self.update, args=([i, cap]), daemon=True)
209
+ print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
210
+ thread.start()
211
+ print('') # newline
212
+
213
+ # check for common shapes
214
+ s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0) # inference shapes
215
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
216
+ if not self.rect:
217
+ print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
218
+
219
+ def update(self, index, cap):
220
+ # Read next stream frame in a daemon thread
221
+ n = 0
222
+ while cap.isOpened():
223
+ n += 1
224
+ # _, self.imgs[index] = cap.read()
225
+ cap.grab()
226
+ if n == 4: # read every 4th frame
227
+ _, self.imgs[index] = cap.retrieve()
228
+ n = 0
229
+ time.sleep(0.01) # wait time
230
+
231
+ def __iter__(self):
232
+ self.count = -1
233
+ return self
234
+
235
+ def __next__(self):
236
+ self.count += 1
237
+ img0 = self.imgs.copy()
238
+ if cv2.waitKey(1) == ord('q'): # q to quit
239
+ cv2.destroyAllWindows()
240
+ raise StopIteration
241
+
242
+ # Letterbox
243
+ img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]
244
+
245
+ # Stack
246
+ img = np.stack(img, 0)
247
+
248
+ # Convert
249
+ img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
250
+ img = np.ascontiguousarray(img)
251
+
252
+ return self.sources, img, img0, None
253
+
254
+ def __len__(self):
255
+ return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
256
+
257
+
258
+ class LoadImagesAndLabels(Dataset): # for training/testing
259
+ def __init__(self, path, img_size=416, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
260
+ cache_images=False, single_cls=False):
261
+ try:
262
+ path = str(Path(path)) # os-agnostic
263
+ parent = str(Path(path).parent) + os.sep
264
+ if os.path.isfile(path): # file
265
+ with open(path, 'r') as f:
266
+ f = f.read().splitlines()
267
+ f = [x.replace('./', parent) if x.startswith('./') else x for x in f] # local to global path
268
+ elif os.path.isdir(path): # folder
269
+ f = glob.iglob(path + os.sep + '*.*')
270
+ else:
271
+ raise Exception('%s does not exist' % path)
272
+ self.img_files = [x.replace('/', os.sep) for x in f if os.path.splitext(x)[-1].lower() in img_formats]
273
+ except:
274
+ raise Exception('Error loading data from %s. See %s' % (path, help_url))
275
+
276
+ n = len(self.img_files)
277
+ assert n > 0, 'No images found in %s. See %s' % (path, help_url)
278
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
279
+ nb = bi[-1] + 1 # number of batches
280
+
281
+ self.n = n # number of images
282
+ self.batch = bi # batch index of image
283
+ self.img_size = img_size
284
+ self.augment = augment
285
+ self.hyp = hyp
286
+ self.image_weights = image_weights
287
+ self.rect = False if image_weights else rect
288
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
289
+
290
+ # Define labels
291
+ self.label_files = [x.replace('images', 'labels').replace(os.path.splitext(x)[-1], '.txt')
292
+ for x in self.img_files]
293
+
294
+ # Rectangular Training https://github.com/ultralytics/yolov3/issues/232
295
+ if self.rect:
296
+ # Read image shapes (wh)
297
+ sp = path.replace('.txt', '') + '.shapes' # shapefile path
298
+ try:
299
+ with open(sp, 'r') as f: # read existing shapefile
300
+ s = [x.split() for x in f.read().splitlines()]
301
+ assert len(s) == n, 'Shapefile out of sync'
302
+ except:
303
+ s = [exif_size(Image.open(f)) for f in tqdm(self.img_files, desc='Reading image shapes')]
304
+ np.savetxt(sp, s, fmt='%g') # overwrites existing (if any)
305
+
306
+ # Sort by aspect ratio
307
+ s = np.array(s, dtype=np.float64)
308
+ ar = s[:, 1] / s[:, 0] # aspect ratio
309
+ irect = ar.argsort()
310
+ self.img_files = [self.img_files[i] for i in irect]
311
+ self.label_files = [self.label_files[i] for i in irect]
312
+ self.shapes = s[irect] # wh
313
+ ar = ar[irect]
314
+
315
+ # Set training image shapes
316
+ shapes = [[1, 1]] * nb
317
+ for i in range(nb):
318
+ ari = ar[bi == i]
319
+ mini, maxi = ari.min(), ari.max()
320
+ if maxi < 1:
321
+ shapes[i] = [maxi, 1]
322
+ elif mini > 1:
323
+ shapes[i] = [1, 1 / mini]
324
+
325
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / 64.).astype(np.int) * 64
326
+
327
+ # Cache labels
328
+ self.imgs = [None] * n
329
+ self.labels = [np.zeros((0, 5), dtype=np.float32)] * n
330
+ create_datasubset, extract_bounding_boxes, labels_loaded = False, False, False
331
+ nm, nf, ne, ns, nd = 0, 0, 0, 0, 0 # number missing, found, empty, datasubset, duplicate
332
+ np_labels_path = str(Path(self.label_files[0]).parent) + '.npy' # saved labels in *.npy file
333
+ if os.path.isfile(np_labels_path):
334
+ s = np_labels_path # print string
335
+ x = np.load(np_labels_path, allow_pickle=True)
336
+ if len(x) == n:
337
+ self.labels = x
338
+ labels_loaded = True
339
+ else:
340
+ s = path.replace('images', 'labels')
341
+
342
+ pbar = tqdm(self.label_files)
343
+ for i, file in enumerate(pbar):
344
+ if labels_loaded:
345
+ l = self.labels[i]
346
+ # np.savetxt(file, l, '%g') # save *.txt from *.npy file
347
+ else:
348
+ try:
349
+ with open(file, 'r') as f:
350
+ l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
351
+ except:
352
+ nm += 1 # print('missing labels for image %s' % self.img_files[i]) # file missing
353
+ continue
354
+
355
+ if l.shape[0]:
356
+ assert l.shape[1] == 5, '> 5 label columns: %s' % file
357
+ assert (l >= 0).all(), 'negative labels: %s' % file
358
+ assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file
359
+ if np.unique(l, axis=0).shape[0] < l.shape[0]: # duplicate rows
360
+ nd += 1 # print('WARNING: duplicate rows in %s' % self.label_files[i]) # duplicate rows
361
+ if single_cls:
362
+ l[:, 0] = 0 # force dataset into single-class mode
363
+ self.labels[i] = l
364
+ nf += 1 # file found
365
+
366
+ # Create subdataset (a smaller dataset)
367
+ if create_datasubset and ns < 1E4:
368
+ if ns == 0:
369
+ create_folder(path='./datasubset')
370
+ os.makedirs('./datasubset/images')
371
+ exclude_classes = 43
372
+ if exclude_classes not in l[:, 0]:
373
+ ns += 1
374
+ # shutil.copy(src=self.img_files[i], dst='./datasubset/images/') # copy image
375
+ with open('./datasubset/images.txt', 'a') as f:
376
+ f.write(self.img_files[i] + '\n')
377
+
378
+ # Extract object detection boxes for a second stage classifier
379
+ if extract_bounding_boxes:
380
+ p = Path(self.img_files[i])
381
+ img = cv2.imread(str(p))
382
+ h, w = img.shape[:2]
383
+ for j, x in enumerate(l):
384
+ f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name)
385
+ if not os.path.exists(Path(f).parent):
386
+ os.makedirs(Path(f).parent) # make new output folder
387
+
388
+ b = x[1:] * [w, h, w, h] # box
389
+ b[2:] = b[2:].max() # rectangle to square
390
+ b[2:] = b[2:] * 1.3 + 30 # pad
391
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
392
+
393
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
394
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
395
+ assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes'
396
+ else:
397
+ ne += 1 # print('empty labels for image %s' % self.img_files[i]) # file empty
398
+ # os.system("rm '%s' '%s'" % (self.img_files[i], self.label_files[i])) # remove
399
+
400
+ pbar.desc = 'Caching labels %s (%g found, %g missing, %g empty, %g duplicate, for %g images)' % (
401
+ s, nf, nm, ne, nd, n)
402
+ assert nf > 0 or n == 20288, 'No labels found in %s. See %s' % (os.path.dirname(file) + os.sep, help_url)
403
+ if not labels_loaded and n > 1000:
404
+ print('Saving labels to %s for faster future loading' % np_labels_path)
405
+ np.save(np_labels_path, self.labels) # save for next time
406
+
407
+ # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
408
+ if cache_images: # if training
409
+ gb = 0 # Gigabytes of cached images
410
+ pbar = tqdm(range(len(self.img_files)), desc='Caching images')
411
+ self.img_hw0, self.img_hw = [None] * n, [None] * n
412
+ for i in pbar: # max 10k images
413
+ self.imgs[i], self.img_hw0[i], self.img_hw[i] = load_image(self, i) # img, hw_original, hw_resized
414
+ gb += self.imgs[i].nbytes
415
+ pbar.desc = 'Caching images (%.1fGB)' % (gb / 1E9)
416
+
417
+ # Detect corrupted images https://medium.com/joelthchao/programmatically-detect-corrupted-image-8c1b2006c3d3
418
+ detect_corrupted_images = False
419
+ if detect_corrupted_images:
420
+ from skimage import io # conda install -c conda-forge scikit-image
421
+ for file in tqdm(self.img_files, desc='Detecting corrupted images'):
422
+ try:
423
+ _ = io.imread(file)
424
+ except:
425
+ print('Corrupted image detected: %s' % file)
426
+
427
+ def __len__(self):
428
+ return len(self.img_files)
429
+
430
+ # def __iter__(self):
431
+ # self.count = -1
432
+ # print('ran dataset iter')
433
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
434
+ # return self
435
+
436
+ def __getitem__(self, index):
437
+ if self.image_weights:
438
+ index = self.indices[index]
439
+
440
+ hyp = self.hyp
441
+ if self.mosaic:
442
+ # Load mosaic
443
+ img, labels = load_mosaic(self, index)
444
+ shapes = None
445
+
446
+ else:
447
+ # Load image
448
+ img, (h0, w0), (h, w) = load_image(self, index)
449
+
450
+ # Letterbox
451
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
452
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
453
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
454
+
455
+ # Load labels
456
+ labels = []
457
+ x = self.labels[index]
458
+ if x.size > 0:
459
+ # Normalized xywh to pixel xyxy format
460
+ labels = x.copy()
461
+ labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0] # pad width
462
+ labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1] # pad height
463
+ labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0]
464
+ labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1]
465
+
466
+ if self.augment:
467
+ # Augment imagespace
468
+ if not self.mosaic:
469
+ img, labels = random_affine(img, labels,
470
+ degrees=hyp['degrees'],
471
+ translate=hyp['translate'],
472
+ scale=hyp['scale'],
473
+ shear=hyp['shear'])
474
+
475
+ # Augment colorspace
476
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
477
+
478
+ # Apply cutouts
479
+ # if random.random() < 0.9:
480
+ # labels = cutout(img, labels)
481
+
482
+ nL = len(labels) # number of labels
483
+ if nL:
484
+ # convert xyxy to xywh
485
+ labels[:, 1:5] = xyxy2xywh(labels[:, 1:5])
486
+
487
+ # Normalize coordinates 0 - 1
488
+ labels[:, [2, 4]] /= img.shape[0] # height
489
+ labels[:, [1, 3]] /= img.shape[1] # width
490
+
491
+ if self.augment:
492
+ # random left-right flip
493
+ lr_flip = True
494
+ if lr_flip and random.random() < 0.5:
495
+ img = np.fliplr(img)
496
+ if nL:
497
+ labels[:, 1] = 1 - labels[:, 1]
498
+
499
+ # random up-down flip
500
+ ud_flip = False
501
+ if ud_flip and random.random() < 0.5:
502
+ img = np.flipud(img)
503
+ if nL:
504
+ labels[:, 2] = 1 - labels[:, 2]
505
+
506
+ labels_out = torch.zeros((nL, 6))
507
+ if nL:
508
+ labels_out[:, 1:] = torch.from_numpy(labels)
509
+
510
+ # Convert
511
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
512
+ img = np.ascontiguousarray(img)
513
+
514
+ return torch.from_numpy(img), labels_out, self.img_files[index], shapes
515
+
516
+ @staticmethod
517
+ def collate_fn(batch):
518
+ img, label, path, shapes = zip(*batch) # transposed
519
+ for i, l in enumerate(label):
520
+ l[:, 0] = i # add target image index for build_targets()
521
+ return torch.stack(img, 0), torch.cat(label, 0), path, shapes
522
+
523
+
524
+ def load_image(self, index):
525
+ # loads 1 image from dataset, returns img, original hw, resized hw
526
+ img = self.imgs[index]
527
+ if img is None: # not cached
528
+ path = self.img_files[index]
529
+ img = cv2.imread(path) # BGR
530
+ assert img is not None, 'Image Not Found ' + path
531
+ h0, w0 = img.shape[:2] # orig hw
532
+ r = self.img_size / max(h0, w0) # resize image to img_size
533
+ if r != 1: # always resize down, only resize up if training with augmentation
534
+ interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
535
+ img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
536
+ return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
537
+ else:
538
+ return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
539
+
540
+
541
+ def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
542
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
543
+ hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
544
+ dtype = img.dtype # uint8
545
+
546
+ x = np.arange(0, 256, dtype=np.int16)
547
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
548
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
549
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
550
+
551
+ img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
552
+ cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
553
+
554
+ # Histogram equalization
555
+ # if random.random() < 0.2:
556
+ # for i in range(3):
557
+ # img[:, :, i] = cv2.equalizeHist(img[:, :, i])
558
+
559
+
560
+ def load_mosaic(self, index):
561
+ # loads images in a mosaic
562
+
563
+ labels4 = []
564
+ s = self.img_size
565
+ xc, yc = [int(random.uniform(s * 0.5, s * 1.5)) for _ in range(2)] # mosaic center x, y
566
+ indices = [index] + [random.randint(0, len(self.labels) - 1) for _ in range(3)] # 3 additional image indices
567
+ for i, index in enumerate(indices):
568
+ # Load image
569
+ img, _, (h, w) = load_image(self, index)
570
+
571
+ # place img in img4
572
+ if i == 0: # top left
573
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
574
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
575
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
576
+ elif i == 1: # top right
577
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
578
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
579
+ elif i == 2: # bottom left
580
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
581
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, max(xc, w), min(y2a - y1a, h)
582
+ elif i == 3: # bottom right
583
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
584
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
585
+
586
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
587
+ padw = x1a - x1b
588
+ padh = y1a - y1b
589
+
590
+ # Labels
591
+ x = self.labels[index]
592
+ labels = x.copy()
593
+ if x.size > 0: # Normalized xywh to pixel xyxy format
594
+ labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw
595
+ labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh
596
+ labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw
597
+ labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh
598
+ labels4.append(labels)
599
+
600
+ # Concat/clip labels
601
+ if len(labels4):
602
+ labels4 = np.concatenate(labels4, 0)
603
+ # np.clip(labels4[:, 1:] - s / 2, 0, s, out=labels4[:, 1:]) # use with center crop
604
+ np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:]) # use with random_affine
605
+
606
+ # Augment
607
+ # img4 = img4[s // 2: int(s * 1.5), s // 2:int(s * 1.5)] # center crop (WARNING, requires box pruning)
608
+ img4, labels4 = random_affine(img4, labels4,
609
+ degrees=self.hyp['degrees'],
610
+ translate=self.hyp['translate'],
611
+ scale=self.hyp['scale'],
612
+ shear=self.hyp['shear'],
613
+ border=-s // 2) # border to remove
614
+
615
+ return img4, labels4
616
+
617
+
618
+ def letterbox(img, new_shape=(416, 416), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
619
+ # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
620
+ shape = img.shape[:2] # current shape [height, width]
621
+ if isinstance(new_shape, int):
622
+ new_shape = (new_shape, new_shape)
623
+
624
+ # Scale ratio (new / old)
625
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
626
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
627
+ r = min(r, 1.0)
628
+
629
+ # Compute padding
630
+ ratio = r, r # width, height ratios
631
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
632
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
633
+ if auto: # minimum rectangle
634
+ dw, dh = np.mod(dw, 64), np.mod(dh, 64) # wh padding
635
+ elif scaleFill: # stretch
636
+ dw, dh = 0.0, 0.0
637
+ new_unpad = new_shape
638
+ ratio = new_shape[0] / shape[1], new_shape[1] / shape[0] # width, height ratios
639
+
640
+ dw /= 2 # divide padding into 2 sides
641
+ dh /= 2
642
+
643
+ if shape[::-1] != new_unpad: # resize
644
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
645
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
646
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
647
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
648
+ return img, ratio, (dw, dh)
649
+
650
+
651
+ def random_affine(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, border=0):
652
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
653
+ # https://medium.com/uruvideo/dataset-augmentation-with-random-homographies-a8f4b44830d4
654
+ # targets = [cls, xyxy]
655
+
656
+ height = img.shape[0] + border * 2
657
+ width = img.shape[1] + border * 2
658
+
659
+ # Rotation and Scale
660
+ R = np.eye(3)
661
+ a = random.uniform(-degrees, degrees)
662
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
663
+ s = random.uniform(1 - scale, 1 + scale)
664
+ # s = 2 ** random.uniform(-scale, scale)
665
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(img.shape[1] / 2, img.shape[0] / 2), scale=s)
666
+
667
+ # Translation
668
+ T = np.eye(3)
669
+ T[0, 2] = random.uniform(-translate, translate) * img.shape[0] + border # x translation (pixels)
670
+ T[1, 2] = random.uniform(-translate, translate) * img.shape[1] + border # y translation (pixels)
671
+
672
+ # Shear
673
+ S = np.eye(3)
674
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
675
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
676
+
677
+ # Combined rotation matrix
678
+ M = S @ T @ R # ORDER IS IMPORTANT HERE!!
679
+ if (border != 0) or (M != np.eye(3)).any(): # image changed
680
+ img = cv2.warpAffine(img, M[:2], dsize=(width, height), flags=cv2.INTER_LINEAR, borderValue=(114, 114, 114))
681
+
682
+ # Transform label coordinates
683
+ n = len(targets)
684
+ if n:
685
+ # warp points
686
+ xy = np.ones((n * 4, 3))
687
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
688
+ xy = (xy @ M.T)[:, :2].reshape(n, 8)
689
+
690
+ # create new boxes
691
+ x = xy[:, [0, 2, 4, 6]]
692
+ y = xy[:, [1, 3, 5, 7]]
693
+ xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
694
+
695
+ # # apply angle-based reduction of bounding boxes
696
+ # radians = a * math.pi / 180
697
+ # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5
698
+ # x = (xy[:, 2] + xy[:, 0]) / 2
699
+ # y = (xy[:, 3] + xy[:, 1]) / 2
700
+ # w = (xy[:, 2] - xy[:, 0]) * reduction
701
+ # h = (xy[:, 3] - xy[:, 1]) * reduction
702
+ # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T
703
+
704
+ # reject warped points outside of image
705
+ xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)
706
+ xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)
707
+ w = xy[:, 2] - xy[:, 0]
708
+ h = xy[:, 3] - xy[:, 1]
709
+ area = w * h
710
+ area0 = (targets[:, 3] - targets[:, 1]) * (targets[:, 4] - targets[:, 2])
711
+ ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16)) # aspect ratio
712
+ i = (w > 4) & (h > 4) & (area / (area0 * s + 1e-16) > 0.2) & (ar < 10)
713
+
714
+ targets = targets[i]
715
+ targets[:, 1:5] = xy[i]
716
+
717
+ return img, targets
718
+
719
+
720
+ def cutout(image, labels):
721
+ # https://arxiv.org/abs/1708.04552
722
+ # https://github.com/hysts/pytorch_cutout/blob/master/dataloader.py
723
+ # https://towardsdatascience.com/when-conventional-wisdom-fails-revisiting-data-augmentation-for-self-driving-cars-4831998c5509
724
+ h, w = image.shape[:2]
725
+
726
+ def bbox_ioa(box1, box2):
727
+ # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
728
+ box2 = box2.transpose()
729
+
730
+ # Get the coordinates of bounding boxes
731
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
732
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
733
+
734
+ # Intersection area
735
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
736
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
737
+
738
+ # box2 area
739
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
740
+
741
+ # Intersection over box2 area
742
+ return inter_area / box2_area
743
+
744
+ # create random masks
745
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
746
+ for s in scales:
747
+ mask_h = random.randint(1, int(h * s))
748
+ mask_w = random.randint(1, int(w * s))
749
+
750
+ # box
751
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
752
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
753
+ xmax = min(w, xmin + mask_w)
754
+ ymax = min(h, ymin + mask_h)
755
+
756
+ # apply random color mask
757
+ image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
758
+
759
+ # return unobscured labels
760
+ if len(labels) and s > 0.03:
761
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
762
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
763
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
764
+
765
+ return labels
766
+
767
+
768
+ def reduce_img_size(path='../data/sm4/images', img_size=1024): # from utils.datasets import *; reduce_img_size()
769
+ # creates a new ./images_reduced folder with reduced size images of maximum size img_size
770
+ path_new = path + '_reduced' # reduced images path
771
+ create_folder(path_new)
772
+ for f in tqdm(glob.glob('%s/*.*' % path)):
773
+ try:
774
+ img = cv2.imread(f)
775
+ h, w = img.shape[:2]
776
+ r = img_size / max(h, w) # size ratio
777
+ if r < 1.0:
778
+ img = cv2.resize(img, (int(w * r), int(h * r)), interpolation=cv2.INTER_AREA) # _LINEAR fastest
779
+ fnew = f.replace(path, path_new) # .replace(Path(f).suffix, '.jpg')
780
+ cv2.imwrite(fnew, img)
781
+ except:
782
+ print('WARNING: image failure %s' % f)
783
+
784
+
785
+ def convert_images2bmp(): # from utils.datasets import *; convert_images2bmp()
786
+ # Save images
787
+ formats = [x.lower() for x in img_formats] + [x.upper() for x in img_formats]
788
+ # for path in ['../coco/images/val2014', '../coco/images/train2014']:
789
+ for path in ['../data/sm4/images', '../data/sm4/background']:
790
+ create_folder(path + 'bmp')
791
+ for ext in formats: # ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.dng']
792
+ for f in tqdm(glob.glob('%s/*%s' % (path, ext)), desc='Converting %s' % ext):
793
+ cv2.imwrite(f.replace(ext.lower(), '.bmp').replace(path, path + 'bmp'), cv2.imread(f))
794
+
795
+ # Save labels
796
+ # for path in ['../coco/trainvalno5k.txt', '../coco/5k.txt']:
797
+ for file in ['../data/sm4/out_train.txt', '../data/sm4/out_test.txt']:
798
+ with open(file, 'r') as f:
799
+ lines = f.read()
800
+ # lines = f.read().replace('2014/', '2014bmp/') # coco
801
+ lines = lines.replace('/images', '/imagesbmp')
802
+ lines = lines.replace('/background', '/backgroundbmp')
803
+ for ext in formats:
804
+ lines = lines.replace(ext, '.bmp')
805
+ with open(file.replace('.txt', 'bmp.txt'), 'w') as f:
806
+ f.write(lines)
807
+
808
+
809
+ def recursive_dataset2bmp(dataset='../data/sm4_bmp'): # from utils.datasets import *; recursive_dataset2bmp()
810
+ # Converts dataset to bmp (for faster training)
811
+ formats = [x.lower() for x in img_formats] + [x.upper() for x in img_formats]
812
+ for a, b, files in os.walk(dataset):
813
+ for file in tqdm(files, desc=a):
814
+ p = a + '/' + file
815
+ s = Path(file).suffix
816
+ if s == '.txt': # replace text
817
+ with open(p, 'r') as f:
818
+ lines = f.read()
819
+ for f in formats:
820
+ lines = lines.replace(f, '.bmp')
821
+ with open(p, 'w') as f:
822
+ f.write(lines)
823
+ elif s in formats: # replace image
824
+ cv2.imwrite(p.replace(s, '.bmp'), cv2.imread(p))
825
+ if s != '.bmp':
826
+ os.system("rm '%s'" % p)
827
+
828
+
829
+ def imagelist2folder(path='data/coco_64img.txt'): # from utils.datasets import *; imagelist2folder()
830
+ # Copies all the images in a text file (list of images) into a folder
831
+ create_folder(path[:-4])
832
+ with open(path, 'r') as f:
833
+ for line in f.read().splitlines():
834
+ os.system('cp "%s" %s' % (line, path[:-4]))
835
+ print(line)
836
+
837
+
838
+ def create_folder(path='./new_folder'):
839
+ # Create folder
840
+ if os.path.exists(path):
841
+ shutil.rmtree(path) # delete output folder
842
+ os.makedirs(path) # make new output folder
utils/gcp.sh ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # New VM
4
+ if [ ! -d ./coco ]
5
+ then
6
+ echo "COCO folder not found. Running startup script."
7
+ git clone https://github.com/ultralytics/yolov5
8
+ # git clone -b test --depth 1 https://github.com/ultralytics/yolov5 test # branch
9
+ # sudo apt-get install zip
10
+ # git clone https://github.com/NVIDIA/apex && cd apex && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" . --user && cd .. && rm -rf apex
11
+ # sudo conda install -yc conda-forge scikit-image pycocotools
12
+ python3 -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1rrL-Jbc68iHiGjXOYc8u9tKfFiOX21Tn','coco2017.zip')"
13
+ python3 -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1Y6Kou6kEB0ZEMCCpJSKStCor4KAReE43','coco2017.zip')"
14
+ sudo docker pull ultralytics/coco:198
15
+
16
+ # Add 64GB swap
17
+ sudo fallocate -l 64G /swapfile
18
+ sudo chmod 600 /swapfile
19
+ sudo mkswap /swapfile
20
+ sudo swapon /swapfile
21
+ free -h # check memory
22
+
23
+ # sudo reboot now
24
+ fi
25
+ n=198 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp2.yaml --bucket ult/coco --name $n --data data/coco.yaml
26
+
27
+
28
+ # Evolve coco
29
+ sudo -s
30
+ t=ultralytics/yolov3:evolve
31
+ # docker kill $(docker ps -a -q --filter ancestor=$t)
32
+ for i in 0 1 6 7
33
+ do
34
+ docker pull $t && docker run --gpus all -d --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t bash utils/evolve.sh $i
35
+ sleep 30
36
+ done
37
+
38
+
39
+ # kmean_anchors(path='../coco/train2017.txt', n=12, img_size=(256, 1024), thr=0.10, gen=10000)
40
+ # 0.10 iou_thr: 1.000 best possible recall, 6.15 anchors > thr
41
+ # n=12, img_size=(256, 1024), IoU_all=0.188/0.641-mean/best, IoU>thr=0.338-mean: 7,9, 13,17, 30,21, 18,38, 31,63, 54,38, 52,110, 90,69, 98,187, 164,116, 218,255, 448,414
42
+
43
+ # from yolov4l_10iou
44
+ # computed with utils.kmean_anchors(path='../coco/train2017.txt', n=12, img_size=(320, 1024), thr=0.10, gen=1000)
45
+ # Evolving anchors: 100%|█████████████████| 1000/1000 [39:57<00:00, 2.40s/it]
46
+ # 0.10 iou_thr: 0.998 best possible recall, 6.07 anchors > thr
47
+ # n=12, img_size=(320, 1024), IoU_all=0.187/0.635-mean/best, IoU>thr=0.339-mean: 9,13, 20,21, 21,50, 43,34, 44,89, 84,59, 76,164, 133,105, 216,176, 153,267, 312,331, 623,467
48
+
49
+ # from yolov4l_10iou_9anchors
50
+ # computed with utils.kmean_anchors(path='../coco/train2017.txt', n=9, img_size=(320, 1024), thr=0.10, gen=1000)
51
+ # Evolving anchors: 100%|█████████████████| 1000/1000 [31:26<00:00, 1.89s/it]
52
+ # 0.10 iou_thr: 0.998 best possible recall, 4.60 anchors > thr
53
+ # n=9, img_size=(320, 1024), IoU_all=0.190/0.604-mean/best, IoU>thr=0.342-mean: 9,13, 20,26, 29,58, 55,37, 57,115, 105,77, 133,165, 254,280, 508,450
54
+
55
+ # ar < 5
56
+ #Evolving anchors: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1000/1000 [14:56<00:00, 1.00it/s]
57
+ #0.10 iou_thr: 0.999 best possible recall, 4.63 anchors > thr
58
+ #n=9, img_size=(320, 1024), IoU_all=0.187/0.601-mean/best, IoU>thr=0.334-mean: 9,11, 15,35, 36,21, 34,61, 86,55, 66,145, 164,110, 185,262, 450,369
59
+
60
+ #Evolving anchors: 10%|████████████ | 1015/10000 [15:59<1:56:24, 1.29it/s]
61
+ #5.00 iou_thr: 1.000 best possible recall, 4.79 anchors > thr
62
+ #n=9, img_size=(320, 1024), IoU_all=9.193/1.535-mean/best, IoU>thr=2.745-mean: 8,8, 14,24, 41,21, 24,56, 64,57, 60,140, 154,102, 174,262, 443,340
63
+
64
+ #Evolving anchors: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10000/10000 [2:15:31<00:00, 1.25it/s]
65
+ #5.00 iou_thr: 1.000 best possible recall, 4.80 anchors > thr
66
+ #n=9, img_size=(320, 1024), IoU_all=9.106/1.531-mean/best, IoU>thr=2.744-mean: 8,8, 12,24, 33,19, 25,53, 64,48, 58,128, 145,93, 164,240, 419,349
67
+
68
+
69
+ Evolving anchors: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10000/10000 [21:39<00:00, 7.83it/s]
70
+ 0.20 iou_thr: 0.992 best possible recall, 3.44 anchors > thr
71
+ n=9, img_size=(640, 640), IoU_all=0.199/0.614-mean/best, IoU>thr=0.421-mean: 9,11, 16,25, 38,25, 26,54, 70,50, 51,102, 113,109, 161,218, 366,343
72
+
73
+ Evolving anchors: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10000/10000 [16:34<00:00, 10.05it/s]
74
+ 0.10 iou_thr: 0.999 best possible recall, 4.87 anchors > thr
75
+ n=9, img_size=(640, 640), IoU_all=0.200/0.614-mean/best, IoU>thr=0.342-mean: 10,12, 16,27, 37,25, 27,56, 69,51, 53,108, 116,107, 163,216, 364,343
76
+
77
+ - [10,13, 16,30, 33,23] # P3/8
78
+ - [30,61, 62,45, 59,119] # P4/16
79
+ - [116,90, 156,198, 373,326] # P5/32
80
+
81
+ # coco (small cancelled, large, medium, small, yolov3)
82
+ n=129 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov4.yaml --bucket ult/coco --name $n && sudo shutdown
83
+ n=130 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 32 --weights '' --cfg models/yolov4.yaml --bucket ult/coco --name $n && sudo shutdown
84
+ n=133 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 16 --weights '' --cfg models/yolov4.yaml --bucket ult/coco --name $n && sudo shutdown
85
+ n=134 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov4s.yaml --bucket ult/coco --name $n && sudo shutdown
86
+ n=135 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 32 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n && sudo shutdown
87
+ n=136 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 16 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n && sudo shutdown
88
+
89
+
90
+ n=138 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n && sudo shutdown
91
+ n=139 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n && sudo shutdown
92
+ n=140 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n && sudo shutdown
93
+
94
+ n=141 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
95
+ n=142 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
96
+ n=143 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
97
+ n=144 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
98
+ n=145 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 12 --weights '' --cfg models/yolov5l.yaml --bucket ult/coco --name $n && sudo shutdown
99
+ n=146 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
100
+
101
+ n=147 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
102
+ n=148 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
103
+ n=149 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 832 --batch 32 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
104
+
105
+ n=150 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 32 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
106
+ n=151 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 320 640 --batch 32 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
107
+
108
+ n=152 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n && sudo shutdown
109
+ n=154 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 32 --weights '' --cfg models/yolov5s_exp.yaml --bucket ult/coco --name $n && sudo shutdown
110
+
111
+ n=153 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_focus1.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
112
+ n=155 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_focus2.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
113
+ n=156 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_exp_focus0.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
114
+
115
+ n=157 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_focus3.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
116
+ n=158 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_focus4.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
117
+ n=159 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_focus5.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
118
+
119
+ n=160 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5_final.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
120
+ n=161 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5_final.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
121
+
122
+ n=162 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5_final.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
123
+ n=163 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5_final.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
124
+
125
+ n=164 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5_final.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
126
+ n=165 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_origami.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
127
+ n=166 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_k3.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
128
+ n=167 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_plus.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
129
+ n=168 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
130
+
131
+ n=169 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
132
+
133
+ n=170 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
134
+
135
+ n=171 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_k3_spp5913.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
136
+ n=172 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
137
+
138
+ n=173 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
139
+ n=174 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
140
+
141
+
142
+ n=178 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 96 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
143
+ n=179 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 48 --weights '' --cfg models/yolov5m.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
144
+ n=180 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 28 --weights '' --cfg models/yolov5l.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
145
+ n=181 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 16 --weights '' --cfg models/yolov5x.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
146
+ n=182 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
147
+ n=183 && t=ultralytics/coco:v178 && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
148
+
149
+ n=184 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
150
+ n=185 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
151
+
152
+
153
+ n=186 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml
154
+ n=187 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml
155
+ n=188 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml
156
+
157
+ n=189 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_focus.yaml --bucket ult/coco --name $n --data data/coco.yaml
158
+ n=190 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml
159
+ n=191 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml
160
+
161
+ n=192 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml
162
+ n=193 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s.yaml --bucket ult/coco --name $n --data data/coco.yaml
163
+
164
+ n=194 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml
165
+ n=195 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml
166
+
167
+ n=196 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml
168
+ n=197 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp1.yaml --bucket ult/coco --name $n --data data/coco.yaml
169
+ n=198 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp2.yaml --bucket ult/coco --name $n --data data/coco.yaml
170
+ n=199 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --epochs 50 --batch 64 --weights '' --cfg models/yolov5s_csp2.yaml --bucket ult/coco --name $n --data data/coco.yaml
171
+
172
+
173
+
174
+ n=201 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 48 --weights '' --cfg models/yolov5m_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml
175
+ n=204 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
176
+
177
+ n=206 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
178
+ n=207 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t python3 train.py --img 640 640 --batch 24 --weights '' --cfg models/yolov3-spp_csp.yaml --bucket ult/coco --name $n --data data/coco.yaml && sudo shutdown
179
+
180
+
181
+ n=205 && t=ultralytics/coco:v$n && sudo docker pull $t && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco $t bash
utils/google_utils.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains google utils: https://cloud.google.com/storage/docs/reference/libraries
2
+ # pip install --upgrade google-cloud-storage
3
+ # from google.cloud import storage
4
+
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+
9
+
10
+ def attempt_download(weights):
11
+ # Attempt to download pretrained weights if not found locally
12
+ weights = weights.strip()
13
+ msg = weights + ' missing, try downloading from https://drive.google.com/open?id=1LezFG5g3BCW6iYaV89B2i64cqEUZD7e0'
14
+
15
+ r = 1
16
+ if len(weights) > 0 and not os.path.isfile(weights):
17
+ d = {'yolov3-spp.pt': '1mM67oNw4fZoIOL1c8M3hHmj66d8e-ni_', # yolov3-spp.yaml
18
+ 'yolov5s.pt': '1R5T6rIyy3lLwgFXNms8whc-387H0tMQO', # yolov5s.yaml
19
+ 'yolov5m.pt': '1vobuEExpWQVpXExsJ2w-Mbf3HJjWkQJr', # yolov5m.yaml
20
+ 'yolov5l.pt': '1hrlqD1Wdei7UT4OgT785BEk1JwnSvNEV', # yolov5l.yaml
21
+ 'yolov5x.pt': '1mM8aZJlWTxOg7BZJvNUMrTnA2AbeCVzS', # yolov5x.yaml
22
+ }
23
+
24
+ file = Path(weights).name
25
+ if file in d:
26
+ r = gdrive_download(id=d[file], name=weights)
27
+
28
+ # Error check
29
+ if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB
30
+ os.system('rm ' + weights) # remove partial downloads
31
+ raise Exception(msg)
32
+
33
+
34
+ def gdrive_download(id='1HaXkef9z6y5l4vUnCYgdmEAj61c6bfWO', name='coco.zip'):
35
+ # https://gist.github.com/tanaikech/f0f2d122e05bf5f971611258c22c110f
36
+ # Downloads a file from Google Drive, accepting presented query
37
+ # from utils.google_utils import *; gdrive_download()
38
+ t = time.time()
39
+
40
+ print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='')
41
+ os.remove(name) if os.path.exists(name) else None # remove existing
42
+ os.remove('cookie') if os.path.exists('cookie') else None
43
+
44
+ # Attempt file download
45
+ os.system("curl -c ./cookie -s -L \"https://drive.google.com/uc?export=download&id=%s\" > /dev/null" % id)
46
+ if os.path.exists('cookie'): # large file
47
+ s = "curl -Lb ./cookie \"https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=%s\" -o %s" % (
48
+ id, name)
49
+ else: # small file
50
+ s = "curl -s -L -o %s 'https://drive.google.com/uc?export=download&id=%s'" % (name, id)
51
+ r = os.system(s) # execute, capture return values
52
+ os.remove('cookie') if os.path.exists('cookie') else None
53
+
54
+ # Error check
55
+ if r != 0:
56
+ os.remove(name) if os.path.exists(name) else None # remove partial
57
+ print('Download error ') # raise Exception('Download error')
58
+ return r
59
+
60
+ # Unzip if archive
61
+ if name.endswith('.zip'):
62
+ print('unzipping... ', end='')
63
+ os.system('unzip -q %s' % name) # unzip
64
+ os.remove(name) # remove zip to free space
65
+
66
+ print('Done (%.1fs)' % (time.time() - t))
67
+ return r
68
+
69
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
70
+ # # Uploads a file to a bucket
71
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
72
+ #
73
+ # storage_client = storage.Client()
74
+ # bucket = storage_client.get_bucket(bucket_name)
75
+ # blob = bucket.blob(destination_blob_name)
76
+ #
77
+ # blob.upload_from_filename(source_file_name)
78
+ #
79
+ # print('File {} uploaded to {}.'.format(
80
+ # source_file_name,
81
+ # destination_blob_name))
82
+ #
83
+ #
84
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
85
+ # # Uploads a blob from a bucket
86
+ # storage_client = storage.Client()
87
+ # bucket = storage_client.get_bucket(bucket_name)
88
+ # blob = bucket.blob(source_blob_name)
89
+ #
90
+ # blob.download_to_filename(destination_file_name)
91
+ #
92
+ # print('Blob {} downloaded to {}.'.format(
93
+ # source_blob_name,
94
+ # destination_file_name))
utils/torch_utils.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import time
4
+ from copy import deepcopy
5
+
6
+ import torch
7
+ import torch.backends.cudnn as cudnn
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+
12
+ def init_seeds(seed=0):
13
+ torch.manual_seed(seed)
14
+
15
+ # Reduce randomness (may be slower on Tesla GPUs) # https://pytorch.org/docs/stable/notes/randomness.html
16
+ if seed == 0:
17
+ cudnn.deterministic = False
18
+ cudnn.benchmark = True
19
+
20
+
21
+ def select_device(device='', apex=False, batch_size=None):
22
+ # device = 'cpu' or '0' or '0,1,2,3'
23
+ cpu_request = device.lower() == 'cpu'
24
+ if device and not cpu_request: # if device requested other than 'cpu'
25
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
26
+ assert torch.cuda.is_available(), 'CUDA unavailable, invalid device %s requested' % device # check availablity
27
+
28
+ cuda = False if cpu_request else torch.cuda.is_available()
29
+ if cuda:
30
+ c = 1024 ** 2 # bytes to MB
31
+ ng = torch.cuda.device_count()
32
+ if ng > 1 and batch_size: # check that batch_size is compatible with device_count
33
+ assert batch_size % ng == 0, 'batch-size %g not multiple of GPU count %g' % (batch_size, ng)
34
+ x = [torch.cuda.get_device_properties(i) for i in range(ng)]
35
+ s = 'Using CUDA ' + ('Apex ' if apex else '') # apex for mixed precision https://github.com/NVIDIA/apex
36
+ for i in range(0, ng):
37
+ if i == 1:
38
+ s = ' ' * len(s)
39
+ print("%sdevice%g _CudaDeviceProperties(name='%s', total_memory=%dMB)" %
40
+ (s, i, x[i].name, x[i].total_memory / c))
41
+ else:
42
+ print('Using CPU')
43
+
44
+ print('') # skip a line
45
+ return torch.device('cuda:0' if cuda else 'cpu')
46
+
47
+
48
+ def time_synchronized():
49
+ torch.cuda.synchronize() if torch.cuda.is_available() else None
50
+ return time.time()
51
+
52
+
53
+ def initialize_weights(model):
54
+ for m in model.modules():
55
+ t = type(m)
56
+ if t is nn.Conv2d:
57
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
58
+ elif t is nn.BatchNorm2d:
59
+ m.eps = 1e-4
60
+ m.momentum = 0.03
61
+ elif t in [nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
62
+ m.inplace = True
63
+
64
+
65
+ def find_modules(model, mclass=nn.Conv2d):
66
+ # finds layer indices matching module class 'mclass'
67
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
68
+
69
+
70
+ def fuse_conv_and_bn(conv, bn):
71
+ # https://tehnokv.com/posts/fusing-batchnorm-and-conv/
72
+ with torch.no_grad():
73
+ # init
74
+ fusedconv = torch.nn.Conv2d(conv.in_channels,
75
+ conv.out_channels,
76
+ kernel_size=conv.kernel_size,
77
+ stride=conv.stride,
78
+ padding=conv.padding,
79
+ bias=True)
80
+
81
+ # prepare filters
82
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
83
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
84
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
85
+
86
+ # prepare spatial bias
87
+ if conv.bias is not None:
88
+ b_conv = conv.bias
89
+ else:
90
+ b_conv = torch.zeros(conv.weight.size(0))
91
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
92
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
93
+
94
+ return fusedconv
95
+
96
+
97
+ def model_info(model, verbose=False):
98
+ # Plots a line-by-line description of a PyTorch model
99
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
100
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
101
+ if verbose:
102
+ print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
103
+ for i, (name, p) in enumerate(model.named_parameters()):
104
+ name = name.replace('module_list.', '')
105
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
106
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
107
+
108
+ try: # FLOPS
109
+ from thop import profile
110
+ macs, _ = profile(model, inputs=(torch.zeros(1, 3, 480, 640),), verbose=False)
111
+ fs = ', %.1f GFLOPS' % (macs / 1E9 * 2)
112
+ except:
113
+ fs = ''
114
+
115
+ print('Model Summary: %g layers, %g parameters, %g gradients%s' % (len(list(model.parameters())), n_p, n_g, fs))
116
+
117
+
118
+ def load_classifier(name='resnet101', n=2):
119
+ # Loads a pretrained model reshaped to n-class output
120
+ import pretrainedmodels # https://github.com/Cadene/pretrained-models.pytorch#torchvision
121
+ model = pretrainedmodels.__dict__[name](num_classes=1000, pretrained='imagenet')
122
+
123
+ # Display model properties
124
+ for x in ['model.input_size', 'model.input_space', 'model.input_range', 'model.mean', 'model.std']:
125
+ print(x + ' =', eval(x))
126
+
127
+ # Reshape output to n classes
128
+ filters = model.last_linear.weight.shape[1]
129
+ model.last_linear.bias = torch.nn.Parameter(torch.zeros(n))
130
+ model.last_linear.weight = torch.nn.Parameter(torch.zeros(n, filters))
131
+ model.last_linear.out_features = n
132
+ return model
133
+
134
+
135
+ def scale_img(img, ratio=1.0, same_shape=True): # img(16,3,256,416), r=ratio
136
+ # scales img(bs,3,y,x) by ratio
137
+ h, w = img.shape[2:]
138
+ s = (int(h * ratio), int(w * ratio)) # new size
139
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
140
+ if not same_shape: # pad/crop img
141
+ gs = 64 # (pixels) grid size
142
+ h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
143
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
144
+
145
+
146
+ class ModelEMA:
147
+ """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
148
+ Keep a moving average of everything in the model state_dict (parameters and buffers).
149
+ This is intended to allow functionality like
150
+ https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
151
+ A smoothed version of the weights is necessary for some training schemes to perform well.
152
+ E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use
153
+ RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA
154
+ smoothing of weights to match results. Pay attention to the decay constant you are using
155
+ relative to your update count per epoch.
156
+ To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but
157
+ disable validation of the EMA weights. Validation will have to be done manually in a separate
158
+ process, or after the training stops converging.
159
+ This class is sensitive where it is initialized in the sequence of model init,
160
+ GPU assignment and distributed training wrappers.
161
+ I've tested with the sequence in my own train.py for torch.DataParallel, apex.DDP, and single-GPU.
162
+ """
163
+
164
+ def __init__(self, model, decay=0.9999, device=''):
165
+ # make a copy of the model for accumulating moving average of weights
166
+ self.ema = deepcopy(model)
167
+ self.ema.eval()
168
+ self.updates = 0 # number of EMA updates
169
+ self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
170
+ self.device = device # perform ema on different device from model if set
171
+ if device:
172
+ self.ema.to(device=device)
173
+ for p in self.ema.parameters():
174
+ p.requires_grad_(False)
175
+
176
+ def update(self, model):
177
+ self.updates += 1
178
+ d = self.decay(self.updates)
179
+ with torch.no_grad():
180
+ if type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel):
181
+ msd, esd = model.module.state_dict(), self.ema.module.state_dict()
182
+ else:
183
+ msd, esd = model.state_dict(), self.ema.state_dict()
184
+
185
+ for k, v in esd.items():
186
+ if v.dtype.is_floating_point:
187
+ v *= d
188
+ v += (1. - d) * msd[k].detach()
189
+
190
+ def update_attr(self, model):
191
+ # Assign attributes (which may change during training)
192
+ for k in model.__dict__.keys():
193
+ if not k.startswith('_'):
194
+ setattr(self.ema, k, getattr(model, k))
utils/utils.py ADDED
@@ -0,0 +1,1085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import math
3
+ import os
4
+ import random
5
+ import shutil
6
+ import subprocess
7
+ import time
8
+ from copy import copy
9
+ from pathlib import Path
10
+ from sys import platform
11
+
12
+ import cv2
13
+ import matplotlib
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn as nn
18
+ import torchvision
19
+ from scipy.signal import butter, filtfilt
20
+ from tqdm import tqdm
21
+
22
+ from . import torch_utils, google_utils # torch_utils, google_utils
23
+
24
+ # Set printoptions
25
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
26
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
27
+ matplotlib.rc('font', **{'size': 11})
28
+
29
+ # Prevent OpenCV from multithreading (to use PyTorch DataLoader)
30
+ cv2.setNumThreads(0)
31
+
32
+
33
+ def init_seeds(seed=0):
34
+ random.seed(seed)
35
+ np.random.seed(seed)
36
+ torch_utils.init_seeds(seed=seed)
37
+
38
+
39
+ def check_git_status():
40
+ if platform in ['linux', 'darwin']:
41
+ # Suggest 'git pull' if repo is out of date
42
+ s = subprocess.check_output('if [ -d .git ]; then git fetch && git status -uno; fi', shell=True).decode('utf-8')
43
+ if 'Your branch is behind' in s:
44
+ print(s[s.find('Your branch is behind'):s.find('\n\n')] + '\n')
45
+
46
+
47
+ def make_divisible(x, divisor):
48
+ # Returns x evenly divisble by divisor
49
+ return math.ceil(x / divisor) * divisor
50
+
51
+
52
+ def labels_to_class_weights(labels, nc=80):
53
+ # Get class weights (inverse frequency) from training labels
54
+ if labels[0] is None: # no labels loaded
55
+ return torch.Tensor()
56
+
57
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
58
+ classes = labels[:, 0].astype(np.int) # labels = [class xywh]
59
+ weights = np.bincount(classes, minlength=nc) # occurences per class
60
+
61
+ # Prepend gridpoint count (for uCE trianing)
62
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
63
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
64
+
65
+ weights[weights == 0] = 1 # replace empty bins with 1
66
+ weights = 1 / weights # number of targets per class
67
+ weights /= weights.sum() # normalize
68
+ return torch.from_numpy(weights)
69
+
70
+
71
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
72
+ # Produces image weights based on class mAPs
73
+ n = len(labels)
74
+ class_counts = np.array([np.bincount(labels[i][:, 0].astype(np.int), minlength=nc) for i in range(n)])
75
+ image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
76
+ # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
77
+ return image_weights
78
+
79
+
80
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
81
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
82
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
83
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
84
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
85
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
86
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
87
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
88
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
89
+ return x
90
+
91
+
92
+ def xyxy2xywh(x):
93
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
94
+ y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
95
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
96
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
97
+ y[:, 2] = x[:, 2] - x[:, 0] # width
98
+ y[:, 3] = x[:, 3] - x[:, 1] # height
99
+ return y
100
+
101
+
102
+ def xywh2xyxy(x):
103
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
104
+ y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
105
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
106
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
107
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
108
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
109
+ return y
110
+
111
+
112
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
113
+ # Rescale coords (xyxy) from img1_shape to img0_shape
114
+ if ratio_pad is None: # calculate from img0_shape
115
+ gain = max(img1_shape) / max(img0_shape) # gain = old / new
116
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
117
+ else:
118
+ gain = ratio_pad[0][0]
119
+ pad = ratio_pad[1]
120
+
121
+ coords[:, [0, 2]] -= pad[0] # x padding
122
+ coords[:, [1, 3]] -= pad[1] # y padding
123
+ coords[:, :4] /= gain
124
+ clip_coords(coords, img0_shape)
125
+ return coords
126
+
127
+
128
+ def clip_coords(boxes, img_shape):
129
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
130
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
131
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
132
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
133
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
134
+
135
+
136
+ def ap_per_class(tp, conf, pred_cls, target_cls):
137
+ """ Compute the average precision, given the recall and precision curves.
138
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
139
+ # Arguments
140
+ tp: True positives (nparray, nx1 or nx10).
141
+ conf: Objectness value from 0-1 (nparray).
142
+ pred_cls: Predicted object classes (nparray).
143
+ target_cls: True object classes (nparray).
144
+ # Returns
145
+ The average precision as computed in py-faster-rcnn.
146
+ """
147
+
148
+ # Sort by objectness
149
+ i = np.argsort(-conf)
150
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
151
+
152
+ # Find unique classes
153
+ unique_classes = np.unique(target_cls)
154
+
155
+ # Create Precision-Recall curve and compute AP for each class
156
+ pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898
157
+ s = [unique_classes.shape[0], tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)
158
+ ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)
159
+ for ci, c in enumerate(unique_classes):
160
+ i = pred_cls == c
161
+ n_gt = (target_cls == c).sum() # Number of ground truth objects
162
+ n_p = i.sum() # Number of predicted objects
163
+
164
+ if n_p == 0 or n_gt == 0:
165
+ continue
166
+ else:
167
+ # Accumulate FPs and TPs
168
+ fpc = (1 - tp[i]).cumsum(0)
169
+ tpc = tp[i].cumsum(0)
170
+
171
+ # Recall
172
+ recall = tpc / (n_gt + 1e-16) # recall curve
173
+ r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases
174
+
175
+ # Precision
176
+ precision = tpc / (tpc + fpc) # precision curve
177
+ p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score
178
+
179
+ # AP from recall-precision curve
180
+ for j in range(tp.shape[1]):
181
+ ap[ci, j] = compute_ap(recall[:, j], precision[:, j])
182
+
183
+ # Plot
184
+ # fig, ax = plt.subplots(1, 1, figsize=(5, 5))
185
+ # ax.plot(recall, precision)
186
+ # ax.set_xlabel('Recall')
187
+ # ax.set_ylabel('Precision')
188
+ # ax.set_xlim(0, 1.01)
189
+ # ax.set_ylim(0, 1.01)
190
+ # fig.tight_layout()
191
+ # fig.savefig('PR_curve.png', dpi=300)
192
+
193
+ # Compute F1 score (harmonic mean of precision and recall)
194
+ f1 = 2 * p * r / (p + r + 1e-16)
195
+
196
+ return p, r, ap, f1, unique_classes.astype('int32')
197
+
198
+
199
+ def compute_ap(recall, precision):
200
+ """ Compute the average precision, given the recall and precision curves.
201
+ Source: https://github.com/rbgirshick/py-faster-rcnn.
202
+ # Arguments
203
+ recall: The recall curve (list).
204
+ precision: The precision curve (list).
205
+ # Returns
206
+ The average precision as computed in py-faster-rcnn.
207
+ """
208
+
209
+ # Append sentinel values to beginning and end
210
+ mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)]))
211
+ mpre = np.concatenate(([0.], precision, [0.]))
212
+
213
+ # Compute the precision envelope
214
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
215
+
216
+ # Integrate area under curve
217
+ method = 'interp' # methods: 'continuous', 'interp'
218
+ if method == 'interp':
219
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
220
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
221
+ else: # 'continuous'
222
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
223
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
224
+
225
+ return ap
226
+
227
+
228
+ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False):
229
+ # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
230
+ box2 = box2.t()
231
+
232
+ # Get the coordinates of bounding boxes
233
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
234
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
235
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
236
+ else: # transform from xywh to xyxy
237
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
238
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
239
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
240
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
241
+
242
+ # Intersection area
243
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
244
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
245
+
246
+ # Union Area
247
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
248
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
249
+ union = (w1 * h1 + 1e-16) + w2 * h2 - inter
250
+
251
+ iou = inter / union # iou
252
+ if GIoU or DIoU or CIoU:
253
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
254
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
255
+ if GIoU: # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
256
+ c_area = cw * ch + 1e-16 # convex area
257
+ return iou - (c_area - union) / c_area # GIoU
258
+ if DIoU or CIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
259
+ # convex diagonal squared
260
+ c2 = cw ** 2 + ch ** 2 + 1e-16
261
+ # centerpoint distance squared
262
+ rho2 = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2)) ** 2 / 4 + ((b2_y1 + b2_y2) - (b1_y1 + b1_y2)) ** 2 / 4
263
+ if DIoU:
264
+ return iou - rho2 / c2 # DIoU
265
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
266
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
267
+ with torch.no_grad():
268
+ alpha = v / (1 - iou + v)
269
+ return iou - (rho2 / c2 + v * alpha) # CIoU
270
+
271
+ return iou
272
+
273
+
274
+ def box_iou(box1, box2):
275
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
276
+ """
277
+ Return intersection-over-union (Jaccard index) of boxes.
278
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
279
+ Arguments:
280
+ box1 (Tensor[N, 4])
281
+ box2 (Tensor[M, 4])
282
+ Returns:
283
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
284
+ IoU values for every element in boxes1 and boxes2
285
+ """
286
+
287
+ def box_area(box):
288
+ # box = 4xn
289
+ return (box[2] - box[0]) * (box[3] - box[1])
290
+
291
+ area1 = box_area(box1.t())
292
+ area2 = box_area(box2.t())
293
+
294
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
295
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
296
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
297
+
298
+
299
+ def wh_iou(wh1, wh2):
300
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
301
+ wh1 = wh1[:, None] # [N,1,2]
302
+ wh2 = wh2[None] # [1,M,2]
303
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
304
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
305
+
306
+
307
+ class FocalLoss(nn.Module):
308
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
309
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
310
+ super(FocalLoss, self).__init__()
311
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
312
+ self.gamma = gamma
313
+ self.alpha = alpha
314
+ self.reduction = loss_fcn.reduction
315
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
316
+
317
+ def forward(self, pred, true):
318
+ loss = self.loss_fcn(pred, true)
319
+ # p_t = torch.exp(-loss)
320
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
321
+
322
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
323
+ pred_prob = torch.sigmoid(pred) # prob from logits
324
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
325
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
326
+ modulating_factor = (1.0 - p_t) ** self.gamma
327
+ loss *= alpha_factor * modulating_factor
328
+
329
+ if self.reduction == 'mean':
330
+ return loss.mean()
331
+ elif self.reduction == 'sum':
332
+ return loss.sum()
333
+ else: # 'none'
334
+ return loss
335
+
336
+
337
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
338
+ # return positive, negative label smoothing BCE targets
339
+ return 1.0 - 0.5 * eps, 0.5 * eps
340
+
341
+
342
+ def compute_loss(p, targets, model): # predictions, targets, model
343
+ ft = torch.cuda.FloatTensor if p[0].is_cuda else torch.Tensor
344
+ lcls, lbox, lobj = ft([0]), ft([0]), ft([0])
345
+ tcls, tbox, indices, anchors = build_targets(p, targets, model) # targets
346
+ h = model.hyp # hyperparameters
347
+ red = 'mean' # Loss reduction (sum or mean)
348
+
349
+ # Define criteria
350
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=ft([h['cls_pw']]), reduction=red)
351
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=ft([h['obj_pw']]), reduction=red)
352
+
353
+ # class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
354
+ cp, cn = smooth_BCE(eps=0.0)
355
+
356
+ # focal loss
357
+ g = h['fl_gamma'] # focal loss gamma
358
+ if g > 0:
359
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
360
+
361
+ # per output
362
+ nt = 0 # targets
363
+ for i, pi in enumerate(p): # layer index, layer predictions
364
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
365
+ tobj = torch.zeros_like(pi[..., 0]) # target obj
366
+
367
+ nb = b.shape[0] # number of targets
368
+ if nb:
369
+ nt += nb # cumulative targets
370
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
371
+
372
+ # GIoU
373
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
374
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
375
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
376
+ giou = bbox_iou(pbox.t(), tbox[i], x1y1x2y2=False, GIoU=True) # giou(prediction, target)
377
+ lbox += (1.0 - giou).sum() if red == 'sum' else (1.0 - giou).mean() # giou loss
378
+
379
+ # Obj
380
+ tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * giou.detach().clamp(0).type(tobj.dtype) # giou ratio
381
+
382
+ # Class
383
+ if model.nc > 1: # cls loss (only if multiple classes)
384
+ t = torch.full_like(ps[:, 5:], cn) # targets
385
+ t[range(nb), tcls[i]] = cp
386
+ lcls += BCEcls(ps[:, 5:], t) # BCE
387
+
388
+ # Append targets to text file
389
+ # with open('targets.txt', 'a') as file:
390
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
391
+
392
+ lobj += BCEobj(pi[..., 4], tobj) # obj loss
393
+
394
+ lbox *= h['giou']
395
+ lobj *= h['obj']
396
+ lcls *= h['cls']
397
+ bs = tobj.shape[0] # batch size
398
+ if red == 'sum':
399
+ g = 3.0 # loss gain
400
+ lobj *= g / bs
401
+ if nt:
402
+ lcls *= g / nt / model.nc
403
+ lbox *= g / nt
404
+
405
+ loss = lbox + lobj + lcls
406
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
407
+
408
+
409
+ def build_targets(p, targets, model):
410
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
411
+ det = model.module.model[-1] if type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) \
412
+ else model.model[-1] # Detect() module
413
+ na, nt = det.na, targets.shape[0] # number of anchors, targets
414
+ tcls, tbox, indices, anch = [], [], [], []
415
+ gain = torch.ones(6, device=targets.device) # normalized to gridspace gain
416
+ off = torch.tensor([[1, 0], [0, 1], [-1, 0], [0, -1]], device=targets.device).float() # overlap offsets
417
+ at = torch.arange(na).view(na, 1).repeat(1, nt) # anchor tensor, same as .repeat_interleave(nt)
418
+
419
+ style = 'rect4'
420
+ for i in range(det.nl):
421
+ anchors = det.anchors[i]
422
+ gain[2:] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
423
+
424
+ # Match targets to anchors
425
+ a, t, offsets = [], targets * gain, 0
426
+ if nt:
427
+ r = t[None, :, 4:6] / anchors[:, None] # wh ratio
428
+ j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare
429
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n) = wh_iou(anchors(3,2), gwh(n,2))
430
+ a, t = at[j], t.repeat(na, 1, 1)[j] # filter
431
+
432
+ # overlaps
433
+ gxy = t[:, 2:4] # grid xy
434
+ z = torch.zeros_like(gxy)
435
+ if style == 'rect2':
436
+ g = 0.2 # offset
437
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
438
+ a, t = torch.cat((a, a[j], a[k]), 0), torch.cat((t, t[j], t[k]), 0)
439
+ offsets = torch.cat((z, z[j] + off[0], z[k] + off[1]), 0) * g
440
+
441
+ elif style == 'rect4':
442
+ g = 0.5 # offset
443
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
444
+ l, m = ((gxy % 1. > (1 - g)) & (gxy < (gain[[2, 3]] - 1.))).T
445
+ a, t = torch.cat((a, a[j], a[k], a[l], a[m]), 0), torch.cat((t, t[j], t[k], t[l], t[m]), 0)
446
+ offsets = torch.cat((z, z[j] + off[0], z[k] + off[1], z[l] + off[2], z[m] + off[3]), 0) * g
447
+
448
+ # Define
449
+ b, c = t[:, :2].long().T # image, class
450
+ gxy = t[:, 2:4] # grid xy
451
+ gwh = t[:, 4:6] # grid wh
452
+ gij = (gxy - offsets).long()
453
+ gi, gj = gij.T # grid xy indices
454
+
455
+ # Append
456
+ indices.append((b, a, gj, gi)) # image, anchor, grid indices
457
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
458
+ anch.append(anchors[a]) # anchors
459
+ tcls.append(c) # class
460
+
461
+ return tcls, tbox, indices, anch
462
+
463
+
464
+ def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, multi_label=True, classes=None, agnostic=False):
465
+ """
466
+ Performs Non-Maximum Suppression on inference results
467
+ Returns detections with shape:
468
+ nx6 (x1, y1, x2, y2, conf, cls)
469
+ """
470
+
471
+ # Settings
472
+ merge = True # merge for best mAP
473
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
474
+ time_limit = 10.0 # seconds to quit after
475
+
476
+ t = time.time()
477
+ nc = prediction[0].shape[1] - 5 # number of classes
478
+ multi_label &= nc > 1 # multiple labels per box
479
+ output = [None] * prediction.shape[0]
480
+ for xi, x in enumerate(prediction): # image index, image inference
481
+ # Apply constraints
482
+ x = x[x[:, 4] > conf_thres] # confidence
483
+ # x = x[((x[:, 2:4] > min_wh) & (x[:, 2:4] < max_wh)).all(1)] # width-height
484
+
485
+ # If none remain process next image
486
+ if not x.shape[0]:
487
+ continue
488
+
489
+ # Compute conf
490
+ x[..., 5:] *= x[..., 4:5] # conf = obj_conf * cls_conf
491
+
492
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
493
+ box = xywh2xyxy(x[:, :4])
494
+
495
+ # Detections matrix nx6 (xyxy, conf, cls)
496
+ if multi_label:
497
+ i, j = (x[:, 5:] > conf_thres).nonzero().t()
498
+ x = torch.cat((box[i], x[i, j + 5].unsqueeze(1), j.float().unsqueeze(1)), 1)
499
+ else: # best class only
500
+ conf, j = x[:, 5:].max(1)
501
+ x = torch.cat((box, conf.unsqueeze(1), j.float().unsqueeze(1)), 1)[conf > conf_thres]
502
+
503
+ # Filter by class
504
+ if classes:
505
+ x = x[(j.view(-1, 1) == torch.tensor(classes, device=j.device)).any(1)]
506
+
507
+ # Apply finite constraint
508
+ # if not torch.isfinite(x).all():
509
+ # x = x[torch.isfinite(x).all(1)]
510
+
511
+ # If none remain process next image
512
+ n = x.shape[0] # number of boxes
513
+ if not n:
514
+ continue
515
+
516
+ # Sort by confidence
517
+ # x = x[x[:, 4].argsort(descending=True)]
518
+
519
+ # Batched NMS
520
+ c = x[:, 5] * 0 if agnostic else x[:, 5] # classes
521
+ boxes, scores = x[:, :4].clone() + c.view(-1, 1) * max_wh, x[:, 4] # boxes (offset by class), scores
522
+ i = torchvision.ops.boxes.nms(boxes, scores, iou_thres)
523
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
524
+ try: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
525
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
526
+ weights = iou * scores[None] # box weights
527
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
528
+ # i = i[iou.sum(1) > 1] # require redundancy
529
+ except: # possible CUDA error https://github.com/ultralytics/yolov3/issues/1139
530
+ print(x, i, x.shape, i.shape)
531
+ pass
532
+
533
+ output[xi] = x[i]
534
+ if (time.time() - t) > time_limit:
535
+ break # time limit exceeded
536
+
537
+ return output
538
+
539
+
540
+ def strip_optimizer(f='weights/best.pt'): # from utils.utils import *; strip_optimizer()
541
+ # Strip optimizer from *.pt files for lighter files (reduced by 2/3 size)
542
+ x = torch.load(f, map_location=torch.device('cpu'))
543
+ x['optimizer'] = None
544
+ torch.save(x, f)
545
+ print('Optimizer stripped from %s' % f)
546
+
547
+
548
+ def create_backbone(f='weights/best.pt', s='weights/backbone.pt'): # from utils.utils import *; create_backbone()
549
+ # create backbone 's' from 'f'
550
+ x = torch.load(f, map_location=torch.device('cpu'))
551
+ x['optimizer'] = None
552
+ x['training_results'] = None
553
+ x['epoch'] = -1
554
+ for p in x['model'].parameters():
555
+ p.requires_grad = True
556
+ torch.save(x, s)
557
+ print('%s modified for backbone use and saved as %s' % (f, s))
558
+
559
+
560
+ def coco_class_count(path='../coco/labels/train2014/'):
561
+ # Histogram of occurrences per class
562
+ nc = 80 # number classes
563
+ x = np.zeros(nc, dtype='int32')
564
+ files = sorted(glob.glob('%s/*.*' % path))
565
+ for i, file in enumerate(files):
566
+ labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
567
+ x += np.bincount(labels[:, 0].astype('int32'), minlength=nc)
568
+ print(i, len(files))
569
+
570
+
571
+ def coco_only_people(path='../coco/labels/train2017/'): # from utils.utils import *; coco_only_people()
572
+ # Find images with only people
573
+ files = sorted(glob.glob('%s/*.*' % path))
574
+ for i, file in enumerate(files):
575
+ labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
576
+ if all(labels[:, 0] == 0):
577
+ print(labels.shape[0], file)
578
+
579
+
580
+ def crop_images_random(path='../images/', scale=0.50): # from utils.utils import *; crop_images_random()
581
+ # crops images into random squares up to scale fraction
582
+ # WARNING: overwrites images!
583
+ for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
584
+ img = cv2.imread(file) # BGR
585
+ if img is not None:
586
+ h, w = img.shape[:2]
587
+
588
+ # create random mask
589
+ a = 30 # minimum size (pixels)
590
+ mask_h = random.randint(a, int(max(a, h * scale))) # mask height
591
+ mask_w = mask_h # mask width
592
+
593
+ # box
594
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
595
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
596
+ xmax = min(w, xmin + mask_w)
597
+ ymax = min(h, ymin + mask_h)
598
+
599
+ # apply random color mask
600
+ cv2.imwrite(file, img[ymin:ymax, xmin:xmax])
601
+
602
+
603
+ def coco_single_class_labels(path='../coco/labels/train2014/', label_class=43):
604
+ # Makes single-class coco datasets. from utils.utils import *; coco_single_class_labels()
605
+ if os.path.exists('new/'):
606
+ shutil.rmtree('new/') # delete output folder
607
+ os.makedirs('new/') # make new output folder
608
+ os.makedirs('new/labels/')
609
+ os.makedirs('new/images/')
610
+ for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
611
+ with open(file, 'r') as f:
612
+ labels = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
613
+ i = labels[:, 0] == label_class
614
+ if any(i):
615
+ img_file = file.replace('labels', 'images').replace('txt', 'jpg')
616
+ labels[:, 0] = 0 # reset class to 0
617
+ with open('new/images.txt', 'a') as f: # add image to dataset list
618
+ f.write(img_file + '\n')
619
+ with open('new/labels/' + Path(file).name, 'a') as f: # write label
620
+ for l in labels[i]:
621
+ f.write('%g %.6f %.6f %.6f %.6f\n' % tuple(l))
622
+ shutil.copyfile(src=img_file, dst='new/images/' + Path(file).name.replace('txt', 'jpg')) # copy images
623
+
624
+
625
+ def kmean_anchors(path='./data/coco128.txt', n=9, img_size=(640, 640), thr=0.20, gen=1000):
626
+ # Creates kmeans anchors for use in *.cfg files: from utils.utils import *; _ = kmean_anchors()
627
+ # n: number of anchors
628
+ # img_size: (min, max) image size used for multi-scale training (can be same values)
629
+ # thr: IoU threshold hyperparameter used for training (0.0 - 1.0)
630
+ # gen: generations to evolve anchors using genetic algorithm
631
+ from utils.datasets import LoadImagesAndLabels
632
+
633
+ def print_results(k):
634
+ k = k[np.argsort(k.prod(1))] # sort small to large
635
+ iou = wh_iou(wh, torch.Tensor(k))
636
+ max_iou = iou.max(1)[0]
637
+ bpr, aat = (max_iou > thr).float().mean(), (iou > thr).float().mean() * n # best possible recall, anch > thr
638
+
639
+ # thr = 5.0
640
+ # r = wh[:, None] / k[None]
641
+ # ar = torch.max(r, 1. / r).max(2)[0]
642
+ # max_ar = ar.min(1)[0]
643
+ # bpr, aat = (max_ar < thr).float().mean(), (ar < thr).float().mean() * n # best possible recall, anch > thr
644
+
645
+ print('%.2f iou_thr: %.3f best possible recall, %.2f anchors > thr' % (thr, bpr, aat))
646
+ print('n=%g, img_size=%s, IoU_all=%.3f/%.3f-mean/best, IoU>thr=%.3f-mean: ' %
647
+ (n, img_size, iou.mean(), max_iou.mean(), iou[iou > thr].mean()), end='')
648
+ for i, x in enumerate(k):
649
+ print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
650
+ return k
651
+
652
+ def fitness(k): # mutation fitness
653
+ iou = wh_iou(wh, torch.Tensor(k)) # iou
654
+ max_iou = iou.max(1)[0]
655
+ return (max_iou * (max_iou > thr).float()).mean() # product
656
+
657
+ # def fitness_ratio(k): # mutation fitness
658
+ # # wh(5316,2), k(9,2)
659
+ # r = wh[:, None] / k[None]
660
+ # x = torch.max(r, 1. / r).max(2)[0]
661
+ # m = x.min(1)[0]
662
+ # return 1. / (m * (m < 5).float()).mean() # product
663
+
664
+ # Get label wh
665
+ wh = []
666
+ dataset = LoadImagesAndLabels(path, augment=True, rect=True)
667
+ nr = 1 if img_size[0] == img_size[1] else 3 # number augmentation repetitions
668
+ for s, l in zip(dataset.shapes, dataset.labels):
669
+ # wh.append(l[:, 3:5] * (s / s.max())) # image normalized to letterbox normalized wh
670
+ wh.append(l[:, 3:5] * s) # image normalized to pixels
671
+ wh = np.concatenate(wh, 0).repeat(nr, axis=0) # augment 3x
672
+ # wh *= np.random.uniform(img_size[0], img_size[1], size=(wh.shape[0], 1)) # normalized to pixels (multi-scale)
673
+ wh = wh[(wh > 2.0).all(1)] # remove below threshold boxes (< 2 pixels wh)
674
+
675
+ # Kmeans calculation
676
+ from scipy.cluster.vq import kmeans
677
+ print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
678
+ s = wh.std(0) # sigmas for whitening
679
+ k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
680
+ k *= s
681
+ wh = torch.Tensor(wh)
682
+ k = print_results(k)
683
+
684
+ # # Plot
685
+ # k, d = [None] * 20, [None] * 20
686
+ # for i in tqdm(range(1, 21)):
687
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
688
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7))
689
+ # ax = ax.ravel()
690
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
691
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
692
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
693
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
694
+ # fig.tight_layout()
695
+ # fig.savefig('wh.png', dpi=200)
696
+
697
+ # Evolve
698
+ npr = np.random
699
+ f, sh, mp, s = fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
700
+ for _ in tqdm(range(gen), desc='Evolving anchors'):
701
+ v = np.ones(sh)
702
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
703
+ v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
704
+ kg = (k.copy() * v).clip(min=2.0)
705
+ fg = fitness(kg)
706
+ if fg > f:
707
+ f, k = fg, kg.copy()
708
+ print_results(k)
709
+ k = print_results(k)
710
+
711
+ return k
712
+
713
+
714
+ def print_mutation(hyp, results, bucket=''):
715
+ # Print mutation results to evolve.txt (for use with train.py --evolve)
716
+ a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
717
+ b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
718
+ c = '%10.4g' * len(results) % results # results (P, R, mAP, F1, test_loss)
719
+ print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
720
+
721
+ if bucket:
722
+ os.system('gsutil cp gs://%s/evolve.txt .' % bucket) # download evolve.txt
723
+
724
+ with open('evolve.txt', 'a') as f: # append result
725
+ f.write(c + b + '\n')
726
+ x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
727
+ np.savetxt('evolve.txt', x[np.argsort(-fitness(x))], '%10.3g') # save sort by fitness
728
+
729
+ if bucket:
730
+ os.system('gsutil cp evolve.txt gs://%s' % bucket) # upload evolve.txt
731
+
732
+
733
+ def apply_classifier(x, model, img, im0):
734
+ # applies a second stage classifier to yolo outputs
735
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
736
+ for i, d in enumerate(x): # per image
737
+ if d is not None and len(d):
738
+ d = d.clone()
739
+
740
+ # Reshape and pad cutouts
741
+ b = xyxy2xywh(d[:, :4]) # boxes
742
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
743
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
744
+ d[:, :4] = xywh2xyxy(b).long()
745
+
746
+ # Rescale boxes from img_size to im0 size
747
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
748
+
749
+ # Classes
750
+ pred_cls1 = d[:, 5].long()
751
+ ims = []
752
+ for j, a in enumerate(d): # per item
753
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
754
+ im = cv2.resize(cutout, (224, 224)) # BGR
755
+ # cv2.imwrite('test%i.jpg' % j, cutout)
756
+
757
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
758
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
759
+ im /= 255.0 # 0 - 255 to 0.0 - 1.0
760
+ ims.append(im)
761
+
762
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
763
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
764
+
765
+ return x
766
+
767
+
768
+ def fitness(x):
769
+ # Returns fitness (for use with results.txt or evolve.txt)
770
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, [email protected], [email protected]:0.95]
771
+ return (x[:, :4] * w).sum(1)
772
+
773
+
774
+ def output_to_target(output, width, height):
775
+ """
776
+ Convert a YOLO model output to target format
777
+ [batch_id, class_id, x, y, w, h, conf]
778
+ """
779
+ if isinstance(output, torch.Tensor):
780
+ output = output.cpu().numpy()
781
+
782
+ targets = []
783
+ for i, o in enumerate(output):
784
+ if o is not None:
785
+ for pred in o:
786
+ box = pred[:4]
787
+ w = (box[2] - box[0]) / width
788
+ h = (box[3] - box[1]) / height
789
+ x = box[0] / width + w / 2
790
+ y = box[1] / height + h / 2
791
+ conf = pred[4]
792
+ cls = int(pred[5])
793
+
794
+ targets.append([i, cls, x, y, w, h, conf])
795
+
796
+ return np.array(targets)
797
+
798
+
799
+ # Plotting functions ---------------------------------------------------------------------------------------------------
800
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
801
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
802
+ def butter_lowpass(cutoff, fs, order):
803
+ nyq = 0.5 * fs
804
+ normal_cutoff = cutoff / nyq
805
+ b, a = butter(order, normal_cutoff, btype='low', analog=False)
806
+ return b, a
807
+
808
+ b, a = butter_lowpass(cutoff, fs, order=order)
809
+ return filtfilt(b, a, data) # forward-backward filter
810
+
811
+
812
+ def plot_one_box(x, img, color=None, label=None, line_thickness=None):
813
+ # Plots one bounding box on image img
814
+ tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
815
+ color = color or [random.randint(0, 255) for _ in range(3)]
816
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
817
+ cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
818
+ if label:
819
+ tf = max(tl - 1, 1) # font thickness
820
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
821
+ c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
822
+ cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
823
+ cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
824
+
825
+
826
+ def plot_wh_methods(): # from utils.utils import *; plot_wh_methods()
827
+ # Compares the two methods for width-height anchor multiplication
828
+ # https://github.com/ultralytics/yolov3/issues/168
829
+ x = np.arange(-4.0, 4.0, .1)
830
+ ya = np.exp(x)
831
+ yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
832
+
833
+ fig = plt.figure(figsize=(6, 3), dpi=150)
834
+ plt.plot(x, ya, '.-', label='yolo method')
835
+ plt.plot(x, yb ** 2, '.-', label='^2 power method')
836
+ plt.plot(x, yb ** 2.5, '.-', label='^2.5 power method')
837
+ plt.xlim(left=-4, right=4)
838
+ plt.ylim(bottom=0, top=6)
839
+ plt.xlabel('input')
840
+ plt.ylabel('output')
841
+ plt.legend()
842
+ fig.tight_layout()
843
+ fig.savefig('comparison.png', dpi=200)
844
+
845
+
846
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
847
+ tl = 3 # line thickness
848
+ tf = max(tl - 1, 1) # font thickness
849
+ if os.path.isfile(fname): # do not overwrite
850
+ return None
851
+
852
+ if isinstance(images, torch.Tensor):
853
+ images = images.cpu().numpy()
854
+
855
+ if isinstance(targets, torch.Tensor):
856
+ targets = targets.cpu().numpy()
857
+
858
+ # un-normalise
859
+ if np.max(images[0]) <= 1:
860
+ images *= 255
861
+
862
+ bs, _, h, w = images.shape # batch size, _, height, width
863
+ bs = min(bs, max_subplots) # limit plot images
864
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
865
+
866
+ # Check if we should resize
867
+ scale_factor = max_size / max(h, w)
868
+ if scale_factor < 1:
869
+ h = math.ceil(scale_factor * h)
870
+ w = math.ceil(scale_factor * w)
871
+
872
+ # Empty array for output
873
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)
874
+
875
+ # Fix class - colour map
876
+ prop_cycle = plt.rcParams['axes.prop_cycle']
877
+ # https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
878
+ hex2rgb = lambda h: tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
879
+ color_lut = [hex2rgb(h) for h in prop_cycle.by_key()['color']]
880
+
881
+ for i, img in enumerate(images):
882
+ if i == max_subplots: # if last batch has fewer images than we expect
883
+ break
884
+
885
+ block_x = int(w * (i // ns))
886
+ block_y = int(h * (i % ns))
887
+
888
+ img = img.transpose(1, 2, 0)
889
+ if scale_factor < 1:
890
+ img = cv2.resize(img, (w, h))
891
+
892
+ mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
893
+ if len(targets) > 0:
894
+ image_targets = targets[targets[:, 0] == i]
895
+ boxes = xywh2xyxy(image_targets[:, 2:6]).T
896
+ classes = image_targets[:, 1].astype('int')
897
+ gt = image_targets.shape[1] == 6 # ground truth if no conf column
898
+ conf = None if gt else image_targets[:, 6] # check for confidence presence (gt vs pred)
899
+
900
+ boxes[[0, 2]] *= w
901
+ boxes[[0, 2]] += block_x
902
+ boxes[[1, 3]] *= h
903
+ boxes[[1, 3]] += block_y
904
+ for j, box in enumerate(boxes.T):
905
+ cls = int(classes[j])
906
+ color = color_lut[cls % len(color_lut)]
907
+ cls = names[cls] if names else cls
908
+ if gt or conf[j] > 0.3: # 0.3 conf thresh
909
+ label = '%s' % cls if gt else '%s %.1f' % (cls, conf[j])
910
+ plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
911
+
912
+ # Draw image filename labels
913
+ if paths is not None:
914
+ label = os.path.basename(paths[i])[:40] # trim to 40 char
915
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
916
+ cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
917
+ lineType=cv2.LINE_AA)
918
+
919
+ # Image border
920
+ cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
921
+
922
+ if fname is not None:
923
+ mosaic = cv2.resize(mosaic, (int(ns * w * 0.5), int(ns * h * 0.5)), interpolation=cv2.INTER_AREA)
924
+ cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB))
925
+
926
+ return mosaic
927
+
928
+
929
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300):
930
+ # Plot LR simulating training for full epochs
931
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
932
+ y = []
933
+ for _ in range(epochs):
934
+ scheduler.step()
935
+ y.append(optimizer.param_groups[0]['lr'])
936
+ plt.plot(y, '.-', label='LR')
937
+ plt.xlabel('epoch')
938
+ plt.ylabel('LR')
939
+ plt.grid()
940
+ plt.xlim(0, epochs)
941
+ plt.ylim(0)
942
+ plt.tight_layout()
943
+ plt.savefig('LR.png', dpi=200)
944
+
945
+
946
+ def plot_test_txt(): # from utils.utils import *; plot_test()
947
+ # Plot test.txt histograms
948
+ x = np.loadtxt('test.txt', dtype=np.float32)
949
+ box = xyxy2xywh(x[:, :4])
950
+ cx, cy = box[:, 0], box[:, 1]
951
+
952
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
953
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
954
+ ax.set_aspect('equal')
955
+ plt.savefig('hist2d.png', dpi=300)
956
+
957
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
958
+ ax[0].hist(cx, bins=600)
959
+ ax[1].hist(cy, bins=600)
960
+ plt.savefig('hist1d.png', dpi=200)
961
+
962
+
963
+ def plot_targets_txt(): # from utils.utils import *; plot_targets_txt()
964
+ # Plot targets.txt histograms
965
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
966
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
967
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
968
+ ax = ax.ravel()
969
+ for i in range(4):
970
+ ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
971
+ ax[i].legend()
972
+ ax[i].set_title(s[i])
973
+ plt.savefig('targets.jpg', dpi=200)
974
+
975
+
976
+ def plot_study_txt(f='study.txt', x=None): # from utils.utils import *; plot_study_txt()
977
+ # Plot study.txt generated by test.py
978
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
979
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
980
+ s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
981
+ fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
982
+ ax = ax.ravel()
983
+ for i in range(7):
984
+ ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
985
+ ax[i].set_title(s[i])
986
+ plt.savefig(f.replace('.txt','.png'), dpi=200)
987
+
988
+
989
+ def plot_labels(labels):
990
+ # plot dataset labels
991
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classees, boxes
992
+
993
+ def hist2d(x, y, n=100):
994
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
995
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
996
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
997
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
998
+ return np.log(hist[xidx, yidx])
999
+
1000
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
1001
+ ax = ax.ravel()
1002
+ ax[0].hist(c, bins=int(c.max() + 1))
1003
+ ax[0].set_xlabel('classes')
1004
+ ax[1].scatter(b[0], b[1], c=hist2d(b[0], b[1], 90), cmap='jet')
1005
+ ax[1].set_xlabel('x')
1006
+ ax[1].set_ylabel('y')
1007
+ ax[2].scatter(b[2], b[3], c=hist2d(b[2], b[3], 90), cmap='jet')
1008
+ ax[2].set_xlabel('width')
1009
+ ax[2].set_ylabel('height')
1010
+ plt.savefig('labels.png', dpi=200)
1011
+
1012
+
1013
+ def plot_evolution_results(hyp): # from utils.utils import *; plot_evolution_results(hyp)
1014
+ # Plot hyperparameter evolution results in evolve.txt
1015
+ x = np.loadtxt('evolve.txt', ndmin=2)
1016
+ f = fitness(x)
1017
+ # weights = (f - f.min()) ** 2 # for weighted results
1018
+ plt.figure(figsize=(12, 10), tight_layout=True)
1019
+ matplotlib.rc('font', **{'size': 8})
1020
+ for i, (k, v) in enumerate(hyp.items()):
1021
+ y = x[:, i + 7]
1022
+ # mu = (y * weights).sum() / weights.sum() # best weighted result
1023
+ mu = y[f.argmax()] # best single result
1024
+ plt.subplot(4, 5, i + 1)
1025
+ plt.plot(mu, f.max(), 'o', markersize=10)
1026
+ plt.plot(y, f, '.')
1027
+ plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
1028
+ print('%15s: %.3g' % (k, mu))
1029
+ plt.savefig('evolve.png', dpi=200)
1030
+
1031
+
1032
+ def plot_results_overlay(start=0, stop=0): # from utils.utils import *; plot_results_overlay()
1033
+ # Plot training 'results*.txt', overlaying train and val losses
1034
+ s = ['train', 'train', 'train', 'Precision', '[email protected]', 'val', 'val', 'val', 'Recall', '[email protected]:0.95'] # legends
1035
+ t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
1036
+ for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
1037
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
1038
+ n = results.shape[1] # number of rows
1039
+ x = range(start, min(stop, n) if stop else n)
1040
+ fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
1041
+ ax = ax.ravel()
1042
+ for i in range(5):
1043
+ for j in [i, i + 5]:
1044
+ y = results[j, x]
1045
+ # ax[i].plot(x, y, marker='.', label=s[j])
1046
+ y_smooth = butter_lowpass_filtfilt(y)
1047
+ ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
1048
+
1049
+ ax[i].set_title(t[i])
1050
+ ax[i].legend()
1051
+ ax[i].set_ylabel(f) if i == 0 else None # add filename
1052
+ fig.savefig(f.replace('.txt', '.png'), dpi=200)
1053
+
1054
+
1055
+ def plot_results(start=0, stop=0, bucket='', id=()): # from utils.utils import *; plot_results()
1056
+ # Plot training 'results*.txt' as seen in https://github.com/ultralytics/yolov3#training
1057
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6))
1058
+ ax = ax.ravel()
1059
+ s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
1060
+ 'val GIoU', 'val Objectness', 'val Classification', '[email protected]', '[email protected]:0.95']
1061
+ if bucket:
1062
+ os.system('rm -rf storage.googleapis.com')
1063
+ files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
1064
+ else:
1065
+ files = glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')
1066
+ for f in sorted(files):
1067
+ try:
1068
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
1069
+ n = results.shape[1] # number of rows
1070
+ x = range(start, min(stop, n) if stop else n)
1071
+ for i in range(10):
1072
+ y = results[i, x]
1073
+ if i in [0, 1, 2, 5, 6, 7]:
1074
+ y[y == 0] = np.nan # dont show zero loss values
1075
+ # y /= y[0] # normalize
1076
+ ax[i].plot(x, y, marker='.', label=Path(f).stem, linewidth=2, markersize=8)
1077
+ ax[i].set_title(s[i])
1078
+ # if i in [5, 6, 7]: # share train and val loss y axes
1079
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
1080
+ except:
1081
+ print('Warning: Plotting error for %s, skipping file' % f)
1082
+
1083
+ fig.tight_layout()
1084
+ ax[1].legend()
1085
+ fig.savefig('results.png', dpi=200)
weights/download_weights.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Download common models
3
+
4
+ python3 -c "from models import *;
5
+ attempt_download('weights/yolov5s.pt');
6
+ attempt_download('weights/yolov5m.pt');
7
+ attempt_download('weights/yolov5l.pt')"