Aniaaaa commited on
Commit
20870de
·
1 Parent(s): 3ada4fd

Upload 26 files

Browse files
Files changed (26) hide show
  1. .gitattributes +5 -31
  2. .gitignore +256 -0
  3. .pre-commit-config.yaml +64 -0
  4. 3.jpeg +0 -0
  5. CONTRIBUTING.md +98 -0
  6. LICENSE +674 -0
  7. PATHS.py +11 -0
  8. README.md +0 -12
  9. best_kitti.pt +3 -0
  10. best_yolos_coco.pt +3 -0
  11. detect.py +259 -0
  12. detect_yolo.py +239 -0
  13. export.py +607 -0
  14. hubconf.py +146 -0
  15. kernel.ipynb +139 -0
  16. main.py +29 -0
  17. requirements.txt +140 -0
  18. requirements2.txt +40 -0
  19. result.jpg +0 -0
  20. setup.cfg +59 -0
  21. train.py +670 -0
  22. tutorial.ipynb +0 -0
  23. utilss.py +80 -0
  24. val.py +394 -0
  25. yolov5-streamlit.py +165 -0
  26. yolov5s.pt +3 -0
.gitattributes CHANGED
@@ -1,31 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ftz filter=lfs diff=lfs merge=lfs -text
6
- *.gz filter=lfs diff=lfs merge=lfs -text
7
- *.h5 filter=lfs diff=lfs merge=lfs -text
8
- *.joblib filter=lfs diff=lfs merge=lfs -text
9
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
- *.model filter=lfs diff=lfs merge=lfs -text
11
- *.msgpack filter=lfs diff=lfs merge=lfs -text
12
- *.npy filter=lfs diff=lfs merge=lfs -text
13
- *.npz filter=lfs diff=lfs merge=lfs -text
14
- *.onnx filter=lfs diff=lfs merge=lfs -text
15
- *.ot filter=lfs diff=lfs merge=lfs -text
16
- *.parquet filter=lfs diff=lfs merge=lfs -text
17
- *.pickle filter=lfs diff=lfs merge=lfs -text
18
- *.pkl filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pt filter=lfs diff=lfs merge=lfs -text
21
- *.pth filter=lfs diff=lfs merge=lfs -text
22
- *.rar filter=lfs diff=lfs merge=lfs -text
23
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
- *.tar.* filter=lfs diff=lfs merge=lfs -text
25
- *.tflite filter=lfs diff=lfs merge=lfs -text
26
- *.tgz filter=lfs diff=lfs merge=lfs -text
27
- *.wasm filter=lfs diff=lfs merge=lfs -text
28
- *.xz filter=lfs diff=lfs merge=lfs -text
29
- *.zip filter=lfs diff=lfs merge=lfs -text
30
- *.zst filter=lfs diff=lfs merge=lfs -text
31
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ # this drop notebooks from GitHub language stats
2
+ *.ipynb linguist-vendored
3
+ best_kitti.pt filter=lfs diff=lfs merge=lfs -text
4
+ best_yolos_coco.pt filter=lfs diff=lfs merge=lfs -text
5
+ yolov5s.pt filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repo-specific GitIgnore ----------------------------------------------------------------------------------------------
2
+ *.jpg
3
+ *.jpeg
4
+ *.png
5
+ *.bmp
6
+ *.tif
7
+ *.tiff
8
+ *.heic
9
+ *.JPG
10
+ *.JPEG
11
+ *.PNG
12
+ *.BMP
13
+ *.TIF
14
+ *.TIFF
15
+ *.HEIC
16
+ *.mp4
17
+ *.mov
18
+ *.MOV
19
+ *.avi
20
+ *.data
21
+ *.json
22
+ *.cfg
23
+ !setup.cfg
24
+ !cfg/yolov3*.cfg
25
+
26
+ storage.googleapis.com
27
+ runs/*
28
+ data/*
29
+ data/images/*
30
+ !data/*.yaml
31
+ !data/hyps
32
+ !data/scripts
33
+ !data/images
34
+ !data/images/zidane.jpg
35
+ !data/images/bus.jpg
36
+ !data/*.sh
37
+
38
+ results*.csv
39
+
40
+ # Datasets -------------------------------------------------------------------------------------------------------------
41
+ coco/
42
+ coco128/
43
+ VOC/
44
+
45
+ # MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
46
+ *.m~
47
+ *.mat
48
+ !targets*.mat
49
+
50
+ # Neural Network weights -----------------------------------------------------------------------------------------------
51
+ *.weights
52
+ *.pt
53
+ *.pb
54
+ *.onnx
55
+ *.engine
56
+ *.mlmodel
57
+ *.torchscript
58
+ *.tflite
59
+ *.h5
60
+ *_saved_model/
61
+ *_web_model/
62
+ *_openvino_model/
63
+ darknet53.conv.74
64
+ yolov3-tiny.conv.15
65
+
66
+ # GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
67
+ # Byte-compiled / optimized / DLL files
68
+ __pycache__/
69
+ *.py[cod]
70
+ *$py.class
71
+
72
+ # C extensions
73
+ *.so
74
+
75
+ # Distribution / packaging
76
+ .Python
77
+ env/
78
+ build/
79
+ develop-eggs/
80
+ dist/
81
+ downloads/
82
+ eggs/
83
+ .eggs/
84
+ lib/
85
+ lib64/
86
+ parts/
87
+ sdist/
88
+ var/
89
+ wheels/
90
+ *.egg-info/
91
+ /wandb/
92
+ .installed.cfg
93
+ *.egg
94
+
95
+
96
+ # PyInstaller
97
+ # Usually these files are written by a python script from a template
98
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
99
+ *.manifest
100
+ *.spec
101
+
102
+ # Installer logs
103
+ pip-log.txt
104
+ pip-delete-this-directory.txt
105
+
106
+ # Unit test / coverage reports
107
+ htmlcov/
108
+ .tox/
109
+ .coverage
110
+ .coverage.*
111
+ .cache
112
+ nosetests.xml
113
+ coverage.xml
114
+ *.cover
115
+ .hypothesis/
116
+
117
+ # Translations
118
+ *.mo
119
+ *.pot
120
+
121
+ # Django stuff:
122
+ *.log
123
+ local_settings.py
124
+
125
+ # Flask stuff:
126
+ instance/
127
+ .webassets-cache
128
+
129
+ # Scrapy stuff:
130
+ .scrapy
131
+
132
+ # Sphinx documentation
133
+ docs/_build/
134
+
135
+ # PyBuilder
136
+ target/
137
+
138
+ # Jupyter Notebook
139
+ .ipynb_checkpoints
140
+
141
+ # pyenv
142
+ .python-version
143
+
144
+ # celery beat schedule file
145
+ celerybeat-schedule
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # dotenv
151
+ .env
152
+
153
+ # virtualenv
154
+ .venv*
155
+ venv*/
156
+ ENV*/
157
+
158
+ # Spyder project settings
159
+ .spyderproject
160
+ .spyproject
161
+
162
+ # Rope project settings
163
+ .ropeproject
164
+
165
+ # mkdocs documentation
166
+ /site
167
+
168
+ # mypy
169
+ .mypy_cache/
170
+
171
+
172
+ # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
173
+
174
+ # General
175
+ .DS_Store
176
+ .AppleDouble
177
+ .LSOverride
178
+
179
+ # Icon must end with two \r
180
+ Icon
181
+ Icon?
182
+
183
+ # Thumbnails
184
+ ._*
185
+
186
+ # Files that might appear in the root of a volume
187
+ .DocumentRevisions-V100
188
+ .fseventsd
189
+ .Spotlight-V100
190
+ .TemporaryItems
191
+ .Trashes
192
+ .VolumeIcon.icns
193
+ .com.apple.timemachine.donotpresent
194
+
195
+ # Directories potentially created on remote AFP share
196
+ .AppleDB
197
+ .AppleDesktop
198
+ Network Trash Folder
199
+ Temporary Items
200
+ .apdisk
201
+
202
+
203
+ # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
204
+ # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
205
+ # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
206
+
207
+ # User-specific stuff:
208
+ .idea/*
209
+ .idea/**/workspace.xml
210
+ .idea/**/tasks.xml
211
+ .idea/dictionaries
212
+ .html # Bokeh Plots
213
+ .pg # TensorFlow Frozen Graphs
214
+ .avi # videos
215
+
216
+ # Sensitive or high-churn files:
217
+ .idea/**/dataSources/
218
+ .idea/**/dataSources.ids
219
+ .idea/**/dataSources.local.xml
220
+ .idea/**/sqlDataSources.xml
221
+ .idea/**/dynamic.xml
222
+ .idea/**/uiDesigner.xml
223
+
224
+ # Gradle:
225
+ .idea/**/gradle.xml
226
+ .idea/**/libraries
227
+
228
+ # CMake
229
+ cmake-build-debug/
230
+ cmake-build-release/
231
+
232
+ # Mongo Explorer plugin:
233
+ .idea/**/mongoSettings.xml
234
+
235
+ ## File-based project format:
236
+ *.iws
237
+
238
+ ## Plugin-specific files:
239
+
240
+ # IntelliJ
241
+ out/
242
+
243
+ # mpeltonen/sbt-idea plugin
244
+ .idea_modules/
245
+
246
+ # JIRA plugin
247
+ atlassian-ide-plugin.xml
248
+
249
+ # Cursive Clojure plugin
250
+ .idea/replstate.xml
251
+
252
+ # Crashlytics plugin (for Android Studio and IntelliJ)
253
+ com_crashlytics_export_strings.xml
254
+ crashlytics.properties
255
+ crashlytics-build.properties
256
+ fabric.properties
.pre-commit-config.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Define hooks for code formations
2
+ # Will be applied on any updated commit files if a user has installed and linked commit hook
3
+
4
+ default_language_version:
5
+ python: python3.8
6
+
7
+ # Define bot property if installed via https://github.com/marketplace/pre-commit-ci
8
+ ci:
9
+ autofix_prs: true
10
+ autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
11
+ autoupdate_schedule: monthly
12
+ # submodules: true
13
+
14
+ repos:
15
+ - repo: https://github.com/pre-commit/pre-commit-hooks
16
+ rev: v4.2.0
17
+ hooks:
18
+ - id: end-of-file-fixer
19
+ - id: trailing-whitespace
20
+ - id: check-case-conflict
21
+ - id: check-yaml
22
+ - id: check-toml
23
+ - id: pretty-format-json
24
+ - id: check-docstring-first
25
+
26
+ - repo: https://github.com/asottile/pyupgrade
27
+ rev: v2.32.1
28
+ hooks:
29
+ - id: pyupgrade
30
+ name: Upgrade code
31
+ args: [ --py37-plus ]
32
+
33
+ - repo: https://github.com/PyCQA/isort
34
+ rev: 5.10.1
35
+ hooks:
36
+ - id: isort
37
+ name: Sort imports
38
+
39
+ - repo: https://github.com/pre-commit/mirrors-yapf
40
+ rev: v0.32.0
41
+ hooks:
42
+ - id: yapf
43
+ name: YAPF formatting
44
+
45
+ - repo: https://github.com/executablebooks/mdformat
46
+ rev: 0.7.14
47
+ hooks:
48
+ - id: mdformat
49
+ name: MD formatting
50
+ additional_dependencies:
51
+ - mdformat-gfm
52
+ - mdformat-black
53
+ exclude: "README.md|README_cn.md"
54
+
55
+ - repo: https://github.com/asottile/yesqa
56
+ rev: v1.3.0
57
+ hooks:
58
+ - id: yesqa
59
+
60
+ - repo: https://github.com/PyCQA/flake8
61
+ rev: 4.0.1
62
+ hooks:
63
+ - id: flake8
64
+ name: PEP8
3.jpeg ADDED
CONTRIBUTING.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Contributing to YOLOv5 🚀
2
+
3
+ We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
4
+
5
+ - Reporting a bug
6
+ - Discussing the current state of the code
7
+ - Submitting a fix
8
+ - Proposing a new feature
9
+ - Becoming a maintainer
10
+
11
+ YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
12
+ helping push the frontiers of what's possible in AI 😃!
13
+
14
+ ## Submitting a Pull Request (PR) 🛠️
15
+
16
+ Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
17
+
18
+ ### 1. Select File to Update
19
+
20
+ Select `requirements.txt` to update by clicking on it in GitHub.
21
+
22
+ <p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
23
+
24
+ ### 2. Click 'Edit this file'
25
+
26
+ Button is in top-right corner.
27
+
28
+ <p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
29
+
30
+ ### 3. Make Changes
31
+
32
+ Change `matplotlib` version from `3.2.2` to `3.3`.
33
+
34
+ <p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
35
+
36
+ ### 4. Preview Changes and Submit PR
37
+
38
+ Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
39
+ for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
40
+ changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
41
+
42
+ <p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
43
+
44
+ ### PR recommendations
45
+
46
+ To allow your work to be integrated as seamlessly as possible, we advise you to:
47
+
48
+ - ✅ Verify your PR is **up-to-date with upstream/master.** If your PR is behind upstream/master an
49
+ automatic [GitHub Actions](https://github.com/ultralytics/yolov5/blob/master/.github/workflows/rebase.yml) merge may
50
+ be attempted by writing /rebase in a new comment, or by running the following code, replacing 'feature' with the name
51
+ of your local branch:
52
+
53
+ ```bash
54
+ git remote add upstream https://github.com/ultralytics/yolov5.git
55
+ git fetch upstream
56
+ # git checkout feature # <--- replace 'feature' with local branch name
57
+ git merge upstream/master
58
+ git push -u origin -f
59
+ ```
60
+
61
+ - ✅ Verify all Continuous Integration (CI) **checks are passing**.
62
+ - ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
63
+ but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
64
+
65
+ ## Submitting a Bug Report 🐛
66
+
67
+ If you spot a problem with YOLOv5 please submit a Bug Report!
68
+
69
+ For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few
70
+ short guidelines below to help users provide what we need in order to get started.
71
+
72
+ When asking a question, people will be better able to provide help if you provide **code** that they can easily
73
+ understand and use to **reproduce** the problem. This is referred to by community members as creating
74
+ a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
75
+ the problem should be:
76
+
77
+ - ✅ **Minimal** – Use as little code as possible that still produces the same problem
78
+ - ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
79
+ - ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
80
+
81
+ In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
82
+ should be:
83
+
84
+ - ✅ **Current** – Verify that your code is up-to-date with current
85
+ GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
86
+ copy to ensure your problem has not already been resolved by previous commits.
87
+ - ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this
88
+ repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
89
+
90
+ If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛
91
+ **Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing
92
+ a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
93
+ understand and diagnose your problem.
94
+
95
+ ## License
96
+
97
+ By contributing, you agree that your contributions will be licensed under
98
+ the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/)
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <http://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
PATHS.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NAVBAR_PATHS = {
2
+ 'Page d\'accueil':'Page d\'accueil',
3
+ 'A propos': 'A propos',
4
+ 'Detection avec Detectron2': 'Detection avec Detectron2',
5
+ 'Detection avec Yolo v5': 'Detection avec Yolo v5'
6
+
7
+ }
8
+
9
+ SETTINGS = {
10
+ 'CONFIGURATION':'configuration'
11
+ }
README.md CHANGED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Code Site
3
- emoji: 😻
4
- colorFrom: green
5
- colorTo: green
6
- sdk: streamlit
7
- sdk_version: 1.10.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
best_kitti.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8749e7f7a658fe9bebe3eccf3c1f9ead93f8e3c64805e15a57a83512e5c92ed4
3
+ size 14325941
best_yolos_coco.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd4b38057855a852e3ae87ace902b75c5440281304e59672c9387b39c2aa2ea1
3
+ size 14865461
detect.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Run inference on images, videos, directories, streams, etc.
4
+
5
+ Usage - sources:
6
+ $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
7
+ img.jpg # image
8
+ vid.mp4 # video
9
+ path/ # directory
10
+ path/*.jpg # glob
11
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
12
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
13
+
14
+ Usage - formats:
15
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
16
+ yolov5s.torchscript # TorchScript
17
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
18
+ yolov5s.xml # OpenVINO
19
+ yolov5s.engine # TensorRT
20
+ yolov5s.mlmodel # CoreML (macOS-only)
21
+ yolov5s_saved_model # TensorFlow SavedModel
22
+ yolov5s.pb # TensorFlow GraphDef
23
+ yolov5s.tflite # TensorFlow Lite
24
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
25
+ """
26
+
27
+ import argparse
28
+ import os
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ import torch
33
+ import torch.backends.cudnn as cudnn
34
+
35
+ FILE = Path(__file__).resolve()
36
+ ROOT = FILE.parents[0] # YOLOv5 root directory
37
+ if str(ROOT) not in sys.path:
38
+ sys.path.append(str(ROOT)) # add ROOT to PATH
39
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
40
+ from models.common import DetectMultiBackend
41
+ from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
42
+ from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
43
+ increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
44
+ from utils.plots import Annotator, colors, save_one_box
45
+ from utils.torch_utils import select_device, time_sync
46
+
47
+
48
+ @torch.no_grad()
49
+ def run(
50
+ weights=ROOT / 'yolov5s.pt', # model.pt path(s)
51
+ source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
52
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
53
+ imgsz=(640, 640), # inference size (height, width)
54
+ conf_thres=0.25, # confidence threshold
55
+ iou_thres=0.45, # NMS IOU threshold
56
+ max_det=1000, # maximum detections per image
57
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
58
+ view_img=False, # show results
59
+ save_txt=False, # save results to *.txt
60
+ save_conf=False, # save confidences in --save-txt labels
61
+ save_crop=False, # save cropped prediction boxes
62
+ nosave=False, # do not save images/videos
63
+ classes=None, # filter by class: --class 0, or --class 0 2 3
64
+ agnostic_nms=False, # class-agnostic NMS
65
+ augment=False, # augmented inference
66
+ visualize=False, # visualize features
67
+ update=False, # update all models
68
+ project=ROOT / 'runs/detect', # save results to project/name
69
+ name='exp', # save results to project/name
70
+ exist_ok=False, # existing project/name ok, do not increment
71
+ line_thickness=3, # bounding box thickness (pixels)
72
+ hide_labels=False, # hide labels
73
+ hide_conf=False, # hide confidences
74
+ half=False, # use FP16 half-precision inference
75
+ dnn=False, # use OpenCV DNN for ONNX inference
76
+ ):
77
+ source = str(source)
78
+ save_img = not nosave and not source.endswith('.txt') # save inference images
79
+ is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
80
+ is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
81
+ webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
82
+ if is_url and is_file:
83
+ source = check_file(source) # download
84
+
85
+ # Directories
86
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
87
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
88
+
89
+ # Load model
90
+ device = select_device(device)
91
+ print(f'weights : {weights}, device : {device}')
92
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
93
+ stride, names, pt = model.stride, model.names, model.pt
94
+ imgsz = check_img_size(imgsz, s=stride) # check image sizerun
95
+
96
+ # Dataloader
97
+ if webcam:
98
+ view_img = check_imshow()
99
+ cudnn.benchmark = True # set True to speed up constant image size inference
100
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
101
+ bs = len(dataset) # batch_size
102
+ else:
103
+ dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
104
+ bs = 1 # batch_size
105
+ vid_path, vid_writer = [None] * bs, [None] * bs
106
+
107
+ # Run inference
108
+ model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
109
+ seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
110
+ for path, im, im0s, vid_cap, s in dataset:
111
+ t1 = time_sync()
112
+ im = torch.from_numpy(im).to(device)
113
+ im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
114
+ im /= 255 # 0 - 255 to 0.0 - 1.0
115
+ if len(im.shape) == 3:
116
+ im = im[None] # expand for batch dim
117
+ t2 = time_sync()
118
+ dt[0] += t2 - t1
119
+
120
+ # Inference
121
+ visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
122
+ pred = model(im, augment=augment, visualize=visualize)
123
+ t3 = time_sync()
124
+ dt[1] += t3 - t2
125
+
126
+ # NMS
127
+ pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
128
+ dt[2] += time_sync() - t3
129
+
130
+ # Second-stage classifier (optional)
131
+ # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
132
+
133
+ # Process predictions
134
+ for i, det in enumerate(pred): # per image
135
+ seen += 1
136
+ if webcam: # batch_size >= 1
137
+ p, im0, frame = path[i], im0s[i].copy(), dataset.count
138
+ s += f'{i}: '
139
+ else:
140
+ p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
141
+
142
+ p = Path(p) # to Path
143
+ save_path = str(save_dir / p.name) # im.jpg
144
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
145
+ s += '%gx%g ' % im.shape[2:] # print string
146
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
147
+ imc = im0.copy() if save_crop else im0 # for save_crop
148
+ annotator = Annotator(im0, line_width=line_thickness, example=str(names))
149
+ if len(det):
150
+ # Rescale boxes from img_size to im0 size
151
+ det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
152
+
153
+ # Print results
154
+ for c in det[:, -1].unique():
155
+ n = (det[:, -1] == c).sum() # detections per class
156
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
157
+
158
+ # Write results
159
+ for *xyxy, conf, cls in reversed(det):
160
+ if save_txt: # Write to file
161
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
162
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
163
+ with open(f'{txt_path}.txt', 'a') as f:
164
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
165
+
166
+ if save_img or save_crop or view_img: # Add bbox to image
167
+ c = int(cls) # integer class
168
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
169
+ annotator.box_label(xyxy, label, color=colors(c, True))
170
+ if save_crop:
171
+ save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
172
+
173
+ # Stream results
174
+ im0 = annotator.result()
175
+ if view_img:
176
+ if p not in windows:
177
+ windows.append(p)
178
+ cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
179
+ cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
180
+ cv2.imshow(str(p), im0)
181
+ cv2.waitKey(1) # 1 millisecond
182
+
183
+ # Save results (image with detections)
184
+ if save_img:
185
+ if dataset.mode == 'image':
186
+ cv2.imwrite(save_path, im0)
187
+ else: # 'video' or 'stream'
188
+ if vid_path[i] != save_path: # new video
189
+ vid_path[i] = save_path
190
+ if isinstance(vid_writer[i], cv2.VideoWriter):
191
+ vid_writer[i].release() # release previous video writer
192
+ if vid_cap: # video
193
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
194
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
195
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
196
+ else: # stream
197
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
198
+ save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
199
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
200
+ vid_writer[i].write(im0)
201
+
202
+ # Print time (inference-only)
203
+ LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
204
+
205
+ # Print results
206
+ t = tuple(x / seen * 1E3 for x in dt) # speeds per image
207
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
208
+ if save_txt or save_img:
209
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
210
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
211
+ if update:
212
+ strip_optimizer(weights) # update model (to fix SourceChangeWarning)
213
+
214
+
215
+ def parse_opt():
216
+ parser = argparse.ArgumentParser()
217
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
218
+ parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
219
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
220
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
221
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
222
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
223
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
224
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
225
+ parser.add_argument('--view-img', action='store_true', help='show results')
226
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
227
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
228
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
229
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
230
+ parser.add_argument('--classes', nargs='+', type=int, default=(0, 1, 2, 3, 5, 7, 9, 11), help='filter by class: --classes 0, or --classes 0 2 3')
231
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
232
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
233
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
234
+ parser.add_argument('--update', action='store_true', help='update all models')
235
+ parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
236
+ parser.add_argument('--name', default='exp', help='save results to project/name')
237
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
238
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
239
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
240
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
241
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
242
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
243
+ opt = parser.parse_args()
244
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
245
+ print_args(vars(opt))
246
+
247
+ return opt
248
+
249
+
250
+ def main(opt):
251
+ print(f"wtf opt {opt}")
252
+ check_requirements(exclude=('tensorboard', 'thop'))
253
+ run(**vars(opt))
254
+
255
+
256
+ if __name__ == "__main__":
257
+ opt = parse_opt()
258
+ print(f"wtf opt {opt}")
259
+ main(opt)
detect_yolo.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import StringIO
2
+ from pathlib import Path
3
+ import streamlit as st
4
+ import time
5
+ from detect import run
6
+ import os
7
+ import sys
8
+ import argparse
9
+ from PIL import Image
10
+ import time
11
+
12
+
13
+ def get_subdirs(b='.'):
14
+ '''
15
+ Returns all sub-directories in a specific Path
16
+ '''
17
+ result = []
18
+ for d in os.listdir(b):
19
+ bd = os.path.join(b, d)
20
+ if os.path.isdir(bd):
21
+ result.append(bd)
22
+ return result
23
+
24
+
25
+ def get_detection_folder():
26
+ '''
27
+ Returns the latest folder in a runs\detect
28
+ '''
29
+ return max(get_subdirs(os.path.join('runs', 'detect')), key=os.path.getmtime)
30
+
31
+
32
+ ############################||||||||||||||||||||||||||||||||----
33
+ #########--------PARTIE RECUP ARGUMENTS OF YOLO-----------------------------------
34
+
35
+ def load_view_yolo():
36
+ st.title('Détection avec YOLOv5')
37
+
38
+ ## From detect.py. add parser for command line run.
39
+ # main function is RUN and it takes a lot of option.
40
+ # when -- is added before each option, parser will seperate them and
41
+ # add to the run function.
42
+ #
43
+
44
+ #########--------PARTIE RECUP ARGUMENTS OF YOLO-----------------------------------
45
+ #########--------PARTIE RECUP ARGUMENTS OF YOLO-----------------------------------
46
+
47
+ parser = argparse.ArgumentParser()
48
+ parser.add_argument('--weights', nargs='+', type=str, default='best.pt', help='model path(s)')
49
+ parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
50
+ parser.add_argument('--data', type=str, default='data/coco128.yaml', help='(optional) dataset.yaml path')
51
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=(640,640), help='inference size h,w')
52
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
53
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
54
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
55
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
56
+ parser.add_argument('--view-img', action='store_true', help='show results')
57
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
58
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
59
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
60
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
61
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
62
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
63
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
64
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
65
+ parser.add_argument('--update', action='store_true', help='update all models')
66
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
67
+ parser.add_argument('--name', default='exp', help='save results to project/name')
68
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
69
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
70
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
71
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
72
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
73
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
74
+ opt = parser.parse_args()
75
+
76
+ #----------------------------------------------------------------------------------------------------------------------------------------------------------
77
+ #----------------------------------------------------------------------------------------------------------------------------------------------------------#----------------------------------------------------------------------------------------------------------------------------------------------------------#----------------------------------------------------------------------------------------------------------------------------------------------------------#----------------------------------------------------------------------------------------------------------------------------------------------------------
78
+ #----------------------------------------------------------------------------------------------------------------------------------------------------------
79
+ #----------------------------------------------------------------------------------------------------------------------------------------------------------
80
+ #----------------------------------------------------------------------------------------------------------------------------------------------------------
81
+
82
+ opt.classes = (0, 1, 2, 3, 5, 7, 9, 11)
83
+
84
+
85
+ opt.weights = 'best_yolos_coco.pt'
86
+
87
+
88
+ ## opt.argument = xxx to change/access argument value
89
+
90
+
91
+ source = ("Image", "Video", "WebCam")
92
+ source_index = st.selectbox("Avec quel type de fichier souhaitez-vous travailler ?:", range(
93
+ len(source)), format_func=lambda x: source[x])
94
+
95
+
96
+
97
+
98
+ if source_index == 0:
99
+ st.title('Détection d\'objets pour les images')
100
+ st.subheader("""Une image est générée avec des cadres de délimitation créés autour des objets routiers de l'image.""")
101
+
102
+
103
+ uploaded_file = st.file_uploader(
104
+
105
+ "Veuillez choisir une image", type=['png', 'jpeg', 'jpg'])
106
+ if uploaded_file is not None:
107
+ is_valid = True
108
+ with st.spinner(text='Téléchargement...'):
109
+ st.image(uploaded_file)
110
+ picture = Image.open(uploaded_file)
111
+ print(f'picture line 89 : {uploaded_file}, type : {type(uploaded_file)}')
112
+ picture = picture.save(f'data\images\{uploaded_file.name}')
113
+ opt.source = f'data\images\{uploaded_file.name}'
114
+ else:
115
+ is_valid = False
116
+ elif source_index == 1 :
117
+
118
+ st.title('Détection d\'objets pour les vidéos')
119
+ st.subheader("""Une vidéo est générée avec des cadres de délimitation créés autour des objets routiers de la vidéo.""")
120
+ uploaded_file = st.file_uploader("Veuillez choisir une video", type=['mp4'])
121
+ if uploaded_file is not None:
122
+ is_valid = True
123
+ with st.spinner(text='Téléchargement...'):
124
+ st.video(uploaded_file)
125
+ with open(os.path.join("data", "videos", uploaded_file.name), "wb") as f:
126
+ f.write(uploaded_file.getbuffer())
127
+ opt.source = f'data/videos/{uploaded_file.name}'
128
+ else:
129
+ is_valid = False
130
+
131
+ elif source_index == 2 :
132
+ st.title('Détection en temps réel')
133
+ is_valid = True # if webcam detection enable, no need to prepare any file. We just go to prediction
134
+
135
+
136
+ if is_valid:
137
+ print('valid')
138
+ #print(f'filepath : {opt.source}')
139
+ #print(f"HERE ---- {opt} ----")
140
+ if st.button('Commencer'):
141
+
142
+ print("-"*25," RUN ", "-"*25)
143
+ print(opt.weights)
144
+ start_time = time.time()
145
+ if source_index in [0,1] :
146
+
147
+ run(
148
+ opt.weights,
149
+ opt.source,
150
+ opt.data,
151
+ opt.imgsz,
152
+ opt.conf_thres,
153
+ opt.iou_thres,
154
+ opt.max_det,
155
+ opt.device,
156
+ opt.view_img,
157
+ opt.save_txt,
158
+ opt.save_conf,
159
+ opt.save_crop,
160
+ opt.nosave,
161
+ opt.classes,
162
+ opt.agnostic_nms,
163
+ opt.augment,
164
+ opt.visualize,
165
+ opt.update,
166
+ opt.project,
167
+ opt.name,
168
+ opt.exist_ok,
169
+ opt.line_thickness,
170
+ opt.hide_labels,
171
+ opt.hide_conf,
172
+ opt.half,
173
+ opt.dnn,
174
+ )
175
+ else :
176
+ opt.source = '0' # enable webcam recording
177
+ run(
178
+ opt.weights,
179
+ opt.source,
180
+ opt.data,
181
+ opt.imgsz,
182
+ opt.conf_thres,
183
+ opt.iou_thres,
184
+ opt.max_det,
185
+ opt.device,
186
+ opt.view_img,
187
+ opt.save_txt,
188
+ opt.save_conf,
189
+ opt.save_crop,
190
+ opt.nosave,
191
+ opt.classes,
192
+ opt.agnostic_nms,
193
+ opt.augment,
194
+ opt.visualize,
195
+ opt.update,
196
+ opt.project,
197
+ opt.name,
198
+ opt.exist_ok,
199
+ opt.line_thickness,
200
+ opt.hide_labels,
201
+ opt.hide_conf,
202
+ opt.half,
203
+ opt.dnn,
204
+ )
205
+
206
+
207
+
208
+ if source_index == 0:
209
+ with st.spinner(text='Téléchargement de l\'image'):
210
+ for img in os.listdir(get_detection_folder()):
211
+ st.image(str(Path(f'{get_detection_folder()}') / img))
212
+ delta1 = time.time() - start_time
213
+ print("Temps d'exécution en secondes:")
214
+ print(delta1)
215
+ st.write("Temps d'exécution en secondes:")
216
+ st.write(delta1)
217
+
218
+ #st.balloons()
219
+ elif source_index == 1 :
220
+ with st.spinner(text='Téléchargement de la vidéo'):
221
+ for vid in os.listdir(get_detection_folder()):
222
+ #st.video(str(Path(f'{get_detection_folder()}') / vid))
223
+ input_file = str(Path(f'{get_detection_folder()}') / vid)
224
+ cmd = f'ffmpeg -i {input_file} -vcodec libx264 play.mp4'
225
+ os.system(cmd)
226
+
227
+ st.video('play.mp4')
228
+
229
+ delta2 = time.time() - start_time
230
+ print("Temps d'exécution en secondes:")
231
+ print(delta2)
232
+ st.write("Temps d'exécution en secondes:")
233
+ st.write(delta2)
234
+
235
+
236
+
237
+ #st.balloons()
238
+
239
+
export.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+
23
+ Usage:
24
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
25
+
26
+ Inference:
27
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
28
+ yolov5s.torchscript # TorchScript
29
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
30
+ yolov5s.xml # OpenVINO
31
+ yolov5s.engine # TensorRT
32
+ yolov5s.mlmodel # CoreML (macOS-only)
33
+ yolov5s_saved_model # TensorFlow SavedModel
34
+ yolov5s.pb # TensorFlow GraphDef
35
+ yolov5s.tflite # TensorFlow Lite
36
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
37
+
38
+ TensorFlow.js:
39
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
40
+ $ npm install
41
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
42
+ $ npm start
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import platform
49
+ import subprocess
50
+ import sys
51
+ import time
52
+ import warnings
53
+ from pathlib import Path
54
+
55
+ import pandas as pd
56
+ import torch
57
+ import yaml
58
+ from torch.utils.mobile_optimizer import optimize_for_mobile
59
+
60
+ FILE = Path(__file__).resolve()
61
+ ROOT = FILE.parents[0] # YOLOv5 root directory
62
+ if str(ROOT) not in sys.path:
63
+ sys.path.append(str(ROOT)) # add ROOT to PATH
64
+ if platform.system() != 'Windows':
65
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
66
+
67
+ from models.experimental import attempt_load
68
+ from models.yolo import Detect
69
+ from utils.dataloaders import LoadImages
70
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
71
+ file_size, print_args, url2file)
72
+ from utils.torch_utils import select_device
73
+
74
+
75
+ def export_formats():
76
+ # YOLOv5 export formats
77
+ x = [
78
+ ['PyTorch', '-', '.pt', True],
79
+ ['TorchScript', 'torchscript', '.torchscript', True],
80
+ ['ONNX', 'onnx', '.onnx', True],
81
+ ['OpenVINO', 'openvino', '_openvino_model', False],
82
+ ['TensorRT', 'engine', '.engine', True],
83
+ ['CoreML', 'coreml', '.mlmodel', False],
84
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True],
85
+ ['TensorFlow GraphDef', 'pb', '.pb', True],
86
+ ['TensorFlow Lite', 'tflite', '.tflite', False],
87
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False],
88
+ ['TensorFlow.js', 'tfjs', '_web_model', False],]
89
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'GPU'])
90
+
91
+
92
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
93
+ # YOLOv5 TorchScript model export
94
+ try:
95
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
96
+ f = file.with_suffix('.torchscript')
97
+
98
+ ts = torch.jit.trace(model, im, strict=False)
99
+ d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
100
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
101
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
102
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
103
+ else:
104
+ ts.save(str(f), _extra_files=extra_files)
105
+
106
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
107
+ return f
108
+ except Exception as e:
109
+ LOGGER.info(f'{prefix} export failure: {e}')
110
+
111
+
112
+ def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
113
+ # YOLOv5 ONNX export
114
+ try:
115
+ check_requirements(('onnx',))
116
+ import onnx
117
+
118
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
119
+ f = file.with_suffix('.onnx')
120
+
121
+ torch.onnx.export(
122
+ model.cpu() if dynamic else model, # --dynamic only compatible with cpu
123
+ im.cpu() if dynamic else im,
124
+ f,
125
+ verbose=False,
126
+ opset_version=opset,
127
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
128
+ do_constant_folding=not train,
129
+ input_names=['images'],
130
+ output_names=['output'],
131
+ dynamic_axes={
132
+ 'images': {
133
+ 0: 'batch',
134
+ 2: 'height',
135
+ 3: 'width'}, # shape(1,3,640,640)
136
+ 'output': {
137
+ 0: 'batch',
138
+ 1: 'anchors'} # shape(1,25200,85)
139
+ } if dynamic else None)
140
+
141
+ # Checks
142
+ model_onnx = onnx.load(f) # load onnx model
143
+ onnx.checker.check_model(model_onnx) # check onnx model
144
+
145
+ # Metadata
146
+ d = {'stride': int(max(model.stride)), 'names': model.names}
147
+ for k, v in d.items():
148
+ meta = model_onnx.metadata_props.add()
149
+ meta.key, meta.value = k, str(v)
150
+ onnx.save(model_onnx, f)
151
+
152
+ # Simplify
153
+ if simplify:
154
+ try:
155
+ check_requirements(('onnx-simplifier',))
156
+ import onnxsim
157
+
158
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
159
+ model_onnx, check = onnxsim.simplify(model_onnx,
160
+ dynamic_input_shape=dynamic,
161
+ input_shapes={'images': list(im.shape)} if dynamic else None)
162
+ assert check, 'assert check failed'
163
+ onnx.save(model_onnx, f)
164
+ except Exception as e:
165
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
166
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
167
+ return f
168
+ except Exception as e:
169
+ LOGGER.info(f'{prefix} export failure: {e}')
170
+
171
+
172
+ def export_openvino(model, file, half, prefix=colorstr('OpenVINO:')):
173
+ # YOLOv5 OpenVINO export
174
+ try:
175
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
176
+ import openvino.inference_engine as ie
177
+
178
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
179
+ f = str(file).replace('.pt', f'_openvino_model{os.sep}')
180
+
181
+ cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
182
+ subprocess.check_output(cmd.split()) # export
183
+ with open(Path(f) / file.with_suffix('.yaml').name, 'w') as g:
184
+ yaml.dump({'stride': int(max(model.stride)), 'names': model.names}, g) # add metadata.yaml
185
+
186
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
187
+ return f
188
+ except Exception as e:
189
+ LOGGER.info(f'\n{prefix} export failure: {e}')
190
+
191
+
192
+ def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
193
+ # YOLOv5 CoreML export
194
+ try:
195
+ check_requirements(('coremltools',))
196
+ import coremltools as ct
197
+
198
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
199
+ f = file.with_suffix('.mlmodel')
200
+
201
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
202
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
203
+ bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
204
+ if bits < 32:
205
+ if platform.system() == 'Darwin': # quantization only supported on macOS
206
+ with warnings.catch_warnings():
207
+ warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
208
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
209
+ else:
210
+ print(f'{prefix} quantization only supported on macOS, skipping...')
211
+ ct_model.save(f)
212
+
213
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
214
+ return ct_model, f
215
+ except Exception as e:
216
+ LOGGER.info(f'\n{prefix} export failure: {e}')
217
+ return None, None
218
+
219
+
220
+ def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
221
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
222
+ try:
223
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
224
+ try:
225
+ import tensorrt as trt
226
+ except Exception:
227
+ if platform.system() == 'Linux':
228
+ check_requirements(('nvidia-tensorrt',), cmds=('-U --index-url https://pypi.ngc.nvidia.com',))
229
+ import tensorrt as trt
230
+
231
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
232
+ grid = model.model[-1].anchor_grid
233
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
234
+ export_onnx(model, im, file, 12, train, False, simplify) # opset 12
235
+ model.model[-1].anchor_grid = grid
236
+ else: # TensorRT >= 8
237
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
238
+ export_onnx(model, im, file, 13, train, False, simplify) # opset 13
239
+ onnx = file.with_suffix('.onnx')
240
+
241
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
242
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
243
+ f = file.with_suffix('.engine') # TensorRT engine file
244
+ logger = trt.Logger(trt.Logger.INFO)
245
+ if verbose:
246
+ logger.min_severity = trt.Logger.Severity.VERBOSE
247
+
248
+ builder = trt.Builder(logger)
249
+ config = builder.create_builder_config()
250
+ config.max_workspace_size = workspace * 1 << 30
251
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
252
+
253
+ flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
254
+ network = builder.create_network(flag)
255
+ parser = trt.OnnxParser(network, logger)
256
+ if not parser.parse_from_file(str(onnx)):
257
+ raise RuntimeError(f'failed to load ONNX file: {onnx}')
258
+
259
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
260
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
261
+ LOGGER.info(f'{prefix} Network Description:')
262
+ for inp in inputs:
263
+ LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
264
+ for out in outputs:
265
+ LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
266
+
267
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}')
268
+ if builder.platform_has_fast_fp16 and half:
269
+ config.set_flag(trt.BuilderFlag.FP16)
270
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
271
+ t.write(engine.serialize())
272
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
273
+ return f
274
+ except Exception as e:
275
+ LOGGER.info(f'\n{prefix} export failure: {e}')
276
+
277
+
278
+ def export_saved_model(model,
279
+ im,
280
+ file,
281
+ dynamic,
282
+ tf_nms=False,
283
+ agnostic_nms=False,
284
+ topk_per_class=100,
285
+ topk_all=100,
286
+ iou_thres=0.45,
287
+ conf_thres=0.25,
288
+ keras=False,
289
+ prefix=colorstr('TensorFlow SavedModel:')):
290
+ # YOLOv5 TensorFlow SavedModel export
291
+ try:
292
+ import tensorflow as tf
293
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
294
+
295
+ from models.tf import TFDetect, TFModel
296
+
297
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
298
+ f = str(file).replace('.pt', '_saved_model')
299
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
300
+
301
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
302
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
303
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
304
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
305
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
306
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
307
+ keras_model.trainable = False
308
+ keras_model.summary()
309
+ if keras:
310
+ keras_model.save(f, save_format='tf')
311
+ else:
312
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
313
+ m = tf.function(lambda x: keras_model(x)) # full model
314
+ m = m.get_concrete_function(spec)
315
+ frozen_func = convert_variables_to_constants_v2(m)
316
+ tfm = tf.Module()
317
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
318
+ tfm.__call__(im)
319
+ tf.saved_model.save(tfm,
320
+ f,
321
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
322
+ if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
323
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
324
+ return keras_model, f
325
+ except Exception as e:
326
+ LOGGER.info(f'\n{prefix} export failure: {e}')
327
+ return None, None
328
+
329
+
330
+ def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
331
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
332
+ try:
333
+ import tensorflow as tf
334
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
335
+
336
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
337
+ f = file.with_suffix('.pb')
338
+
339
+ m = tf.function(lambda x: keras_model(x)) # full model
340
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
341
+ frozen_func = convert_variables_to_constants_v2(m)
342
+ frozen_func.graph.as_graph_def()
343
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
344
+
345
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
346
+ return f
347
+ except Exception as e:
348
+ LOGGER.info(f'\n{prefix} export failure: {e}')
349
+
350
+
351
+ def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
352
+ # YOLOv5 TensorFlow Lite export
353
+ try:
354
+ import tensorflow as tf
355
+
356
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
357
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
358
+ f = str(file).replace('.pt', '-fp16.tflite')
359
+
360
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
361
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
362
+ converter.target_spec.supported_types = [tf.float16]
363
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
364
+ if int8:
365
+ from models.tf import representative_dataset_gen
366
+ dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
367
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
368
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
369
+ converter.target_spec.supported_types = []
370
+ converter.inference_input_type = tf.uint8 # or tf.int8
371
+ converter.inference_output_type = tf.uint8 # or tf.int8
372
+ converter.experimental_new_quantizer = True
373
+ f = str(file).replace('.pt', '-int8.tflite')
374
+ if nms or agnostic_nms:
375
+ converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
376
+
377
+ tflite_model = converter.convert()
378
+ open(f, "wb").write(tflite_model)
379
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
380
+ return f
381
+ except Exception as e:
382
+ LOGGER.info(f'\n{prefix} export failure: {e}')
383
+
384
+
385
+ def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
386
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
387
+ try:
388
+ cmd = 'edgetpu_compiler --version'
389
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
390
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
391
+ if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
392
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
393
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
394
+ for c in (
395
+ 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
396
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
397
+ 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
398
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
399
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
400
+
401
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
402
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
403
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
404
+
405
+ cmd = f"edgetpu_compiler -s -o {file.parent} {f_tfl}"
406
+ subprocess.run(cmd.split(), check=True)
407
+
408
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
409
+ return f
410
+ except Exception as e:
411
+ LOGGER.info(f'\n{prefix} export failure: {e}')
412
+
413
+
414
+ def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
415
+ # YOLOv5 TensorFlow.js export
416
+ try:
417
+ check_requirements(('tensorflowjs',))
418
+ import re
419
+
420
+ import tensorflowjs as tfjs
421
+
422
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
423
+ f = str(file).replace('.pt', '_web_model') # js dir
424
+ f_pb = file.with_suffix('.pb') # *.pb path
425
+ f_json = f'{f}/model.json' # *.json path
426
+
427
+ cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
428
+ f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
429
+ subprocess.run(cmd.split())
430
+
431
+ with open(f_json) as j:
432
+ json = j.read()
433
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
434
+ subst = re.sub(
435
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
436
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
437
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
438
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
439
+ r'"Identity_1": {"name": "Identity_1"}, '
440
+ r'"Identity_2": {"name": "Identity_2"}, '
441
+ r'"Identity_3": {"name": "Identity_3"}}}', json)
442
+ j.write(subst)
443
+
444
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
445
+ return f
446
+ except Exception as e:
447
+ LOGGER.info(f'\n{prefix} export failure: {e}')
448
+
449
+
450
+ @torch.no_grad()
451
+ def run(
452
+ data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
453
+ weights=ROOT / 'yolov5s.pt', # weights path
454
+ imgsz=(640, 640), # image (height, width)
455
+ batch_size=1, # batch size
456
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
457
+ include=('torchscript', 'onnx'), # include formats
458
+ half=False, # FP16 half-precision export
459
+ inplace=False, # set YOLOv5 Detect() inplace=True
460
+ train=False, # model.train() mode
461
+ keras=False, # use Keras
462
+ optimize=False, # TorchScript: optimize for mobile
463
+ int8=False, # CoreML/TF INT8 quantization
464
+ dynamic=False, # ONNX/TF: dynamic axes
465
+ simplify=False, # ONNX: simplify model
466
+ opset=12, # ONNX: opset version
467
+ verbose=False, # TensorRT: verbose log
468
+ workspace=4, # TensorRT: workspace size (GB)
469
+ nms=False, # TF: add NMS to model
470
+ agnostic_nms=False, # TF: add agnostic NMS to model
471
+ topk_per_class=100, # TF.js NMS: topk per class to keep
472
+ topk_all=100, # TF.js NMS: topk for all classes to keep
473
+ iou_thres=0.45, # TF.js NMS: IoU threshold
474
+ conf_thres=0.25, # TF.js NMS: confidence threshold
475
+ ):
476
+ t = time.time()
477
+ include = [x.lower() for x in include] # to lowercase
478
+ fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
479
+ flags = [x in include for x in fmts]
480
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
481
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
482
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
483
+
484
+ # Load PyTorch model
485
+ device = select_device(device)
486
+ if half:
487
+ assert device.type != 'cpu' or coreml or xml, '--half only compatible with GPU export, i.e. use --device 0'
488
+ assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
489
+ model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
490
+ nc, names = model.nc, model.names # number of classes, class names
491
+
492
+ # Checks
493
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
494
+ assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
495
+
496
+ # Input
497
+ gs = int(max(model.stride)) # grid size (max stride)
498
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
499
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
500
+
501
+ # Update model
502
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
503
+ for k, m in model.named_modules():
504
+ if isinstance(m, Detect):
505
+ m.inplace = inplace
506
+ m.onnx_dynamic = dynamic
507
+ m.export = True
508
+
509
+ for _ in range(2):
510
+ y = model(im) # dry runs
511
+ if half and not coreml:
512
+ im, model = im.half(), model.half() # to FP16
513
+ shape = tuple(y[0].shape) # model output shape
514
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
515
+
516
+ # Exports
517
+ f = [''] * 10 # exported filenames
518
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
519
+ if jit:
520
+ f[0] = export_torchscript(model, im, file, optimize)
521
+ if engine: # TensorRT required before ONNX
522
+ f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
523
+ if onnx or xml: # OpenVINO requires ONNX
524
+ f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
525
+ if xml: # OpenVINO
526
+ f[3] = export_openvino(model, file, half)
527
+ if coreml:
528
+ _, f[4] = export_coreml(model, im, file, int8, half)
529
+
530
+ # TensorFlow Exports
531
+ if any((saved_model, pb, tflite, edgetpu, tfjs)):
532
+ if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
533
+ check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
534
+ assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
535
+ model, f[5] = export_saved_model(model.cpu(),
536
+ im,
537
+ file,
538
+ dynamic,
539
+ tf_nms=nms or agnostic_nms or tfjs,
540
+ agnostic_nms=agnostic_nms or tfjs,
541
+ topk_per_class=topk_per_class,
542
+ topk_all=topk_all,
543
+ iou_thres=iou_thres,
544
+ conf_thres=conf_thres,
545
+ keras=keras)
546
+ if pb or tfjs: # pb prerequisite to tfjs
547
+ f[6] = export_pb(model, file)
548
+ if tflite or edgetpu:
549
+ f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
550
+ if edgetpu:
551
+ f[8] = export_edgetpu(file)
552
+ if tfjs:
553
+ f[9] = export_tfjs(file)
554
+
555
+ # Finish
556
+ f = [str(x) for x in f if x] # filter out '' and None
557
+ if any(f):
558
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
559
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
560
+ f"\nDetect: python detect.py --weights {f[-1]}"
561
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
562
+ f"\nValidate: python val.py --weights {f[-1]}"
563
+ f"\nVisualize: https://netron.app")
564
+ return f # return list of exported files/dirs
565
+
566
+
567
+ def parse_opt():
568
+ parser = argparse.ArgumentParser()
569
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
570
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
571
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
572
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
573
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
574
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
575
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
576
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
577
+ parser.add_argument('--keras', action='store_true', help='TF: use Keras')
578
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
579
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
580
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
581
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
582
+ parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
583
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
584
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
585
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
586
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
587
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
588
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
589
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
590
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
591
+ parser.add_argument('--include',
592
+ nargs='+',
593
+ default=['torchscript', 'onnx'],
594
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
595
+ opt = parser.parse_args()
596
+ print_args(vars(opt))
597
+ return opt
598
+
599
+
600
+ def main(opt):
601
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
602
+ run(**vars(opt))
603
+
604
+
605
+ if __name__ == "__main__":
606
+ opt = parse_opt()
607
+ main(opt)
hubconf.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
4
+
5
+ Usage:
6
+ import torch
7
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
8
+ model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch
9
+ """
10
+
11
+ import torch
12
+
13
+
14
+ def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
15
+ """Creates or loads a YOLOv5 model
16
+
17
+ Arguments:
18
+ name (str): model name 'yolov5s' or path 'path/to/best.pt'
19
+ pretrained (bool): load pretrained weights into the model
20
+ channels (int): number of input channels
21
+ classes (int): number of model classes
22
+ autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
23
+ verbose (bool): print all information to screen
24
+ device (str, torch.device, None): device to use for model parameters
25
+
26
+ Returns:
27
+ YOLOv5 model
28
+ """
29
+ from pathlib import Path
30
+
31
+ from models.common import AutoShape, DetectMultiBackend
32
+ from models.yolo import Model
33
+ from utils.downloads import attempt_download
34
+ from utils.general import LOGGER, check_requirements, intersect_dicts, logging
35
+ from utils.torch_utils import select_device
36
+
37
+ if not verbose:
38
+ LOGGER.setLevel(logging.WARNING)
39
+
40
+ check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
41
+ name = Path(name)
42
+ path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
43
+ try:
44
+ device = select_device(device)
45
+
46
+ if pretrained and channels == 3 and classes == 80:
47
+ model = DetectMultiBackend(path, device=device) # download/load FP32 model
48
+ # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model
49
+ else:
50
+ cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
51
+ model = Model(cfg, channels, classes) # create model
52
+ if pretrained:
53
+ ckpt = torch.load(attempt_download(path), map_location=device) # load
54
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
55
+ csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
56
+ model.load_state_dict(csd, strict=False) # load
57
+ if len(ckpt['model'].names) == classes:
58
+ model.names = ckpt['model'].names # set class names attribute
59
+ if autoshape:
60
+ model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
61
+ return model.to(device)
62
+
63
+ except Exception as e:
64
+ help_url = 'https://github.com/ultralytics/yolov5/issues/36'
65
+ s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
66
+ raise Exception(s) from e
67
+
68
+
69
+ def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
70
+ # YOLOv5 custom or local model
71
+ return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
72
+
73
+
74
+ def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
75
+ # YOLOv5-nano model https://github.com/ultralytics/yolov5
76
+ return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
77
+
78
+
79
+ def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
80
+ # YOLOv5-small model https://github.com/ultralytics/yolov5
81
+ return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
82
+
83
+
84
+ def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
85
+ # YOLOv5-medium model https://github.com/ultralytics/yolov5
86
+ return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
87
+
88
+
89
+ def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
90
+ # YOLOv5-large model https://github.com/ultralytics/yolov5
91
+ return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
92
+
93
+
94
+ def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
95
+ # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
96
+ return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
97
+
98
+
99
+ def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
100
+ # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
101
+ return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
102
+
103
+
104
+ def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
105
+ # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
106
+ return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
107
+
108
+
109
+ def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
110
+ # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
111
+ return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
112
+
113
+
114
+ def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
115
+ # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
116
+ return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
117
+
118
+
119
+ def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
120
+ # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
121
+ return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
122
+
123
+
124
+ if __name__ == '__main__':
125
+ model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
126
+ # model = custom(path='path/to/model.pt') # custom
127
+
128
+ # Verify inference
129
+ from pathlib import Path
130
+
131
+ import numpy as np
132
+ from PIL import Image
133
+
134
+ from utils.general import cv2
135
+
136
+ imgs = [
137
+ 'data/images/zidane.jpg', # filename
138
+ Path('data/images/zidane.jpg'), # Path
139
+ 'https://ultralytics.com/images/zidane.jpg', # URI
140
+ cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
141
+ Image.open('data/images/bus.jpg'), # PIL
142
+ np.zeros((320, 640, 3))] # numpy
143
+
144
+ results = model(imgs, size=320) # batched inference
145
+ results.print()
146
+ results.save()
kernel.ipynb ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 2,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stderr",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "2022-06-29 01:44:19.380 INFO numexpr.utils: Note: NumExpr detected 16 cores but \"NUMEXPR_MAX_THREADS\" not set, so enforcing safe limit of 8.\n",
13
+ "2022-06-29 01:44:19.381 INFO numexpr.utils: NumExpr defaulting to 8 threads.\n"
14
+ ]
15
+ }
16
+ ],
17
+ "source": [
18
+ "from io import StringIO\n",
19
+ "from pathlib import Path\n",
20
+ "import streamlit as st\n",
21
+ "import time\n",
22
+ "from detect import run\n",
23
+ "import os\n",
24
+ "import sys\n",
25
+ "import argparse\n",
26
+ "from PIL import Image"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": 10,
32
+ "metadata": {},
33
+ "outputs": [
34
+ {
35
+ "data": {
36
+ "text/plain": [
37
+ "_StoreAction(option_strings=['--source'], dest='source', nargs=None, const=None, default='data/images', type=<class 'str'>, choices=None, help='file/dir/URL/glob, 0 for webcam', metavar=None)"
38
+ ]
39
+ },
40
+ "execution_count": 10,
41
+ "metadata": {},
42
+ "output_type": "execute_result"
43
+ }
44
+ ],
45
+ "source": [
46
+ "parser = argparse.ArgumentParser()\n",
47
+ "parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model path(s)')\n",
48
+ "parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": 9,
54
+ "metadata": {},
55
+ "outputs": [
56
+ {
57
+ "name": "stdout",
58
+ "output_type": "stream",
59
+ "text": [
60
+ "ipykernel_launcher.py\n"
61
+ ]
62
+ }
63
+ ],
64
+ "source": [
65
+ "print(parser.prog)"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": 11,
71
+ "metadata": {},
72
+ "outputs": [
73
+ {
74
+ "name": "stderr",
75
+ "output_type": "stream",
76
+ "text": [
77
+ "usage: ipykernel_launcher.py [-h] [--weights WEIGHTS [WEIGHTS ...]]\n",
78
+ " [--source SOURCE]\n",
79
+ "ipykernel_launcher.py: error: unrecognized arguments: --ip=127.0.0.1 --stdin=9011 --control=9009 --hb=9008 --Session.signature_scheme=\"hmac-sha256\" --Session.key=b\"e7e5eef2-0dd4-438e-b623-479572400c6a\" --shell=9010 --transport=\"tcp\" --iopub=9012 --f=c:\\Users\\alexa\\AppData\\Roaming\\jupyter\\runtime\\kernel-v2-596OaYAo2JGhjq5.json\n"
80
+ ]
81
+ },
82
+ {
83
+ "ename": "SystemExit",
84
+ "evalue": "2",
85
+ "output_type": "error",
86
+ "traceback": [
87
+ "An exception has occurred, use %tb to see the full traceback.\n",
88
+ "\u001b[1;31mSystemExit\u001b[0m\u001b[1;31m:\u001b[0m 2\n"
89
+ ]
90
+ },
91
+ {
92
+ "name": "stderr",
93
+ "output_type": "stream",
94
+ "text": [
95
+ "c:\\Users\\alexa\\anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3452: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.\n",
96
+ " warn(\"To exit: use 'exit', 'quit', or Ctrl-D.\", stacklevel=1)\n"
97
+ ]
98
+ }
99
+ ],
100
+ "source": [
101
+ "opt = parser.parse_args()\n"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": null,
107
+ "metadata": {},
108
+ "outputs": [],
109
+ "source": []
110
+ }
111
+ ],
112
+ "metadata": {
113
+ "kernelspec": {
114
+ "display_name": "Python 3.9.7 ('base')",
115
+ "language": "python",
116
+ "name": "python3"
117
+ },
118
+ "language_info": {
119
+ "codemirror_mode": {
120
+ "name": "ipython",
121
+ "version": 3
122
+ },
123
+ "file_extension": ".py",
124
+ "mimetype": "text/x-python",
125
+ "name": "python",
126
+ "nbconvert_exporter": "python",
127
+ "pygments_lexer": "ipython3",
128
+ "version": "3.9.7"
129
+ },
130
+ "orig_nbformat": 4,
131
+ "vscode": {
132
+ "interpreter": {
133
+ "hash": "277d713a2869ad522e0f58de96fa3cb2620734b34dd3b3afd7f1966d69d2580f"
134
+ }
135
+ }
136
+ },
137
+ "nbformat": 4,
138
+ "nbformat_minor": 2
139
+ }
main.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import utilss as utl
3
+ from views import home,about,detect_D2,configuration
4
+ import detect_yolo
5
+
6
+
7
+ st.set_page_config(layout="wide", page_title='Détection d\'objets routiers')
8
+ st.set_option('deprecation.showPyplotGlobalUse', False)
9
+ utl.inject_custom_css()
10
+ utl.navbar_component()
11
+
12
+
13
+ def navigation():
14
+ route = utl.get_current_route()
15
+ if route == "Page d\'accueil":
16
+ home.load_view()
17
+ elif route == "A propos":
18
+ about.load_view()
19
+ elif route == "Detection avec Detectron2":
20
+ detect_D2.load_view_D2()
21
+ elif route == "Detection avec Yolo v5":
22
+ detect_yolo.load_view_yolo()
23
+ elif route == "configuration":
24
+ configuration.load_view()
25
+ elif route == None:
26
+ home.load_view()
27
+
28
+ navigation()
29
+
requirements.txt ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file may be used to create an environment using:
2
+ # $ conda create --name <env> --file <this file>
3
+ # platform: win-64
4
+ aioice=0.7.6=pypi_0
5
+ aiortc=1.3.2=pypi_0
6
+ argon2-cffi=20.1.0=py39h2bbff1b_1
7
+ astor=0.8.1=pypi_0
8
+ asttokens=2.0.5=pyhd3eb1b0_0
9
+ attrs=21.4.0=pyhd3eb1b0_0
10
+ av=9.2.0=pypi_0
11
+ backcall=0.2.0=pyhd3eb1b0_0
12
+ base58=2.1.1=pypi_0
13
+ beautifulsoup4=4.11.1=py39haa95532_0
14
+ black=22.3.0=pypi_0
15
+ blas=1.0=mkl
16
+ bleach=4.1.0=pyhd3eb1b0_0
17
+ brotlipy=0.7.0=py39h2bbff1b_1003
18
+ ca-certificates=2022.07.19=haa95532_0
19
+ certifi=2022.6.15=py39haa95532_0
20
+ cffi=1.15.0=py39h2bbff1b_1
21
+ charset-normalizer=2.0.4=pyhd3eb1b0_0
22
+ click=7.1.2=pypi_0
23
+ colorama=0.4.5=py39haa95532_0
24
+ console_shortcut=0.1.1=4
25
+ cryptography=37.0.1=py39h21b164f_0
26
+ cudatoolkit=10.2.89=h74a9793_1
27
+ cython=0.29.32=pypi_0
28
+ debugpy=1.5.1=py39hd77b12b_0
29
+ decorator=5.1.1=pyhd3eb1b0_0
30
+ defusedxml=0.7.1=pyhd3eb1b0_0
31
+ detectron2=0.6=dev_0
32
+ dnspython=2.2.1=pypi_0
33
+ entrypoints=0.4=py39haa95532_0
34
+ executing=0.8.3=pyhd3eb1b0_0
35
+ fairscale=0.4.8=pypi_0
36
+ freetype=2.10.4=hd328e21_0
37
+ google-crc32c=1.3.0=pypi_0
38
+ idna=3.3=pyhd3eb1b0_0
39
+ intel-openmp=2021.4.0=haa95532_3556
40
+ ipykernel=6.9.1=py39haa95532_0
41
+ ipython=8.4.0=py39haa95532_0
42
+ ipython_genutils=0.2.0=pyhd3eb1b0_1
43
+ jedi=0.18.1=py39haa95532_1
44
+ jinja2=3.0.3=pyhd3eb1b0_0
45
+ jpeg=9e=h2bbff1b_0
46
+ jsonschema=4.4.0=py39haa95532_0
47
+ jupyter_client=7.2.2=py39haa95532_0
48
+ jupyter_core=4.10.0=py39haa95532_0
49
+ jupyterlab_pygments=0.1.2=py_0
50
+ libpng=1.6.37=h2a8f88b_0
51
+ libsodium=1.0.18=h62dcd97_0
52
+ libtiff=4.2.0=he0120a3_1
53
+ libuv=1.40.0=he774522_0
54
+ libwebp=1.2.2=h2bbff1b_0
55
+ lz4-c=1.9.3=h2bbff1b_1
56
+ markupsafe=2.1.1=py39h2bbff1b_0
57
+ matplotlib-inline=0.1.2=pyhd3eb1b0_2
58
+ mistune=0.8.4=py39h2bbff1b_1000
59
+ mkl=2021.4.0=haa95532_640
60
+ mkl-service=2.4.0=py39h2bbff1b_0
61
+ mkl_fft=1.3.1=py39h277e83a_0
62
+ mkl_random=1.2.2=py39hf11a4ad_0
63
+ nbclient=0.5.13=py39haa95532_0
64
+ nbconvert=6.4.4=py39haa95532_0
65
+ nbformat=5.3.0=py39haa95532_0
66
+ nest-asyncio=1.5.5=py39haa95532_0
67
+ netifaces=0.11.0=pypi_0
68
+ networkx=2.8.6=pypi_0
69
+ notebook=6.4.12=py39haa95532_0
70
+ numpy=1.21.5=pypi_0
71
+ omegaconf=2.1.2=pypi_0
72
+ openssl=1.1.1q=h2bbff1b_0
73
+ packaging=21.3=pyhd3eb1b0_0
74
+ pandas=1.4.3=pypi_0
75
+ pandocfilters=1.5.0=pyhd3eb1b0_0
76
+ parso=0.8.3=pyhd3eb1b0_0
77
+ pickleshare=0.7.5=pyhd3eb1b0_1003
78
+ pillow=9.2.0=py39hdc2b20a_1
79
+ pip=22.1.2=py39haa95532_0
80
+ powershell_shortcut=0.0.1=3
81
+ prometheus_client=0.14.1=py39haa95532_0
82
+ prompt-toolkit=3.0.20=pyhd3eb1b0_0
83
+ psutil=5.9.1=pypi_0
84
+ pure_eval=0.2.2=pyhd3eb1b0_0
85
+ pyarrow=4.0.1=pypi_0
86
+ pycocotools=2.0.4=pypi_0
87
+ pycparser=2.21=pyhd3eb1b0_0
88
+ pyee=9.0.4=pypi_0
89
+ pygments=2.11.2=pyhd3eb1b0_0
90
+ pylibsrtp=0.7.1=pypi_0
91
+ pyopenssl=22.0.0=pyhd3eb1b0_0
92
+ pyparsing=3.0.4=pyhd3eb1b0_0
93
+ pypiwin32=223=pypi_0
94
+ pyrsistent=0.18.0=py39h196d8e1_0
95
+ pysocks=1.7.1=py39haa95532_0
96
+ python=3.9.12=h6244533_0
97
+ python-dateutil=2.8.2=pyhd3eb1b0_0
98
+ python-fastjsonschema=2.15.1=pyhd3eb1b0_0
99
+ pytorch=1.12.0=py3.9_cpu_0
100
+ pytorch-mutex=1.0=cpu
101
+ pywin32=304=pypi_0
102
+ pywinpty=2.0.2=py39h5da7b33_0
103
+ pyzmq=23.2.0=py39hd77b12b_0
104
+ requests=2.28.1=py39haa95532_0
105
+ scipy=1.8.0=pypi_0
106
+ send2trash=1.8.0=pyhd3eb1b0_1
107
+ setuptools=61.2.0=py39haa95532_0
108
+ six=1.16.0=pyhd3eb1b0_1
109
+ soupsieve=2.3.1=pyhd3eb1b0_0
110
+ sqlite=3.38.5=h2bbff1b_0
111
+ stack_data=0.2.0=pyhd3eb1b0_0
112
+ streamlit=1.10.0=pypi_0
113
+ streamlit-webrtc=0.42.0=pypi_0
114
+ tabulate=0.8.10=pypi_0
115
+ terminado=0.13.1=py39haa95532_0
116
+ testpath=0.6.0=py39haa95532_0
117
+ thop=0.1.1-2207130030=pypi_0
118
+ timm=0.6.7=pypi_0
119
+ tk=8.6.12=h2bbff1b_0
120
+ tomli=2.0.1=pypi_0
121
+ torchvision=0.13.0=py39_cpu
122
+ tornado=6.1=py39h2bbff1b_0
123
+ tqdm=4.64.0=pypi_0
124
+ traitlets=5.1.1=pyhd3eb1b0_0
125
+ typing-extensions=4.3.0=pypi_0
126
+ typing_extensions=4.1.1=pyh06a4308_0
127
+ tzdata=2022a=hda174b7_0
128
+ urllib3=1.26.11=py39haa95532_0
129
+ vc=14.2=h21ff451_1
130
+ vs2015_runtime=14.27.29016=h5e58377_2
131
+ wcwidth=0.2.5=pyhd3eb1b0_0
132
+ webencodings=0.5.1=py39haa95532_1
133
+ wheel=0.37.1=pyhd3eb1b0_0
134
+ win_inet_pton=1.1.0=py39haa95532_0
135
+ wincertstore=0.2=py39haa95532_2
136
+ winpty=0.4.3=4
137
+ xz=5.2.5=h8cc25b3_1
138
+ zeromq=4.3.4=hd77b12b_0
139
+ zlib=1.2.12=h8cc25b3_2
140
+ zstd=1.5.2=h19a0ad4_0
requirements2.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 requirements
2
+ # Usage: pip install -r requirements.txt
3
+
4
+ # Base ----------------------------------------
5
+ matplotlib>=3.2.2
6
+ numpy>=1.18.5
7
+ opencv-python>=4.1.1
8
+ Pillow>=7.1.2
9
+ PyYAML>=5.3.1
10
+ requests>=2.23.0
11
+ scipy>=1.4.1 # Google Colab version
12
+ torch>=1.7.0
13
+ torchvision>=0.8.1
14
+ tqdm>=4.41.0
15
+ protobuf<4.21.3 # https://github.com/ultralytics/yolov5/issues/8012
16
+ streamlit
17
+ # Logging -------------------------------------
18
+ tensorboard>=2.4.1
19
+ # wandb
20
+
21
+ # Plotting ------------------------------------
22
+ pandas>=1.1.4
23
+ seaborn>=0.11.0
24
+
25
+ # Export --------------------------------------
26
+ # coremltools>=4.1 # CoreML export
27
+ # onnx>=1.9.0 # ONNX export
28
+ # onnx-simplifier>=0.3.6 # ONNX simplifier
29
+ # scikit-learn==0.19.2 # CoreML quantization
30
+ # tensorflow>=2.4.1 # TFLite export
31
+ # tensorflowjs>=3.9.0 # TF.js export
32
+ # openvino-dev # OpenVINO export
33
+
34
+ # Extras --------------------------------------
35
+ ipython # interactive notebook
36
+ psutil # system utilization
37
+ thop # FLOPs computation
38
+ # albumentations>=1.0.3
39
+ # pycocotools>=2.0 # COCO mAP
40
+ # roboflow
result.jpg ADDED
setup.cfg ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project-wide configuration file, can be used for package metadata and other toll configurations
2
+ # Example usage: global configuration for PEP8 (via flake8) setting or default pytest arguments
3
+ # Local usage: pip install pre-commit, pre-commit run --all-files
4
+
5
+ [metadata]
6
+ license_file = LICENSE
7
+ description_file = README.md
8
+
9
+
10
+ [tool:pytest]
11
+ norecursedirs =
12
+ .git
13
+ dist
14
+ build
15
+ addopts =
16
+ --doctest-modules
17
+ --durations=25
18
+ --color=yes
19
+
20
+
21
+ [flake8]
22
+ max-line-length = 120
23
+ exclude = .tox,*.egg,build,temp
24
+ select = E,W,F
25
+ doctests = True
26
+ verbose = 2
27
+ # https://pep8.readthedocs.io/en/latest/intro.html#error-codes
28
+ format = pylint
29
+ # see: https://www.flake8rules.com/
30
+ ignore =
31
+ E731 # Do not assign a lambda expression, use a def
32
+ F405 # name may be undefined, or defined from star imports: module
33
+ E402 # module level import not at top of file
34
+ F401 # module imported but unused
35
+ W504 # line break after binary operator
36
+ E127 # continuation line over-indented for visual indent
37
+ W504 # line break after binary operator
38
+ E231 # missing whitespace after ‘,’, ‘;’, or ‘:’
39
+ E501 # line too long
40
+ F403 # ‘from module import *’ used; unable to detect undefined names
41
+
42
+
43
+ [isort]
44
+ # https://pycqa.github.io/isort/docs/configuration/options.html
45
+ line_length = 120
46
+ # see: https://pycqa.github.io/isort/docs/configuration/multi_line_output_modes.html
47
+ multi_line_output = 0
48
+
49
+
50
+ [yapf]
51
+ based_on_style = pep8
52
+ spaces_before_comment = 2
53
+ COLUMN_LIMIT = 120
54
+ COALESCE_BRACKETS = True
55
+ SPACES_AROUND_POWER_OPERATOR = True
56
+ SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET = False
57
+ SPLIT_BEFORE_CLOSING_BRACKET = False
58
+ SPLIT_BEFORE_FIRST_ARGUMENT = False
59
+ # EACH_DICT_ENTRY_ON_SEPARATE_LINE = False
train.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Train a YOLOv5 model on a custom dataset.
4
+
5
+ Models and datasets download automatically from the latest YOLOv5 release.
6
+ Models: https://github.com/ultralytics/yolov5/tree/master/models
7
+ Datasets: https://github.com/ultralytics/yolov5/tree/master/data
8
+ Tutorial: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data
9
+
10
+ Usage:
11
+ $ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (RECOMMENDED)
12
+ $ python path/to/train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch
13
+ """
14
+
15
+ import argparse
16
+ import math
17
+ import os
18
+ import random
19
+ import sys
20
+ import time
21
+ from copy import deepcopy
22
+ from datetime import datetime
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.distributed as dist
28
+ import torch.nn as nn
29
+ import yaml
30
+ from torch.nn.parallel import DistributedDataParallel as DDP
31
+ from torch.optim import SGD, Adam, AdamW, lr_scheduler
32
+ from tqdm import tqdm
33
+
34
+ FILE = Path(__file__).resolve()
35
+ ROOT = FILE.parents[0] # YOLOv5 root directory
36
+ if str(ROOT) not in sys.path:
37
+ sys.path.append(str(ROOT)) # add ROOT to PATH
38
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
39
+
40
+ import val # for end-of-epoch mAP
41
+ from models.experimental import attempt_load
42
+ from models.yolo import Model
43
+ from utils.autoanchor import check_anchors
44
+ from utils.autobatch import check_train_batch_size
45
+ from utils.callbacks import Callbacks
46
+ from utils.dataloaders import create_dataloader
47
+ from utils.downloads import attempt_download
48
+ from utils.general import (LOGGER, check_amp, check_dataset, check_file, check_git_status, check_img_size,
49
+ check_requirements, check_suffix, check_version, check_yaml, colorstr, get_latest_run,
50
+ increment_path, init_seeds, intersect_dicts, labels_to_class_weights,
51
+ labels_to_image_weights, methods, one_cycle, print_args, print_mutation, strip_optimizer)
52
+ from utils.loggers import Loggers
53
+ from utils.loggers.wandb.wandb_utils import check_wandb_resume
54
+ from utils.loss import ComputeLoss
55
+ from utils.metrics import fitness
56
+ from utils.plots import plot_evolve, plot_labels
57
+ from utils.torch_utils import EarlyStopping, ModelEMA, de_parallel, select_device, torch_distributed_zero_first
58
+
59
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
60
+ RANK = int(os.getenv('RANK', -1))
61
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
62
+
63
+
64
+ def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hyp dictionary
65
+ save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \
66
+ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \
67
+ opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze
68
+ callbacks.run('on_pretrain_routine_start')
69
+
70
+ # Directories
71
+ w = save_dir / 'weights' # weights dir
72
+ (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
73
+ last, best = w / 'last.pt', w / 'best.pt'
74
+
75
+ # Hyperparameters
76
+ if isinstance(hyp, str):
77
+ with open(hyp, errors='ignore') as f:
78
+ hyp = yaml.safe_load(f) # load hyps dict
79
+ LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
80
+
81
+ # Save run settings
82
+ if not evolve:
83
+ with open(save_dir / 'hyp.yaml', 'w') as f:
84
+ yaml.safe_dump(hyp, f, sort_keys=False)
85
+ with open(save_dir / 'opt.yaml', 'w') as f:
86
+ yaml.safe_dump(vars(opt), f, sort_keys=False)
87
+
88
+ # Loggers
89
+ data_dict = None
90
+ if RANK in {-1, 0}:
91
+ loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
92
+ if loggers.wandb:
93
+ data_dict = loggers.wandb.data_dict
94
+ if resume:
95
+ weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
96
+
97
+ # Register actions
98
+ for k in methods(loggers):
99
+ callbacks.register_action(k, callback=getattr(loggers, k))
100
+
101
+ # Config
102
+ plots = not evolve and not opt.noplots # create plots
103
+ cuda = device.type != 'cpu'
104
+ init_seeds(1 + RANK)
105
+ with torch_distributed_zero_first(LOCAL_RANK):
106
+ data_dict = data_dict or check_dataset(data) # check if None
107
+ train_path, val_path = data_dict['train'], data_dict['val']
108
+ nc = 1 if single_cls else int(data_dict['nc']) # number of classes
109
+ names = ['item'] if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
110
+ assert len(names) == nc, f'{len(names)} names found for nc={nc} dataset in {data}' # check
111
+ is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset
112
+
113
+ # Model
114
+ check_suffix(weights, '.pt') # check weights
115
+ pretrained = weights.endswith('.pt')
116
+ if pretrained:
117
+ with torch_distributed_zero_first(LOCAL_RANK):
118
+ weights = attempt_download(weights) # download if not found locally
119
+ ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak
120
+ model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
121
+ exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
122
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
123
+ csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
124
+ model.load_state_dict(csd, strict=False) # load
125
+ LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
126
+ else:
127
+ model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
128
+ amp = check_amp(model) # check AMP
129
+
130
+ # Freeze
131
+ freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
132
+ for k, v in model.named_parameters():
133
+ v.requires_grad = True # train all layers
134
+ if any(x in k for x in freeze):
135
+ LOGGER.info(f'freezing {k}')
136
+ v.requires_grad = False
137
+
138
+ # Image size
139
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
140
+ imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
141
+
142
+ # Batch size
143
+ if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
144
+ batch_size = check_train_batch_size(model, imgsz, amp)
145
+ loggers.on_params_update({"batch_size": batch_size})
146
+
147
+ # Optimizer
148
+ nbs = 64 # nominal batch size
149
+ accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
150
+ hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
151
+ LOGGER.info(f"Scaled weight_decay = {hyp['weight_decay']}")
152
+
153
+ g = [], [], [] # optimizer parameter groups
154
+ bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k) # normalization layers, i.e. BatchNorm2d()
155
+ for v in model.modules():
156
+ if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): # bias
157
+ g[2].append(v.bias)
158
+ if isinstance(v, bn): # weight (no decay)
159
+ g[1].append(v.weight)
160
+ elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): # weight (with decay)
161
+ g[0].append(v.weight)
162
+
163
+ if opt.optimizer == 'Adam':
164
+ optimizer = Adam(g[2], lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
165
+ elif opt.optimizer == 'AdamW':
166
+ optimizer = AdamW(g[2], lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
167
+ else:
168
+ optimizer = SGD(g[2], lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
169
+
170
+ optimizer.add_param_group({'params': g[0], 'weight_decay': hyp['weight_decay']}) # add g0 with weight_decay
171
+ optimizer.add_param_group({'params': g[1]}) # add g1 (BatchNorm2d weights)
172
+ LOGGER.info(f"{colorstr('optimizer:')} {type(optimizer).__name__} with parameter groups "
173
+ f"{len(g[1])} weight (no decay), {len(g[0])} weight, {len(g[2])} bias")
174
+ del g
175
+
176
+ # Scheduler
177
+ if opt.cos_lr:
178
+ lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
179
+ else:
180
+ lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
181
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
182
+
183
+ # EMA
184
+ ema = ModelEMA(model) if RANK in {-1, 0} else None
185
+
186
+ # Resume
187
+ start_epoch, best_fitness = 0, 0.0
188
+ if pretrained:
189
+ # Optimizer
190
+ if ckpt['optimizer'] is not None:
191
+ optimizer.load_state_dict(ckpt['optimizer'])
192
+ best_fitness = ckpt['best_fitness']
193
+
194
+ # EMA
195
+ if ema and ckpt.get('ema'):
196
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict())
197
+ ema.updates = ckpt['updates']
198
+
199
+ # Epochs
200
+ start_epoch = ckpt['epoch'] + 1
201
+ if resume:
202
+ assert start_epoch > 0, f'{weights} training to {epochs} epochs is finished, nothing to resume.'
203
+ if epochs < start_epoch:
204
+ LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.")
205
+ epochs += ckpt['epoch'] # finetune additional epochs
206
+
207
+ del ckpt, csd
208
+
209
+ # DP mode
210
+ if cuda and RANK == -1 and torch.cuda.device_count() > 1:
211
+ LOGGER.warning('WARNING: DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n'
212
+ 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.')
213
+ model = torch.nn.DataParallel(model)
214
+
215
+ # SyncBatchNorm
216
+ if opt.sync_bn and cuda and RANK != -1:
217
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
218
+ LOGGER.info('Using SyncBatchNorm()')
219
+
220
+ # Trainloader
221
+ train_loader, dataset = create_dataloader(train_path,
222
+ imgsz,
223
+ batch_size // WORLD_SIZE,
224
+ gs,
225
+ single_cls,
226
+ hyp=hyp,
227
+ augment=True,
228
+ cache=None if opt.cache == 'val' else opt.cache,
229
+ rect=opt.rect,
230
+ rank=LOCAL_RANK,
231
+ workers=workers,
232
+ image_weights=opt.image_weights,
233
+ quad=opt.quad,
234
+ prefix=colorstr('train: '),
235
+ shuffle=True)
236
+ mlc = int(np.concatenate(dataset.labels, 0)[:, 0].max()) # max label class
237
+ nb = len(train_loader) # number of batches
238
+ assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
239
+
240
+ # Process 0
241
+ if RANK in {-1, 0}:
242
+ val_loader = create_dataloader(val_path,
243
+ imgsz,
244
+ batch_size // WORLD_SIZE * 2,
245
+ gs,
246
+ single_cls,
247
+ hyp=hyp,
248
+ cache=None if noval else opt.cache,
249
+ rect=True,
250
+ rank=-1,
251
+ workers=workers * 2,
252
+ pad=0.5,
253
+ prefix=colorstr('val: '))[0]
254
+
255
+ if not resume:
256
+ labels = np.concatenate(dataset.labels, 0)
257
+ # c = torch.tensor(labels[:, 0]) # classes
258
+ # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
259
+ # model._initialize_biases(cf.to(device))
260
+ if plots:
261
+ plot_labels(labels, names, save_dir)
262
+
263
+ # Anchors
264
+ if not opt.noautoanchor:
265
+ check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
266
+ model.half().float() # pre-reduce anchor precision
267
+
268
+ callbacks.run('on_pretrain_routine_end')
269
+
270
+ # DDP mode
271
+ if cuda and RANK != -1:
272
+ if check_version(torch.__version__, '1.11.0'):
273
+ model = DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK, static_graph=True)
274
+ else:
275
+ model = DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK)
276
+
277
+ # Model attributes
278
+ nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
279
+ hyp['box'] *= 3 / nl # scale to layers
280
+ hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers
281
+ hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
282
+ hyp['label_smoothing'] = opt.label_smoothing
283
+ model.nc = nc # attach number of classes to model
284
+ model.hyp = hyp # attach hyperparameters to model
285
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
286
+ model.names = names
287
+
288
+ # Start training
289
+ t0 = time.time()
290
+ nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
291
+ # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
292
+ last_opt_step = -1
293
+ maps = np.zeros(nc) # mAP per class
294
+ results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
295
+ scheduler.last_epoch = start_epoch - 1 # do not move
296
+ scaler = torch.cuda.amp.GradScaler(enabled=amp)
297
+ stopper = EarlyStopping(patience=opt.patience)
298
+ compute_loss = ComputeLoss(model) # init loss class
299
+ callbacks.run('on_train_start')
300
+ LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
301
+ f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
302
+ f"Logging results to {colorstr('bold', save_dir)}\n"
303
+ f'Starting training for {epochs} epochs...')
304
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
305
+ callbacks.run('on_train_epoch_start')
306
+ model.train()
307
+
308
+ # Update image weights (optional, single-GPU only)
309
+ if opt.image_weights:
310
+ cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
311
+ iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
312
+ dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
313
+
314
+ # Update mosaic border (optional)
315
+ # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
316
+ # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
317
+
318
+ mloss = torch.zeros(3, device=device) # mean losses
319
+ if RANK != -1:
320
+ train_loader.sampler.set_epoch(epoch)
321
+ pbar = enumerate(train_loader)
322
+ LOGGER.info(('\n' + '%10s' * 7) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'labels', 'img_size'))
323
+ if RANK in {-1, 0}:
324
+ pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
325
+ optimizer.zero_grad()
326
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
327
+ callbacks.run('on_train_batch_start')
328
+ ni = i + nb * epoch # number integrated batches (since train start)
329
+ imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
330
+
331
+ # Warmup
332
+ if ni <= nw:
333
+ xi = [0, nw] # x interp
334
+ # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
335
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
336
+ for j, x in enumerate(optimizer.param_groups):
337
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
338
+ x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 0 else 0.0, x['initial_lr'] * lf(epoch)])
339
+ if 'momentum' in x:
340
+ x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
341
+
342
+ # Multi-scale
343
+ if opt.multi_scale:
344
+ sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
345
+ sf = sz / max(imgs.shape[2:]) # scale factor
346
+ if sf != 1:
347
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
348
+ imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
349
+
350
+ # Forward
351
+ with torch.cuda.amp.autocast(amp):
352
+ pred = model(imgs) # forward
353
+ loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
354
+ if RANK != -1:
355
+ loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
356
+ if opt.quad:
357
+ loss *= 4.
358
+
359
+ # Backward
360
+ scaler.scale(loss).backward()
361
+
362
+ # Optimize
363
+ if ni - last_opt_step >= accumulate:
364
+ scaler.step(optimizer) # optimizer.step
365
+ scaler.update()
366
+ optimizer.zero_grad()
367
+ if ema:
368
+ ema.update(model)
369
+ last_opt_step = ni
370
+
371
+ # Log
372
+ if RANK in {-1, 0}:
373
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
374
+ mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
375
+ pbar.set_description(('%10s' * 2 + '%10.4g' * 5) %
376
+ (f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
377
+ callbacks.run('on_train_batch_end', ni, model, imgs, targets, paths, plots)
378
+ if callbacks.stop_training:
379
+ return
380
+ # end batch ------------------------------------------------------------------------------------------------
381
+
382
+ # Scheduler
383
+ lr = [x['lr'] for x in optimizer.param_groups] # for loggers
384
+ scheduler.step()
385
+
386
+ if RANK in {-1, 0}:
387
+ # mAP
388
+ callbacks.run('on_train_epoch_end', epoch=epoch)
389
+ ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
390
+ final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
391
+ if not noval or final_epoch: # Calculate mAP
392
+ results, maps, _ = val.run(data_dict,
393
+ batch_size=batch_size // WORLD_SIZE * 2,
394
+ imgsz=imgsz,
395
+ model=ema.ema,
396
+ single_cls=single_cls,
397
+ dataloader=val_loader,
398
+ save_dir=save_dir,
399
+ plots=False,
400
+ callbacks=callbacks,
401
+ compute_loss=compute_loss)
402
+
403
+ # Update best mAP
404
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
405
+ if fi > best_fitness:
406
+ best_fitness = fi
407
+ log_vals = list(mloss) + list(results) + lr
408
+ callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
409
+
410
+ # Save model
411
+ if (not nosave) or (final_epoch and not evolve): # if save
412
+ ckpt = {
413
+ 'epoch': epoch,
414
+ 'best_fitness': best_fitness,
415
+ 'model': deepcopy(de_parallel(model)).half(),
416
+ 'ema': deepcopy(ema.ema).half(),
417
+ 'updates': ema.updates,
418
+ 'optimizer': optimizer.state_dict(),
419
+ 'wandb_id': loggers.wandb.wandb_run.id if loggers.wandb else None,
420
+ 'date': datetime.now().isoformat()}
421
+
422
+ # Save last, best and delete
423
+ torch.save(ckpt, last)
424
+ if best_fitness == fi:
425
+ torch.save(ckpt, best)
426
+ if opt.save_period > 0 and epoch % opt.save_period == 0:
427
+ torch.save(ckpt, w / f'epoch{epoch}.pt')
428
+ del ckpt
429
+ callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
430
+
431
+ # Stop Single-GPU
432
+ if RANK == -1 and stopper(epoch=epoch, fitness=fi):
433
+ break
434
+
435
+ # Stop DDP TODO: known issues shttps://github.com/ultralytics/yolov5/pull/4576
436
+ # stop = stopper(epoch=epoch, fitness=fi)
437
+ # if RANK == 0:
438
+ # dist.broadcast_object_list([stop], 0) # broadcast 'stop' to all ranks
439
+
440
+ # Stop DPP
441
+ # with torch_distributed_zero_first(RANK):
442
+ # if stop:
443
+ # break # must break all DDP ranks
444
+
445
+ # end epoch ----------------------------------------------------------------------------------------------------
446
+ # end training -----------------------------------------------------------------------------------------------------
447
+ if RANK in {-1, 0}:
448
+ LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
449
+ for f in last, best:
450
+ if f.exists():
451
+ strip_optimizer(f) # strip optimizers
452
+ if f is best:
453
+ LOGGER.info(f'\nValidating {f}...')
454
+ results, _, _ = val.run(
455
+ data_dict,
456
+ batch_size=batch_size // WORLD_SIZE * 2,
457
+ imgsz=imgsz,
458
+ model=attempt_load(f, device).half(),
459
+ iou_thres=0.65 if is_coco else 0.60, # best pycocotools results at 0.65
460
+ single_cls=single_cls,
461
+ dataloader=val_loader,
462
+ save_dir=save_dir,
463
+ save_json=is_coco,
464
+ verbose=True,
465
+ plots=plots,
466
+ callbacks=callbacks,
467
+ compute_loss=compute_loss) # val best model with plots
468
+ if is_coco:
469
+ callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
470
+
471
+ callbacks.run('on_train_end', last, best, plots, epoch, results)
472
+
473
+ torch.cuda.empty_cache()
474
+ return results
475
+
476
+
477
+ def parse_opt(known=False):
478
+ parser = argparse.ArgumentParser()
479
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path')
480
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
481
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
482
+ parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
483
+ parser.add_argument('--epochs', type=int, default=300)
484
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
485
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
486
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
487
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
488
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
489
+ parser.add_argument('--noval', action='store_true', help='only validate final epoch')
490
+ parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
491
+ parser.add_argument('--noplots', action='store_true', help='save no plot files')
492
+ parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
493
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
494
+ parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
495
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
496
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
497
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
498
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
499
+ parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
500
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
501
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
502
+ parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name')
503
+ parser.add_argument('--name', default='exp', help='save to project/name')
504
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
505
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
506
+ parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
507
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
508
+ parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
509
+ parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
510
+ parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
511
+ parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
512
+
513
+ # Weights & Biases arguments
514
+ parser.add_argument('--entity', default=None, help='W&B: Entity')
515
+ parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option')
516
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval')
517
+ parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use')
518
+
519
+ opt = parser.parse_known_args()[0] if known else parser.parse_args()
520
+ return opt
521
+
522
+
523
+ def main(opt, callbacks=Callbacks()):
524
+ # Checks
525
+ if RANK in {-1, 0}:
526
+ print_args(vars(opt))
527
+ check_git_status()
528
+ check_requirements(exclude=['thop'])
529
+
530
+ # Resume
531
+ if opt.resume and not check_wandb_resume(opt) and not opt.evolve: # resume an interrupted run
532
+ ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
533
+ assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
534
+ with open(Path(ckpt).parent.parent / 'opt.yaml', errors='ignore') as f:
535
+ opt = argparse.Namespace(**yaml.safe_load(f)) # replace
536
+ opt.cfg, opt.weights, opt.resume = '', ckpt, True # reinstate
537
+ LOGGER.info(f'Resuming training from {ckpt}')
538
+ else:
539
+ opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \
540
+ check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks
541
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
542
+ if opt.evolve:
543
+ if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve
544
+ opt.project = str(ROOT / 'runs/evolve')
545
+ opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
546
+ if opt.name == 'cfg':
547
+ opt.name = Path(opt.cfg).stem # use model.yaml as name
548
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
549
+
550
+ # DDP mode
551
+ device = select_device(opt.device, batch_size=opt.batch_size)
552
+ if LOCAL_RANK != -1:
553
+ msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
554
+ assert not opt.image_weights, f'--image-weights {msg}'
555
+ assert not opt.evolve, f'--evolve {msg}'
556
+ assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size'
557
+ assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
558
+ assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
559
+ torch.cuda.set_device(LOCAL_RANK)
560
+ device = torch.device('cuda', LOCAL_RANK)
561
+ dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
562
+
563
+ # Train
564
+ if not opt.evolve:
565
+ train(opt.hyp, opt, device, callbacks)
566
+ if WORLD_SIZE > 1 and RANK == 0:
567
+ LOGGER.info('Destroying process group... ')
568
+ dist.destroy_process_group()
569
+
570
+ # Evolve hyperparameters (optional)
571
+ else:
572
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
573
+ meta = {
574
+ 'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
575
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
576
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
577
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
578
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
579
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
580
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
581
+ 'box': (1, 0.02, 0.2), # box loss gain
582
+ 'cls': (1, 0.2, 4.0), # cls loss gain
583
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
584
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
585
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
586
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
587
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
588
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
589
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
590
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
591
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
592
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
593
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
594
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
595
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
596
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
597
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
598
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
599
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
600
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
601
+ 'mixup': (1, 0.0, 1.0), # image mixup (probability)
602
+ 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability)
603
+
604
+ with open(opt.hyp, errors='ignore') as f:
605
+ hyp = yaml.safe_load(f) # load hyps dict
606
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
607
+ hyp['anchors'] = 3
608
+ opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
609
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
610
+ evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv'
611
+ if opt.bucket:
612
+ os.system(f'gsutil cp gs://{opt.bucket}/evolve.csv {evolve_csv}') # download evolve.csv if exists
613
+
614
+ for _ in range(opt.evolve): # generations to evolve
615
+ if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
616
+ # Select parent(s)
617
+ parent = 'single' # parent selection method: 'single' or 'weighted'
618
+ x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
619
+ n = min(5, len(x)) # number of previous results to consider
620
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
621
+ w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0)
622
+ if parent == 'single' or len(x) == 1:
623
+ # x = x[random.randint(0, n - 1)] # random selection
624
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
625
+ elif parent == 'weighted':
626
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
627
+
628
+ # Mutate
629
+ mp, s = 0.8, 0.2 # mutation probability, sigma
630
+ npr = np.random
631
+ npr.seed(int(time.time()))
632
+ g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
633
+ ng = len(meta)
634
+ v = np.ones(ng)
635
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
636
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
637
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
638
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
639
+
640
+ # Constrain to limits
641
+ for k, v in meta.items():
642
+ hyp[k] = max(hyp[k], v[1]) # lower limit
643
+ hyp[k] = min(hyp[k], v[2]) # upper limit
644
+ hyp[k] = round(hyp[k], 5) # significant digits
645
+
646
+ # Train mutation
647
+ results = train(hyp.copy(), opt, device, callbacks)
648
+ callbacks = Callbacks()
649
+ # Write mutation results
650
+ print_mutation(results, hyp.copy(), save_dir, opt.bucket)
651
+
652
+ # Plot results
653
+ plot_evolve(evolve_csv)
654
+ LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n'
655
+ f"Results saved to {colorstr('bold', save_dir)}\n"
656
+ f'Usage example: $ python train.py --hyp {evolve_yaml}')
657
+
658
+
659
+ def run(**kwargs):
660
+ # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
661
+ opt = parse_opt(True)
662
+ for k, v in kwargs.items():
663
+ setattr(opt, k, v)
664
+ main(opt)
665
+ return opt
666
+
667
+
668
+ if __name__ == "__main__":
669
+ opt = parse_opt()
670
+ main(opt)
tutorial.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
utilss.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import base64
3
+ from streamlit.components.v1 import html
4
+
5
+ from PATHS import NAVBAR_PATHS, SETTINGS
6
+
7
+
8
+ def inject_custom_css():
9
+ with open('C:/Users/DELL Latitude 7270/Desktop/Code_Site_Web/assets/styles.css') as f:
10
+ st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
11
+
12
+
13
+ def get_current_route():
14
+ try:
15
+ return st.experimental_get_query_params()['nav'][0]
16
+ except:
17
+ return None
18
+
19
+
20
+ def navbar_component():
21
+ with open("C:/Users/DELL Latitude 7270/Desktop/Code_Site_Web/assets/images/settings.png", "rb") as image_file:
22
+ image_as_base64 = base64.b64encode(image_file.read())
23
+
24
+ navbar_items = ''
25
+ for key, value in NAVBAR_PATHS.items():
26
+ navbar_items += (f'<a class="navitem" href="/?nav={value}">{key}</a>')
27
+
28
+ settings_items = ''
29
+ for key, value in SETTINGS.items():
30
+ settings_items += (
31
+ f'<a href="/?nav={value}" class="settingsNav">{key}</a>')
32
+
33
+ component = rf'''
34
+ <nav class="container navbar" id="navbar">
35
+ <ul class="navlist">
36
+ {navbar_items}
37
+ </ul>
38
+ <div class="dropdown" id="settingsDropDown">
39
+ <img class="dropbtn" src="data:image/png;base64, {image_as_base64.decode("utf-8")}"/>
40
+ <div id="myDropdown" class="dropdown-content">
41
+ {settings_items}
42
+ </div>
43
+ </div>
44
+ </nav>
45
+ '''
46
+ st.markdown(component, unsafe_allow_html=True)
47
+ js = '''
48
+ <script>
49
+ // navbar elements
50
+ var navigationTabs = window.parent.document.getElementsByClassName("navitem");
51
+ var cleanNavbar = function(navigation_element) {
52
+ navigation_element.removeAttribute('target')
53
+ }
54
+
55
+ for (var i = 0; i < navigationTabs.length; i++) {
56
+ cleanNavbar(navigationTabs[i]);
57
+ }
58
+
59
+ // Dropdown hide / show
60
+ var dropdown = window.parent.document.getElementById("settingsDropDown");
61
+ dropdown.onclick = function() {
62
+ var dropWindow = window.parent.document.getElementById("myDropdown");
63
+ if (dropWindow.style.visibility == "hidden"){
64
+ dropWindow.style.visibility = "visible";
65
+ }else{
66
+ dropWindow.style.visibility = "hidden";
67
+ }
68
+ };
69
+
70
+ var settingsNavs = window.parent.document.getElementsByClassName("settingsNav");
71
+ var cleanSettings = function(navigation_element) {
72
+ navigation_element.removeAttribute('target')
73
+ }
74
+
75
+ for (var i = 0; i < settingsNavs.length; i++) {
76
+ cleanSettings(settingsNavs[i]);
77
+ }
78
+ </script>
79
+ '''
80
+ html(js)
val.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Validate a trained YOLOv5 model accuracy on a custom dataset
4
+
5
+ Usage:
6
+ $ python path/to/val.py --weights yolov5s.pt --data coco128.yaml --img 640
7
+
8
+ Usage - formats:
9
+ $ python path/to/val.py --weights yolov5s.pt # PyTorch
10
+ yolov5s.torchscript # TorchScript
11
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
12
+ yolov5s.xml # OpenVINO
13
+ yolov5s.engine # TensorRT
14
+ yolov5s.mlmodel # CoreML (macOS-only)
15
+ yolov5s_saved_model # TensorFlow SavedModel
16
+ yolov5s.pb # TensorFlow GraphDef
17
+ yolov5s.tflite # TensorFlow Lite
18
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
19
+ """
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import torch
29
+ from tqdm import tqdm
30
+
31
+ FILE = Path(__file__).resolve()
32
+ ROOT = FILE.parents[0] # YOLOv5 root directory
33
+ if str(ROOT) not in sys.path:
34
+ sys.path.append(str(ROOT)) # add ROOT to PATH
35
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
36
+
37
+ from models.common import DetectMultiBackend
38
+ from utils.callbacks import Callbacks
39
+ from utils.dataloaders import create_dataloader
40
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_yaml,
41
+ coco80_to_coco91_class, colorstr, emojis, increment_path, non_max_suppression, print_args,
42
+ scale_coords, xywh2xyxy, xyxy2xywh)
43
+ from utils.metrics import ConfusionMatrix, ap_per_class, box_iou
44
+ from utils.plots import output_to_target, plot_images, plot_val_study
45
+ from utils.torch_utils import select_device, time_sync
46
+
47
+
48
+ def save_one_txt(predn, save_conf, shape, file):
49
+ # Save one txt result
50
+ gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
51
+ for *xyxy, conf, cls in predn.tolist():
52
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
53
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
54
+ with open(file, 'a') as f:
55
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
56
+
57
+
58
+ def save_one_json(predn, jdict, path, class_map):
59
+ # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
60
+ image_id = int(path.stem) if path.stem.isnumeric() else path.stem
61
+ box = xyxy2xywh(predn[:, :4]) # xywh
62
+ box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
63
+ for p, b in zip(predn.tolist(), box.tolist()):
64
+ jdict.append({
65
+ 'image_id': image_id,
66
+ 'category_id': class_map[int(p[5])],
67
+ 'bbox': [round(x, 3) for x in b],
68
+ 'score': round(p[4], 5)})
69
+
70
+
71
+ def process_batch(detections, labels, iouv):
72
+ """
73
+ Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format.
74
+ Arguments:
75
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
76
+ labels (Array[M, 5]), class, x1, y1, x2, y2
77
+ Returns:
78
+ correct (Array[N, 10]), for 10 IoU levels
79
+ """
80
+ correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool)
81
+ iou = box_iou(labels[:, 1:], detections[:, :4])
82
+ correct_class = labels[:, 0:1] == detections[:, 5]
83
+ for i in range(len(iouv)):
84
+ x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match
85
+ if x[0].shape[0]:
86
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou]
87
+ if x[0].shape[0] > 1:
88
+ matches = matches[matches[:, 2].argsort()[::-1]]
89
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
90
+ # matches = matches[matches[:, 2].argsort()[::-1]]
91
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
92
+ correct[matches[:, 1].astype(int), i] = True
93
+ return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
94
+
95
+
96
+ @torch.no_grad()
97
+ def run(
98
+ data,
99
+ weights=None, # model.pt path(s)
100
+ batch_size=32, # batch size
101
+ imgsz=640, # inference size (pixels)
102
+ conf_thres=0.001, # confidence threshold
103
+ iou_thres=0.6, # NMS IoU threshold
104
+ task='val', # train, val, test, speed or study
105
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
106
+ workers=8, # max dataloader workers (per RANK in DDP mode)
107
+ single_cls=False, # treat as single-class dataset
108
+ augment=False, # augmented inference
109
+ verbose=False, # verbose output
110
+ save_txt=False, # save results to *.txt
111
+ save_hybrid=False, # save label+prediction hybrid results to *.txt
112
+ save_conf=False, # save confidences in --save-txt labels
113
+ save_json=False, # save a COCO-JSON results file
114
+ project=ROOT / 'runs/val', # save to project/name
115
+ name='exp', # save to project/name
116
+ exist_ok=False, # existing project/name ok, do not increment
117
+ half=True, # use FP16 half-precision inference
118
+ dnn=False, # use OpenCV DNN for ONNX inference
119
+ model=None,
120
+ dataloader=None,
121
+ save_dir=Path(''),
122
+ plots=True,
123
+ callbacks=Callbacks(),
124
+ compute_loss=None,
125
+ ):
126
+ # Initialize/load model and set device
127
+ training = model is not None
128
+ if training: # called by train.py
129
+ device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
130
+ half &= device.type != 'cpu' # half precision only supported on CUDA
131
+ model.half() if half else model.float()
132
+ else: # called directly
133
+ device = select_device(device, batch_size=batch_size)
134
+
135
+ # Directories
136
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
137
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
138
+
139
+ # Load model
140
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
141
+ stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
142
+ imgsz = check_img_size(imgsz, s=stride) # check image size
143
+ half = model.fp16 # FP16 supported on limited backends with CUDA
144
+ if engine:
145
+ batch_size = model.batch_size
146
+ else:
147
+ device = model.device
148
+ if not (pt or jit):
149
+ batch_size = 1 # export.py models default to batch-size 1
150
+ LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
151
+
152
+ # Data
153
+ data = check_dataset(data) # check
154
+
155
+ # Configure
156
+ model.eval()
157
+ cuda = device.type != 'cpu'
158
+ is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset
159
+ nc = 1 if single_cls else int(data['nc']) # number of classes
160
+ iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95
161
+ niou = iouv.numel()
162
+
163
+ # Dataloader
164
+ if not training:
165
+ if pt and not single_cls: # check --weights are trained on --data
166
+ ncm = model.model.nc
167
+ assert ncm == nc, f'{weights[0]} ({ncm} classes) trained on different --data than what you passed ({nc} ' \
168
+ f'classes). Pass correct combination of --weights and --data that are trained together.'
169
+ model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup
170
+ pad = 0.0 if task in ('speed', 'benchmark') else 0.5
171
+ rect = False if task == 'benchmark' else pt # square inference for benchmarks
172
+ task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
173
+ dataloader = create_dataloader(data[task],
174
+ imgsz,
175
+ batch_size,
176
+ stride,
177
+ single_cls,
178
+ pad=pad,
179
+ rect=rect,
180
+ workers=workers,
181
+ prefix=colorstr(f'{task}: '))[0]
182
+
183
+ seen = 0
184
+ confusion_matrix = ConfusionMatrix(nc=nc)
185
+ names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
186
+ class_map = coco80_to_coco91_class() if is_coco else list(range(1000))
187
+ s = ('%20s' + '%11s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
188
+ dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
189
+ loss = torch.zeros(3, device=device)
190
+ jdict, stats, ap, ap_class = [], [], [], []
191
+ callbacks.run('on_val_start')
192
+ pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
193
+ for batch_i, (im, targets, paths, shapes) in enumerate(pbar):
194
+ callbacks.run('on_val_batch_start')
195
+ t1 = time_sync()
196
+ if cuda:
197
+ im = im.to(device, non_blocking=True)
198
+ targets = targets.to(device)
199
+ im = im.half() if half else im.float() # uint8 to fp16/32
200
+ im /= 255 # 0 - 255 to 0.0 - 1.0
201
+ nb, _, height, width = im.shape # batch size, channels, height, width
202
+ t2 = time_sync()
203
+ dt[0] += t2 - t1
204
+
205
+ # Inference
206
+ out, train_out = model(im) if training else model(im, augment=augment, val=True) # inference, loss outputs
207
+ dt[1] += time_sync() - t2
208
+
209
+ # Loss
210
+ if compute_loss:
211
+ loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls
212
+
213
+ # NMS
214
+ targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels
215
+ lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
216
+ t3 = time_sync()
217
+ out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls)
218
+ dt[2] += time_sync() - t3
219
+
220
+ # Metrics
221
+ for si, pred in enumerate(out):
222
+ labels = targets[targets[:, 0] == si, 1:]
223
+ nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions
224
+ path, shape = Path(paths[si]), shapes[si][0]
225
+ correct = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init
226
+ seen += 1
227
+
228
+ if npr == 0:
229
+ if nl:
230
+ stats.append((correct, *torch.zeros((3, 0), device=device)))
231
+ continue
232
+
233
+ # Predictions
234
+ if single_cls:
235
+ pred[:, 5] = 0
236
+ predn = pred.clone()
237
+ scale_coords(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred
238
+
239
+ # Evaluate
240
+ if nl:
241
+ tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
242
+ scale_coords(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels
243
+ labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
244
+ correct = process_batch(predn, labelsn, iouv)
245
+ if plots:
246
+ confusion_matrix.process_batch(predn, labelsn)
247
+ stats.append((correct, pred[:, 4], pred[:, 5], labels[:, 0])) # (correct, conf, pcls, tcls)
248
+
249
+ # Save/log
250
+ if save_txt:
251
+ save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / (path.stem + '.txt'))
252
+ if save_json:
253
+ save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary
254
+ callbacks.run('on_val_image_end', pred, predn, path, names, im[si])
255
+
256
+ # Plot images
257
+ if plots and batch_i < 3:
258
+ plot_images(im, targets, paths, save_dir / f'val_batch{batch_i}_labels.jpg', names) # labels
259
+ plot_images(im, output_to_target(out), paths, save_dir / f'val_batch{batch_i}_pred.jpg', names) # pred
260
+
261
+ callbacks.run('on_val_batch_end')
262
+
263
+ # Compute metrics
264
+ stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpy
265
+ if len(stats) and stats[0].any():
266
+ tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
267
+ ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
268
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
269
+ nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class
270
+ else:
271
+ nt = torch.zeros(1)
272
+
273
+ # Print results
274
+ pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format
275
+ LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
276
+
277
+ # Print results per class
278
+ if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
279
+ for i, c in enumerate(ap_class):
280
+ LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
281
+
282
+ # Print speeds
283
+ t = tuple(x / seen * 1E3 for x in dt) # speeds per image
284
+ if not training:
285
+ shape = (batch_size, 3, imgsz, imgsz)
286
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t)
287
+
288
+ # Plots
289
+ if plots:
290
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
291
+ callbacks.run('on_val_end')
292
+
293
+ # Save JSON
294
+ if save_json and len(jdict):
295
+ w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
296
+ anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json
297
+ pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
298
+ LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...')
299
+ with open(pred_json, 'w') as f:
300
+ json.dump(jdict, f)
301
+
302
+ try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
303
+ check_requirements(['pycocotools'])
304
+ from pycocotools.coco import COCO
305
+ from pycocotools.cocoeval import COCOeval
306
+
307
+ anno = COCO(anno_json) # init annotations api
308
+ pred = anno.loadRes(pred_json) # init predictions api
309
+ eval = COCOeval(anno, pred, 'bbox')
310
+ if is_coco:
311
+ eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluate
312
+ eval.evaluate()
313
+ eval.accumulate()
314
+ eval.summarize()
315
+ map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
316
+ except Exception as e:
317
+ LOGGER.info(f'pycocotools unable to run: {e}')
318
+
319
+ # Return results
320
+ model.float() # for training
321
+ if not training:
322
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
323
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
324
+ maps = np.zeros(nc) + map
325
+ for i, c in enumerate(ap_class):
326
+ maps[c] = ap[i]
327
+ return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
328
+
329
+
330
+ def parse_opt():
331
+ parser = argparse.ArgumentParser()
332
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
333
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
334
+ parser.add_argument('--batch-size', type=int, default=32, help='batch size')
335
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
336
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold')
337
+ parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold')
338
+ parser.add_argument('--task', default='val', help='train, val, test, speed or study')
339
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
340
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
341
+ parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
342
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
343
+ parser.add_argument('--verbose', action='store_true', help='report mAP by class')
344
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
345
+ parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
346
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
347
+ parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file')
348
+ parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name')
349
+ parser.add_argument('--name', default='exp', help='save to project/name')
350
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
351
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
352
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
353
+ opt = parser.parse_args()
354
+ opt.data = check_yaml(opt.data) # check YAML
355
+ opt.save_json |= opt.data.endswith('coco.yaml')
356
+ opt.save_txt |= opt.save_hybrid
357
+ print_args(vars(opt))
358
+ return opt
359
+
360
+
361
+ def main(opt):
362
+ check_requirements(requirements=ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
363
+
364
+ if opt.task in ('train', 'val', 'test'): # run normally
365
+ if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466
366
+ LOGGER.info(emojis(f'WARNING: confidence threshold {opt.conf_thres} > 0.001 produces invalid results ⚠️'))
367
+ run(**vars(opt))
368
+
369
+ else:
370
+ weights = opt.weights if isinstance(opt.weights, list) else [opt.weights]
371
+ opt.half = True # FP16 for fastest results
372
+ if opt.task == 'speed': # speed benchmarks
373
+ # python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt...
374
+ opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False
375
+ for opt.weights in weights:
376
+ run(**vars(opt), plots=False)
377
+
378
+ elif opt.task == 'study': # speed vs mAP benchmarks
379
+ # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt...
380
+ for opt.weights in weights:
381
+ f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt' # filename to save to
382
+ x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis
383
+ for opt.imgsz in x: # img-size
384
+ LOGGER.info(f'\nRunning {f} --imgsz {opt.imgsz}...')
385
+ r, _, t = run(**vars(opt), plots=False)
386
+ y.append(r + t) # results and times
387
+ np.savetxt(f, y, fmt='%10.4g') # save
388
+ os.system('zip -r study.zip study_*.txt')
389
+ plot_val_study(x=x) # plot
390
+
391
+
392
+ if __name__ == "__main__":
393
+ opt = parse_opt()
394
+ main(opt)
yolov5-streamlit.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import StringIO
2
+ from pathlib import Path
3
+ import streamlit as st
4
+ import time
5
+ from detect import run
6
+ import os
7
+ import sys
8
+ import argparse
9
+ from PIL import Image
10
+
11
+
12
+ def get_subdirs(b='.'):
13
+ '''
14
+ Returns all sub-directories in a specific Path
15
+ '''
16
+ result = []
17
+ for d in os.listdir(b):
18
+ bd = os.path.join(b, d)
19
+ if os.path.isdir(bd):
20
+ result.append(bd)
21
+ return result
22
+
23
+
24
+ def get_detection_folder():
25
+ '''
26
+ Returns the latest folder in a runs\detect
27
+ '''
28
+ return max(get_subdirs(os.path.join('runs', 'detect')), key=os.path.getmtime)
29
+
30
+
31
+ if __name__ == '__main__':
32
+
33
+ st.title('YOLOv5 Streamlit App')
34
+ ## From detect.py. add parser for command line run.
35
+ # main function is RUN and it takes a lot of option.
36
+ # when -- is added before each option, parser will seperate them and
37
+ # add to the run function.
38
+ #
39
+ parser = argparse.ArgumentParser()
40
+ parser.add_argument('--weights', nargs='+', type=str, default='best.pt', help='model path(s)')
41
+ parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
42
+ parser.add_argument('--data', type=str, default='data/coco128.yaml', help='(optional) dataset.yaml path')
43
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=(640,640), help='inference size h,w')
44
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
45
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
46
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
47
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
48
+ parser.add_argument('--view-img', action='store_true', help='show results')
49
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
50
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
51
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
52
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
53
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
54
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
55
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
56
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
57
+ parser.add_argument('--update', action='store_true', help='update all models')
58
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
59
+ parser.add_argument('--name', default='exp', help='save results to project/name')
60
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
61
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
62
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
63
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
64
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
65
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
66
+ opt = parser.parse_args()
67
+
68
+ ## opt.argument = xxx to change/access argument value
69
+
70
+
71
+ source = ("Image detection", "Video detection", "Web Cam detection")
72
+ source_index = st.sidebar.selectbox("Select input", range(
73
+ len(source)), format_func=lambda x: source[x])
74
+
75
+ if source_index == 0:
76
+ uploaded_file = st.sidebar.file_uploader(
77
+ "Upload images", type=['png', 'jpeg', 'jpg'])
78
+ if uploaded_file is not None:
79
+ is_valid = True
80
+ with st.spinner(text='loading...'):
81
+ st.sidebar.image(uploaded_file)
82
+ picture = Image.open(uploaded_file)
83
+ print(f'picture line 89 : {uploaded_file}, type : {type(uploaded_file)}')
84
+ picture = picture.save(f'data\images\{uploaded_file.name}')
85
+ opt.source = f'data\images\{uploaded_file.name}'
86
+ else:
87
+ is_valid = False
88
+ elif source_index == 1 :
89
+ uploaded_file = st.sidebar.file_uploader("Upload video", type=['mp4'])
90
+ if uploaded_file is not None:
91
+ is_valid = True
92
+ with st.spinner(text='loading...'):
93
+ st.sidebar.video(uploaded_file)
94
+ with open(os.path.join("data", "videos", uploaded_file.name), "wb") as f:
95
+ f.write(uploaded_file.getbuffer())
96
+ opt.source = f'data/videos/{uploaded_file.name}'
97
+ else:
98
+ is_valid = False
99
+
100
+ elif source_index == 2 :
101
+ is_valid = True # if webcam detection enable, no need to prepare any file. We just go to prediction
102
+
103
+
104
+
105
+ if is_valid:
106
+ print('valid')
107
+ #print(f'filepath : {opt.source}')
108
+ #print(f"HERE ---- {opt} ----")
109
+ if st.button('Start'):
110
+ print("-"*25," RUN ", "-"*25)
111
+ print(opt.weights)
112
+ if source_index in [0,1] :
113
+ run(
114
+ opt.weights,
115
+ opt.source,
116
+ opt.data,
117
+ opt.imgsz,
118
+ opt.conf_thres,
119
+ opt.iou_thres,
120
+ opt.max_det,
121
+ opt.device,
122
+ opt.view_img,
123
+ opt.save_txt,
124
+ opt.save_conf,
125
+ opt.save_crop,
126
+ opt.nosave,
127
+ opt.classes,
128
+ opt.agnostic_nms,
129
+ opt.augment,
130
+ opt.visualize,
131
+ opt.update,
132
+ opt.project,
133
+ opt.name,
134
+ opt.exist_ok,
135
+ opt.line_thickness,
136
+ opt.hide_labels,
137
+ opt.hide_conf,
138
+ opt.half,
139
+ opt.dnn,
140
+ )
141
+ else :
142
+ opt.source = '0' # enable webcam recording
143
+ run(
144
+ opt.weights,
145
+ opt.source
146
+ )
147
+
148
+ if source_index == 0:
149
+ with st.spinner(text='Preparing Images'):
150
+ for img in os.listdir(get_detection_folder()):
151
+ st.image(str(Path(f'{get_detection_folder()}') / img))
152
+
153
+ #st.balloons()
154
+ elif source_index == 1 :
155
+ with st.spinner(text='Preparing Video'):
156
+ for vid in os.listdir(get_detection_folder()):
157
+ #st.video(str(Path(f'{get_detection_folder()}') / vid))
158
+ input_file = str(Path(f'{get_detection_folder()}') / vid)
159
+ cmd = f'ffmpeg -i {input_file} -vcodec libx264 play.mp4'
160
+ os.system(cmd)
161
+
162
+ st.video('play.mp4')
163
+
164
+
165
+ #st.balloons()
yolov5s.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b3b748c1e592ddd8868022e8732fde20025197328490623cc16c6f24d0782ee
3
+ size 14808437