onipot commited on
Commit
c939ae6
β€’
1 Parent(s): 78d3520
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. .gitignore +3 -0
  2. face_detector/.dockerignore +220 -0
  3. face_detector/.gitignore +5 -0
  4. face_detector/.pre-commit-config.yaml +67 -0
  5. face_detector/Dockerfile +61 -0
  6. face_detector/LICENSE +674 -0
  7. face_detector/data/Argoverse.yaml +67 -0
  8. face_detector/data/GlobalWheat2020.yaml +53 -0
  9. face_detector/data/Objects365.yaml +104 -0
  10. face_detector/data/SKU-110K.yaml +52 -0
  11. face_detector/data/VOC.yaml +80 -0
  12. face_detector/data/VisDrone.yaml +61 -0
  13. face_detector/data/coco.yaml +44 -0
  14. face_detector/data/coco128.yaml +30 -0
  15. face_detector/data/hyps/hyp.finetune.yaml +39 -0
  16. face_detector/data/hyps/hyp.finetune_objects365.yaml +31 -0
  17. face_detector/data/hyps/hyp.scratch-high.yaml +34 -0
  18. face_detector/data/hyps/hyp.scratch-low.yaml +34 -0
  19. face_detector/data/hyps/hyp.scratch.yaml +34 -0
  20. face_detector/data/xView.yaml +102 -0
  21. face_detector/detect.py +342 -0
  22. face_detector/export.py +363 -0
  23. face_detector/hubconf.py +142 -0
  24. face_detector/main.py +36 -0
  25. face_detector/models/__init__.py +0 -0
  26. face_detector/models/common.py +469 -0
  27. face_detector/models/experimental.py +119 -0
  28. face_detector/models/hub/anchors.yaml +59 -0
  29. face_detector/models/hub/yolov3-spp.yaml +51 -0
  30. face_detector/models/hub/yolov3-tiny.yaml +41 -0
  31. face_detector/models/hub/yolov3.yaml +51 -0
  32. face_detector/models/hub/yolov5-bifpn.yaml +48 -0
  33. face_detector/models/hub/yolov5-fpn.yaml +42 -0
  34. face_detector/models/hub/yolov5-p2.yaml +54 -0
  35. face_detector/models/hub/yolov5-p6.yaml +56 -0
  36. face_detector/models/hub/yolov5-p7.yaml +67 -0
  37. face_detector/models/hub/yolov5-panet.yaml +48 -0
  38. face_detector/models/hub/yolov5l6.yaml +60 -0
  39. face_detector/models/hub/yolov5m6.yaml +60 -0
  40. face_detector/models/hub/yolov5n6.yaml +60 -0
  41. face_detector/models/hub/yolov5s-ghost.yaml +48 -0
  42. face_detector/models/hub/yolov5s-transformer.yaml +48 -0
  43. face_detector/models/hub/yolov5s6.yaml +60 -0
  44. face_detector/models/hub/yolov5x6.yaml +60 -0
  45. face_detector/models/tf.py +463 -0
  46. face_detector/models/yolo.py +327 -0
  47. face_detector/models/yolov5l.yaml +48 -0
  48. face_detector/models/yolov5m.yaml +48 -0
  49. face_detector/models/yolov5n.yaml +48 -0
  50. face_detector/models/yolov5s.yaml +48 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ *.jpg
2
+ __pycache__/
3
+ *.sh
face_detector/.dockerignore ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repo-specific DockerIgnore -------------------------------------------------------------------------------------------
2
+ #.git
3
+ .cache
4
+ .idea
5
+ runs
6
+ output
7
+ coco
8
+ storage.googleapis.com
9
+
10
+ data/samples/*
11
+ **/results*.csv
12
+ *.jpg
13
+
14
+ # Neural Network weights -----------------------------------------------------------------------------------------------
15
+ **/*.pt
16
+ **/*.pth
17
+ **/*.onnx
18
+ **/*.mlmodel
19
+ **/*.torchscript
20
+ **/*.torchscript.pt
21
+ **/*.tflite
22
+ **/*.h5
23
+ **/*.pb
24
+ *_saved_model/
25
+ *_web_model/
26
+
27
+ # Below Copied From .gitignore -----------------------------------------------------------------------------------------
28
+ # Below Copied From .gitignore -----------------------------------------------------------------------------------------
29
+
30
+
31
+ # GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
32
+ # Byte-compiled / optimized / DLL files
33
+ __pycache__/
34
+ *.py[cod]
35
+ *$py.class
36
+
37
+ # C extensions
38
+ *.so
39
+
40
+ # Distribution / packaging
41
+ .Python
42
+ env/
43
+ build/
44
+ develop-eggs/
45
+ dist/
46
+ downloads/
47
+ eggs/
48
+ .eggs/
49
+ lib/
50
+ lib64/
51
+ parts/
52
+ sdist/
53
+ var/
54
+ wheels/
55
+ *.egg-info/
56
+ wandb/
57
+ .installed.cfg
58
+ *.egg
59
+
60
+ # PyInstaller
61
+ # Usually these files are written by a python script from a template
62
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
63
+ *.manifest
64
+ *.spec
65
+
66
+ # Installer logs
67
+ pip-log.txt
68
+ pip-delete-this-directory.txt
69
+
70
+ # Unit test / coverage reports
71
+ htmlcov/
72
+ .tox/
73
+ .coverage
74
+ .coverage.*
75
+ .cache
76
+ nosetests.xml
77
+ coverage.xml
78
+ *.cover
79
+ .hypothesis/
80
+
81
+ # Translations
82
+ *.mo
83
+ *.pot
84
+
85
+ # Django stuff:
86
+ *.log
87
+ local_settings.py
88
+
89
+ # Flask stuff:
90
+ instance/
91
+ .webassets-cache
92
+
93
+ # Scrapy stuff:
94
+ .scrapy
95
+
96
+ # Sphinx documentation
97
+ docs/_build/
98
+
99
+ # PyBuilder
100
+ target/
101
+
102
+ # Jupyter Notebook
103
+ .ipynb_checkpoints
104
+
105
+ # pyenv
106
+ .python-version
107
+
108
+ # celery beat schedule file
109
+ celerybeat-schedule
110
+
111
+ # SageMath parsed files
112
+ *.sage.py
113
+
114
+ # dotenv
115
+ .env
116
+
117
+ # virtualenv
118
+ .venv*
119
+ venv*/
120
+ ENV*/
121
+
122
+ # Spyder project settings
123
+ .spyderproject
124
+ .spyproject
125
+
126
+ # Rope project settings
127
+ .ropeproject
128
+
129
+ # mkdocs documentation
130
+ /site
131
+
132
+ # mypy
133
+ .mypy_cache/
134
+
135
+
136
+ # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
137
+
138
+ # General
139
+ .DS_Store
140
+ .AppleDouble
141
+ .LSOverride
142
+
143
+ # Icon must end with two \r
144
+ Icon
145
+ Icon?
146
+
147
+ # Thumbnails
148
+ ._*
149
+
150
+ # Files that might appear in the root of a volume
151
+ .DocumentRevisions-V100
152
+ .fseventsd
153
+ .Spotlight-V100
154
+ .TemporaryItems
155
+ .Trashes
156
+ .VolumeIcon.icns
157
+ .com.apple.timemachine.donotpresent
158
+
159
+ # Directories potentially created on remote AFP share
160
+ .AppleDB
161
+ .AppleDesktop
162
+ Network Trash Folder
163
+ Temporary Items
164
+ .apdisk
165
+
166
+
167
+ # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
168
+ # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
169
+ # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
170
+
171
+ # User-specific stuff:
172
+ .idea/*
173
+ .idea/**/workspace.xml
174
+ .idea/**/tasks.xml
175
+ .idea/dictionaries
176
+ .html # Bokeh Plots
177
+ .pg # TensorFlow Frozen Graphs
178
+ .avi # videos
179
+
180
+ # Sensitive or high-churn files:
181
+ .idea/**/dataSources/
182
+ .idea/**/dataSources.ids
183
+ .idea/**/dataSources.local.xml
184
+ .idea/**/sqlDataSources.xml
185
+ .idea/**/dynamic.xml
186
+ .idea/**/uiDesigner.xml
187
+
188
+ # Gradle:
189
+ .idea/**/gradle.xml
190
+ .idea/**/libraries
191
+
192
+ # CMake
193
+ cmake-build-debug/
194
+ cmake-build-release/
195
+
196
+ # Mongo Explorer plugin:
197
+ .idea/**/mongoSettings.xml
198
+
199
+ ## File-based project format:
200
+ *.iws
201
+
202
+ ## Plugin-specific files:
203
+
204
+ # IntelliJ
205
+ out/
206
+
207
+ # mpeltonen/sbt-idea plugin
208
+ .idea_modules/
209
+
210
+ # JIRA plugin
211
+ atlassian-ide-plugin.xml
212
+
213
+ # Cursive Clojure plugin
214
+ .idea/replstate.xml
215
+
216
+ # Crashlytics plugin (for Android Studio and IntelliJ)
217
+ com_crashlytics_export_strings.xml
218
+ crashlytics.properties
219
+ crashlytics-build.properties
220
+ fabric.properties
face_detector/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ /dataset.zip
2
+ /dataset
3
+ /test.json
4
+ /runs/*
5
+ /yolov5s.pt
face_detector/.pre-commit-config.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: quarterly
12
+ # submodules: true
13
+
14
+ repos:
15
+ - repo: https://github.com/pre-commit/pre-commit-hooks
16
+ rev: v4.0.1
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.23.1
28
+ hooks:
29
+ - id: pyupgrade
30
+ args: [--py36-plus]
31
+ name: Upgrade code
32
+
33
+ # TODO
34
+ #- repo: https://github.com/PyCQA/isort
35
+ # rev: 5.9.3
36
+ # hooks:
37
+ # - id: isort
38
+ # name: imports
39
+
40
+ # TODO
41
+ #- repo: https://github.com/pre-commit/mirrors-yapf
42
+ # rev: v0.31.0
43
+ # hooks:
44
+ # - id: yapf
45
+ # name: formatting
46
+
47
+ # TODO
48
+ #- repo: https://github.com/executablebooks/mdformat
49
+ # rev: 0.7.7
50
+ # hooks:
51
+ # - id: mdformat
52
+ # additional_dependencies:
53
+ # - mdformat-gfm
54
+ # - mdformat-black
55
+ # - mdformat_frontmatter
56
+
57
+ # TODO
58
+ #- repo: https://github.com/asottile/yesqa
59
+ # rev: v1.2.3
60
+ # hooks:
61
+ # - id: yesqa
62
+
63
+ - repo: https://github.com/PyCQA/flake8
64
+ rev: 3.9.2
65
+ hooks:
66
+ - id: flake8
67
+ name: PEP8
face_detector/Dockerfile ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
4
+ FROM nvcr.io/nvidia/pytorch:21.05-py3
5
+
6
+ # Install linux packages
7
+ RUN apt update && apt install -y zip htop screen libgl1-mesa-glx
8
+
9
+ # Install python dependencies
10
+ COPY requirements.txt .
11
+ RUN python -m pip install --upgrade pip
12
+ RUN pip uninstall -y nvidia-tensorboard nvidia-tensorboard-plugin-dlprof
13
+ RUN pip install --no-cache -r requirements.txt coremltools onnx gsutil notebook wandb>=0.12.2
14
+ RUN pip install --no-cache -U torch torchvision numpy
15
+ # RUN pip install --no-cache torch==1.9.1+cu111 torchvision==0.10.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html
16
+
17
+ # Create working directory
18
+ RUN mkdir -p /usr/src/app
19
+ WORKDIR /usr/src/app
20
+
21
+ # Copy contents
22
+ COPY . /usr/src/app
23
+
24
+ # Downloads to user config dir
25
+ ADD https://ultralytics.com/assets/Arial.ttf /root/.config/Ultralytics/
26
+
27
+ # Set environment variables
28
+ # ENV HOME=/usr/src/app
29
+
30
+
31
+ # Usage Examples -------------------------------------------------------------------------------------------------------
32
+
33
+ # Build and Push
34
+ # t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t
35
+
36
+ # Pull and Run
37
+ # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t
38
+
39
+ # Pull and Run with local directory access
40
+ # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t
41
+
42
+ # Kill all
43
+ # sudo docker kill $(sudo docker ps -q)
44
+
45
+ # Kill all image-based
46
+ # sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)
47
+
48
+ # Bash into running container
49
+ # sudo docker exec -it 5a9b5863d93d bash
50
+
51
+ # Bash into stopped container
52
+ # id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash
53
+
54
+ # Clean up
55
+ # docker system prune -a --volumes
56
+
57
+ # Update Ubuntu drivers
58
+ # https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/
59
+
60
+ # DDP test
61
+ # python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3
face_detector/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>.
face_detector/data/Argoverse.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
3
+ # Example usage: python train.py --data Argoverse.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── Argoverse ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/Argoverse # dataset root dir
12
+ train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
13
+ val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
14
+ test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
15
+
16
+ # Classes
17
+ nc: 8 # number of classes
18
+ names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names
19
+
20
+
21
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
22
+ download: |
23
+ import json
24
+
25
+ from tqdm import tqdm
26
+ from utils.general import download, Path
27
+
28
+
29
+ def argoverse2yolo(set):
30
+ labels = {}
31
+ a = json.load(open(set, "rb"))
32
+ for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
33
+ img_id = annot['image_id']
34
+ img_name = a['images'][img_id]['name']
35
+ img_label_name = img_name[:-3] + "txt"
36
+
37
+ cls = annot['category_id'] # instance class id
38
+ x_center, y_center, width, height = annot['bbox']
39
+ x_center = (x_center + width / 2) / 1920.0 # offset and scale
40
+ y_center = (y_center + height / 2) / 1200.0 # offset and scale
41
+ width /= 1920.0 # scale
42
+ height /= 1200.0 # scale
43
+
44
+ img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
45
+ if not img_dir.exists():
46
+ img_dir.mkdir(parents=True, exist_ok=True)
47
+
48
+ k = str(img_dir / img_label_name)
49
+ if k not in labels:
50
+ labels[k] = []
51
+ labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
52
+
53
+ for k in labels:
54
+ with open(k, "w") as f:
55
+ f.writelines(labels[k])
56
+
57
+
58
+ # Download
59
+ dir = Path('../datasets/Argoverse') # dataset root dir
60
+ urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
61
+ download(urls, dir=dir, delete=False)
62
+
63
+ # Convert
64
+ annotations_dir = 'Argoverse-HD/annotations/'
65
+ (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
66
+ for d in "train.json", "val.json":
67
+ argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
face_detector/data/GlobalWheat2020.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Global Wheat 2020 dataset http://www.global-wheat.com/
3
+ # Example usage: python train.py --data GlobalWheat2020.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── GlobalWheat2020 ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/GlobalWheat2020 # dataset root dir
12
+ train: # train images (relative to 'path') 3422 images
13
+ - images/arvalis_1
14
+ - images/arvalis_2
15
+ - images/arvalis_3
16
+ - images/ethz_1
17
+ - images/rres_1
18
+ - images/inrae_1
19
+ - images/usask_1
20
+ val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
21
+ - images/ethz_1
22
+ test: # test images (optional) 1276 images
23
+ - images/utokyo_1
24
+ - images/utokyo_2
25
+ - images/nau_1
26
+ - images/uq_1
27
+
28
+ # Classes
29
+ nc: 1 # number of classes
30
+ names: ['wheat_head'] # class names
31
+
32
+
33
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
34
+ download: |
35
+ from utils.general import download, Path
36
+
37
+ # Download
38
+ dir = Path(yaml['path']) # dataset root dir
39
+ urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
40
+ 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
41
+ download(urls, dir=dir)
42
+
43
+ # Make Directories
44
+ for p in 'annotations', 'images', 'labels':
45
+ (dir / p).mkdir(parents=True, exist_ok=True)
46
+
47
+ # Move
48
+ for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
49
+ 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
50
+ (dir / p).rename(dir / 'images' / p) # move to /images
51
+ f = (dir / p).with_suffix('.json') # json file
52
+ if f.exists():
53
+ f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
face_detector/data/Objects365.yaml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Objects365 dataset https://www.objects365.org/
3
+ # Example usage: python train.py --data Objects365.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── Objects365 ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/Objects365 # dataset root dir
12
+ train: images/train # train images (relative to 'path') 1742289 images
13
+ val: images/val # val images (relative to 'path') 5570 images
14
+ test: # test images (optional)
15
+
16
+ # Classes
17
+ nc: 365 # number of classes
18
+ names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup',
19
+ 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book',
20
+ 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag',
21
+ 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV',
22
+ 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle',
23
+ 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird',
24
+ 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck',
25
+ 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning',
26
+ 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife',
27
+ 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock',
28
+ 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish',
29
+ 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan',
30
+ 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard',
31
+ 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign',
32
+ 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat',
33
+ 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard',
34
+ 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry',
35
+ 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks',
36
+ 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors',
37
+ 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape',
38
+ 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck',
39
+ 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette',
40
+ 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket',
41
+ 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine',
42
+ 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine',
43
+ 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon',
44
+ 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse',
45
+ 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball',
46
+ 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin',
47
+ 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts',
48
+ 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit',
49
+ 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD',
50
+ 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder',
51
+ 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips',
52
+ 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab',
53
+ 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal',
54
+ 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart',
55
+ 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French',
56
+ 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell',
57
+ 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil',
58
+ 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis']
59
+
60
+
61
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
62
+ download: |
63
+ from pycocotools.coco import COCO
64
+ from tqdm import tqdm
65
+
66
+ from utils.general import download, Path
67
+
68
+ # Make Directories
69
+ dir = Path(yaml['path']) # dataset root dir
70
+ for p in 'images', 'labels':
71
+ (dir / p).mkdir(parents=True, exist_ok=True)
72
+ for q in 'train', 'val':
73
+ (dir / p / q).mkdir(parents=True, exist_ok=True)
74
+
75
+ # Download
76
+ url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/"
77
+ download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json
78
+ download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train',
79
+ curl=True, delete=False, threads=8)
80
+
81
+ # Move
82
+ train = dir / 'images' / 'train'
83
+ for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'):
84
+ f.rename(train / f.name) # move to /images/train
85
+
86
+ # Labels
87
+ coco = COCO(dir / 'zhiyuan_objv2_train.json')
88
+ names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
89
+ for cid, cat in enumerate(names):
90
+ catIds = coco.getCatIds(catNms=[cat])
91
+ imgIds = coco.getImgIds(catIds=catIds)
92
+ for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
93
+ width, height = im["width"], im["height"]
94
+ path = Path(im["file_name"]) # image filename
95
+ try:
96
+ with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file:
97
+ annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
98
+ for a in coco.loadAnns(annIds):
99
+ x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
100
+ x, y = x + w / 2, y + h / 2 # xy to center
101
+ file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n")
102
+
103
+ except Exception as e:
104
+ print(e)
face_detector/data/SKU-110K.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19
3
+ # Example usage: python train.py --data SKU-110K.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── SKU-110K ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/SKU-110K # dataset root dir
12
+ train: train.txt # train images (relative to 'path') 8219 images
13
+ val: val.txt # val images (relative to 'path') 588 images
14
+ test: test.txt # test images (optional) 2936 images
15
+
16
+ # Classes
17
+ nc: 1 # number of classes
18
+ names: ['object'] # class names
19
+
20
+
21
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
22
+ download: |
23
+ import shutil
24
+ from tqdm import tqdm
25
+ from utils.general import np, pd, Path, download, xyxy2xywh
26
+
27
+ # Download
28
+ dir = Path(yaml['path']) # dataset root dir
29
+ parent = Path(dir.parent) # download dir
30
+ urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
31
+ download(urls, dir=parent, delete=False)
32
+
33
+ # Rename directories
34
+ if dir.exists():
35
+ shutil.rmtree(dir)
36
+ (parent / 'SKU110K_fixed').rename(dir) # rename dir
37
+ (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
38
+
39
+ # Convert labels
40
+ names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
41
+ for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
42
+ x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
43
+ images, unique_images = x[:, 0], np.unique(x[:, 0])
44
+ with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
45
+ f.writelines(f'./images/{s}\n' for s in unique_images)
46
+ for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
47
+ cls = 0 # single-class dataset
48
+ with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
49
+ for r in x[images == im]:
50
+ w, h = r[6], r[7] # image width, height
51
+ xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
52
+ f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
face_detector/data/VOC.yaml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC
3
+ # Example usage: python train.py --data VOC.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── VOC ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/VOC
12
+ train: # train images (relative to 'path') 16551 images
13
+ - images/train2012
14
+ - images/train2007
15
+ - images/val2012
16
+ - images/val2007
17
+ val: # val images (relative to 'path') 4952 images
18
+ - images/test2007
19
+ test: # test images (optional)
20
+ - images/test2007
21
+
22
+ # Classes
23
+ nc: 20 # number of classes
24
+ names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
25
+ 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names
26
+
27
+
28
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
29
+ download: |
30
+ import xml.etree.ElementTree as ET
31
+
32
+ from tqdm import tqdm
33
+ from utils.general import download, Path
34
+
35
+
36
+ def convert_label(path, lb_path, year, image_id):
37
+ def convert_box(size, box):
38
+ dw, dh = 1. / size[0], 1. / size[1]
39
+ x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
40
+ return x * dw, y * dh, w * dw, h * dh
41
+
42
+ in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
43
+ out_file = open(lb_path, 'w')
44
+ tree = ET.parse(in_file)
45
+ root = tree.getroot()
46
+ size = root.find('size')
47
+ w = int(size.find('width').text)
48
+ h = int(size.find('height').text)
49
+
50
+ for obj in root.iter('object'):
51
+ cls = obj.find('name').text
52
+ if cls in yaml['names'] and not int(obj.find('difficult').text) == 1:
53
+ xmlbox = obj.find('bndbox')
54
+ bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
55
+ cls_id = yaml['names'].index(cls) # class id
56
+ out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
57
+
58
+
59
+ # Download
60
+ dir = Path(yaml['path']) # dataset root dir
61
+ url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
62
+ urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
63
+ url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
64
+ url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
65
+ download(urls, dir=dir / 'images', delete=False)
66
+
67
+ # Convert
68
+ path = dir / f'images/VOCdevkit'
69
+ for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
70
+ imgs_path = dir / 'images' / f'{image_set}{year}'
71
+ lbs_path = dir / 'labels' / f'{image_set}{year}'
72
+ imgs_path.mkdir(exist_ok=True, parents=True)
73
+ lbs_path.mkdir(exist_ok=True, parents=True)
74
+
75
+ image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split()
76
+ for id in tqdm(image_ids, desc=f'{image_set}{year}'):
77
+ f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
78
+ lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
79
+ f.rename(imgs_path / f.name) # move image
80
+ convert_label(path, lb_path, year, id) # convert labels to YOLO format
face_detector/data/VisDrone.yaml ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset
3
+ # Example usage: python train.py --data VisDrone.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── VisDrone ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/VisDrone # dataset root dir
12
+ train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
13
+ val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
14
+ test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
15
+
16
+ # Classes
17
+ nc: 10 # number of classes
18
+ names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor']
19
+
20
+
21
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
22
+ download: |
23
+ from utils.general import download, os, Path
24
+
25
+ def visdrone2yolo(dir):
26
+ from PIL import Image
27
+ from tqdm import tqdm
28
+
29
+ def convert_box(size, box):
30
+ # Convert VisDrone box to YOLO xywh box
31
+ dw = 1. / size[0]
32
+ dh = 1. / size[1]
33
+ return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
34
+
35
+ (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
36
+ pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
37
+ for f in pbar:
38
+ img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
39
+ lines = []
40
+ with open(f, 'r') as file: # read annotation.txt
41
+ for row in [x.split(',') for x in file.read().strip().splitlines()]:
42
+ if row[4] == '0': # VisDrone 'ignored regions' class 0
43
+ continue
44
+ cls = int(row[5]) - 1
45
+ box = convert_box(img_size, tuple(map(int, row[:4])))
46
+ lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
47
+ with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
48
+ fl.writelines(lines) # write label.txt
49
+
50
+
51
+ # Download
52
+ dir = Path(yaml['path']) # dataset root dir
53
+ urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
54
+ 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
55
+ 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
56
+ 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
57
+ download(urls, dir=dir)
58
+
59
+ # Convert
60
+ for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
61
+ visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
face_detector/data/coco.yaml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # COCO 2017 dataset http://cocodataset.org
3
+ # Example usage: python train.py --data coco.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── coco ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/coco # dataset root dir
12
+ train: train2017.txt # train images (relative to 'path') 118287 images
13
+ val: val2017.txt # train images (relative to 'path') 5000 images
14
+ test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
15
+
16
+ # Classes
17
+ nc: 80 # number of classes
18
+ names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
19
+ 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
20
+ 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
21
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
22
+ 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
23
+ 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
24
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
25
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
26
+ 'hair drier', 'toothbrush'] # class names
27
+
28
+
29
+ # Download script/URL (optional)
30
+ download: |
31
+ from utils.general import download, Path
32
+
33
+ # Download labels
34
+ segments = False # segment or box labels
35
+ dir = Path(yaml['path']) # dataset root dir
36
+ url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
37
+ urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
38
+ download(urls, dir=dir.parent)
39
+
40
+ # Download data
41
+ urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
42
+ 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
43
+ 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
44
+ download(urls, dir=dir / 'images', threads=3)
face_detector/data/coco128.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
3
+ # Example usage: python train.py --data coco128.yaml
4
+ # parent
5
+ # β”œβ”€β”€ yolov5
6
+ # └── datasets
7
+ # └── coco128 ← downloads here
8
+
9
+
10
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11
+ path: ../datasets/coco128 # dataset root dir
12
+ train: images/train2017 # train images (relative to 'path') 128 images
13
+ val: images/train2017 # val images (relative to 'path') 128 images
14
+ test: # test images (optional)
15
+
16
+ # Classes
17
+ nc: 80 # number of classes
18
+ names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
19
+ 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
20
+ 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
21
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
22
+ 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
23
+ 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
24
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
25
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
26
+ 'hair drier', 'toothbrush'] # class names
27
+
28
+
29
+ # Download script/URL (optional)
30
+ download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
face_detector/data/hyps/hyp.finetune.yaml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Hyperparameters for VOC finetuning
3
+ # python train.py --batch 64 --weights yolov5m.pt --data VOC.yaml --img 512 --epochs 50
4
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5
+
6
+ # Hyperparameter Evolution Results
7
+ # Generations: 306
8
+ # P R mAP.5 mAP.5:.95 box obj cls
9
+ # Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146
10
+
11
+ lr0: 0.0032
12
+ lrf: 0.12
13
+ momentum: 0.843
14
+ weight_decay: 0.00036
15
+ warmup_epochs: 2.0
16
+ warmup_momentum: 0.5
17
+ warmup_bias_lr: 0.05
18
+ box: 0.0296
19
+ cls: 0.243
20
+ cls_pw: 0.631
21
+ obj: 0.301
22
+ obj_pw: 0.911
23
+ iou_t: 0.2
24
+ anchor_t: 2.91
25
+ # anchors: 3.63
26
+ fl_gamma: 0.0
27
+ hsv_h: 0.0138
28
+ hsv_s: 0.664
29
+ hsv_v: 0.464
30
+ degrees: 0.373
31
+ translate: 0.245
32
+ scale: 0.898
33
+ shear: 0.602
34
+ perspective: 0.0
35
+ flipud: 0.00856
36
+ fliplr: 0.5
37
+ mosaic: 1.0
38
+ mixup: 0.243
39
+ copy_paste: 0.0
face_detector/data/hyps/hyp.finetune_objects365.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ lr0: 0.00258
4
+ lrf: 0.17
5
+ momentum: 0.779
6
+ weight_decay: 0.00058
7
+ warmup_epochs: 1.33
8
+ warmup_momentum: 0.86
9
+ warmup_bias_lr: 0.0711
10
+ box: 0.0539
11
+ cls: 0.299
12
+ cls_pw: 0.825
13
+ obj: 0.632
14
+ obj_pw: 1.0
15
+ iou_t: 0.2
16
+ anchor_t: 3.44
17
+ anchors: 3.2
18
+ fl_gamma: 0.0
19
+ hsv_h: 0.0188
20
+ hsv_s: 0.704
21
+ hsv_v: 0.36
22
+ degrees: 0.0
23
+ translate: 0.0902
24
+ scale: 0.491
25
+ shear: 0.0
26
+ perspective: 0.0
27
+ flipud: 0.0
28
+ fliplr: 0.5
29
+ mosaic: 1.0
30
+ mixup: 0.0
31
+ copy_paste: 0.0
face_detector/data/hyps/hyp.scratch-high.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Hyperparameters for high-augmentation COCO training from scratch
3
+ # python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
4
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8
+ momentum: 0.937 # SGD momentum/Adam beta1
9
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
10
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
11
+ warmup_momentum: 0.8 # warmup initial momentum
12
+ warmup_bias_lr: 0.1 # warmup initial bias lr
13
+ box: 0.05 # box loss gain
14
+ cls: 0.3 # cls loss gain
15
+ cls_pw: 1.0 # cls BCELoss positive_weight
16
+ obj: 0.7 # obj loss gain (scale with pixels)
17
+ obj_pw: 1.0 # obj BCELoss positive_weight
18
+ iou_t: 0.20 # IoU training threshold
19
+ anchor_t: 4.0 # anchor-multiple threshold
20
+ # anchors: 3 # anchors per output layer (0 to ignore)
21
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25
+ degrees: 0.0 # image rotation (+/- deg)
26
+ translate: 0.1 # image translation (+/- fraction)
27
+ scale: 0.9 # image scale (+/- gain)
28
+ shear: 0.0 # image shear (+/- deg)
29
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30
+ flipud: 0.0 # image flip up-down (probability)
31
+ fliplr: 0.5 # image flip left-right (probability)
32
+ mosaic: 1.0 # image mosaic (probability)
33
+ mixup: 0.1 # image mixup (probability)
34
+ copy_paste: 0.1 # segment copy-paste (probability)
face_detector/data/hyps/hyp.scratch-low.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Hyperparameters for low-augmentation COCO training from scratch
3
+ # python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear
4
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
8
+ momentum: 0.937 # SGD momentum/Adam beta1
9
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
10
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
11
+ warmup_momentum: 0.8 # warmup initial momentum
12
+ warmup_bias_lr: 0.1 # warmup initial bias lr
13
+ box: 0.05 # box loss gain
14
+ cls: 0.5 # cls loss gain
15
+ cls_pw: 1.0 # cls BCELoss positive_weight
16
+ obj: 1.0 # obj loss gain (scale with pixels)
17
+ obj_pw: 1.0 # obj BCELoss positive_weight
18
+ iou_t: 0.20 # IoU training threshold
19
+ anchor_t: 4.0 # anchor-multiple threshold
20
+ # anchors: 3 # anchors per output layer (0 to ignore)
21
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25
+ degrees: 0.0 # image rotation (+/- deg)
26
+ translate: 0.1 # image translation (+/- fraction)
27
+ scale: 0.5 # image scale (+/- gain)
28
+ shear: 0.0 # image shear (+/- deg)
29
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30
+ flipud: 0.0 # image flip up-down (probability)
31
+ fliplr: 0.5 # image flip left-right (probability)
32
+ mosaic: 1.0 # image mosaic (probability)
33
+ mixup: 0.0 # image mixup (probability)
34
+ copy_paste: 0.0 # segment copy-paste (probability)
face_detector/data/hyps/hyp.scratch.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Hyperparameters for COCO training from scratch
3
+ # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
4
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
8
+ momentum: 0.937 # SGD momentum/Adam beta1
9
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
10
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
11
+ warmup_momentum: 0.8 # warmup initial momentum
12
+ warmup_bias_lr: 0.1 # warmup initial bias lr
13
+ box: 0.05 # box loss gain
14
+ cls: 0.5 # cls loss gain
15
+ cls_pw: 1.0 # cls BCELoss positive_weight
16
+ obj: 1.0 # obj loss gain (scale with pixels)
17
+ obj_pw: 1.0 # obj BCELoss positive_weight
18
+ iou_t: 0.20 # IoU training threshold
19
+ anchor_t: 4.0 # anchor-multiple threshold
20
+ # anchors: 3 # anchors per output layer (0 to ignore)
21
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25
+ degrees: 0.0 # image rotation (+/- deg)
26
+ translate: 0.1 # image translation (+/- fraction)
27
+ scale: 0.5 # image scale (+/- gain)
28
+ shear: 0.0 # image shear (+/- deg)
29
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30
+ flipud: 0.0 # image flip up-down (probability)
31
+ fliplr: 0.5 # image flip left-right (probability)
32
+ mosaic: 1.0 # image mosaic (probability)
33
+ mixup: 0.0 # image mixup (probability)
34
+ copy_paste: 0.0 # segment copy-paste (probability)
face_detector/data/xView.yaml ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # xView 2018 dataset https://challenge.xviewdataset.org
3
+ # -------- DOWNLOAD DATA MANUALLY from URL above and unzip to 'datasets/xView' before running train command! --------
4
+ # Example usage: python train.py --data xView.yaml
5
+ # parent
6
+ # β”œβ”€β”€ yolov5
7
+ # └── datasets
8
+ # └── xView ← downloads here
9
+
10
+
11
+ # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
+ path: ../datasets/xView # dataset root dir
13
+ train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images
14
+ val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images
15
+
16
+ # Classes
17
+ nc: 60 # number of classes
18
+ names: ['Fixed-wing Aircraft', 'Small Aircraft', 'Cargo Plane', 'Helicopter', 'Passenger Vehicle', 'Small Car', 'Bus',
19
+ 'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck w/Box', 'Truck Tractor', 'Trailer',
20
+ 'Truck w/Flatbed', 'Truck w/Liquid', 'Crane Truck', 'Railway Vehicle', 'Passenger Car', 'Cargo Car',
21
+ 'Flat Car', 'Tank car', 'Locomotive', 'Maritime Vessel', 'Motorboat', 'Sailboat', 'Tugboat', 'Barge',
22
+ 'Fishing Vessel', 'Ferry', 'Yacht', 'Container Ship', 'Oil Tanker', 'Engineering Vehicle', 'Tower crane',
23
+ 'Container Crane', 'Reach Stacker', 'Straddle Carrier', 'Mobile Crane', 'Dump Truck', 'Haul Truck',
24
+ 'Scraper/Tractor', 'Front loader/Bulldozer', 'Excavator', 'Cement Mixer', 'Ground Grader', 'Hut/Tent', 'Shed',
25
+ 'Building', 'Aircraft Hangar', 'Damaged Building', 'Facility', 'Construction Site', 'Vehicle Lot', 'Helipad',
26
+ 'Storage Tank', 'Shipping container lot', 'Shipping Container', 'Pylon', 'Tower'] # class names
27
+
28
+
29
+ # Download script/URL (optional) ---------------------------------------------------------------------------------------
30
+ download: |
31
+ import json
32
+ import os
33
+ from pathlib import Path
34
+
35
+ import numpy as np
36
+ from PIL import Image
37
+ from tqdm import tqdm
38
+
39
+ from utils.datasets import autosplit
40
+ from utils.general import download, xyxy2xywhn
41
+
42
+
43
+ def convert_labels(fname=Path('xView/xView_train.geojson')):
44
+ # Convert xView geoJSON labels to YOLO format
45
+ path = fname.parent
46
+ with open(fname) as f:
47
+ print(f'Loading {fname}...')
48
+ data = json.load(f)
49
+
50
+ # Make dirs
51
+ labels = Path(path / 'labels' / 'train')
52
+ os.system(f'rm -rf {labels}')
53
+ labels.mkdir(parents=True, exist_ok=True)
54
+
55
+ # xView classes 11-94 to 0-59
56
+ xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11,
57
+ 12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,
58
+ 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,
59
+ 47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]
60
+
61
+ shapes = {}
62
+ for feature in tqdm(data['features'], desc=f'Converting {fname}'):
63
+ p = feature['properties']
64
+ if p['bounds_imcoords']:
65
+ id = p['image_id']
66
+ file = path / 'train_images' / id
67
+ if file.exists(): # 1395.tif missing
68
+ try:
69
+ box = np.array([int(num) for num in p['bounds_imcoords'].split(",")])
70
+ assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'
71
+ cls = p['type_id']
72
+ cls = xview_class2index[int(cls)] # xView class to 0-60
73
+ assert 59 >= cls >= 0, f'incorrect class index {cls}'
74
+
75
+ # Write YOLO label
76
+ if id not in shapes:
77
+ shapes[id] = Image.open(file).size
78
+ box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)
79
+ with open((labels / id).with_suffix('.txt'), 'a') as f:
80
+ f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt
81
+ except Exception as e:
82
+ print(f'WARNING: skipping one label for {file}: {e}')
83
+
84
+
85
+ # Download manually from https://challenge.xviewdataset.org
86
+ dir = Path(yaml['path']) # dataset root dir
87
+ # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels
88
+ # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images
89
+ # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels)
90
+ # download(urls, dir=dir, delete=False)
91
+
92
+ # Convert labels
93
+ convert_labels(dir / 'xView_train.geojson')
94
+
95
+ # Move images
96
+ images = Path(dir / 'images')
97
+ images.mkdir(parents=True, exist_ok=True)
98
+ Path(dir / 'train_images').rename(dir / 'images' / 'train')
99
+ Path(dir / 'val_images').rename(dir / 'images' / 'val')
100
+
101
+ # Split
102
+ autosplit(dir / 'images' / 'train')
face_detector/detect.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ """
3
+ Run inference on images, videos, directories, streams, etc.
4
+ Usage:
5
+ $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
6
+ img.jpg # image
7
+ vid.mp4 # video
8
+ path/ # directory
9
+ path/*.jpg # glob
10
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
11
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
12
+ """
13
+
14
+ import argparse
15
+ import os
16
+ import platform
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import torch
23
+ import torch.backends.cudnn as cudnn
24
+
25
+ FILE = Path(__file__).resolve()
26
+ ROOT = FILE.parents[0] # YOLOv5 root directory
27
+ if str(ROOT) not in sys.path:
28
+ sys.path.append(str(ROOT)) # add ROOT to PATH
29
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
30
+
31
+ from models.experimental import attempt_load
32
+ from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
33
+ from utils.general import (LOGGER, apply_classifier, check_file, check_img_size, check_imshow, check_requirements,
34
+ check_suffix, colorstr, increment_path, non_max_suppression, print_args, scale_coords,
35
+ strip_optimizer, xyxy2xywh)
36
+ from utils.plots import Annotator, colors
37
+ from utils.torch_utils import load_classifier, select_device, time_sync
38
+ import yaml
39
+
40
+ @torch.no_grad()
41
+ def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s)
42
+ source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
43
+ imgsz=640, # inference size (pixels)
44
+ conf_thres=0.25, # confidence threshold
45
+ iou_thres=0.45, # NMS IOU threshold
46
+ max_det=1000, # maximum detections per image
47
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
48
+ view_img=False, # show results
49
+ save_txt=False, # save results to *.txt
50
+ save_conf=False, # save confidences in --save-txt labels
51
+ save_crop=False, # save cropped prediction boxes
52
+ nosave=False, # do not save images/videos
53
+ classes=None, # filter by class: --class 0, or --class 0 2 3
54
+ agnostic_nms=False, # class-agnostic NMS
55
+ augment=False, # augmented inference
56
+ visualize=False, # visualize features
57
+ update=False, # update all models
58
+ project=ROOT / 'runs/detect', # save results to project/name
59
+ name='exp', # save results to project/name
60
+ exist_ok=False, # existing project/name ok, do not increment
61
+ line_thickness=3, # bounding box thickness (pixels)
62
+ hide_labels=False, # hide labels
63
+ hide_conf=False, # hide confidences
64
+ half=False, # use FP16 half-precision inference
65
+ dnn=False, # use OpenCV DNN for ONNX inference
66
+ ):
67
+ source = str(source)
68
+ save_img = not nosave and not source.endswith('.txt') # save inference images
69
+ is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
70
+ is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
71
+ webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
72
+ if is_url and is_file:
73
+ source = check_file(source) # download
74
+
75
+ # Directories
76
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
77
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
78
+
79
+ # Initialize
80
+ device = select_device(device)
81
+ half &= device.type != 'cpu' # half precision only supported on CUDA
82
+
83
+ # Load model
84
+ w = str(weights[0] if isinstance(weights, list) else weights)
85
+ classify, suffix, suffixes = False, Path(w).suffix.lower(), ['.pt', '.onnx', '.tflite', '.pb', '']
86
+ check_suffix(w, suffixes) # check weights have acceptable suffix
87
+ pt, onnx, tflite, pb, saved_model = (suffix == x for x in suffixes) # backend booleans
88
+ stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults
89
+ if pt:
90
+ model = torch.jit.load(w) if 'torchscript' in w else attempt_load(weights, map_location=device)
91
+ stride = int(model.stride.max()) # model stride
92
+ names = model.module.names if hasattr(model, 'module') else model.names # get class names
93
+ if half:
94
+ model.half() # to FP16
95
+ if classify: # second-stage classifier
96
+ modelc = load_classifier(name='resnet50', n=2) # initialize
97
+ modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
98
+ elif onnx:
99
+ if dnn:
100
+ check_requirements(('opencv-python>=4.5.4',))
101
+ net = cv2.dnn.readNetFromONNX(w)
102
+ else:
103
+ check_requirements(('onnx', 'onnxruntime-gpu' if torch.has_cuda else 'onnxruntime'))
104
+ import onnxruntime
105
+ session = onnxruntime.InferenceSession(w, None)
106
+ else: # TensorFlow models
107
+ import tensorflow as tf
108
+ if pb: # https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
109
+ def wrap_frozen_graph(gd, inputs, outputs):
110
+ x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped import
111
+ return x.prune(tf.nest.map_structure(x.graph.as_graph_element, inputs),
112
+ tf.nest.map_structure(x.graph.as_graph_element, outputs))
113
+
114
+ graph_def = tf.Graph().as_graph_def()
115
+ graph_def.ParseFromString(open(w, 'rb').read())
116
+ frozen_func = wrap_frozen_graph(gd=graph_def, inputs="x:0", outputs="Identity:0")
117
+ elif saved_model:
118
+ model = tf.keras.models.load_model(w)
119
+ elif tflite:
120
+ if "edgetpu" in w: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
121
+ import tflite_runtime.interpreter as tflri
122
+ delegate = {'Linux': 'libedgetpu.so.1', # install libedgetpu https://coral.ai/software/#edgetpu-runtime
123
+ 'Darwin': 'libedgetpu.1.dylib',
124
+ 'Windows': 'edgetpu.dll'}[platform.system()]
125
+ interpreter = tflri.Interpreter(model_path=w, experimental_delegates=[tflri.load_delegate(delegate)])
126
+ else:
127
+ interpreter = tf.lite.Interpreter(model_path=w) # load TFLite model
128
+ interpreter.allocate_tensors() # allocate
129
+ input_details = interpreter.get_input_details() # inputs
130
+ output_details = interpreter.get_output_details() # outputs
131
+ int8 = input_details[0]['dtype'] == np.uint8 # is TFLite quantized uint8 model
132
+ imgsz = check_img_size(imgsz, s=stride) # check image size
133
+
134
+ # Dataloader
135
+ if webcam:
136
+ view_img = check_imshow()
137
+ cudnn.benchmark = True # set True to speed up constant image size inference
138
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
139
+ bs = len(dataset) # batch_size
140
+ else:
141
+ dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
142
+ bs = 1 # batch_size
143
+ vid_path, vid_writer = [None] * bs, [None] * bs
144
+
145
+ # Run inference
146
+ if pt and device.type != 'cpu':
147
+ model(torch.zeros(1, 3,imgsz,imgsz).to(device).type_as(next(model.parameters()))) # run once
148
+ dt, seen = [0.0, 0.0, 0.0], 0
149
+
150
+ counter = -1
151
+ data = {}
152
+
153
+ for path, img, im0s, vid_cap, s in dataset:
154
+ counter += 1
155
+ coordinates = list()
156
+ t1 = time_sync()
157
+ if onnx:
158
+ img = img.astype('float32')
159
+ else:
160
+ img = torch.from_numpy(img).to(device)
161
+ img = img.half() if half else img.float() # uint8 to fp16/32
162
+ img /= 255 # 0 - 255 to 0.0 - 1.0
163
+ if len(img.shape) == 3:
164
+ img = img[None] # expand for batch dim
165
+ t2 = time_sync()
166
+ dt[0] += t2 - t1
167
+
168
+ # Inference
169
+ if pt:
170
+ visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
171
+ pred = model(img, augment=augment, visualize=visualize)[0]
172
+ elif onnx:
173
+ if dnn:
174
+ net.setInput(img)
175
+ pred = torch.tensor(net.forward())
176
+ else:
177
+ pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
178
+ else: # tensorflow model (tflite, pb, saved_model)
179
+ imn = img.permute(0, 2, 3, 1).cpu().numpy() # image in numpy
180
+ if pb:
181
+ pred = frozen_func(x=tf.constant(imn)).numpy()
182
+ elif saved_model:
183
+ pred = model(imn, training=False).numpy()
184
+ elif tflite:
185
+ if int8:
186
+ scale, zero_point = input_details[0]['quantization']
187
+ imn = (imn / scale + zero_point).astype(np.uint8) # de-scale
188
+ interpreter.set_tensor(input_details[0]['index'], imn)
189
+ interpreter.invoke()
190
+ pred = interpreter.get_tensor(output_details[0]['index'])
191
+ if int8:
192
+ scale, zero_point = output_details[0]['quantization']
193
+ pred = (pred.astype(np.float32) - zero_point) * scale # re-scale
194
+ pred[..., 0] *= imgsz[1] # x
195
+ pred[..., 1] *= imgsz[0] # y
196
+ pred[..., 2] *= imgsz[1] # w
197
+ pred[..., 3] *= imgsz[0] # h
198
+ pred = torch.tensor(pred)
199
+ t3 = time_sync()
200
+ dt[1] += t3 - t2
201
+
202
+ # NMS
203
+ pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
204
+ dt[2] += time_sync() - t3
205
+
206
+ # Second-stage classifier (optional)
207
+ if classify:
208
+ pred = apply_classifier(pred, modelc, img, im0s)
209
+
210
+ # Process predictions
211
+ for i, det in enumerate(pred): # per image
212
+ seen += 1
213
+ if webcam: # batch_size >= 1
214
+ p, im0, frame = path[i], im0s[i].copy(), dataset.count
215
+ s += f'{i}: '
216
+ else:
217
+ p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
218
+
219
+ p = Path(p) # to Path
220
+ save_path = str(save_dir / p.name) # img.jpg
221
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
222
+ s += '%gx%g ' % img.shape[2:] # print string
223
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
224
+ imc = im0.copy() if save_crop else im0 # for save_crop
225
+ annotator = Annotator(im0, line_width=line_thickness, example=str(names))
226
+ if len(det):
227
+ # Rescale boxes from img_size to im0 size
228
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
229
+
230
+ # Print results
231
+ for c in det[:, -1].unique():
232
+ n = (det[:, -1] == c).sum() # detections per class
233
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
234
+
235
+ # Write results
236
+ for *xyxy, conf, cls in reversed(det):
237
+ if save_txt: # Write to file
238
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
239
+ coordinates.append(xywh)
240
+
241
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
242
+ with open(txt_path + '.txt', 'a') as f:
243
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
244
+
245
+ if save_img or save_crop or view_img: # Add bbox to image
246
+ c = int(cls) # integer class
247
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
248
+ annotator.box_label(xyxy, label, color=colors(c, True))
249
+
250
+ data.update({f"img{counter}": {"name": p.name, "coordinates": coordinates}})
251
+
252
+ # Print time (inference-only)
253
+ LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
254
+
255
+ # Stream results
256
+ im0 = annotator.result()
257
+ if view_img:
258
+ cv2.imshow(str(p), im0)
259
+ cv2.waitKey(1) # 1 millisecond
260
+
261
+ # Save results (image with detections)
262
+ if save_img:
263
+ if dataset.mode == 'image':
264
+ cv2.imwrite(save_path, im0)
265
+ else: # 'video' or 'stream'
266
+ if vid_path[i] != save_path: # new video
267
+ vid_path[i] = save_path
268
+ if isinstance(vid_writer[i], cv2.VideoWriter):
269
+ vid_writer[i].release() # release previous video writer
270
+ if vid_cap: # video
271
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
272
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
273
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
274
+ else: # stream
275
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
276
+ save_path += '.mp4'
277
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
278
+ vid_writer[i].write(im0)
279
+
280
+
281
+ import json
282
+ with open('test.json', 'w', encoding='utf-8') as f:
283
+ json.dump(data, f, ensure_ascii=False, indent=4)
284
+ # Print results
285
+ t = tuple(x / seen * 1E3 for x in dt) # speeds per image
286
+ #LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
287
+ if save_txt or save_img:
288
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
289
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
290
+ if update:
291
+ strip_optimizer(weights) # update model (to fix SourceChangeWarning)
292
+
293
+
294
+ def parse_opt():
295
+ parser = argparse.ArgumentParser()
296
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
297
+ parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
298
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
299
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
300
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
301
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
302
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
303
+ parser.add_argument('--view-img', action='store_true', help='show results')
304
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
305
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
306
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
307
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
308
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
309
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
310
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
311
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
312
+ parser.add_argument('--update', action='store_true', help='update all models')
313
+ parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
314
+ parser.add_argument('--name', default='exp', help='save results to project/name')
315
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
316
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
317
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
318
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
319
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
320
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
321
+ opt = parser.parse_args()
322
+
323
+ params = None
324
+ with open("params.yaml", 'r') as fd:
325
+ params = yaml.safe_load(fd)
326
+
327
+ opt.imgsz = params['test']['image_size']
328
+ opt.conf_thres = params['test']['conf']
329
+
330
+ opt.imgsz *= 2 if len(str(opt.imgsz)) == 1 else 1 # expand
331
+ print_args(FILE.stem, opt)
332
+ return opt
333
+
334
+
335
+ def main(opt):
336
+ check_requirements(exclude=('tensorboard', 'thop'))
337
+ run(**vars(opt))
338
+
339
+
340
+ if __name__ == "__main__":
341
+ opt = parse_opt()
342
+ main(opt)
face_detector/export.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ """
3
+ Export a YOLOv5 PyTorch model to TorchScript, ONNX, CoreML, TensorFlow (saved_model, pb, TFLite, TF.js,) formats
4
+ TensorFlow exports authored by https://github.com/zldrobit
5
+
6
+ Usage:
7
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx coreml saved_model pb tflite tfjs
8
+
9
+ Inference:
10
+ $ python path/to/detect.py --weights yolov5s.pt
11
+ yolov5s.onnx (must export with --dynamic)
12
+ yolov5s_saved_model
13
+ yolov5s.pb
14
+ yolov5s.tflite
15
+
16
+ TensorFlow.js:
17
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
18
+ $ npm install
19
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
20
+ $ npm start
21
+ """
22
+
23
+ import argparse
24
+ import os
25
+ import subprocess
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ from torch.utils.mobile_optimizer import optimize_for_mobile
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
+ from models.common import Conv
41
+ from models.experimental import attempt_load
42
+ from models.yolo import Detect
43
+ from utils.activations import SiLU
44
+ from utils.datasets import LoadImages
45
+ from utils.general import check_dataset, check_img_size, check_requirements, colorstr, file_size, print_args, \
46
+ url2file, LOGGER
47
+ from utils.torch_utils import select_device
48
+
49
+
50
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
51
+ # YOLOv5 TorchScript model export
52
+ try:
53
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
54
+ f = file.with_suffix('.torchscript.pt')
55
+
56
+ ts = torch.jit.trace(model, im, strict=False)
57
+ (optimize_for_mobile(ts) if optimize else ts).save(f)
58
+
59
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
60
+ except Exception as e:
61
+ LOGGER.info(f'{prefix} export failure: {e}')
62
+
63
+
64
+ def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
65
+ # YOLOv5 ONNX export
66
+ try:
67
+ check_requirements(('onnx',))
68
+ import onnx
69
+
70
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
71
+ f = file.with_suffix('.onnx')
72
+
73
+ torch.onnx.export(model, im, f, verbose=False, opset_version=opset,
74
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
75
+ do_constant_folding=not train,
76
+ input_names=['images'],
77
+ output_names=['output'],
78
+ dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
79
+ 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
80
+ } if dynamic else None)
81
+
82
+ # Checks
83
+ model_onnx = onnx.load(f) # load onnx model
84
+ onnx.checker.check_model(model_onnx) # check onnx model
85
+ # LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print
86
+
87
+ # Simplify
88
+ if simplify:
89
+ try:
90
+ check_requirements(('onnx-simplifier',))
91
+ import onnxsim
92
+
93
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
94
+ model_onnx, check = onnxsim.simplify(
95
+ model_onnx,
96
+ dynamic_input_shape=dynamic,
97
+ input_shapes={'images': list(im.shape)} if dynamic else None)
98
+ assert check, 'assert check failed'
99
+ onnx.save(model_onnx, f)
100
+ except Exception as e:
101
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
102
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
103
+ LOGGER.info(f"{prefix} run --dynamic ONNX model inference with: 'python detect.py --weights {f}'")
104
+ except Exception as e:
105
+ LOGGER.info(f'{prefix} export failure: {e}')
106
+
107
+
108
+ def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
109
+ # YOLOv5 CoreML export
110
+ ct_model = None
111
+ try:
112
+ check_requirements(('coremltools',))
113
+ import coremltools as ct
114
+
115
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
116
+ f = file.with_suffix('.mlmodel')
117
+
118
+ model.train() # CoreML exports should be placed in model.train() mode
119
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
120
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255.0, bias=[0, 0, 0])])
121
+ ct_model.save(f)
122
+
123
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
124
+ except Exception as e:
125
+ LOGGER.info(f'\n{prefix} export failure: {e}')
126
+
127
+ return ct_model
128
+
129
+
130
+ def export_saved_model(model, im, file, dynamic,
131
+ tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
132
+ conf_thres=0.25, prefix=colorstr('TensorFlow saved_model:')):
133
+ # YOLOv5 TensorFlow saved_model export
134
+ keras_model = None
135
+ try:
136
+ import tensorflow as tf
137
+ from tensorflow import keras
138
+ from models.tf import TFModel, TFDetect
139
+
140
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
141
+ f = str(file).replace('.pt', '_saved_model')
142
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
143
+
144
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
145
+ im = tf.zeros((batch_size, *imgsz, 3)) # BHWC order for TensorFlow
146
+ y = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
147
+ inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
148
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
149
+ keras_model = keras.Model(inputs=inputs, outputs=outputs)
150
+ keras_model.trainable = False
151
+ keras_model.summary()
152
+ keras_model.save(f, save_format='tf')
153
+
154
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
155
+ except Exception as e:
156
+ LOGGER.info(f'\n{prefix} export failure: {e}')
157
+
158
+ return keras_model
159
+
160
+
161
+ def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
162
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
163
+ try:
164
+ import tensorflow as tf
165
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
166
+
167
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
168
+ f = file.with_suffix('.pb')
169
+
170
+ m = tf.function(lambda x: keras_model(x)) # full model
171
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
172
+ frozen_func = convert_variables_to_constants_v2(m)
173
+ frozen_func.graph.as_graph_def()
174
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
175
+
176
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
177
+ except Exception as e:
178
+ LOGGER.info(f'\n{prefix} export failure: {e}')
179
+
180
+
181
+ def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):
182
+ # YOLOv5 TensorFlow Lite export
183
+ try:
184
+ import tensorflow as tf
185
+ from models.tf import representative_dataset_gen
186
+
187
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
188
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
189
+ f = str(file).replace('.pt', '-fp16.tflite')
190
+
191
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
192
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
193
+ converter.target_spec.supported_types = [tf.float16]
194
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
195
+ if int8:
196
+ dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
197
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
198
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
199
+ converter.target_spec.supported_types = []
200
+ converter.inference_input_type = tf.uint8 # or tf.int8
201
+ converter.inference_output_type = tf.uint8 # or tf.int8
202
+ converter.experimental_new_quantizer = False
203
+ f = str(file).replace('.pt', '-int8.tflite')
204
+
205
+ tflite_model = converter.convert()
206
+ open(f, "wb").write(tflite_model)
207
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
208
+
209
+ except Exception as e:
210
+ LOGGER.info(f'\n{prefix} export failure: {e}')
211
+
212
+
213
+ def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
214
+ # YOLOv5 TensorFlow.js export
215
+ try:
216
+ check_requirements(('tensorflowjs',))
217
+ import re
218
+ import tensorflowjs as tfjs
219
+
220
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
221
+ f = str(file).replace('.pt', '_web_model') # js dir
222
+ f_pb = file.with_suffix('.pb') # *.pb path
223
+ f_json = f + '/model.json' # *.json path
224
+
225
+ cmd = f"tensorflowjs_converter --input_format=tf_frozen_model " \
226
+ f"--output_node_names='Identity,Identity_1,Identity_2,Identity_3' {f_pb} {f}"
227
+ subprocess.run(cmd, shell=True)
228
+
229
+ json = open(f_json).read()
230
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
231
+ subst = re.sub(
232
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
233
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
234
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
235
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}',
236
+ r'{"outputs": {"Identity": {"name": "Identity"}, '
237
+ r'"Identity_1": {"name": "Identity_1"}, '
238
+ r'"Identity_2": {"name": "Identity_2"}, '
239
+ r'"Identity_3": {"name": "Identity_3"}}}',
240
+ json)
241
+ j.write(subst)
242
+
243
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
244
+ except Exception as e:
245
+ LOGGER.info(f'\n{prefix} export failure: {e}')
246
+
247
+
248
+ @torch.no_grad()
249
+ def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
250
+ weights=ROOT / 'yolov5s.pt', # weights path
251
+ imgsz=(640, 640), # image (height, width)
252
+ batch_size=1, # batch size
253
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
254
+ include=('torchscript', 'onnx', 'coreml'), # include formats
255
+ half=False, # FP16 half-precision export
256
+ inplace=False, # set YOLOv5 Detect() inplace=True
257
+ train=False, # model.train() mode
258
+ optimize=False, # TorchScript: optimize for mobile
259
+ int8=False, # CoreML/TF INT8 quantization
260
+ dynamic=False, # ONNX/TF: dynamic axes
261
+ simplify=False, # ONNX: simplify model
262
+ opset=12, # ONNX: opset version
263
+ topk_per_class=100, # TF.js NMS: topk per class to keep
264
+ topk_all=100, # TF.js NMS: topk for all classes to keep
265
+ iou_thres=0.45, # TF.js NMS: IoU threshold
266
+ conf_thres=0.25 # TF.js NMS: confidence threshold
267
+ ):
268
+ t = time.time()
269
+ include = [x.lower() for x in include]
270
+ tf_exports = list(x in include for x in ('saved_model', 'pb', 'tflite', 'tfjs')) # TensorFlow exports
271
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
272
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights)
273
+
274
+ # Load PyTorch model
275
+ device = select_device(device)
276
+ assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
277
+ model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
278
+ nc, names = model.nc, model.names # number of classes, class names
279
+
280
+ # Input
281
+ gs = int(max(model.stride)) # grid size (max stride)
282
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
283
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
284
+
285
+ # Update model
286
+ if half:
287
+ im, model = im.half(), model.half() # to FP16
288
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
289
+ for k, m in model.named_modules():
290
+ if isinstance(m, Conv): # assign export-friendly activations
291
+ if isinstance(m.act, nn.SiLU):
292
+ m.act = SiLU()
293
+ elif isinstance(m, Detect):
294
+ m.inplace = inplace
295
+ m.onnx_dynamic = dynamic
296
+ # m.forward = m.forward_export # assign forward (optional)
297
+
298
+ for _ in range(2):
299
+ y = model(im) # dry runs
300
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} ({file_size(file):.1f} MB)")
301
+
302
+ # Exports
303
+ if 'torchscript' in include:
304
+ export_torchscript(model, im, file, optimize)
305
+ if 'onnx' in include:
306
+ export_onnx(model, im, file, opset, train, dynamic, simplify)
307
+ if 'coreml' in include:
308
+ export_coreml(model, im, file)
309
+
310
+ # TensorFlow Exports
311
+ if any(tf_exports):
312
+ pb, tflite, tfjs = tf_exports[1:]
313
+ assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
314
+ model = export_saved_model(model, im, file, dynamic, tf_nms=tfjs, agnostic_nms=tfjs,
315
+ topk_per_class=topk_per_class, topk_all=topk_all, conf_thres=conf_thres,
316
+ iou_thres=iou_thres) # keras model
317
+ if pb or tfjs: # pb prerequisite to tfjs
318
+ export_pb(model, im, file)
319
+ if tflite:
320
+ export_tflite(model, im, file, int8=int8, data=data, ncalib=100)
321
+ if tfjs:
322
+ export_tfjs(model, im, file)
323
+
324
+ # Finish
325
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
326
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
327
+ f'\nVisualize with https://netron.app')
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', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
334
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
335
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
336
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
337
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
338
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
339
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
340
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
341
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
342
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
343
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
344
+ parser.add_argument('--opset', type=int, default=13, help='ONNX: opset version')
345
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
346
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
347
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
348
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
349
+ parser.add_argument('--include', nargs='+',
350
+ default=['torchscript', 'onnx'],
351
+ help='available formats are (torchscript, onnx, coreml, saved_model, pb, tflite, tfjs)')
352
+ opt = parser.parse_args()
353
+ print_args(FILE.stem, opt)
354
+ return opt
355
+
356
+
357
+ def main(opt):
358
+ run(**vars(opt))
359
+
360
+
361
+ if __name__ == "__main__":
362
+ opt = parse_opt()
363
+ main(opt)
face_detector/hubconf.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
9
+
10
+ import torch
11
+
12
+
13
+ def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
14
+ """Creates a specified YOLOv5 model
15
+
16
+ Arguments:
17
+ name (str): name of model, i.e. 'yolov5s'
18
+ pretrained (bool): load pretrained weights into the model
19
+ channels (int): number of input channels
20
+ classes (int): number of model classes
21
+ autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
22
+ verbose (bool): print all information to screen
23
+ device (str, torch.device, None): device to use for model parameters
24
+
25
+ Returns:
26
+ YOLOv5 pytorch model
27
+ """
28
+ from pathlib import Path
29
+
30
+ from models.yolo import Model
31
+ from models.experimental import attempt_load
32
+ from utils.general import check_requirements, set_logging
33
+ from utils.downloads import attempt_download
34
+ from utils.torch_utils import select_device
35
+
36
+ file = Path(__file__).resolve()
37
+ check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
38
+ set_logging(verbose=verbose)
39
+
40
+ save_dir = Path('') if str(name).endswith('.pt') else file.parent
41
+ path = (save_dir / name).with_suffix('.pt') # checkpoint path
42
+ try:
43
+ device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device)
44
+
45
+ if pretrained and channels == 3 and classes == 80:
46
+ model = attempt_load(path, map_location=device) # download/load FP32 model
47
+ else:
48
+ cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
49
+ model = Model(cfg, channels, classes) # create model
50
+ if pretrained:
51
+ ckpt = torch.load(attempt_download(path), map_location=device) # load
52
+ msd = model.state_dict() # model state_dict
53
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
54
+ csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
55
+ model.load_state_dict(csd, strict=False) # load
56
+ if len(ckpt['model'].names) == classes:
57
+ model.names = ckpt['model'].names # set class names attribute
58
+ if autoshape:
59
+ model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
60
+ return model.to(device)
61
+
62
+ except Exception as e:
63
+ help_url = 'https://github.com/ultralytics/yolov5/issues/36'
64
+ s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url
65
+ raise Exception(s) from e
66
+
67
+
68
+ def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None):
69
+ # YOLOv5 custom or local model
70
+ return _create(path, autoshape=autoshape, verbose=verbose, device=device)
71
+
72
+
73
+ def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
74
+ # YOLOv5-nano model https://github.com/ultralytics/yolov5
75
+ return _create('yolov5n', pretrained, channels, classes, autoshape, verbose, device)
76
+
77
+
78
+ def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
79
+ # YOLOv5-small model https://github.com/ultralytics/yolov5
80
+ return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device)
81
+
82
+
83
+ def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
84
+ # YOLOv5-medium model https://github.com/ultralytics/yolov5
85
+ return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device)
86
+
87
+
88
+ def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
89
+ # YOLOv5-large model https://github.com/ultralytics/yolov5
90
+ return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device)
91
+
92
+
93
+ def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
94
+ # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
95
+ return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device)
96
+
97
+
98
+ def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
99
+ # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
100
+ return _create('yolov5n6', pretrained, channels, classes, autoshape, verbose, device)
101
+
102
+
103
+ def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
104
+ # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
105
+ return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device)
106
+
107
+
108
+ def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
109
+ # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
110
+ return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device)
111
+
112
+
113
+ def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
114
+ # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
115
+ return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device)
116
+
117
+
118
+ def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
119
+ # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
120
+ return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device)
121
+
122
+
123
+ if __name__ == '__main__':
124
+ model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
125
+ # model = custom(path='path/to/model.pt') # custom
126
+
127
+ # Verify inference
128
+ import cv2
129
+ import numpy as np
130
+ from PIL import Image
131
+ from pathlib import Path
132
+
133
+ imgs = ['data/images/zidane.jpg', # filename
134
+ Path('data/images/zidane.jpg'), # Path
135
+ 'https://ultralytics.com/images/zidane.jpg', # URI
136
+ cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
137
+ Image.open('data/images/bus.jpg'), # PIL
138
+ np.zeros((320, 640, 3))] # numpy
139
+
140
+ results = model(imgs) # batched inference
141
+ results.print()
142
+ results.save()
face_detector/main.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from IPython.display import Image, clear_output # to display images
4
+ #from utils.google_utils import gdrive_downl#ad # to download models/datasets
5
+
6
+ # clear_output()
7
+ print('Setup complete. Using torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))
8
+
9
+
10
+ dataset_base = "/content/drive/MyDrive/AI Playground/face_detector/dataset/faces/"
11
+
12
+
13
+ dataset_yolo = dataset_base + "yolo/"
14
+
15
+ data_yaml = dataset_yolo + "data.yaml"
16
+
17
+ #pretrained = "/content/drive/MyDrive/AI Playground/face_detector/yolov5s.pt"
18
+
19
+ #trained_custom = "/content/drive/MyDrive/AI Playground/face_detector/dataset/faces/best_l.pt"
20
+
21
+ test_path = dataset_base + "yolo/test/images"
22
+
23
+ # define number of classes based on YAML
24
+ import yaml
25
+ with open("dataset/yolo/data.yaml", 'r') as stream:
26
+ num_classes = str(yaml.safe_load(stream)['nc'])
27
+
28
+ from IPython.core.magic import register_line_cell_magic
29
+
30
+ @register_line_cell_magic
31
+ def writetemplate(line, cell):
32
+ with open(line, 'w') as f:
33
+ f.write(cell.format(**globals()))
34
+
35
+
36
+
face_detector/models/__init__.py ADDED
File without changes
face_detector/models/common.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ """
3
+ Common modules
4
+ """
5
+
6
+ import logging
7
+ import math
8
+ import warnings
9
+ from copy import copy
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import requests
15
+ import torch
16
+ import torch.nn as nn
17
+ from PIL import Image
18
+ from torch.cuda import amp
19
+
20
+ from utils.datasets import exif_transpose, letterbox
21
+ from utils.general import colorstr, increment_path, make_divisible, non_max_suppression, save_one_box, \
22
+ scale_coords, xyxy2xywh
23
+ from utils.plots import Annotator, colors
24
+ from utils.torch_utils import time_sync
25
+
26
+ LOGGER = logging.getLogger(__name__)
27
+
28
+
29
+ def autopad(k, p=None): # kernel, padding
30
+ # Pad to 'same'
31
+ if p is None:
32
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
33
+ return p
34
+
35
+
36
+ class Conv(nn.Module):
37
+ # Standard convolution
38
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
39
+ super().__init__()
40
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
41
+ self.bn = nn.BatchNorm2d(c2)
42
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
43
+
44
+ def forward(self, x):
45
+ return self.act(self.bn(self.conv(x)))
46
+
47
+ def forward_fuse(self, x):
48
+ return self.act(self.conv(x))
49
+
50
+
51
+ class DWConv(Conv):
52
+ # Depth-wise convolution class
53
+ def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
54
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
55
+
56
+
57
+ class TransformerLayer(nn.Module):
58
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
59
+ def __init__(self, c, num_heads):
60
+ super().__init__()
61
+ self.q = nn.Linear(c, c, bias=False)
62
+ self.k = nn.Linear(c, c, bias=False)
63
+ self.v = nn.Linear(c, c, bias=False)
64
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
65
+ self.fc1 = nn.Linear(c, c, bias=False)
66
+ self.fc2 = nn.Linear(c, c, bias=False)
67
+
68
+ def forward(self, x):
69
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
70
+ x = self.fc2(self.fc1(x)) + x
71
+ return x
72
+
73
+
74
+ class TransformerBlock(nn.Module):
75
+ # Vision Transformer https://arxiv.org/abs/2010.11929
76
+ def __init__(self, c1, c2, num_heads, num_layers):
77
+ super().__init__()
78
+ self.conv = None
79
+ if c1 != c2:
80
+ self.conv = Conv(c1, c2)
81
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
82
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
83
+ self.c2 = c2
84
+
85
+ def forward(self, x):
86
+ if self.conv is not None:
87
+ x = self.conv(x)
88
+ b, _, w, h = x.shape
89
+ p = x.flatten(2).unsqueeze(0).transpose(0, 3).squeeze(3)
90
+ return self.tr(p + self.linear(p)).unsqueeze(3).transpose(0, 3).reshape(b, self.c2, w, h)
91
+
92
+
93
+ class Bottleneck(nn.Module):
94
+ # Standard bottleneck
95
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
96
+ super().__init__()
97
+ c_ = int(c2 * e) # hidden channels
98
+ self.cv1 = Conv(c1, c_, 1, 1)
99
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
100
+ self.add = shortcut and c1 == c2
101
+
102
+ def forward(self, x):
103
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
104
+
105
+
106
+ class BottleneckCSP(nn.Module):
107
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
108
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
109
+ super().__init__()
110
+ c_ = int(c2 * e) # hidden channels
111
+ self.cv1 = Conv(c1, c_, 1, 1)
112
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
113
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
114
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
115
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
116
+ self.act = nn.SiLU()
117
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
118
+
119
+ def forward(self, x):
120
+ y1 = self.cv3(self.m(self.cv1(x)))
121
+ y2 = self.cv2(x)
122
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
123
+
124
+
125
+ class C3(nn.Module):
126
+ # CSP Bottleneck with 3 convolutions
127
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
128
+ super().__init__()
129
+ c_ = int(c2 * e) # hidden channels
130
+ self.cv1 = Conv(c1, c_, 1, 1)
131
+ self.cv2 = Conv(c1, c_, 1, 1)
132
+ self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
133
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
134
+ # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
135
+
136
+ def forward(self, x):
137
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
138
+
139
+
140
+ class C3TR(C3):
141
+ # C3 module with TransformerBlock()
142
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
143
+ super().__init__(c1, c2, n, shortcut, g, e)
144
+ c_ = int(c2 * e)
145
+ self.m = TransformerBlock(c_, c_, 4, n)
146
+
147
+
148
+ class C3SPP(C3):
149
+ # C3 module with SPP()
150
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
151
+ super().__init__(c1, c2, n, shortcut, g, e)
152
+ c_ = int(c2 * e)
153
+ self.m = SPP(c_, c_, k)
154
+
155
+
156
+ class C3Ghost(C3):
157
+ # C3 module with GhostBottleneck()
158
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
159
+ super().__init__(c1, c2, n, shortcut, g, e)
160
+ c_ = int(c2 * e) # hidden channels
161
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
162
+
163
+
164
+ class SPP(nn.Module):
165
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
166
+ def __init__(self, c1, c2, k=(5, 9, 13)):
167
+ super().__init__()
168
+ c_ = c1 // 2 # hidden channels
169
+ self.cv1 = Conv(c1, c_, 1, 1)
170
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
171
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
172
+
173
+ def forward(self, x):
174
+ x = self.cv1(x)
175
+ with warnings.catch_warnings():
176
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
177
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
178
+
179
+
180
+ class SPPF(nn.Module):
181
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
182
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
183
+ super().__init__()
184
+ c_ = c1 // 2 # hidden channels
185
+ self.cv1 = Conv(c1, c_, 1, 1)
186
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
187
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
188
+
189
+ def forward(self, x):
190
+ x = self.cv1(x)
191
+ with warnings.catch_warnings():
192
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
193
+ y1 = self.m(x)
194
+ y2 = self.m(y1)
195
+ return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
196
+
197
+
198
+ class Focus(nn.Module):
199
+ # Focus wh information into c-space
200
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
201
+ super().__init__()
202
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
203
+ # self.contract = Contract(gain=2)
204
+
205
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
206
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
207
+ # return self.conv(self.contract(x))
208
+
209
+
210
+ class GhostConv(nn.Module):
211
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
212
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
213
+ super().__init__()
214
+ c_ = c2 // 2 # hidden channels
215
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
216
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
217
+
218
+ def forward(self, x):
219
+ y = self.cv1(x)
220
+ return torch.cat([y, self.cv2(y)], 1)
221
+
222
+
223
+ class GhostBottleneck(nn.Module):
224
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
225
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
226
+ super().__init__()
227
+ c_ = c2 // 2
228
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
229
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
230
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
231
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
232
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
233
+
234
+ def forward(self, x):
235
+ return self.conv(x) + self.shortcut(x)
236
+
237
+
238
+ class Contract(nn.Module):
239
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
240
+ def __init__(self, gain=2):
241
+ super().__init__()
242
+ self.gain = gain
243
+
244
+ def forward(self, x):
245
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
246
+ s = self.gain
247
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
248
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
249
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
250
+
251
+
252
+ class Expand(nn.Module):
253
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
254
+ def __init__(self, gain=2):
255
+ super().__init__()
256
+ self.gain = gain
257
+
258
+ def forward(self, x):
259
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
260
+ s = self.gain
261
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
262
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
263
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
264
+
265
+
266
+ class Concat(nn.Module):
267
+ # Concatenate a list of tensors along dimension
268
+ def __init__(self, dimension=1):
269
+ super().__init__()
270
+ self.d = dimension
271
+
272
+ def forward(self, x):
273
+ return torch.cat(x, self.d)
274
+
275
+
276
+ class AutoShape(nn.Module):
277
+ # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
278
+ conf = 0.25 # NMS confidence threshold
279
+ iou = 0.45 # NMS IoU threshold
280
+ classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
281
+ multi_label = False # NMS multiple labels per box
282
+ max_det = 1000 # maximum number of detections per image
283
+
284
+ def __init__(self, model):
285
+ super().__init__()
286
+ self.model = model.eval()
287
+
288
+ def autoshape(self):
289
+ LOGGER.info('AutoShape already enabled, skipping... ') # model already converted to model.autoshape()
290
+ return self
291
+
292
+ def _apply(self, fn):
293
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
294
+ self = super()._apply(fn)
295
+ m = self.model.model[-1] # Detect()
296
+ m.stride = fn(m.stride)
297
+ m.grid = list(map(fn, m.grid))
298
+ if isinstance(m.anchor_grid, list):
299
+ m.anchor_grid = list(map(fn, m.anchor_grid))
300
+ return self
301
+
302
+ @torch.no_grad()
303
+ def forward(self, imgs, size=640, augment=False, profile=False):
304
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
305
+ # file: imgs = 'data/images/zidane.jpg' # str or PosixPath
306
+ # URI: = 'https://ultralytics.com/images/zidane.jpg'
307
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
308
+ # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
309
+ # numpy: = np.zeros((640,1280,3)) # HWC
310
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
311
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
312
+
313
+ t = [time_sync()]
314
+ p = next(self.model.parameters()) # for device and type
315
+ if isinstance(imgs, torch.Tensor): # torch
316
+ with amp.autocast(enabled=p.device.type != 'cpu'):
317
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
318
+
319
+ # Pre-process
320
+ n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
321
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
322
+ for i, im in enumerate(imgs):
323
+ f = f'image{i}' # filename
324
+ if isinstance(im, (str, Path)): # filename or uri
325
+ im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
326
+ im = np.asarray(exif_transpose(im))
327
+ elif isinstance(im, Image.Image): # PIL Image
328
+ im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
329
+ files.append(Path(f).with_suffix('.jpg').name)
330
+ if im.shape[0] < 5: # image in CHW
331
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
332
+ im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
333
+ s = im.shape[:2] # HWC
334
+ shape0.append(s) # image shape
335
+ g = (size / max(s)) # gain
336
+ shape1.append([y * g for y in s])
337
+ imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
338
+ shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
339
+ x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
340
+ x = np.stack(x, 0) if n > 1 else x[0][None] # stack
341
+ x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
342
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
343
+ t.append(time_sync())
344
+
345
+ with amp.autocast(enabled=p.device.type != 'cpu'):
346
+ # Inference
347
+ y = self.model(x, augment, profile)[0] # forward
348
+ t.append(time_sync())
349
+
350
+ # Post-process
351
+ y = non_max_suppression(y, self.conf, iou_thres=self.iou, classes=self.classes,
352
+ multi_label=self.multi_label, max_det=self.max_det) # NMS
353
+ for i in range(n):
354
+ scale_coords(shape1, y[i][:, :4], shape0[i])
355
+
356
+ t.append(time_sync())
357
+ return Detections(imgs, y, files, t, self.names, x.shape)
358
+
359
+
360
+ class Detections:
361
+ # YOLOv5 detections class for inference results
362
+ def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
363
+ super().__init__()
364
+ d = pred[0].device # device
365
+ gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1., 1.], device=d) for im in imgs] # normalizations
366
+ self.imgs = imgs # list of images as numpy arrays
367
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
368
+ self.names = names # class names
369
+ self.files = files # image filenames
370
+ self.xyxy = pred # xyxy pixels
371
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
372
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
373
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
374
+ self.n = len(self.pred) # number of images (batch size)
375
+ self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
376
+ self.s = shape # inference BCHW shape
377
+
378
+ def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
379
+ crops = []
380
+ for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
381
+ s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
382
+ if pred.shape[0]:
383
+ for c in pred[:, -1].unique():
384
+ n = (pred[:, -1] == c).sum() # detections per class
385
+ s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
386
+ if show or save or render or crop:
387
+ annotator = Annotator(im, example=str(self.names))
388
+ for *box, conf, cls in reversed(pred): # xyxy, confidence, class
389
+ label = f'{self.names[int(cls)]} {conf:.2f}'
390
+ if crop:
391
+ file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
392
+ crops.append({'box': box, 'conf': conf, 'cls': cls, 'label': label,
393
+ 'im': save_one_box(box, im, file=file, save=save)})
394
+ else: # all others
395
+ annotator.box_label(box, label, color=colors(cls))
396
+ im = annotator.im
397
+ else:
398
+ s += '(no detections)'
399
+
400
+ im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
401
+ if pprint:
402
+ LOGGER.info(s.rstrip(', '))
403
+ if show:
404
+ im.show(self.files[i]) # show
405
+ if save:
406
+ f = self.files[i]
407
+ im.save(save_dir / f) # save
408
+ if i == self.n - 1:
409
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
410
+ if render:
411
+ self.imgs[i] = np.asarray(im)
412
+ if crop:
413
+ if save:
414
+ LOGGER.info(f'Saved results to {save_dir}\n')
415
+ return crops
416
+
417
+ def print(self):
418
+ self.display(pprint=True) # print results
419
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
420
+ self.t)
421
+
422
+ def show(self):
423
+ self.display(show=True) # show results
424
+
425
+ def save(self, save_dir='runs/detect/exp'):
426
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
427
+ self.display(save=True, save_dir=save_dir) # save results
428
+
429
+ def crop(self, save=True, save_dir='runs/detect/exp'):
430
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
431
+ return self.display(crop=True, save=save, save_dir=save_dir) # crop results
432
+
433
+ def render(self):
434
+ self.display(render=True) # render results
435
+ return self.imgs
436
+
437
+ def pandas(self):
438
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
439
+ new = copy(self) # return copy
440
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
441
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
442
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
443
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
444
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
445
+ return new
446
+
447
+ def tolist(self):
448
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
449
+ x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
450
+ for d in x:
451
+ for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
452
+ setattr(d, k, getattr(d, k)[0]) # pop out of list
453
+ return x
454
+
455
+ def __len__(self):
456
+ return self.n
457
+
458
+
459
+ class Classify(nn.Module):
460
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
461
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
462
+ super().__init__()
463
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
464
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
465
+ self.flat = nn.Flatten()
466
+
467
+ def forward(self, x):
468
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
469
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
face_detector/models/experimental.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ """
3
+ Experimental modules
4
+ """
5
+ import math
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ from models.common import Conv
11
+ from utils.downloads import attempt_download
12
+
13
+
14
+ class CrossConv(nn.Module):
15
+ # Cross Convolution Downsample
16
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
17
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
18
+ super().__init__()
19
+ c_ = int(c2 * e) # hidden channels
20
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
21
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
22
+ self.add = shortcut and c1 == c2
23
+
24
+ def forward(self, x):
25
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
26
+
27
+
28
+ class Sum(nn.Module):
29
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
30
+ def __init__(self, n, weight=False): # n: number of inputs
31
+ super().__init__()
32
+ self.weight = weight # apply weights boolean
33
+ self.iter = range(n - 1) # iter object
34
+ if weight:
35
+ self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
36
+
37
+ def forward(self, x):
38
+ y = x[0] # no weight
39
+ if self.weight:
40
+ w = torch.sigmoid(self.w) * 2
41
+ for i in self.iter:
42
+ y = y + x[i + 1] * w[i]
43
+ else:
44
+ for i in self.iter:
45
+ y = y + x[i + 1]
46
+ return y
47
+
48
+
49
+ class MixConv2d(nn.Module):
50
+ # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
51
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
52
+ super().__init__()
53
+ n = len(k) # number of convolutions
54
+ if equal_ch: # equal c_ per group
55
+ i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
56
+ c_ = [(i == g).sum() for g in range(n)] # intermediate channels
57
+ else: # equal weight.numel() per group
58
+ b = [c2] + [0] * n
59
+ a = np.eye(n + 1, n, k=-1)
60
+ a -= np.roll(a, 1, axis=1)
61
+ a *= np.array(k) ** 2
62
+ a[0] = 1
63
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
64
+
65
+ self.m = nn.ModuleList(
66
+ [nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
67
+ self.bn = nn.BatchNorm2d(c2)
68
+ self.act = nn.SiLU()
69
+
70
+ def forward(self, x):
71
+ return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
72
+
73
+
74
+ class Ensemble(nn.ModuleList):
75
+ # Ensemble of models
76
+ def __init__(self):
77
+ super().__init__()
78
+
79
+ def forward(self, x, augment=False, profile=False, visualize=False):
80
+ y = []
81
+ for module in self:
82
+ y.append(module(x, augment, profile, visualize)[0])
83
+ # y = torch.stack(y).max(0)[0] # max ensemble
84
+ # y = torch.stack(y).mean(0) # mean ensemble
85
+ y = torch.cat(y, 1) # nms ensemble
86
+ return y, None # inference, train output
87
+
88
+
89
+ def attempt_load(weights, map_location=None, inplace=True, fuse=True):
90
+ from models.yolo import Detect, Model
91
+
92
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
93
+ model = Ensemble()
94
+ for w in weights if isinstance(weights, list) else [weights]:
95
+ ckpt = torch.load(attempt_download(w), map_location=map_location) # load
96
+ if fuse:
97
+ model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
98
+ else:
99
+ model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse
100
+
101
+ # Compatibility updates
102
+ for m in model.modules():
103
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
104
+ m.inplace = inplace # pytorch 1.7.0 compatibility
105
+ if type(m) is Detect:
106
+ if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
107
+ delattr(m, 'anchor_grid')
108
+ setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
109
+ elif type(m) is Conv:
110
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
111
+
112
+ if len(model) == 1:
113
+ return model[-1] # return model
114
+ else:
115
+ print(f'Ensemble created with {weights}\n')
116
+ for k in ['names']:
117
+ setattr(model, k, getattr(model[-1], k))
118
+ model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
119
+ return model # return ensemble
face_detector/models/hub/anchors.yaml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ # Default anchors for COCO data
3
+
4
+
5
+ # P5 -------------------------------------------------------------------------------------------------------------------
6
+ # P5-640:
7
+ anchors_p5_640:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+
13
+ # P6 -------------------------------------------------------------------------------------------------------------------
14
+ # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
15
+ anchors_p6_640:
16
+ - [9,11, 21,19, 17,41] # P3/8
17
+ - [43,32, 39,70, 86,64] # P4/16
18
+ - [65,131, 134,130, 120,265] # P5/32
19
+ - [282,180, 247,354, 512,387] # P6/64
20
+
21
+ # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
22
+ anchors_p6_1280:
23
+ - [19,27, 44,40, 38,94] # P3/8
24
+ - [96,68, 86,152, 180,137] # P4/16
25
+ - [140,301, 303,264, 238,542] # P5/32
26
+ - [436,615, 739,380, 925,792] # P6/64
27
+
28
+ # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
29
+ anchors_p6_1920:
30
+ - [28,41, 67,59, 57,141] # P3/8
31
+ - [144,103, 129,227, 270,205] # P4/16
32
+ - [209,452, 455,396, 358,812] # P5/32
33
+ - [653,922, 1109,570, 1387,1187] # P6/64
34
+
35
+
36
+ # P7 -------------------------------------------------------------------------------------------------------------------
37
+ # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
38
+ anchors_p7_640:
39
+ - [11,11, 13,30, 29,20] # P3/8
40
+ - [30,46, 61,38, 39,92] # P4/16
41
+ - [78,80, 146,66, 79,163] # P5/32
42
+ - [149,150, 321,143, 157,303] # P6/64
43
+ - [257,402, 359,290, 524,372] # P7/128
44
+
45
+ # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
46
+ anchors_p7_1280:
47
+ - [19,22, 54,36, 32,77] # P3/8
48
+ - [70,83, 138,71, 75,173] # P4/16
49
+ - [165,159, 148,334, 375,151] # P5/32
50
+ - [334,317, 251,626, 499,474] # P6/64
51
+ - [750,326, 534,814, 1079,818] # P7/128
52
+
53
+ # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
54
+ anchors_p7_1920:
55
+ - [29,34, 81,55, 47,115] # P3/8
56
+ - [105,124, 207,107, 113,259] # P4/16
57
+ - [247,238, 222,500, 563,227] # P5/32
58
+ - [501,476, 376,939, 749,711] # P6/64
59
+ - [1126,489, 801,1222, 1618,1227] # P7/128
face_detector/models/hub/yolov3-spp.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # darknet53 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [32, 3, 1]], # 0
16
+ [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17
+ [-1, 1, Bottleneck, [64]],
18
+ [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19
+ [-1, 2, Bottleneck, [128]],
20
+ [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21
+ [-1, 8, Bottleneck, [256]],
22
+ [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23
+ [-1, 8, Bottleneck, [512]],
24
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25
+ [-1, 4, Bottleneck, [1024]], # 10
26
+ ]
27
+
28
+ # YOLOv3-SPP head
29
+ head:
30
+ [[-1, 1, Bottleneck, [1024, False]],
31
+ [-1, 1, SPP, [512, [5, 9, 13]]],
32
+ [-1, 1, Conv, [1024, 3, 1]],
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35
+
36
+ [-2, 1, Conv, [256, 1, 1]],
37
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38
+ [[-1, 8], 1, Concat, [1]], # cat backbone P4
39
+ [-1, 1, Bottleneck, [512, False]],
40
+ [-1, 1, Bottleneck, [512, False]],
41
+ [-1, 1, Conv, [256, 1, 1]],
42
+ [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43
+
44
+ [-2, 1, Conv, [128, 1, 1]],
45
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46
+ [[-1, 6], 1, Concat, [1]], # cat backbone P3
47
+ [-1, 1, Bottleneck, [256, False]],
48
+ [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49
+
50
+ [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51
+ ]
face_detector/models/hub/yolov3-tiny.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,14, 23,27, 37,58] # P4/16
9
+ - [81,82, 135,169, 344,319] # P5/32
10
+
11
+ # YOLOv3-tiny backbone
12
+ backbone:
13
+ # [from, number, module, args]
14
+ [[-1, 1, Conv, [16, 3, 1]], # 0
15
+ [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16
+ [-1, 1, Conv, [32, 3, 1]],
17
+ [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18
+ [-1, 1, Conv, [64, 3, 1]],
19
+ [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20
+ [-1, 1, Conv, [128, 3, 1]],
21
+ [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22
+ [-1, 1, Conv, [256, 3, 1]],
23
+ [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24
+ [-1, 1, Conv, [512, 3, 1]],
25
+ [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26
+ [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27
+ ]
28
+
29
+ # YOLOv3-tiny head
30
+ head:
31
+ [[-1, 1, Conv, [1024, 3, 1]],
32
+ [-1, 1, Conv, [256, 1, 1]],
33
+ [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
34
+
35
+ [-2, 1, Conv, [128, 1, 1]],
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 8], 1, Concat, [1]], # cat backbone P4
38
+ [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
39
+
40
+ [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
41
+ ]
face_detector/models/hub/yolov3.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # darknet53 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [32, 3, 1]], # 0
16
+ [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17
+ [-1, 1, Bottleneck, [64]],
18
+ [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19
+ [-1, 2, Bottleneck, [128]],
20
+ [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21
+ [-1, 8, Bottleneck, [256]],
22
+ [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23
+ [-1, 8, Bottleneck, [512]],
24
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25
+ [-1, 4, Bottleneck, [1024]], # 10
26
+ ]
27
+
28
+ # YOLOv3 head
29
+ head:
30
+ [[-1, 1, Bottleneck, [1024, False]],
31
+ [-1, 1, Conv, [512, [1, 1]]],
32
+ [-1, 1, Conv, [1024, 3, 1]],
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35
+
36
+ [-2, 1, Conv, [256, 1, 1]],
37
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38
+ [[-1, 8], 1, Concat, [1]], # cat backbone P4
39
+ [-1, 1, Bottleneck, [512, False]],
40
+ [-1, 1, Bottleneck, [512, False]],
41
+ [-1, 1, Conv, [256, 1, 1]],
42
+ [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43
+
44
+ [-2, 1, Conv, [128, 1, 1]],
45
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46
+ [[-1, 6], 1, Concat, [1]], # cat backbone P3
47
+ [-1, 1, Bottleneck, [256, False]],
48
+ [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49
+
50
+ [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51
+ ]
face_detector/models/hub/yolov5-bifpn.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, C3, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 BiFPN head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14, 6], 1, Concat, [1]], # cat P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/hub/yolov5-fpn.yaml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, Bottleneck, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 6, BottleneckCSP, [1024]], # 9
25
+ ]
26
+
27
+ # YOLOv5 FPN head
28
+ head:
29
+ [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
30
+
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
35
+
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
40
+
41
+ [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42
+ ]
face_detector/models/hub/yolov5-p2.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3
8
+
9
+ # YOLOv5 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 9, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
20
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
21
+ [-1, 3, C3, [1024, False]], # 9
22
+ ]
23
+
24
+ # YOLOv5 head
25
+ head:
26
+ [[-1, 1, Conv, [512, 1, 1]],
27
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
28
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
29
+ [-1, 3, C3, [512, False]], # 13
30
+
31
+ [-1, 1, Conv, [256, 1, 1]],
32
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
34
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
35
+
36
+ [-1, 1, Conv, [128, 1, 1]],
37
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38
+ [[-1, 2], 1, Concat, [1]], # cat backbone P2
39
+ [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall)
40
+
41
+ [-1, 1, Conv, [128, 3, 2]],
42
+ [[-1, 18], 1, Concat, [1]], # cat head P3
43
+ [-1, 3, C3, [256, False]], # 24 (P3/8-small)
44
+
45
+ [-1, 1, Conv, [256, 3, 2]],
46
+ [[-1, 14], 1, Concat, [1]], # cat head P4
47
+ [-1, 3, C3, [512, False]], # 27 (P4/16-medium)
48
+
49
+ [-1, 1, Conv, [512, 3, 2]],
50
+ [[-1, 10], 1, Concat, [1]], # cat head P5
51
+ [-1, 3, C3, [1024, False]], # 30 (P5/32-large)
52
+
53
+ [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
54
+ ]
face_detector/models/hub/yolov5-p6.yaml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3
8
+
9
+ # YOLOv5 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 9, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [768]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22
+ [-1, 1, SPP, [1024, [3, 5, 7]]],
23
+ [-1, 3, C3, [1024, False]], # 11
24
+ ]
25
+
26
+ # YOLOv5 head
27
+ head:
28
+ [[-1, 1, Conv, [768, 1, 1]],
29
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
30
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
31
+ [-1, 3, C3, [768, False]], # 15
32
+
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
35
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
36
+ [-1, 3, C3, [512, False]], # 19
37
+
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
40
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
41
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
42
+
43
+ [-1, 1, Conv, [256, 3, 2]],
44
+ [[-1, 20], 1, Concat, [1]], # cat head P4
45
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
46
+
47
+ [-1, 1, Conv, [512, 3, 2]],
48
+ [[-1, 16], 1, Concat, [1]], # cat head P5
49
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
50
+
51
+ [-1, 1, Conv, [768, 3, 2]],
52
+ [[-1, 12], 1, Concat, [1]], # cat head P6
53
+ [-1, 3, C3, [1024, False]], # 32 (P5/64-xlarge)
54
+
55
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
56
+ ]
face_detector/models/hub/yolov5-p7.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3
8
+
9
+ # YOLOv5 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 9, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [768]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22
+ [-1, 3, C3, [1024]],
23
+ [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128
24
+ [-1, 1, SPP, [1280, [3, 5]]],
25
+ [-1, 3, C3, [1280, False]], # 13
26
+ ]
27
+
28
+ # YOLOv5 head
29
+ head:
30
+ [[-1, 1, Conv, [1024, 1, 1]],
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 10], 1, Concat, [1]], # cat backbone P6
33
+ [-1, 3, C3, [1024, False]], # 17
34
+
35
+ [-1, 1, Conv, [768, 1, 1]],
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
38
+ [-1, 3, C3, [768, False]], # 21
39
+
40
+ [-1, 1, Conv, [512, 1, 1]],
41
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
42
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
43
+ [-1, 3, C3, [512, False]], # 25
44
+
45
+ [-1, 1, Conv, [256, 1, 1]],
46
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
47
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
48
+ [-1, 3, C3, [256, False]], # 29 (P3/8-small)
49
+
50
+ [-1, 1, Conv, [256, 3, 2]],
51
+ [[-1, 26], 1, Concat, [1]], # cat head P4
52
+ [-1, 3, C3, [512, False]], # 32 (P4/16-medium)
53
+
54
+ [-1, 1, Conv, [512, 3, 2]],
55
+ [[-1, 22], 1, Concat, [1]], # cat head P5
56
+ [-1, 3, C3, [768, False]], # 35 (P5/32-large)
57
+
58
+ [-1, 1, Conv, [768, 3, 2]],
59
+ [[-1, 18], 1, Concat, [1]], # cat head P6
60
+ [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge)
61
+
62
+ [-1, 1, Conv, [1024, 3, 2]],
63
+ [[-1, 14], 1, Concat, [1]], # cat head P7
64
+ [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge)
65
+
66
+ [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7)
67
+ ]
face_detector/models/hub/yolov5-panet.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 PANet head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, BottleneckCSP, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/hub/yolov5l6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
face_detector/models/hub/yolov5m6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.67 # model depth multiple
6
+ width_multiple: 0.75 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
face_detector/models/hub/yolov5n6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.25 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
face_detector/models/hub/yolov5s-ghost.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3Ghost, [128]],
18
+ [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, C3Ghost, [256]],
20
+ [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3Ghost, [512]],
22
+ [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, C3Ghost, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 head
28
+ head:
29
+ [[-1, 1, GhostConv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3Ghost, [512, False]], # 13
33
+
34
+ [-1, 1, GhostConv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, GhostConv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, GhostConv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/hub/yolov5s-transformer.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module
25
+ ]
26
+
27
+ # YOLOv5 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/hub/yolov5s6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
face_detector/models/hub/yolov5x6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.33 # model depth multiple
6
+ width_multiple: 1.25 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
face_detector/models/tf.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ """
3
+ TensorFlow, Keras and TFLite versions of YOLOv5
4
+ Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127
5
+
6
+ Usage:
7
+ $ python models/tf.py --weights yolov5s.pt
8
+
9
+ Export:
10
+ $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs
11
+ """
12
+
13
+ import argparse
14
+ import logging
15
+ import sys
16
+ from copy import deepcopy
17
+ from pathlib import Path
18
+
19
+ FILE = Path(__file__).resolve()
20
+ ROOT = FILE.parents[1] # YOLOv5 root directory
21
+ if str(ROOT) not in sys.path:
22
+ sys.path.append(str(ROOT)) # add ROOT to PATH
23
+ # ROOT = ROOT.relative_to(Path.cwd()) # relative
24
+
25
+ import numpy as np
26
+ import tensorflow as tf
27
+ import torch
28
+ import torch.nn as nn
29
+ from tensorflow import keras
30
+
31
+ from models.common import Bottleneck, BottleneckCSP, Concat, Conv, C3, DWConv, Focus, SPP, SPPF, autopad
32
+ from models.experimental import CrossConv, MixConv2d, attempt_load
33
+ from models.yolo import Detect
34
+ from utils.general import make_divisible, print_args, LOGGER
35
+ from utils.activations import SiLU
36
+
37
+
38
+ class TFBN(keras.layers.Layer):
39
+ # TensorFlow BatchNormalization wrapper
40
+ def __init__(self, w=None):
41
+ super().__init__()
42
+ self.bn = keras.layers.BatchNormalization(
43
+ beta_initializer=keras.initializers.Constant(w.bias.numpy()),
44
+ gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
45
+ moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
46
+ moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
47
+ epsilon=w.eps)
48
+
49
+ def call(self, inputs):
50
+ return self.bn(inputs)
51
+
52
+
53
+ class TFPad(keras.layers.Layer):
54
+ def __init__(self, pad):
55
+ super().__init__()
56
+ self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
57
+
58
+ def call(self, inputs):
59
+ return tf.pad(inputs, self.pad, mode='constant', constant_values=0)
60
+
61
+
62
+ class TFConv(keras.layers.Layer):
63
+ # Standard convolution
64
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
65
+ # ch_in, ch_out, weights, kernel, stride, padding, groups
66
+ super().__init__()
67
+ assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
68
+ assert isinstance(k, int), "Convolution with multiple kernels are not allowed."
69
+ # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
70
+ # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
71
+
72
+ conv = keras.layers.Conv2D(
73
+ c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False if hasattr(w, 'bn') else True,
74
+ kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
75
+ bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
76
+ self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
77
+ self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
78
+
79
+ # YOLOv5 activations
80
+ if isinstance(w.act, nn.LeakyReLU):
81
+ self.act = (lambda x: keras.activations.relu(x, alpha=0.1)) if act else tf.identity
82
+ elif isinstance(w.act, nn.Hardswish):
83
+ self.act = (lambda x: x * tf.nn.relu6(x + 3) * 0.166666667) if act else tf.identity
84
+ elif isinstance(w.act, (nn.SiLU, SiLU)):
85
+ self.act = (lambda x: keras.activations.swish(x)) if act else tf.identity
86
+ else:
87
+ raise Exception(f'no matching TensorFlow activation found for {w.act}')
88
+
89
+ def call(self, inputs):
90
+ return self.act(self.bn(self.conv(inputs)))
91
+
92
+
93
+ class TFFocus(keras.layers.Layer):
94
+ # Focus wh information into c-space
95
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
96
+ # ch_in, ch_out, kernel, stride, padding, groups
97
+ super().__init__()
98
+ self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
99
+
100
+ def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
101
+ # inputs = inputs / 255. # normalize 0-255 to 0-1
102
+ return self.conv(tf.concat([inputs[:, ::2, ::2, :],
103
+ inputs[:, 1::2, ::2, :],
104
+ inputs[:, ::2, 1::2, :],
105
+ inputs[:, 1::2, 1::2, :]], 3))
106
+
107
+
108
+ class TFBottleneck(keras.layers.Layer):
109
+ # Standard bottleneck
110
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion
111
+ super().__init__()
112
+ c_ = int(c2 * e) # hidden channels
113
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
114
+ self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
115
+ self.add = shortcut and c1 == c2
116
+
117
+ def call(self, inputs):
118
+ return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
119
+
120
+
121
+ class TFConv2d(keras.layers.Layer):
122
+ # Substitution for PyTorch nn.Conv2D
123
+ def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
124
+ super().__init__()
125
+ assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
126
+ self.conv = keras.layers.Conv2D(
127
+ c2, k, s, 'VALID', use_bias=bias,
128
+ kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),
129
+ bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None, )
130
+
131
+ def call(self, inputs):
132
+ return self.conv(inputs)
133
+
134
+
135
+ class TFBottleneckCSP(keras.layers.Layer):
136
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
137
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
138
+ # ch_in, ch_out, number, shortcut, groups, expansion
139
+ super().__init__()
140
+ c_ = int(c2 * e) # hidden channels
141
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
142
+ self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
143
+ self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
144
+ self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
145
+ self.bn = TFBN(w.bn)
146
+ self.act = lambda x: keras.activations.relu(x, alpha=0.1)
147
+ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
148
+
149
+ def call(self, inputs):
150
+ y1 = self.cv3(self.m(self.cv1(inputs)))
151
+ y2 = self.cv2(inputs)
152
+ return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
153
+
154
+
155
+ class TFC3(keras.layers.Layer):
156
+ # CSP Bottleneck with 3 convolutions
157
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
158
+ # ch_in, ch_out, number, shortcut, groups, expansion
159
+ super().__init__()
160
+ c_ = int(c2 * e) # hidden channels
161
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
162
+ self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
163
+ self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
164
+ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
165
+
166
+ def call(self, inputs):
167
+ return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
168
+
169
+
170
+ class TFSPP(keras.layers.Layer):
171
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
172
+ def __init__(self, c1, c2, k=(5, 9, 13), w=None):
173
+ super().__init__()
174
+ c_ = c1 // 2 # hidden channels
175
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
176
+ self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
177
+ self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]
178
+
179
+ def call(self, inputs):
180
+ x = self.cv1(inputs)
181
+ return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
182
+
183
+
184
+ class TFSPPF(keras.layers.Layer):
185
+ # Spatial pyramid pooling-Fast layer
186
+ def __init__(self, c1, c2, k=5, w=None):
187
+ super().__init__()
188
+ c_ = c1 // 2 # hidden channels
189
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
190
+ self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
191
+ self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')
192
+
193
+ def call(self, inputs):
194
+ x = self.cv1(inputs)
195
+ y1 = self.m(x)
196
+ y2 = self.m(y1)
197
+ return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
198
+
199
+
200
+ class TFDetect(keras.layers.Layer):
201
+ def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer
202
+ super().__init__()
203
+ self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
204
+ self.nc = nc # number of classes
205
+ self.no = nc + 5 # number of outputs per anchor
206
+ self.nl = len(anchors) # number of detection layers
207
+ self.na = len(anchors[0]) // 2 # number of anchors
208
+ self.grid = [tf.zeros(1)] * self.nl # init grid
209
+ self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
210
+ self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]),
211
+ [self.nl, 1, -1, 1, 2])
212
+ self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
213
+ self.training = False # set to False after building model
214
+ self.imgsz = imgsz
215
+ for i in range(self.nl):
216
+ ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
217
+ self.grid[i] = self._make_grid(nx, ny)
218
+
219
+ def call(self, inputs):
220
+ z = [] # inference output
221
+ x = []
222
+ for i in range(self.nl):
223
+ x.append(self.m[i](inputs[i]))
224
+ # x(bs,20,20,255) to x(bs,3,20,20,85)
225
+ ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
226
+ x[i] = tf.transpose(tf.reshape(x[i], [-1, ny * nx, self.na, self.no]), [0, 2, 1, 3])
227
+
228
+ if not self.training: # inference
229
+ y = tf.sigmoid(x[i])
230
+ xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
231
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]
232
+ # Normalize xywh to 0-1 to reduce calibration error
233
+ xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
234
+ wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
235
+ y = tf.concat([xy, wh, y[..., 4:]], -1)
236
+ z.append(tf.reshape(y, [-1, 3 * ny * nx, self.no]))
237
+
238
+ return x if self.training else (tf.concat(z, 1), x)
239
+
240
+ @staticmethod
241
+ def _make_grid(nx=20, ny=20):
242
+ # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
243
+ # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
244
+ xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
245
+ return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
246
+
247
+
248
+ class TFUpsample(keras.layers.Layer):
249
+ def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'
250
+ super().__init__()
251
+ assert scale_factor == 2, "scale_factor must be 2"
252
+ self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode)
253
+ # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
254
+ # with default arguments: align_corners=False, half_pixel_centers=False
255
+ # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
256
+ # size=(x.shape[1] * 2, x.shape[2] * 2))
257
+
258
+ def call(self, inputs):
259
+ return self.upsample(inputs)
260
+
261
+
262
+ class TFConcat(keras.layers.Layer):
263
+ def __init__(self, dimension=1, w=None):
264
+ super().__init__()
265
+ assert dimension == 1, "convert only NCHW to NHWC concat"
266
+ self.d = 3
267
+
268
+ def call(self, inputs):
269
+ return tf.concat(inputs, self.d)
270
+
271
+
272
+ def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
273
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
274
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
275
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
276
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
277
+
278
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
279
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
280
+ m_str = m
281
+ m = eval(m) if isinstance(m, str) else m # eval strings
282
+ for j, a in enumerate(args):
283
+ try:
284
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
285
+ except NameError:
286
+ pass
287
+
288
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
289
+ if m in [nn.Conv2d, Conv, Bottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:
290
+ c1, c2 = ch[f], args[0]
291
+ c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
292
+
293
+ args = [c1, c2, *args[1:]]
294
+ if m in [BottleneckCSP, C3]:
295
+ args.insert(2, n)
296
+ n = 1
297
+ elif m is nn.BatchNorm2d:
298
+ args = [ch[f]]
299
+ elif m is Concat:
300
+ c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
301
+ elif m is Detect:
302
+ args.append([ch[x + 1] for x in f])
303
+ if isinstance(args[1], int): # number of anchors
304
+ args[1] = [list(range(args[1] * 2))] * len(f)
305
+ args.append(imgsz)
306
+ else:
307
+ c2 = ch[f]
308
+
309
+ tf_m = eval('TF' + m_str.replace('nn.', ''))
310
+ m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \
311
+ else tf_m(*args, w=model.model[i]) # module
312
+
313
+ torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
314
+ t = str(m)[8:-2].replace('__main__.', '') # module type
315
+ np = sum(x.numel() for x in torch_m_.parameters()) # number params
316
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
317
+ LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print
318
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
319
+ layers.append(m_)
320
+ ch.append(c2)
321
+ return keras.Sequential(layers), sorted(save)
322
+
323
+
324
+ class TFModel:
325
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes
326
+ super().__init__()
327
+ if isinstance(cfg, dict):
328
+ self.yaml = cfg # model dict
329
+ else: # is *.yaml
330
+ import yaml # for torch hub
331
+ self.yaml_file = Path(cfg).name
332
+ with open(cfg) as f:
333
+ self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
334
+
335
+ # Define model
336
+ if nc and nc != self.yaml['nc']:
337
+ LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
338
+ self.yaml['nc'] = nc # override yaml value
339
+ self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
340
+
341
+ def predict(self, inputs, tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
342
+ conf_thres=0.25):
343
+ y = [] # outputs
344
+ x = inputs
345
+ for i, m in enumerate(self.model.layers):
346
+ if m.f != -1: # if not from previous layer
347
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
348
+
349
+ x = m(x) # run
350
+ y.append(x if m.i in self.savelist else None) # save output
351
+
352
+ # Add TensorFlow NMS
353
+ if tf_nms:
354
+ boxes = self._xywh2xyxy(x[0][..., :4])
355
+ probs = x[0][:, :, 4:5]
356
+ classes = x[0][:, :, 5:]
357
+ scores = probs * classes
358
+ if agnostic_nms:
359
+ nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
360
+ return nms, x[1]
361
+ else:
362
+ boxes = tf.expand_dims(boxes, 2)
363
+ nms = tf.image.combined_non_max_suppression(
364
+ boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False)
365
+ return nms, x[1]
366
+
367
+ return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]
368
+ # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85)
369
+ # xywh = x[..., :4] # x(6300,4) boxes
370
+ # conf = x[..., 4:5] # x(6300,1) confidences
371
+ # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
372
+ # return tf.concat([conf, cls, xywh], 1)
373
+
374
+ @staticmethod
375
+ def _xywh2xyxy(xywh):
376
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
377
+ x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
378
+ return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
379
+
380
+
381
+ class AgnosticNMS(keras.layers.Layer):
382
+ # TF Agnostic NMS
383
+ def call(self, input, topk_all, iou_thres, conf_thres):
384
+ # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450
385
+ return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres), input,
386
+ fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
387
+ name='agnostic_nms')
388
+
389
+ @staticmethod
390
+ def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
391
+ boxes, classes, scores = x
392
+ class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
393
+ scores_inp = tf.reduce_max(scores, -1)
394
+ selected_inds = tf.image.non_max_suppression(
395
+ boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres)
396
+ selected_boxes = tf.gather(boxes, selected_inds)
397
+ padded_boxes = tf.pad(selected_boxes,
398
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
399
+ mode="CONSTANT", constant_values=0.0)
400
+ selected_scores = tf.gather(scores_inp, selected_inds)
401
+ padded_scores = tf.pad(selected_scores,
402
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
403
+ mode="CONSTANT", constant_values=-1.0)
404
+ selected_classes = tf.gather(class_inds, selected_inds)
405
+ padded_classes = tf.pad(selected_classes,
406
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
407
+ mode="CONSTANT", constant_values=-1.0)
408
+ valid_detections = tf.shape(selected_inds)[0]
409
+ return padded_boxes, padded_scores, padded_classes, valid_detections
410
+
411
+
412
+ def representative_dataset_gen(dataset, ncalib=100):
413
+ # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
414
+ for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
415
+ input = np.transpose(img, [1, 2, 0])
416
+ input = np.expand_dims(input, axis=0).astype(np.float32)
417
+ input /= 255.0
418
+ yield [input]
419
+ if n >= ncalib:
420
+ break
421
+
422
+
423
+ def run(weights=ROOT / 'yolov5s.pt', # weights path
424
+ imgsz=(640, 640), # inference size h,w
425
+ batch_size=1, # batch size
426
+ dynamic=False, # dynamic batch size
427
+ ):
428
+ # PyTorch model
429
+ im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
430
+ model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False)
431
+ y = model(im) # inference
432
+ model.info()
433
+
434
+ # TensorFlow model
435
+ im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
436
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
437
+ y = tf_model.predict(im) # inference
438
+
439
+ # Keras model
440
+ im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
441
+ keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
442
+ keras_model.summary()
443
+
444
+
445
+ def parse_opt():
446
+ parser = argparse.ArgumentParser()
447
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
448
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
449
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
450
+ parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')
451
+ opt = parser.parse_args()
452
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
453
+ print_args(FILE.stem, opt)
454
+ return opt
455
+
456
+
457
+ def main(opt):
458
+ run(**vars(opt))
459
+
460
+
461
+ if __name__ == "__main__":
462
+ opt = parse_opt()
463
+ main(opt)
face_detector/models/yolo.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+ """
3
+ YOLO-specific modules
4
+
5
+ Usage:
6
+ $ python path/to/models/yolo.py --cfg yolov5s.yaml
7
+ """
8
+
9
+ import argparse
10
+ import sys
11
+ from copy import deepcopy
12
+ from pathlib import Path
13
+
14
+ FILE = Path(__file__).resolve()
15
+ ROOT = FILE.parents[1] # YOLOv5 root directory
16
+ if str(ROOT) not in sys.path:
17
+ sys.path.append(str(ROOT)) # add ROOT to PATH
18
+ # ROOT = ROOT.relative_to(Path.cwd()) # relative
19
+
20
+ from models.common import *
21
+ from models.experimental import *
22
+ from utils.autoanchor import check_anchor_order
23
+ from utils.general import check_version, check_yaml, make_divisible, print_args, LOGGER
24
+ from utils.plots import feature_visualization
25
+ from utils.torch_utils import copy_attr, fuse_conv_and_bn, initialize_weights, model_info, scale_img, \
26
+ select_device, time_sync
27
+
28
+ try:
29
+ import thop # for FLOPs computation
30
+ except ImportError:
31
+ thop = None
32
+
33
+
34
+ class Detect(nn.Module):
35
+ stride = None # strides computed during build
36
+ onnx_dynamic = False # ONNX export parameter
37
+
38
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
39
+ super().__init__()
40
+ self.nc = nc # number of classes
41
+ self.no = nc + 5 # number of outputs per anchor
42
+ self.nl = len(anchors) # number of detection layers
43
+ self.na = len(anchors[0]) // 2 # number of anchors
44
+ self.grid = [torch.zeros(1)] * self.nl # init grid
45
+ self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
46
+ self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
47
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
48
+ self.inplace = inplace # use in-place ops (e.g. slice assignment)
49
+
50
+ def forward(self, x):
51
+ z = [] # inference output
52
+ for i in range(self.nl):
53
+ x[i] = self.m[i](x[i]) # conv
54
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
55
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
56
+
57
+ if not self.training: # inference
58
+ if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
59
+ self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
60
+
61
+ y = x[i].sigmoid()
62
+ if self.inplace:
63
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
64
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
65
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
66
+ xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
67
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
68
+ y = torch.cat((xy, wh, y[..., 4:]), -1)
69
+ z.append(y.view(bs, -1, self.no))
70
+
71
+ return x if self.training else (torch.cat(z, 1), x)
72
+
73
+ def _make_grid(self, nx=20, ny=20, i=0):
74
+ d = self.anchors[i].device
75
+ if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
76
+ yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)], indexing='ij')
77
+ else:
78
+ yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)])
79
+ grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float()
80
+ anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
81
+ .view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float()
82
+ return grid, anchor_grid
83
+
84
+
85
+ class Model(nn.Module):
86
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
87
+ super().__init__()
88
+ if isinstance(cfg, dict):
89
+ self.yaml = cfg # model dict
90
+ else: # is *.yaml
91
+ import yaml # for torch hub
92
+ self.yaml_file = Path(cfg).name
93
+ with open(cfg, errors='ignore') as f:
94
+ self.yaml = yaml.safe_load(f) # model dict
95
+
96
+ # Define model
97
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
98
+ if nc and nc != self.yaml['nc']:
99
+ LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
100
+ self.yaml['nc'] = nc # override yaml value
101
+ if anchors:
102
+ LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
103
+ self.yaml['anchors'] = round(anchors) # override yaml value
104
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
105
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
106
+ self.inplace = self.yaml.get('inplace', True)
107
+
108
+ # Build strides, anchors
109
+ m = self.model[-1] # Detect()
110
+ if isinstance(m, Detect):
111
+ s = 256 # 2x min stride
112
+ m.inplace = self.inplace
113
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
114
+ m.anchors /= m.stride.view(-1, 1, 1)
115
+ check_anchor_order(m)
116
+ self.stride = m.stride
117
+ self._initialize_biases() # only run once
118
+
119
+ # Init weights, biases
120
+ initialize_weights(self)
121
+ self.info()
122
+ LOGGER.info('')
123
+
124
+ def forward(self, x, augment=False, profile=False, visualize=False):
125
+ if augment:
126
+ return self._forward_augment(x) # augmented inference, None
127
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
128
+
129
+ def _forward_augment(self, x):
130
+ img_size = x.shape[-2:] # height, width
131
+ s = [1, 0.83, 0.67] # scales
132
+ f = [None, 3, None] # flips (2-ud, 3-lr)
133
+ y = [] # outputs
134
+ for si, fi in zip(s, f):
135
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
136
+ yi = self._forward_once(xi)[0] # forward
137
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
138
+ yi = self._descale_pred(yi, fi, si, img_size)
139
+ y.append(yi)
140
+ y = self._clip_augmented(y) # clip augmented tails
141
+ return torch.cat(y, 1), None # augmented inference, train
142
+
143
+ def _forward_once(self, x, profile=False, visualize=False):
144
+ y, dt = [], [] # outputs
145
+ for m in self.model:
146
+ if m.f != -1: # if not from previous layer
147
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
148
+ if profile:
149
+ self._profile_one_layer(m, x, dt)
150
+ x = m(x) # run
151
+ y.append(x if m.i in self.save else None) # save output
152
+ if visualize:
153
+ feature_visualization(x, m.type, m.i, save_dir=visualize)
154
+ return x
155
+
156
+ def _descale_pred(self, p, flips, scale, img_size):
157
+ # de-scale predictions following augmented inference (inverse operation)
158
+ if self.inplace:
159
+ p[..., :4] /= scale # de-scale
160
+ if flips == 2:
161
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
162
+ elif flips == 3:
163
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
164
+ else:
165
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
166
+ if flips == 2:
167
+ y = img_size[0] - y # de-flip ud
168
+ elif flips == 3:
169
+ x = img_size[1] - x # de-flip lr
170
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
171
+ return p
172
+
173
+ def _clip_augmented(self, y):
174
+ # Clip YOLOv5 augmented inference tails
175
+ nl = self.model[-1].nl # number of detection layers (P3-P5)
176
+ g = sum(4 ** x for x in range(nl)) # grid points
177
+ e = 1 # exclude layer count
178
+ i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
179
+ y[0] = y[0][:, :-i] # large
180
+ i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
181
+ y[-1] = y[-1][:, i:] # small
182
+ return y
183
+
184
+ def _profile_one_layer(self, m, x, dt):
185
+ c = isinstance(m, Detect) # is final layer, copy input as inplace fix
186
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
187
+ t = time_sync()
188
+ for _ in range(10):
189
+ m(x.copy() if c else x)
190
+ dt.append((time_sync() - t) * 100)
191
+ if m == self.model[0]:
192
+ LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
193
+ LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
194
+ if c:
195
+ LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
196
+
197
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
198
+ # https://arxiv.org/abs/1708.02002 section 3.3
199
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
200
+ m = self.model[-1] # Detect() module
201
+ for mi, s in zip(m.m, m.stride): # from
202
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
203
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
204
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
205
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
206
+
207
+ def _print_biases(self):
208
+ m = self.model[-1] # Detect() module
209
+ for mi in m.m: # from
210
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
211
+ LOGGER.info(
212
+ ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
213
+
214
+ # def _print_weights(self):
215
+ # for m in self.model.modules():
216
+ # if type(m) is Bottleneck:
217
+ # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
218
+
219
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
220
+ LOGGER.info('Fusing layers... ')
221
+ for m in self.model.modules():
222
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
223
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
224
+ delattr(m, 'bn') # remove batchnorm
225
+ m.forward = m.forward_fuse # update forward
226
+ self.info()
227
+ return self
228
+
229
+ def autoshape(self): # add AutoShape module
230
+ LOGGER.info('Adding AutoShape... ')
231
+ m = AutoShape(self) # wrap model
232
+ copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
233
+ return m
234
+
235
+ def info(self, verbose=False, img_size=640): # print model information
236
+ model_info(self, verbose, img_size)
237
+
238
+ def _apply(self, fn):
239
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
240
+ self = super()._apply(fn)
241
+ m = self.model[-1] # Detect()
242
+ if isinstance(m, Detect):
243
+ m.stride = fn(m.stride)
244
+ m.grid = list(map(fn, m.grid))
245
+ if isinstance(m.anchor_grid, list):
246
+ m.anchor_grid = list(map(fn, m.anchor_grid))
247
+ return self
248
+
249
+
250
+ def parse_model(d, ch): # model_dict, input_channels(3)
251
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
252
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
253
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
254
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
255
+
256
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
257
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
258
+ m = eval(m) if isinstance(m, str) else m # eval strings
259
+ for j, a in enumerate(args):
260
+ try:
261
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
262
+ except NameError:
263
+ pass
264
+
265
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
266
+ if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
267
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
268
+ c1, c2 = ch[f], args[0]
269
+ if c2 != no: # if not output
270
+ c2 = make_divisible(c2 * gw, 8)
271
+
272
+ args = [c1, c2, *args[1:]]
273
+ if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
274
+ args.insert(2, n) # number of repeats
275
+ n = 1
276
+ elif m is nn.BatchNorm2d:
277
+ args = [ch[f]]
278
+ elif m is Concat:
279
+ c2 = sum(ch[x] for x in f)
280
+ elif m is Detect:
281
+ args.append([ch[x] for x in f])
282
+ if isinstance(args[1], int): # number of anchors
283
+ args[1] = [list(range(args[1] * 2))] * len(f)
284
+ elif m is Contract:
285
+ c2 = ch[f] * args[0] ** 2
286
+ elif m is Expand:
287
+ c2 = ch[f] // args[0] ** 2
288
+ else:
289
+ c2 = ch[f]
290
+
291
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
292
+ t = str(m)[8:-2].replace('__main__.', '') # module type
293
+ np = sum(x.numel() for x in m_.parameters()) # number params
294
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
295
+ LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
296
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
297
+ layers.append(m_)
298
+ if i == 0:
299
+ ch = []
300
+ ch.append(c2)
301
+ return nn.Sequential(*layers), sorted(save)
302
+
303
+
304
+ if __name__ == '__main__':
305
+ parser = argparse.ArgumentParser()
306
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
307
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
308
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
309
+ opt = parser.parse_args()
310
+ opt.cfg = check_yaml(opt.cfg) # check YAML
311
+ print_args(FILE.stem, opt)
312
+ device = select_device(opt.device)
313
+
314
+ # Create model
315
+ model = Model(opt.cfg).to(device)
316
+ model.train()
317
+
318
+ # Profile
319
+ if opt.profile:
320
+ img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
321
+ y = model(img, profile=True)
322
+
323
+ # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
324
+ # from torch.utils.tensorboard import SummaryWriter
325
+ # tb_writer = SummaryWriter('.')
326
+ # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
327
+ # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
face_detector/models/yolov5l.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/yolov5m.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.67 # model depth multiple
6
+ width_multiple: 0.75 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/yolov5n.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.25 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
face_detector/models/yolov5s.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 1 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]