Satoru commited on
Commit
447b47e
1 Parent(s): 41d8bd5

feat: initial commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +5 -0
  2. app.py +37 -0
  3. best.pt +3 -0
  4. init.sh +2 -0
  5. requirements.txt +31 -0
  6. ultralytics/yolov5/export.py +559 -0
  7. ultralytics/yolov5/hubconf.py +143 -0
  8. ultralytics/yolov5/models/__init__.py +0 -0
  9. ultralytics/yolov5/models/common.py +684 -0
  10. ultralytics/yolov5/models/experimental.py +121 -0
  11. ultralytics/yolov5/models/hub/anchors.yaml +59 -0
  12. ultralytics/yolov5/models/hub/yolov3-spp.yaml +51 -0
  13. ultralytics/yolov5/models/hub/yolov3-tiny.yaml +41 -0
  14. ultralytics/yolov5/models/hub/yolov3.yaml +51 -0
  15. ultralytics/yolov5/models/hub/yolov5-bifpn.yaml +48 -0
  16. ultralytics/yolov5/models/hub/yolov5-fpn.yaml +42 -0
  17. ultralytics/yolov5/models/hub/yolov5-p2.yaml +54 -0
  18. ultralytics/yolov5/models/hub/yolov5-p34.yaml +41 -0
  19. ultralytics/yolov5/models/hub/yolov5-p6.yaml +56 -0
  20. ultralytics/yolov5/models/hub/yolov5-p7.yaml +67 -0
  21. ultralytics/yolov5/models/hub/yolov5-panet.yaml +48 -0
  22. ultralytics/yolov5/models/hub/yolov5l6.yaml +60 -0
  23. ultralytics/yolov5/models/hub/yolov5m6.yaml +60 -0
  24. ultralytics/yolov5/models/hub/yolov5n6.yaml +60 -0
  25. ultralytics/yolov5/models/hub/yolov5s-ghost.yaml +48 -0
  26. ultralytics/yolov5/models/hub/yolov5s-transformer.yaml +48 -0
  27. ultralytics/yolov5/models/hub/yolov5s6.yaml +60 -0
  28. ultralytics/yolov5/models/hub/yolov5x6.yaml +60 -0
  29. ultralytics/yolov5/models/tf.py +466 -0
  30. ultralytics/yolov5/models/yolo.py +329 -0
  31. ultralytics/yolov5/models/yolov5l.yaml +48 -0
  32. ultralytics/yolov5/models/yolov5m.yaml +48 -0
  33. ultralytics/yolov5/models/yolov5n.yaml +48 -0
  34. ultralytics/yolov5/models/yolov5s.yaml +48 -0
  35. ultralytics/yolov5/models/yolov5x.yaml +48 -0
  36. ultralytics/yolov5/utils/__init__.py +36 -0
  37. ultralytics/yolov5/utils/activations.py +101 -0
  38. ultralytics/yolov5/utils/augmentations.py +277 -0
  39. ultralytics/yolov5/utils/autoanchor.py +170 -0
  40. ultralytics/yolov5/utils/autobatch.py +58 -0
  41. ultralytics/yolov5/utils/aws/__init__.py +0 -0
  42. ultralytics/yolov5/utils/aws/mime.sh +26 -0
  43. ultralytics/yolov5/utils/aws/resume.py +40 -0
  44. ultralytics/yolov5/utils/aws/userdata.sh +27 -0
  45. ultralytics/yolov5/utils/benchmarks.py +104 -0
  46. ultralytics/yolov5/utils/callbacks.py +78 -0
  47. ultralytics/yolov5/utils/datasets.py +1039 -0
  48. ultralytics/yolov5/utils/downloads.py +153 -0
  49. ultralytics/yolov5/utils/flask_rest_api/README.md +73 -0
  50. ultralytics/yolov5/utils/flask_rest_api/example_request.py +13 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ .DS_Store
2
+ yolov5s.pt
3
+ __pycache__
4
+ *.jpg
5
+ gradio_queue.db
app.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from PIL import Image
4
+
5
+ # Images
6
+ torch.hub.download_url_to_file(
7
+ 'https://iiif.dl.itc.u-tokyo.ac.jp/iiif/genji/TIFF/A00_6587/01/01_0004.tif/full/1024,/0/default.jpg', '『源氏物語』(東京大学総合図書館所蔵).jpg')
8
+ torch.hub.download_url_to_file(
9
+ 'https://rmda.kulib.kyoto-u.ac.jp/iiif/RB00007030/01/RB00007030_00003_0.ptif/full/1024,/0/default.jpg', '『源氏物語』(京都大学所蔵).jpg')
10
+ torch.hub.download_url_to_file(
11
+ 'https://kotenseki.nijl.ac.jp/api/iiif/100312034/v4/HRSM/HRSM-00396/HRSM-00396-00012.tif/full/1024,/0/default.jpg', '『平家物語』(国文学研究資料館提供).jpg')
12
+
13
+ # Model
14
+ # model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # force_reload=True to update
15
+ model = torch.hub.load('ultralytics/yolov5', 'custom',
16
+ path='best.pt', source="local")
17
+
18
+
19
+ def yolo(im, size=1024):
20
+ g = (size / max(im.size)) # gain
21
+ im = im.resize((int(x * g) for x in im.size), resample=Image.Resampling.LANCZOS) # resize
22
+
23
+ results = model(im) # inference
24
+ results.render() # updates results.imgs with boxes and labels
25
+ return Image.fromarray(results.imgs[0])
26
+
27
+
28
+ inputs = gr.inputs.Image(type='pil', label="Original Image")
29
+ outputs = gr.outputs.Image(type="pil", label="Output Image")
30
+
31
+ title = "YOLOv5 NDL-DocL Datasets"
32
+ description = "YOLOv5 NDL-DocL Datasets Gradio demo for object detection. Upload an image or click an example image to use."
33
+ article = "<p style='text-align: center'>YOLOv5 NDL-DocL Datasets is an object detection model trained on the <a href=\"https://github.com/ndl-lab/layout-dataset\">NDL-DocL Datasets</a>.</p>"
34
+
35
+ examples = [['『源氏物語』(東京大学総合図書館所蔵).jpg'], ['『源氏物語』(京都大学所蔵).jpg'], ['『平家物語』(国文学研究資料館提供).jpg']]
36
+ gr.Interface(yolo, inputs, outputs, title=title, description=description, article=article,
37
+ examples=examples, theme="huggingface").launch(enable_queue=True) # cache_examples=True,
best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:497dd54a738a54abfc938507c16b77e4e46930372e6e189ae87895aa5bba0b7c
3
+ size 173348189
init.sh ADDED
@@ -0,0 +1,2 @@
 
 
1
+ rm best.pt
2
+ gdown https://drive.google.com/uc?id=1DduqMfElGLPYWZTbrEO8F3qn6VPOZDPM
requirements.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pip install -r requirements.txt
2
+
3
+ # base ----------------------------------------
4
+ matplotlib>=3.2.2
5
+ numpy>=1.18.5
6
+ opencv-python-headless
7
+ Pillow
8
+ PyYAML>=5.3.1
9
+ scipy>=1.4.1
10
+ torch>=1.7.0
11
+ torchvision>=0.8.1
12
+ tqdm>=4.41.0
13
+
14
+ # logging -------------------------------------
15
+ tensorboard>=2.4.1
16
+ # wandb
17
+
18
+ # plotting ------------------------------------
19
+ seaborn>=0.11.0
20
+ pandas
21
+
22
+ # export --------------------------------------
23
+ # coremltools>=4.1
24
+ # onnx>=1.9.0
25
+ # scikit-learn==0.19.2 # for coreml quantization
26
+
27
+ # extras --------------------------------------
28
+ # Cython # for pycocotools https://github.com/cocodataset/cocoapi/issues/172
29
+ # pycocotools>=2.0 # COCO mAP
30
+ # albumentations>=1.0.3
31
+ thop # FLOPs computation
ultralytics/yolov5/export.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+
23
+ Usage:
24
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
25
+
26
+ Inference:
27
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
28
+ yolov5s.torchscript # TorchScript
29
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
30
+ yolov5s.xml # OpenVINO
31
+ yolov5s.engine # TensorRT
32
+ yolov5s.mlmodel # CoreML (MacOS-only)
33
+ yolov5s_saved_model # TensorFlow SavedModel
34
+ yolov5s.pb # TensorFlow GraphDef
35
+ yolov5s.tflite # TensorFlow Lite
36
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
37
+
38
+ TensorFlow.js:
39
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
40
+ $ npm install
41
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
42
+ $ npm start
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import platform
49
+ import subprocess
50
+ import sys
51
+ import time
52
+ import warnings
53
+ from pathlib import Path
54
+
55
+ import pandas as pd
56
+ import torch
57
+ import torch.nn as nn
58
+ from torch.utils.mobile_optimizer import optimize_for_mobile
59
+
60
+ FILE = Path(__file__).resolve()
61
+ ROOT = FILE.parents[0] # YOLOv5 root directory
62
+ if str(ROOT) not in sys.path:
63
+ sys.path.append(str(ROOT)) # add ROOT to PATH
64
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
65
+
66
+ from models.common import Conv
67
+ from models.experimental import attempt_load
68
+ from models.yolo import Detect
69
+ from utils.activations import SiLU
70
+ from utils.datasets import LoadImages
71
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
72
+ file_size, print_args, url2file)
73
+ from utils.torch_utils import select_device
74
+
75
+
76
+ def export_formats():
77
+ # YOLOv5 export formats
78
+ x = [['PyTorch', '-', '.pt', True],
79
+ ['TorchScript', 'torchscript', '.torchscript', True],
80
+ ['ONNX', 'onnx', '.onnx', True],
81
+ ['OpenVINO', 'openvino', '_openvino_model', False],
82
+ ['TensorRT', 'engine', '.engine', True],
83
+ ['CoreML', 'coreml', '.mlmodel', False],
84
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True],
85
+ ['TensorFlow GraphDef', 'pb', '.pb', True],
86
+ ['TensorFlow Lite', 'tflite', '.tflite', False],
87
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False],
88
+ ['TensorFlow.js', 'tfjs', '_web_model', False]]
89
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'GPU'])
90
+
91
+
92
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
93
+ # YOLOv5 TorchScript model export
94
+ try:
95
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
96
+ f = file.with_suffix('.torchscript')
97
+
98
+ ts = torch.jit.trace(model, im, strict=False)
99
+ d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
100
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
101
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
102
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
103
+ else:
104
+ ts.save(str(f), _extra_files=extra_files)
105
+
106
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
107
+ return f
108
+ except Exception as e:
109
+ LOGGER.info(f'{prefix} export failure: {e}')
110
+
111
+
112
+ def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
113
+ # YOLOv5 ONNX export
114
+ try:
115
+ check_requirements(('onnx',))
116
+ import onnx
117
+
118
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
119
+ f = file.with_suffix('.onnx')
120
+
121
+ torch.onnx.export(model, im, f, verbose=False, opset_version=opset,
122
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
123
+ do_constant_folding=not train,
124
+ input_names=['images'],
125
+ output_names=['output'],
126
+ dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
127
+ 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
128
+ } if dynamic else None)
129
+
130
+ # Checks
131
+ model_onnx = onnx.load(f) # load onnx model
132
+ onnx.checker.check_model(model_onnx) # check onnx model
133
+ # LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print
134
+
135
+ # Simplify
136
+ if simplify:
137
+ try:
138
+ check_requirements(('onnx-simplifier',))
139
+ import onnxsim
140
+
141
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
142
+ model_onnx, check = onnxsim.simplify(
143
+ model_onnx,
144
+ dynamic_input_shape=dynamic,
145
+ input_shapes={'images': list(im.shape)} if dynamic else None)
146
+ assert check, 'assert check failed'
147
+ onnx.save(model_onnx, f)
148
+ except Exception as e:
149
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
150
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
151
+ return f
152
+ except Exception as e:
153
+ LOGGER.info(f'{prefix} export failure: {e}')
154
+
155
+
156
+ def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):
157
+ # YOLOv5 OpenVINO export
158
+ try:
159
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
160
+ import openvino.inference_engine as ie
161
+
162
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
163
+ f = str(file).replace('.pt', '_openvino_model' + os.sep)
164
+
165
+ cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"
166
+ subprocess.check_output(cmd, shell=True)
167
+
168
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
169
+ return f
170
+ except Exception as e:
171
+ LOGGER.info(f'\n{prefix} export failure: {e}')
172
+
173
+
174
+ def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
175
+ # YOLOv5 CoreML export
176
+ try:
177
+ check_requirements(('coremltools',))
178
+ import coremltools as ct
179
+
180
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
181
+ f = file.with_suffix('.mlmodel')
182
+
183
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
184
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
185
+ ct_model.save(f)
186
+
187
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
188
+ return ct_model, f
189
+ except Exception as e:
190
+ LOGGER.info(f'\n{prefix} export failure: {e}')
191
+ return None, None
192
+
193
+
194
+ def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
195
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
196
+ try:
197
+ check_requirements(('tensorrt',))
198
+ import tensorrt as trt
199
+
200
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
201
+ grid = model.model[-1].anchor_grid
202
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
203
+ export_onnx(model, im, file, 12, train, False, simplify) # opset 12
204
+ model.model[-1].anchor_grid = grid
205
+ else: # TensorRT >= 8
206
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
207
+ export_onnx(model, im, file, 13, train, False, simplify) # opset 13
208
+ onnx = file.with_suffix('.onnx')
209
+
210
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
211
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
212
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
213
+ f = file.with_suffix('.engine') # TensorRT engine file
214
+ logger = trt.Logger(trt.Logger.INFO)
215
+ if verbose:
216
+ logger.min_severity = trt.Logger.Severity.VERBOSE
217
+
218
+ builder = trt.Builder(logger)
219
+ config = builder.create_builder_config()
220
+ config.max_workspace_size = workspace * 1 << 30
221
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
222
+
223
+ flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
224
+ network = builder.create_network(flag)
225
+ parser = trt.OnnxParser(network, logger)
226
+ if not parser.parse_from_file(str(onnx)):
227
+ raise RuntimeError(f'failed to load ONNX file: {onnx}')
228
+
229
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
230
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
231
+ LOGGER.info(f'{prefix} Network Description:')
232
+ for inp in inputs:
233
+ LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
234
+ for out in outputs:
235
+ LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
236
+
237
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 else 32} engine in {f}')
238
+ if builder.platform_has_fast_fp16:
239
+ config.set_flag(trt.BuilderFlag.FP16)
240
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
241
+ t.write(engine.serialize())
242
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
243
+ return f
244
+ except Exception as e:
245
+ LOGGER.info(f'\n{prefix} export failure: {e}')
246
+
247
+
248
+ def export_saved_model(model, im, file, dynamic,
249
+ tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
250
+ conf_thres=0.25, keras=False, prefix=colorstr('TensorFlow SavedModel:')):
251
+ # YOLOv5 TensorFlow SavedModel export
252
+ try:
253
+ import tensorflow as tf
254
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
255
+
256
+ from models.tf import TFDetect, TFModel
257
+
258
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
259
+ f = str(file).replace('.pt', '_saved_model')
260
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
261
+
262
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
263
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
264
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
265
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
266
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
267
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
268
+ keras_model.trainable = False
269
+ keras_model.summary()
270
+ if keras:
271
+ keras_model.save(f, save_format='tf')
272
+ else:
273
+ m = tf.function(lambda x: keras_model(x)) # full model
274
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
275
+ m = m.get_concrete_function(spec)
276
+ frozen_func = convert_variables_to_constants_v2(m)
277
+ tfm = tf.Module()
278
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[0], [spec])
279
+ tfm.__call__(im)
280
+ tf.saved_model.save(
281
+ tfm,
282
+ f,
283
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False) if
284
+ check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
285
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
286
+ return keras_model, f
287
+ except Exception as e:
288
+ LOGGER.info(f'\n{prefix} export failure: {e}')
289
+ return None, None
290
+
291
+
292
+ def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
293
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
294
+ try:
295
+ import tensorflow as tf
296
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
297
+
298
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
299
+ f = file.with_suffix('.pb')
300
+
301
+ m = tf.function(lambda x: keras_model(x)) # full model
302
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
303
+ frozen_func = convert_variables_to_constants_v2(m)
304
+ frozen_func.graph.as_graph_def()
305
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
306
+
307
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
308
+ return f
309
+ except Exception as e:
310
+ LOGGER.info(f'\n{prefix} export failure: {e}')
311
+
312
+
313
+ def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):
314
+ # YOLOv5 TensorFlow Lite export
315
+ try:
316
+ import tensorflow as tf
317
+
318
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
319
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
320
+ f = str(file).replace('.pt', '-fp16.tflite')
321
+
322
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
323
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
324
+ converter.target_spec.supported_types = [tf.float16]
325
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
326
+ if int8:
327
+ from models.tf import representative_dataset_gen
328
+ dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
329
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
330
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
331
+ converter.target_spec.supported_types = []
332
+ converter.inference_input_type = tf.uint8 # or tf.int8
333
+ converter.inference_output_type = tf.uint8 # or tf.int8
334
+ converter.experimental_new_quantizer = True
335
+ f = str(file).replace('.pt', '-int8.tflite')
336
+
337
+ tflite_model = converter.convert()
338
+ open(f, "wb").write(tflite_model)
339
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
340
+ return f
341
+ except Exception as e:
342
+ LOGGER.info(f'\n{prefix} export failure: {e}')
343
+
344
+
345
+ def export_edgetpu(keras_model, im, file, prefix=colorstr('Edge TPU:')):
346
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
347
+ try:
348
+ cmd = 'edgetpu_compiler --version'
349
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
350
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
351
+ if subprocess.run(cmd + ' >/dev/null', shell=True).returncode != 0:
352
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
353
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
354
+ for c in ['curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
355
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
356
+ 'sudo apt-get update',
357
+ 'sudo apt-get install edgetpu-compiler']:
358
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
359
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
360
+
361
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
362
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
363
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
364
+
365
+ cmd = f"edgetpu_compiler -s {f_tfl}"
366
+ subprocess.run(cmd, shell=True, check=True)
367
+
368
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
369
+ return f
370
+ except Exception as e:
371
+ LOGGER.info(f'\n{prefix} export failure: {e}')
372
+
373
+
374
+ def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
375
+ # YOLOv5 TensorFlow.js export
376
+ try:
377
+ check_requirements(('tensorflowjs',))
378
+ import re
379
+
380
+ import tensorflowjs as tfjs
381
+
382
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
383
+ f = str(file).replace('.pt', '_web_model') # js dir
384
+ f_pb = file.with_suffix('.pb') # *.pb path
385
+ f_json = f + '/model.json' # *.json path
386
+
387
+ cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
388
+ f'--output_node_names="Identity,Identity_1,Identity_2,Identity_3" {f_pb} {f}'
389
+ subprocess.run(cmd, shell=True)
390
+
391
+ json = open(f_json).read()
392
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
393
+ subst = re.sub(
394
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
395
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
396
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
397
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}',
398
+ r'{"outputs": {"Identity": {"name": "Identity"}, '
399
+ r'"Identity_1": {"name": "Identity_1"}, '
400
+ r'"Identity_2": {"name": "Identity_2"}, '
401
+ r'"Identity_3": {"name": "Identity_3"}}}',
402
+ json)
403
+ j.write(subst)
404
+
405
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
406
+ return f
407
+ except Exception as e:
408
+ LOGGER.info(f'\n{prefix} export failure: {e}')
409
+
410
+
411
+ @torch.no_grad()
412
+ def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
413
+ weights=ROOT / 'yolov5s.pt', # weights path
414
+ imgsz=(640, 640), # image (height, width)
415
+ batch_size=1, # batch size
416
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
417
+ include=('torchscript', 'onnx'), # include formats
418
+ half=False, # FP16 half-precision export
419
+ inplace=False, # set YOLOv5 Detect() inplace=True
420
+ train=False, # model.train() mode
421
+ optimize=False, # TorchScript: optimize for mobile
422
+ int8=False, # CoreML/TF INT8 quantization
423
+ dynamic=False, # ONNX/TF: dynamic axes
424
+ simplify=False, # ONNX: simplify model
425
+ opset=12, # ONNX: opset version
426
+ verbose=False, # TensorRT: verbose log
427
+ workspace=4, # TensorRT: workspace size (GB)
428
+ nms=False, # TF: add NMS to model
429
+ agnostic_nms=False, # TF: add agnostic NMS to model
430
+ topk_per_class=100, # TF.js NMS: topk per class to keep
431
+ topk_all=100, # TF.js NMS: topk for all classes to keep
432
+ iou_thres=0.45, # TF.js NMS: IoU threshold
433
+ conf_thres=0.25 # TF.js NMS: confidence threshold
434
+ ):
435
+ t = time.time()
436
+ include = [x.lower() for x in include] # to lowercase
437
+ formats = tuple(export_formats()['Argument'][1:]) # --include arguments
438
+ flags = [x in include for x in formats]
439
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {formats}'
440
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
441
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
442
+
443
+ # Load PyTorch model
444
+ device = select_device(device)
445
+ assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
446
+ model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
447
+ nc, names = model.nc, model.names # number of classes, class names
448
+
449
+ # Checks
450
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
451
+ opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
452
+ assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
453
+
454
+ # Input
455
+ gs = int(max(model.stride)) # grid size (max stride)
456
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
457
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
458
+
459
+ # Update model
460
+ if half:
461
+ im, model = im.half(), model.half() # to FP16
462
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
463
+ for k, m in model.named_modules():
464
+ if isinstance(m, Conv): # assign export-friendly activations
465
+ if isinstance(m.act, nn.SiLU):
466
+ m.act = SiLU()
467
+ elif isinstance(m, Detect):
468
+ m.inplace = inplace
469
+ m.onnx_dynamic = dynamic
470
+ if hasattr(m, 'forward_export'):
471
+ m.forward = m.forward_export # assign custom forward (optional)
472
+
473
+ for _ in range(2):
474
+ y = model(im) # dry runs
475
+ shape = tuple(y[0].shape) # model output shape
476
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
477
+
478
+ # Exports
479
+ f = [''] * 10 # exported filenames
480
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
481
+ if jit:
482
+ f[0] = export_torchscript(model, im, file, optimize)
483
+ if engine: # TensorRT required before ONNX
484
+ f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
485
+ if onnx or xml: # OpenVINO requires ONNX
486
+ f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
487
+ if xml: # OpenVINO
488
+ f[3] = export_openvino(model, im, file)
489
+ if coreml:
490
+ _, f[4] = export_coreml(model, im, file)
491
+
492
+ # TensorFlow Exports
493
+ if any((saved_model, pb, tflite, edgetpu, tfjs)):
494
+ if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
495
+ check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
496
+ assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
497
+ model, f[5] = export_saved_model(model.cpu(), im, file, dynamic, tf_nms=nms or agnostic_nms or tfjs,
498
+ agnostic_nms=agnostic_nms or tfjs, topk_per_class=topk_per_class,
499
+ topk_all=topk_all, conf_thres=conf_thres, iou_thres=iou_thres) # keras model
500
+ if pb or tfjs: # pb prerequisite to tfjs
501
+ f[6] = export_pb(model, im, file)
502
+ if tflite or edgetpu:
503
+ f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, ncalib=100)
504
+ if edgetpu:
505
+ f[8] = export_edgetpu(model, im, file)
506
+ if tfjs:
507
+ f[9] = export_tfjs(model, im, file)
508
+
509
+ # Finish
510
+ f = [str(x) for x in f if x] # filter out '' and None
511
+ if any(f):
512
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
513
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
514
+ f"\nDetect: python detect.py --weights {f[-1]}"
515
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
516
+ f"\nValidate: python val.py --weights {f[-1]}"
517
+ f"\nVisualize: https://netron.app")
518
+ return f # return list of exported files/dirs
519
+
520
+
521
+ def parse_opt():
522
+ parser = argparse.ArgumentParser()
523
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
524
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
525
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
526
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
527
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
528
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
529
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
530
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
531
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
532
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
533
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
534
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
535
+ parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
536
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
537
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
538
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
539
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
540
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
541
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
542
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
543
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
544
+ parser.add_argument('--include', nargs='+',
545
+ default=['torchscript', 'onnx'],
546
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
547
+ opt = parser.parse_args()
548
+ print_args(FILE.stem, opt)
549
+ return opt
550
+
551
+
552
+ def main(opt):
553
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
554
+ run(**vars(opt))
555
+
556
+
557
+ if __name__ == "__main__":
558
+ opt = parse_opt()
559
+ main(opt)
ultralytics/yolov5/hubconf.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
4
+
5
+ Usage:
6
+ import torch
7
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
8
+ model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch
9
+ """
10
+
11
+ import torch
12
+
13
+
14
+ def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
15
+ """Creates or loads a YOLOv5 model
16
+
17
+ Arguments:
18
+ name (str): model name 'yolov5s' or path 'path/to/best.pt'
19
+ pretrained (bool): load pretrained weights into the model
20
+ channels (int): number of input channels
21
+ classes (int): number of model classes
22
+ autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
23
+ verbose (bool): print all information to screen
24
+ device (str, torch.device, None): device to use for model parameters
25
+
26
+ Returns:
27
+ YOLOv5 model
28
+ """
29
+ from pathlib import Path
30
+
31
+ from models.common import AutoShape, DetectMultiBackend
32
+ from models.yolo import Model
33
+ from utils.downloads import attempt_download
34
+ from utils.general import LOGGER, check_requirements, intersect_dicts, logging
35
+ from utils.torch_utils import select_device
36
+
37
+ if not verbose:
38
+ LOGGER.setLevel(logging.WARNING)
39
+ check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
40
+ name = Path(name)
41
+ path = name.with_suffix('.pt') if name.suffix == '' else name # 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 = DetectMultiBackend(path, device=device) # download/load FP32 model
47
+ # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model
48
+ else:
49
+ cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
50
+ model = Model(cfg, channels, classes) # create model
51
+ if pretrained:
52
+ ckpt = torch.load(attempt_download(path), map_location=device) # load
53
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
54
+ csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
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 = AutoShape(model) # 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 = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
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
+ from pathlib import Path
129
+
130
+ import cv2
131
+ import numpy as np
132
+ from PIL import Image
133
+
134
+ imgs = ['data/images/zidane.jpg', # filename
135
+ Path('data/images/zidane.jpg'), # Path
136
+ 'https://ultralytics.com/images/zidane.jpg', # URI
137
+ cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
138
+ Image.open('data/images/bus.jpg'), # PIL
139
+ np.zeros((320, 640, 3))] # numpy
140
+
141
+ results = model(imgs, size=320) # batched inference
142
+ results.print()
143
+ results.save()
ultralytics/yolov5/models/__init__.py ADDED
File without changes
ultralytics/yolov5/models/common.py ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Common modules
4
+ """
5
+
6
+ import json
7
+ import math
8
+ import platform
9
+ import warnings
10
+ from collections import OrderedDict, namedtuple
11
+ from copy import copy
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import pandas as pd
17
+ import requests
18
+ import torch
19
+ import torch.nn as nn
20
+ import yaml
21
+ from PIL import Image
22
+ from torch.cuda import amp
23
+
24
+ from utils.datasets import exif_transpose, letterbox
25
+ from utils.general import (LOGGER, check_requirements, check_suffix, check_version, colorstr, increment_path,
26
+ make_divisible, non_max_suppression, scale_coords, xywh2xyxy, xyxy2xywh)
27
+ from utils.plots import Annotator, colors, save_one_box
28
+ from utils.torch_utils import copy_attr, time_sync
29
+
30
+
31
+ def autopad(k, p=None): # kernel, padding
32
+ # Pad to 'same'
33
+ if p is None:
34
+ p = k // 2 if isinstance(k, int) else (x // 2 for x in k) # auto-pad
35
+ return p
36
+
37
+
38
+ class Conv(nn.Module):
39
+ # Standard convolution
40
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
41
+ super().__init__()
42
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
43
+ self.bn = nn.BatchNorm2d(c2)
44
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
45
+
46
+ def forward(self, x):
47
+ return self.act(self.bn(self.conv(x)))
48
+
49
+ def forward_fuse(self, x):
50
+ return self.act(self.conv(x))
51
+
52
+
53
+ class DWConv(Conv):
54
+ # Depth-wise convolution class
55
+ def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
56
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
57
+
58
+
59
+ class TransformerLayer(nn.Module):
60
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
61
+ def __init__(self, c, num_heads):
62
+ super().__init__()
63
+ self.q = nn.Linear(c, c, bias=False)
64
+ self.k = nn.Linear(c, c, bias=False)
65
+ self.v = nn.Linear(c, c, bias=False)
66
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
67
+ self.fc1 = nn.Linear(c, c, bias=False)
68
+ self.fc2 = nn.Linear(c, c, bias=False)
69
+
70
+ def forward(self, x):
71
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
72
+ x = self.fc2(self.fc1(x)) + x
73
+ return x
74
+
75
+
76
+ class TransformerBlock(nn.Module):
77
+ # Vision Transformer https://arxiv.org/abs/2010.11929
78
+ def __init__(self, c1, c2, num_heads, num_layers):
79
+ super().__init__()
80
+ self.conv = None
81
+ if c1 != c2:
82
+ self.conv = Conv(c1, c2)
83
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
84
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
85
+ self.c2 = c2
86
+
87
+ def forward(self, x):
88
+ if self.conv is not None:
89
+ x = self.conv(x)
90
+ b, _, w, h = x.shape
91
+ p = x.flatten(2).permute(2, 0, 1)
92
+ return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
93
+
94
+
95
+ class Bottleneck(nn.Module):
96
+ # Standard bottleneck
97
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
98
+ super().__init__()
99
+ c_ = int(c2 * e) # hidden channels
100
+ self.cv1 = Conv(c1, c_, 1, 1)
101
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
102
+ self.add = shortcut and c1 == c2
103
+
104
+ def forward(self, x):
105
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
106
+
107
+
108
+ class BottleneckCSP(nn.Module):
109
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
110
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
111
+ super().__init__()
112
+ c_ = int(c2 * e) # hidden channels
113
+ self.cv1 = Conv(c1, c_, 1, 1)
114
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
115
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
116
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
117
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
118
+ self.act = nn.SiLU()
119
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
120
+
121
+ def forward(self, x):
122
+ y1 = self.cv3(self.m(self.cv1(x)))
123
+ y2 = self.cv2(x)
124
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
125
+
126
+
127
+ class C3(nn.Module):
128
+ # CSP Bottleneck with 3 convolutions
129
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
130
+ super().__init__()
131
+ c_ = int(c2 * e) # hidden channels
132
+ self.cv1 = Conv(c1, c_, 1, 1)
133
+ self.cv2 = Conv(c1, c_, 1, 1)
134
+ self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
135
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
136
+ # self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
137
+
138
+ def forward(self, x):
139
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
140
+
141
+
142
+ class C3TR(C3):
143
+ # C3 module with TransformerBlock()
144
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
145
+ super().__init__(c1, c2, n, shortcut, g, e)
146
+ c_ = int(c2 * e)
147
+ self.m = TransformerBlock(c_, c_, 4, n)
148
+
149
+
150
+ class C3SPP(C3):
151
+ # C3 module with SPP()
152
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
153
+ super().__init__(c1, c2, n, shortcut, g, e)
154
+ c_ = int(c2 * e)
155
+ self.m = SPP(c_, c_, k)
156
+
157
+
158
+ class C3Ghost(C3):
159
+ # C3 module with GhostBottleneck()
160
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
161
+ super().__init__(c1, c2, n, shortcut, g, e)
162
+ c_ = int(c2 * e) # hidden channels
163
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
164
+
165
+
166
+ class SPP(nn.Module):
167
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
168
+ def __init__(self, c1, c2, k=(5, 9, 13)):
169
+ super().__init__()
170
+ c_ = c1 // 2 # hidden channels
171
+ self.cv1 = Conv(c1, c_, 1, 1)
172
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
173
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
174
+
175
+ def forward(self, x):
176
+ x = self.cv1(x)
177
+ with warnings.catch_warnings():
178
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
179
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
180
+
181
+
182
+ class SPPF(nn.Module):
183
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
184
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
185
+ super().__init__()
186
+ c_ = c1 // 2 # hidden channels
187
+ self.cv1 = Conv(c1, c_, 1, 1)
188
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
189
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
190
+
191
+ def forward(self, x):
192
+ x = self.cv1(x)
193
+ with warnings.catch_warnings():
194
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
195
+ y1 = self.m(x)
196
+ y2 = self.m(y1)
197
+ return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
198
+
199
+
200
+ class Focus(nn.Module):
201
+ # Focus wh information into c-space
202
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
203
+ super().__init__()
204
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
205
+ # self.contract = Contract(gain=2)
206
+
207
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
208
+ return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
209
+ # return self.conv(self.contract(x))
210
+
211
+
212
+ class GhostConv(nn.Module):
213
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
214
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
215
+ super().__init__()
216
+ c_ = c2 // 2 # hidden channels
217
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
218
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
219
+
220
+ def forward(self, x):
221
+ y = self.cv1(x)
222
+ return torch.cat((y, self.cv2(y)), 1)
223
+
224
+
225
+ class GhostBottleneck(nn.Module):
226
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
227
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
228
+ super().__init__()
229
+ c_ = c2 // 2
230
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
231
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
232
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
233
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
234
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
235
+
236
+ def forward(self, x):
237
+ return self.conv(x) + self.shortcut(x)
238
+
239
+
240
+ class Contract(nn.Module):
241
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
242
+ def __init__(self, gain=2):
243
+ super().__init__()
244
+ self.gain = gain
245
+
246
+ def forward(self, x):
247
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
248
+ s = self.gain
249
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
250
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
251
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
252
+
253
+
254
+ class Expand(nn.Module):
255
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
256
+ def __init__(self, gain=2):
257
+ super().__init__()
258
+ self.gain = gain
259
+
260
+ def forward(self, x):
261
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
262
+ s = self.gain
263
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
264
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
265
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
266
+
267
+
268
+ class Concat(nn.Module):
269
+ # Concatenate a list of tensors along dimension
270
+ def __init__(self, dimension=1):
271
+ super().__init__()
272
+ self.d = dimension
273
+
274
+ def forward(self, x):
275
+ return torch.cat(x, self.d)
276
+
277
+
278
+ class DetectMultiBackend(nn.Module):
279
+ # YOLOv5 MultiBackend class for python inference on various backends
280
+ def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False):
281
+ # Usage:
282
+ # PyTorch: weights = *.pt
283
+ # TorchScript: *.torchscript
284
+ # ONNX Runtime: *.onnx
285
+ # ONNX OpenCV DNN: *.onnx with --dnn
286
+ # OpenVINO: *.xml
287
+ # CoreML: *.mlmodel
288
+ # TensorRT: *.engine
289
+ # TensorFlow SavedModel: *_saved_model
290
+ # TensorFlow GraphDef: *.pb
291
+ # TensorFlow Lite: *.tflite
292
+ # TensorFlow Edge TPU: *_edgetpu.tflite
293
+ from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
294
+
295
+ super().__init__()
296
+ w = str(weights[0] if isinstance(weights, list) else weights)
297
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = self.model_type(w) # get backend
298
+ stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults
299
+ w = attempt_download(w) # download if not local
300
+ fp16 &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16
301
+ if data: # data.yaml path (optional)
302
+ with open(data, errors='ignore') as f:
303
+ names = yaml.safe_load(f)['names'] # class names
304
+
305
+ if pt: # PyTorch
306
+ model = attempt_load(weights if isinstance(weights, list) else w, map_location=device)
307
+ stride = max(int(model.stride.max()), 32) # model stride
308
+ names = model.module.names if hasattr(model, 'module') else model.names # get class names
309
+ model.half() if fp16 else model.float()
310
+ self.model = model # explicitly assign for to(), cpu(), cuda(), half()
311
+ elif jit: # TorchScript
312
+ LOGGER.info(f'Loading {w} for TorchScript inference...')
313
+ extra_files = {'config.txt': ''} # model metadata
314
+ model = torch.jit.load(w, _extra_files=extra_files)
315
+ model.half() if fp16 else model.float()
316
+ if extra_files['config.txt']:
317
+ d = json.loads(extra_files['config.txt']) # extra_files dict
318
+ stride, names = int(d['stride']), d['names']
319
+ elif dnn: # ONNX OpenCV DNN
320
+ LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')
321
+ check_requirements(('opencv-python>=4.5.4',))
322
+ net = cv2.dnn.readNetFromONNX(w)
323
+ elif onnx: # ONNX Runtime
324
+ LOGGER.info(f'Loading {w} for ONNX Runtime inference...')
325
+ cuda = torch.cuda.is_available()
326
+ check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))
327
+ import onnxruntime
328
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
329
+ session = onnxruntime.InferenceSession(w, providers=providers)
330
+ elif xml: # OpenVINO
331
+ LOGGER.info(f'Loading {w} for OpenVINO inference...')
332
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
333
+ import openvino.inference_engine as ie
334
+ core = ie.IECore()
335
+ if not Path(w).is_file(): # if not *.xml
336
+ w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir
337
+ network = core.read_network(model=w, weights=Path(w).with_suffix('.bin')) # *.xml, *.bin paths
338
+ executable_network = core.load_network(network, device_name='CPU', num_requests=1)
339
+ elif engine: # TensorRT
340
+ LOGGER.info(f'Loading {w} for TensorRT inference...')
341
+ import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
342
+ check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
343
+ Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))
344
+ logger = trt.Logger(trt.Logger.INFO)
345
+ with open(w, 'rb') as f, trt.Runtime(logger) as runtime:
346
+ model = runtime.deserialize_cuda_engine(f.read())
347
+ bindings = OrderedDict()
348
+ fp16 = False # default updated below
349
+ for index in range(model.num_bindings):
350
+ name = model.get_binding_name(index)
351
+ dtype = trt.nptype(model.get_binding_dtype(index))
352
+ shape = tuple(model.get_binding_shape(index))
353
+ data = torch.from_numpy(np.empty(shape, dtype=np.dtype(dtype))).to(device)
354
+ bindings[name] = Binding(name, dtype, shape, data, int(data.data_ptr()))
355
+ if model.binding_is_input(index) and dtype == np.float16:
356
+ fp16 = True
357
+ binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
358
+ context = model.create_execution_context()
359
+ batch_size = bindings['images'].shape[0]
360
+ elif coreml: # CoreML
361
+ LOGGER.info(f'Loading {w} for CoreML inference...')
362
+ import coremltools as ct
363
+ model = ct.models.MLModel(w)
364
+ else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
365
+ if saved_model: # SavedModel
366
+ LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')
367
+ import tensorflow as tf
368
+ keras = False # assume TF1 saved_model
369
+ model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
370
+ elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
371
+ LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')
372
+ import tensorflow as tf
373
+
374
+ def wrap_frozen_graph(gd, inputs, outputs):
375
+ x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
376
+ ge = x.graph.as_graph_element
377
+ return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
378
+
379
+ gd = tf.Graph().as_graph_def() # graph_def
380
+ gd.ParseFromString(open(w, 'rb').read())
381
+ frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs="Identity:0")
382
+ elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
383
+ try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
384
+ from tflite_runtime.interpreter import Interpreter, load_delegate
385
+ except ImportError:
386
+ import tensorflow as tf
387
+ Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,
388
+ if edgetpu: # Edge TPU https://coral.ai/software/#edgetpu-runtime
389
+ LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')
390
+ delegate = {'Linux': 'libedgetpu.so.1',
391
+ 'Darwin': 'libedgetpu.1.dylib',
392
+ 'Windows': 'edgetpu.dll'}[platform.system()]
393
+ interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
394
+ else: # Lite
395
+ LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')
396
+ interpreter = Interpreter(model_path=w) # load TFLite model
397
+ interpreter.allocate_tensors() # allocate
398
+ input_details = interpreter.get_input_details() # inputs
399
+ output_details = interpreter.get_output_details() # outputs
400
+ elif tfjs:
401
+ raise Exception('ERROR: YOLOv5 TF.js inference is not supported')
402
+ self.__dict__.update(locals()) # assign all variables to self
403
+
404
+ def forward(self, im, augment=False, visualize=False, val=False):
405
+ # YOLOv5 MultiBackend inference
406
+ b, ch, h, w = im.shape # batch, channel, height, width
407
+ if self.pt or self.jit: # PyTorch
408
+ y = self.model(im) if self.jit else self.model(im, augment=augment, visualize=visualize)
409
+ return y if val else y[0]
410
+ elif self.dnn: # ONNX OpenCV DNN
411
+ im = im.cpu().numpy() # torch to numpy
412
+ self.net.setInput(im)
413
+ y = self.net.forward()
414
+ elif self.onnx: # ONNX Runtime
415
+ im = im.cpu().numpy() # torch to numpy
416
+ y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0]
417
+ elif self.xml: # OpenVINO
418
+ im = im.cpu().numpy() # FP32
419
+ desc = self.ie.TensorDesc(precision='FP32', dims=im.shape, layout='NCHW') # Tensor Description
420
+ request = self.executable_network.requests[0] # inference request
421
+ request.set_blob(blob_name='images', blob=self.ie.Blob(desc, im)) # name=next(iter(request.input_blobs))
422
+ request.infer()
423
+ y = request.output_blobs['output'].buffer # name=next(iter(request.output_blobs))
424
+ elif self.engine: # TensorRT
425
+ assert im.shape == self.bindings['images'].shape, (im.shape, self.bindings['images'].shape)
426
+ self.binding_addrs['images'] = int(im.data_ptr())
427
+ self.context.execute_v2(list(self.binding_addrs.values()))
428
+ y = self.bindings['output'].data
429
+ elif self.coreml: # CoreML
430
+ im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
431
+ im = Image.fromarray((im[0] * 255).astype('uint8'))
432
+ # im = im.resize((192, 320), Image.ANTIALIAS)
433
+ y = self.model.predict({'image': im}) # coordinates are xywh normalized
434
+ if 'confidence' in y:
435
+ box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
436
+ conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
437
+ y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
438
+ else:
439
+ k = 'var_' + str(sorted(int(k.replace('var_', '')) for k in y)[-1]) # output key
440
+ y = y[k] # output
441
+ else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
442
+ im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
443
+ if self.saved_model: # SavedModel
444
+ y = (self.model(im, training=False) if self.keras else self.model(im)).numpy()
445
+ elif self.pb: # GraphDef
446
+ y = self.frozen_func(x=self.tf.constant(im)).numpy()
447
+ else: # Lite or Edge TPU
448
+ input, output = self.input_details[0], self.output_details[0]
449
+ int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
450
+ if int8:
451
+ scale, zero_point = input['quantization']
452
+ im = (im / scale + zero_point).astype(np.uint8) # de-scale
453
+ self.interpreter.set_tensor(input['index'], im)
454
+ self.interpreter.invoke()
455
+ y = self.interpreter.get_tensor(output['index'])
456
+ if int8:
457
+ scale, zero_point = output['quantization']
458
+ y = (y.astype(np.float32) - zero_point) * scale # re-scale
459
+ y[..., :4] *= [w, h, w, h] # xywh normalized to pixels
460
+
461
+ if isinstance(y, np.ndarray):
462
+ y = torch.tensor(y, device=self.device)
463
+ return (y, []) if val else y
464
+
465
+ def warmup(self, imgsz=(1, 3, 640, 640)):
466
+ # Warmup model by running inference once
467
+ if any((self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb)): # warmup types
468
+ if self.device.type != 'cpu': # only warmup GPU models
469
+ im = torch.zeros(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
470
+ for _ in range(2 if self.jit else 1): #
471
+ self.forward(im) # warmup
472
+
473
+ @staticmethod
474
+ def model_type(p='path/to/model.pt'):
475
+ # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx
476
+ from export import export_formats
477
+ suffixes = list(export_formats().Suffix) + ['.xml'] # export suffixes
478
+ check_suffix(p, suffixes) # checks
479
+ p = Path(p).name # eliminate trailing separators
480
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes)
481
+ xml |= xml2 # *_openvino_model or *.xml
482
+ tflite &= not edgetpu # *.tflite
483
+ return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs
484
+
485
+
486
+ class AutoShape(nn.Module):
487
+ # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
488
+ conf = 0.25 # NMS confidence threshold
489
+ iou = 0.45 # NMS IoU threshold
490
+ agnostic = False # NMS class-agnostic
491
+ multi_label = False # NMS multiple labels per box
492
+ classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
493
+ max_det = 1000 # maximum number of detections per image
494
+ amp = False # Automatic Mixed Precision (AMP) inference
495
+
496
+ def __init__(self, model):
497
+ super().__init__()
498
+ LOGGER.info('Adding AutoShape... ')
499
+ copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
500
+ self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
501
+ self.pt = not self.dmb or model.pt # PyTorch model
502
+ self.model = model.eval()
503
+
504
+ def _apply(self, fn):
505
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
506
+ self = super()._apply(fn)
507
+ if self.pt:
508
+ m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
509
+ m.stride = fn(m.stride)
510
+ m.grid = list(map(fn, m.grid))
511
+ if isinstance(m.anchor_grid, list):
512
+ m.anchor_grid = list(map(fn, m.anchor_grid))
513
+ return self
514
+
515
+ @torch.no_grad()
516
+ def forward(self, imgs, size=640, augment=False, profile=False):
517
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
518
+ # file: imgs = 'data/images/zidane.jpg' # str or PosixPath
519
+ # URI: = 'https://ultralytics.com/images/zidane.jpg'
520
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
521
+ # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
522
+ # numpy: = np.zeros((640,1280,3)) # HWC
523
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
524
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
525
+
526
+ t = [time_sync()]
527
+ p = next(self.model.parameters()) if self.pt else torch.zeros(1) # for device and type
528
+ autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
529
+ if isinstance(imgs, torch.Tensor): # torch
530
+ with amp.autocast(autocast):
531
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
532
+
533
+ # Pre-process
534
+ n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
535
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
536
+ for i, im in enumerate(imgs):
537
+ f = f'image{i}' # filename
538
+ if isinstance(im, (str, Path)): # filename or uri
539
+ im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
540
+ im = np.asarray(exif_transpose(im))
541
+ elif isinstance(im, Image.Image): # PIL Image
542
+ im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
543
+ files.append(Path(f).with_suffix('.jpg').name)
544
+ if im.shape[0] < 5: # image in CHW
545
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
546
+ im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
547
+ s = im.shape[:2] # HWC
548
+ shape0.append(s) # image shape
549
+ g = (size / max(s)) # gain
550
+ shape1.append([y * g for y in s])
551
+ imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
552
+ shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)] # inf shape
553
+ x = [letterbox(im, shape1, auto=False)[0] for im in imgs] # pad
554
+ x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
555
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
556
+ t.append(time_sync())
557
+
558
+ with amp.autocast(autocast):
559
+ # Inference
560
+ y = self.model(x, augment, profile) # forward
561
+ t.append(time_sync())
562
+
563
+ # Post-process
564
+ y = non_max_suppression(y if self.dmb else y[0], self.conf, self.iou, self.classes, self.agnostic,
565
+ self.multi_label, max_det=self.max_det) # NMS
566
+ for i in range(n):
567
+ scale_coords(shape1, y[i][:, :4], shape0[i])
568
+
569
+ t.append(time_sync())
570
+ return Detections(imgs, y, files, t, self.names, x.shape)
571
+
572
+
573
+ class Detections:
574
+ # YOLOv5 detections class for inference results
575
+ def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None):
576
+ super().__init__()
577
+ d = pred[0].device # device
578
+ gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations
579
+ self.imgs = imgs # list of images as numpy arrays
580
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
581
+ self.names = names # class names
582
+ self.files = files # image filenames
583
+ self.times = times # profiling times
584
+ self.xyxy = pred # xyxy pixels
585
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
586
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
587
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
588
+ self.n = len(self.pred) # number of images (batch size)
589
+ self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
590
+ self.s = shape # inference BCHW shape
591
+
592
+ def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
593
+ crops = []
594
+ for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
595
+ s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
596
+ if pred.shape[0]:
597
+ for c in pred[:, -1].unique():
598
+ n = (pred[:, -1] == c).sum() # detections per class
599
+ s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
600
+ if show or save or render or crop:
601
+ annotator = Annotator(im, example=str(self.names))
602
+ for *box, conf, cls in reversed(pred): # xyxy, confidence, class
603
+ label = f'{self.names[int(cls)]} {conf:.2f}'
604
+ if crop:
605
+ file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
606
+ crops.append({'box': box, 'conf': conf, 'cls': cls, 'label': label,
607
+ 'im': save_one_box(box, im, file=file, save=save)})
608
+ else: # all others
609
+ annotator.box_label(box, label, color=colors(cls))
610
+ im = annotator.im
611
+ else:
612
+ s += '(no detections)'
613
+
614
+ im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
615
+ if pprint:
616
+ LOGGER.info(s.rstrip(', '))
617
+ if show:
618
+ im.show(self.files[i]) # show
619
+ if save:
620
+ f = self.files[i]
621
+ im.save(save_dir / f) # save
622
+ if i == self.n - 1:
623
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
624
+ if render:
625
+ self.imgs[i] = np.asarray(im)
626
+ if crop:
627
+ if save:
628
+ LOGGER.info(f'Saved results to {save_dir}\n')
629
+ return crops
630
+
631
+ def print(self):
632
+ self.display(pprint=True) # print results
633
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
634
+ self.t)
635
+
636
+ def show(self):
637
+ self.display(show=True) # show results
638
+
639
+ def save(self, save_dir='runs/detect/exp'):
640
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
641
+ self.display(save=True, save_dir=save_dir) # save results
642
+
643
+ def crop(self, save=True, save_dir='runs/detect/exp'):
644
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
645
+ return self.display(crop=True, save=save, save_dir=save_dir) # crop results
646
+
647
+ def render(self):
648
+ self.display(render=True) # render results
649
+ return self.imgs
650
+
651
+ def pandas(self):
652
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
653
+ new = copy(self) # return copy
654
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
655
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
656
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
657
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
658
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
659
+ return new
660
+
661
+ def tolist(self):
662
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
663
+ r = range(self.n) # iterable
664
+ x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
665
+ # for d in x:
666
+ # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
667
+ # setattr(d, k, getattr(d, k)[0]) # pop out of list
668
+ return x
669
+
670
+ def __len__(self):
671
+ return self.n
672
+
673
+
674
+ class Classify(nn.Module):
675
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
676
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
677
+ super().__init__()
678
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
679
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
680
+ self.flat = nn.Flatten()
681
+
682
+ def forward(self, x):
683
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
684
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
ultralytics/yolov5/models/experimental.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Experimental modules
4
+ """
5
+ import math
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ from models.common import Conv
12
+ from utils.downloads import attempt_download
13
+
14
+
15
+ class CrossConv(nn.Module):
16
+ # Cross Convolution Downsample
17
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
18
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
19
+ super().__init__()
20
+ c_ = int(c2 * e) # hidden channels
21
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
22
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
23
+ self.add = shortcut and c1 == c2
24
+
25
+ def forward(self, x):
26
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
27
+
28
+
29
+ class Sum(nn.Module):
30
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
31
+ def __init__(self, n, weight=False): # n: number of inputs
32
+ super().__init__()
33
+ self.weight = weight # apply weights boolean
34
+ self.iter = range(n - 1) # iter object
35
+ if weight:
36
+ self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
37
+
38
+ def forward(self, x):
39
+ y = x[0] # no weight
40
+ if self.weight:
41
+ w = torch.sigmoid(self.w) * 2
42
+ for i in self.iter:
43
+ y = y + x[i + 1] * w[i]
44
+ else:
45
+ for i in self.iter:
46
+ y = y + x[i + 1]
47
+ return y
48
+
49
+
50
+ class MixConv2d(nn.Module):
51
+ # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
52
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
53
+ super().__init__()
54
+ n = len(k) # number of convolutions
55
+ if equal_ch: # equal c_ per group
56
+ i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
57
+ c_ = [(i == g).sum() for g in range(n)] # intermediate channels
58
+ else: # equal weight.numel() per group
59
+ b = [c2] + [0] * n
60
+ a = np.eye(n + 1, n, k=-1)
61
+ a -= np.roll(a, 1, axis=1)
62
+ a *= np.array(k) ** 2
63
+ a[0] = 1
64
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
65
+
66
+ self.m = nn.ModuleList(
67
+ [nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
68
+ self.bn = nn.BatchNorm2d(c2)
69
+ self.act = nn.SiLU()
70
+
71
+ def forward(self, x):
72
+ return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
73
+
74
+
75
+ class Ensemble(nn.ModuleList):
76
+ # Ensemble of models
77
+ def __init__(self):
78
+ super().__init__()
79
+
80
+ def forward(self, x, augment=False, profile=False, visualize=False):
81
+ y = []
82
+ for module in self:
83
+ y.append(module(x, augment, profile, visualize)[0])
84
+ # y = torch.stack(y).max(0)[0] # max ensemble
85
+ # y = torch.stack(y).mean(0) # mean ensemble
86
+ y = torch.cat(y, 1) # nms ensemble
87
+ return y, None # inference, train output
88
+
89
+
90
+ def attempt_load(weights, map_location=None, inplace=True, fuse=True):
91
+ from models.yolo import Detect, Model
92
+
93
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
94
+ model = Ensemble()
95
+ for w in weights if isinstance(weights, list) else [weights]:
96
+ ckpt = torch.load(attempt_download(w), map_location=map_location) # load
97
+ ckpt = (ckpt.get('ema') or ckpt['model']).float() # FP32 model
98
+ model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode
99
+
100
+ # Compatibility updates
101
+ for m in model.modules():
102
+ t = type(m)
103
+ if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
104
+ m.inplace = inplace # torch 1.7.0 compatibility
105
+ if t 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 t is Conv:
110
+ m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility
111
+ elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
112
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
113
+
114
+ if len(model) == 1:
115
+ return model[-1] # return model
116
+ else:
117
+ print(f'Ensemble created with {weights}\n')
118
+ for k in ['names']:
119
+ setattr(model, k, getattr(model[-1], k))
120
+ model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
121
+ return model # return ensemble
ultralytics/yolov5/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
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/models/hub/yolov5-bifpn.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 BiFPN head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
ultralytics/yolov5/models/hub/yolov5-fpn.yaml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 FPN head
28
+ head:
29
+ [[-1, 3, C3, [1024, False]], # 10 (P5/32-large)
30
+
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 3, C3, [512, False]], # 14 (P4/16-medium)
35
+
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 3, C3, [256, False]], # 18 (P3/8-small)
40
+
41
+ [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42
+ ]
ultralytics/yolov5/models/hub/yolov5-p2.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 6, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [1024]],
21
+ [-1, 1, SPPF, [1024, 5]], # 9
22
+ ]
23
+
24
+ # YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs
25
+ head:
26
+ [[-1, 1, Conv, [512, 1, 1]],
27
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
28
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
29
+ [-1, 3, C3, [512, False]], # 13
30
+
31
+ [-1, 1, Conv, [256, 1, 1]],
32
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
34
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
35
+
36
+ [-1, 1, Conv, [128, 1, 1]],
37
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38
+ [[-1, 2], 1, Concat, [1]], # cat backbone P2
39
+ [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall)
40
+
41
+ [-1, 1, Conv, [128, 3, 2]],
42
+ [[-1, 18], 1, Concat, [1]], # cat head P3
43
+ [-1, 3, C3, [256, False]], # 24 (P3/8-small)
44
+
45
+ [-1, 1, Conv, [256, 3, 2]],
46
+ [[-1, 14], 1, Concat, [1]], # cat head P4
47
+ [-1, 3, C3, [512, False]], # 27 (P4/16-medium)
48
+
49
+ [-1, 1, Conv, [512, 3, 2]],
50
+ [[-1, 10], 1, Concat, [1]], # cat head P5
51
+ [-1, 3, C3, [1024, False]], # 30 (P5/32-large)
52
+
53
+ [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
54
+ ]
ultralytics/yolov5/models/hub/yolov5-p34.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 0-P1/2
13
+ [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14
+ [ -1, 3, C3, [ 128 ] ],
15
+ [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16
+ [ -1, 6, C3, [ 256 ] ],
17
+ [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18
+ [ -1, 9, C3, [ 512 ] ],
19
+ [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32
20
+ [ -1, 3, C3, [ 1024 ] ],
21
+ [ -1, 1, SPPF, [ 1024, 5 ] ], # 9
22
+ ]
23
+
24
+ # YOLOv5 v6.0 head with (P3, P4) outputs
25
+ head:
26
+ [ [ -1, 1, Conv, [ 512, 1, 1 ] ],
27
+ [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
28
+ [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
29
+ [ -1, 3, C3, [ 512, False ] ], # 13
30
+
31
+ [ -1, 1, Conv, [ 256, 1, 1 ] ],
32
+ [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
33
+ [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
34
+ [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
35
+
36
+ [ -1, 1, Conv, [ 256, 3, 2 ] ],
37
+ [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
38
+ [ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium)
39
+
40
+ [ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4)
41
+ ]
ultralytics/yolov5/models/hub/yolov5-p6.yaml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 6, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [768]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22
+ [-1, 3, C3, [1024]],
23
+ [-1, 1, SPPF, [1024, 5]], # 11
24
+ ]
25
+
26
+ # YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs
27
+ head:
28
+ [[-1, 1, Conv, [768, 1, 1]],
29
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
30
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
31
+ [-1, 3, C3, [768, False]], # 15
32
+
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
35
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
36
+ [-1, 3, C3, [512, False]], # 19
37
+
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
40
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
41
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
42
+
43
+ [-1, 1, Conv, [256, 3, 2]],
44
+ [[-1, 20], 1, Concat, [1]], # cat head P4
45
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
46
+
47
+ [-1, 1, Conv, [512, 3, 2]],
48
+ [[-1, 16], 1, Concat, [1]], # cat head P5
49
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
50
+
51
+ [-1, 1, Conv, [768, 3, 2]],
52
+ [[-1, 12], 1, Concat, [1]], # cat head P6
53
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
54
+
55
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
56
+ ]
ultralytics/yolov5/models/hub/yolov5-p7.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 6, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [768]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22
+ [-1, 3, C3, [1024]],
23
+ [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128
24
+ [-1, 3, C3, [1280]],
25
+ [-1, 1, SPPF, [1280, 5]], # 13
26
+ ]
27
+
28
+ # YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs
29
+ head:
30
+ [[-1, 1, Conv, [1024, 1, 1]],
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 10], 1, Concat, [1]], # cat backbone P6
33
+ [-1, 3, C3, [1024, False]], # 17
34
+
35
+ [-1, 1, Conv, [768, 1, 1]],
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
38
+ [-1, 3, C3, [768, False]], # 21
39
+
40
+ [-1, 1, Conv, [512, 1, 1]],
41
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
42
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
43
+ [-1, 3, C3, [512, False]], # 25
44
+
45
+ [-1, 1, Conv, [256, 1, 1]],
46
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
47
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
48
+ [-1, 3, C3, [256, False]], # 29 (P3/8-small)
49
+
50
+ [-1, 1, Conv, [256, 3, 2]],
51
+ [[-1, 26], 1, Concat, [1]], # cat head P4
52
+ [-1, 3, C3, [512, False]], # 32 (P4/16-medium)
53
+
54
+ [-1, 1, Conv, [512, 3, 2]],
55
+ [[-1, 22], 1, Concat, [1]], # cat head P5
56
+ [-1, 3, C3, [768, False]], # 35 (P5/32-large)
57
+
58
+ [-1, 1, Conv, [768, 3, 2]],
59
+ [[-1, 18], 1, Concat, [1]], # cat head P6
60
+ [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge)
61
+
62
+ [-1, 1, Conv, [1024, 3, 2]],
63
+ [[-1, 14], 1, Concat, [1]], # cat head P7
64
+ [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge)
65
+
66
+ [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7)
67
+ ]
ultralytics/yolov5/models/hub/yolov5-panet.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 PANet head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 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, 6, 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, 3, C3Ghost, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 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
+ ]
ultralytics/yolov5/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 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, C3TR, [1024]], # 9 <--- C3TR() Transformer module
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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/models/tf.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sys
15
+ from copy import deepcopy
16
+ from pathlib import Path
17
+
18
+ FILE = Path(__file__).resolve()
19
+ ROOT = FILE.parents[1] # YOLOv5 root directory
20
+ if str(ROOT) not in sys.path:
21
+ sys.path.append(str(ROOT)) # add ROOT to PATH
22
+ # ROOT = ROOT.relative_to(Path.cwd()) # relative
23
+
24
+ import numpy as np
25
+ import tensorflow as tf
26
+ import torch
27
+ import torch.nn as nn
28
+ from tensorflow import keras
29
+
30
+ from models.common import C3, SPP, SPPF, Bottleneck, BottleneckCSP, Concat, Conv, DWConv, Focus, autopad
31
+ from models.experimental import CrossConv, MixConv2d, attempt_load
32
+ from models.yolo import Detect
33
+ from utils.activations import SiLU
34
+ from utils.general import LOGGER, make_divisible, print_args
35
+
36
+
37
+ class TFBN(keras.layers.Layer):
38
+ # TensorFlow BatchNormalization wrapper
39
+ def __init__(self, w=None):
40
+ super().__init__()
41
+ self.bn = keras.layers.BatchNormalization(
42
+ beta_initializer=keras.initializers.Constant(w.bias.numpy()),
43
+ gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
44
+ moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
45
+ moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
46
+ epsilon=w.eps)
47
+
48
+ def call(self, inputs):
49
+ return self.bn(inputs)
50
+
51
+
52
+ class TFPad(keras.layers.Layer):
53
+ def __init__(self, pad):
54
+ super().__init__()
55
+ self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
56
+
57
+ def call(self, inputs):
58
+ return tf.pad(inputs, self.pad, mode='constant', constant_values=0)
59
+
60
+
61
+ class TFConv(keras.layers.Layer):
62
+ # Standard convolution
63
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
64
+ # ch_in, ch_out, weights, kernel, stride, padding, groups
65
+ super().__init__()
66
+ assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
67
+ assert isinstance(k, int), "Convolution with multiple kernels are not allowed."
68
+ # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
69
+ # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
70
+
71
+ conv = keras.layers.Conv2D(
72
+ c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False if hasattr(w, 'bn') else True,
73
+ kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
74
+ bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
75
+ self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
76
+ self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
77
+
78
+ # YOLOv5 activations
79
+ if isinstance(w.act, nn.LeakyReLU):
80
+ self.act = (lambda x: keras.activations.relu(x, alpha=0.1)) if act else tf.identity
81
+ elif isinstance(w.act, nn.Hardswish):
82
+ self.act = (lambda x: x * tf.nn.relu6(x + 3) * 0.166666667) if act else tf.identity
83
+ elif isinstance(w.act, (nn.SiLU, SiLU)):
84
+ self.act = (lambda x: keras.activations.swish(x)) if act else tf.identity
85
+ else:
86
+ raise Exception(f'no matching TensorFlow activation found for {w.act}')
87
+
88
+ def call(self, inputs):
89
+ return self.act(self.bn(self.conv(inputs)))
90
+
91
+
92
+ class TFFocus(keras.layers.Layer):
93
+ # Focus wh information into c-space
94
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
95
+ # ch_in, ch_out, kernel, stride, padding, groups
96
+ super().__init__()
97
+ self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
98
+
99
+ def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
100
+ # inputs = inputs / 255 # normalize 0-255 to 0-1
101
+ return self.conv(tf.concat([inputs[:, ::2, ::2, :],
102
+ inputs[:, 1::2, ::2, :],
103
+ inputs[:, ::2, 1::2, :],
104
+ inputs[:, 1::2, 1::2, :]], 3))
105
+
106
+
107
+ class TFBottleneck(keras.layers.Layer):
108
+ # Standard bottleneck
109
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion
110
+ super().__init__()
111
+ c_ = int(c2 * e) # hidden channels
112
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
113
+ self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
114
+ self.add = shortcut and c1 == c2
115
+
116
+ def call(self, inputs):
117
+ return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
118
+
119
+
120
+ class TFConv2d(keras.layers.Layer):
121
+ # Substitution for PyTorch nn.Conv2D
122
+ def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
123
+ super().__init__()
124
+ assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
125
+ self.conv = keras.layers.Conv2D(
126
+ c2, k, s, 'VALID', use_bias=bias,
127
+ kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),
128
+ bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None, )
129
+
130
+ def call(self, inputs):
131
+ return self.conv(inputs)
132
+
133
+
134
+ class TFBottleneckCSP(keras.layers.Layer):
135
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
136
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
137
+ # ch_in, ch_out, number, shortcut, groups, expansion
138
+ super().__init__()
139
+ c_ = int(c2 * e) # hidden channels
140
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
141
+ self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
142
+ self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
143
+ self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
144
+ self.bn = TFBN(w.bn)
145
+ self.act = lambda x: keras.activations.relu(x, alpha=0.1)
146
+ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
147
+
148
+ def call(self, inputs):
149
+ y1 = self.cv3(self.m(self.cv1(inputs)))
150
+ y2 = self.cv2(inputs)
151
+ return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
152
+
153
+
154
+ class TFC3(keras.layers.Layer):
155
+ # CSP Bottleneck with 3 convolutions
156
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
157
+ # ch_in, ch_out, number, shortcut, groups, expansion
158
+ super().__init__()
159
+ c_ = int(c2 * e) # hidden channels
160
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
161
+ self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
162
+ self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
163
+ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
164
+
165
+ def call(self, inputs):
166
+ return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
167
+
168
+
169
+ class TFSPP(keras.layers.Layer):
170
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
171
+ def __init__(self, c1, c2, k=(5, 9, 13), w=None):
172
+ super().__init__()
173
+ c_ = c1 // 2 # hidden channels
174
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
175
+ self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
176
+ self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]
177
+
178
+ def call(self, inputs):
179
+ x = self.cv1(inputs)
180
+ return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
181
+
182
+
183
+ class TFSPPF(keras.layers.Layer):
184
+ # Spatial pyramid pooling-Fast layer
185
+ def __init__(self, c1, c2, k=5, w=None):
186
+ super().__init__()
187
+ c_ = c1 // 2 # hidden channels
188
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
189
+ self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
190
+ self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')
191
+
192
+ def call(self, inputs):
193
+ x = self.cv1(inputs)
194
+ y1 = self.m(x)
195
+ y2 = self.m(y1)
196
+ return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
197
+
198
+
199
+ class TFDetect(keras.layers.Layer):
200
+ def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer
201
+ super().__init__()
202
+ self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
203
+ self.nc = nc # number of classes
204
+ self.no = nc + 5 # number of outputs per anchor
205
+ self.nl = len(anchors) # number of detection layers
206
+ self.na = len(anchors[0]) // 2 # number of anchors
207
+ self.grid = [tf.zeros(1)] * self.nl # init grid
208
+ self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
209
+ self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]),
210
+ [self.nl, 1, -1, 1, 2])
211
+ self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
212
+ self.training = False # set to False after building model
213
+ self.imgsz = imgsz
214
+ for i in range(self.nl):
215
+ ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
216
+ self.grid[i] = self._make_grid(nx, ny)
217
+
218
+ def call(self, inputs):
219
+ z = [] # inference output
220
+ x = []
221
+ for i in range(self.nl):
222
+ x.append(self.m[i](inputs[i]))
223
+ # x(bs,20,20,255) to x(bs,3,20,20,85)
224
+ ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
225
+ x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])
226
+
227
+ if not self.training: # inference
228
+ y = tf.sigmoid(x[i])
229
+ grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5
230
+ anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4
231
+ xy = (y[..., 0:2] * 2 + grid) * self.stride[i] # xy
232
+ wh = y[..., 2:4] ** 2 * anchor_grid
233
+ # Normalize xywh to 0-1 to reduce calibration error
234
+ xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
235
+ wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
236
+ y = tf.concat([xy, wh, y[..., 4:]], -1)
237
+ z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))
238
+
239
+ return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1), x)
240
+
241
+ @staticmethod
242
+ def _make_grid(nx=20, ny=20):
243
+ # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
244
+ # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
245
+ xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
246
+ return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
247
+
248
+
249
+ class TFUpsample(keras.layers.Layer):
250
+ def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'
251
+ super().__init__()
252
+ assert scale_factor == 2, "scale_factor must be 2"
253
+ self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode)
254
+ # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
255
+ # with default arguments: align_corners=False, half_pixel_centers=False
256
+ # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
257
+ # size=(x.shape[1] * 2, x.shape[2] * 2))
258
+
259
+ def call(self, inputs):
260
+ return self.upsample(inputs)
261
+
262
+
263
+ class TFConcat(keras.layers.Layer):
264
+ def __init__(self, dimension=1, w=None):
265
+ super().__init__()
266
+ assert dimension == 1, "convert only NCHW to NHWC concat"
267
+ self.d = 3
268
+
269
+ def call(self, inputs):
270
+ return tf.concat(inputs, self.d)
271
+
272
+
273
+ def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
274
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
275
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
276
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
277
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
278
+
279
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
280
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
281
+ m_str = m
282
+ m = eval(m) if isinstance(m, str) else m # eval strings
283
+ for j, a in enumerate(args):
284
+ try:
285
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
286
+ except NameError:
287
+ pass
288
+
289
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
290
+ if m in [nn.Conv2d, Conv, Bottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:
291
+ c1, c2 = ch[f], args[0]
292
+ c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
293
+
294
+ args = [c1, c2, *args[1:]]
295
+ if m in [BottleneckCSP, C3]:
296
+ args.insert(2, n)
297
+ n = 1
298
+ elif m is nn.BatchNorm2d:
299
+ args = [ch[f]]
300
+ elif m is Concat:
301
+ c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
302
+ elif m is Detect:
303
+ args.append([ch[x + 1] for x in f])
304
+ if isinstance(args[1], int): # number of anchors
305
+ args[1] = [list(range(args[1] * 2))] * len(f)
306
+ args.append(imgsz)
307
+ else:
308
+ c2 = ch[f]
309
+
310
+ tf_m = eval('TF' + m_str.replace('nn.', ''))
311
+ m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \
312
+ else tf_m(*args, w=model.model[i]) # module
313
+
314
+ torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
315
+ t = str(m)[8:-2].replace('__main__.', '') # module type
316
+ np = sum(x.numel() for x in torch_m_.parameters()) # number params
317
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
318
+ LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print
319
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
320
+ layers.append(m_)
321
+ ch.append(c2)
322
+ return keras.Sequential(layers), sorted(save)
323
+
324
+
325
+ class TFModel:
326
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes
327
+ super().__init__()
328
+ if isinstance(cfg, dict):
329
+ self.yaml = cfg # model dict
330
+ else: # is *.yaml
331
+ import yaml # for torch hub
332
+ self.yaml_file = Path(cfg).name
333
+ with open(cfg) as f:
334
+ self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
335
+
336
+ # Define model
337
+ if nc and nc != self.yaml['nc']:
338
+ LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
339
+ self.yaml['nc'] = nc # override yaml value
340
+ self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
341
+
342
+ def predict(self, inputs, tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
343
+ conf_thres=0.25):
344
+ y = [] # outputs
345
+ x = inputs
346
+ for i, m in enumerate(self.model.layers):
347
+ if m.f != -1: # if not from previous layer
348
+ 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
349
+
350
+ x = m(x) # run
351
+ y.append(x if m.i in self.savelist else None) # save output
352
+
353
+ # Add TensorFlow NMS
354
+ if tf_nms:
355
+ boxes = self._xywh2xyxy(x[0][..., :4])
356
+ probs = x[0][:, :, 4:5]
357
+ classes = x[0][:, :, 5:]
358
+ scores = probs * classes
359
+ if agnostic_nms:
360
+ nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
361
+ return nms, x[1]
362
+ else:
363
+ boxes = tf.expand_dims(boxes, 2)
364
+ nms = tf.image.combined_non_max_suppression(
365
+ boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False)
366
+ return nms, x[1]
367
+
368
+ return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]
369
+ # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85)
370
+ # xywh = x[..., :4] # x(6300,4) boxes
371
+ # conf = x[..., 4:5] # x(6300,1) confidences
372
+ # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
373
+ # return tf.concat([conf, cls, xywh], 1)
374
+
375
+ @staticmethod
376
+ def _xywh2xyxy(xywh):
377
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
378
+ x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
379
+ return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
380
+
381
+
382
+ class AgnosticNMS(keras.layers.Layer):
383
+ # TF Agnostic NMS
384
+ def call(self, input, topk_all, iou_thres, conf_thres):
385
+ # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450
386
+ return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres), input,
387
+ fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
388
+ name='agnostic_nms')
389
+
390
+ @staticmethod
391
+ def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
392
+ boxes, classes, scores = x
393
+ class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
394
+ scores_inp = tf.reduce_max(scores, -1)
395
+ selected_inds = tf.image.non_max_suppression(
396
+ boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres)
397
+ selected_boxes = tf.gather(boxes, selected_inds)
398
+ padded_boxes = tf.pad(selected_boxes,
399
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
400
+ mode="CONSTANT", constant_values=0.0)
401
+ selected_scores = tf.gather(scores_inp, selected_inds)
402
+ padded_scores = tf.pad(selected_scores,
403
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
404
+ mode="CONSTANT", constant_values=-1.0)
405
+ selected_classes = tf.gather(class_inds, selected_inds)
406
+ padded_classes = tf.pad(selected_classes,
407
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
408
+ mode="CONSTANT", constant_values=-1.0)
409
+ valid_detections = tf.shape(selected_inds)[0]
410
+ return padded_boxes, padded_scores, padded_classes, valid_detections
411
+
412
+
413
+ def representative_dataset_gen(dataset, ncalib=100):
414
+ # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
415
+ for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
416
+ input = np.transpose(img, [1, 2, 0])
417
+ input = np.expand_dims(input, axis=0).astype(np.float32)
418
+ input /= 255
419
+ yield [input]
420
+ if n >= ncalib:
421
+ break
422
+
423
+
424
+ def run(weights=ROOT / 'yolov5s.pt', # weights path
425
+ imgsz=(640, 640), # inference size h,w
426
+ batch_size=1, # batch size
427
+ dynamic=False, # dynamic batch size
428
+ ):
429
+ # PyTorch model
430
+ im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
431
+ model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False)
432
+ _ = model(im) # inference
433
+ model.info()
434
+
435
+ # TensorFlow model
436
+ im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
437
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
438
+ _ = tf_model.predict(im) # inference
439
+
440
+ # Keras model
441
+ im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
442
+ keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
443
+ keras_model.summary()
444
+
445
+ LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.')
446
+
447
+
448
+ def parse_opt():
449
+ parser = argparse.ArgumentParser()
450
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
451
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
452
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
453
+ parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')
454
+ opt = parser.parse_args()
455
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
456
+ print_args(FILE.stem, opt)
457
+ return opt
458
+
459
+
460
+ def main(opt):
461
+ run(**vars(opt))
462
+
463
+
464
+ if __name__ == "__main__":
465
+ opt = parse_opt()
466
+ main(opt)
ultralytics/yolov5/models/yolo.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LOGGER, check_version, check_yaml, make_divisible, print_args
24
+ from utils.plots import feature_visualization
25
+ from utils.torch_utils import fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device, time_sync
26
+
27
+ try:
28
+ import thop # for FLOPs computation
29
+ except ImportError:
30
+ thop = None
31
+
32
+
33
+ class Detect(nn.Module):
34
+ stride = None # strides computed during build
35
+ onnx_dynamic = False # ONNX export parameter
36
+
37
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
38
+ super().__init__()
39
+ self.nc = nc # number of classes
40
+ self.no = nc + 5 # number of outputs per anchor
41
+ self.nl = len(anchors) # number of detection layers
42
+ self.na = len(anchors[0]) // 2 # number of anchors
43
+ self.grid = [torch.zeros(1)] * self.nl # init grid
44
+ self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
45
+ self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
46
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
47
+ self.inplace = inplace # use in-place ops (e.g. slice assignment)
48
+
49
+ def forward(self, x):
50
+ z = [] # inference output
51
+ for i in range(self.nl):
52
+ x[i] = self.m[i](x[i]) # conv
53
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
54
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
55
+
56
+ if not self.training: # inference
57
+ if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
58
+ self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
59
+
60
+ y = x[i].sigmoid()
61
+ if self.inplace:
62
+ y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
63
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
64
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
65
+ xy = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
66
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
67
+ y = torch.cat((xy, wh, y[..., 4:]), -1)
68
+ z.append(y.view(bs, -1, self.no))
69
+
70
+ return x if self.training else (torch.cat(z, 1), x)
71
+
72
+ def _make_grid(self, nx=20, ny=20, i=0):
73
+ d = self.anchors[i].device
74
+ shape = 1, self.na, ny, nx, 2 # grid shape
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, device=d), torch.arange(nx, device=d), indexing='ij')
77
+ else:
78
+ yv, xv = torch.meshgrid(torch.arange(ny, device=d), torch.arange(nx, device=d))
79
+ grid = torch.stack((xv, yv), 2).expand(shape).float()
80
+ anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape).float()
81
+ return grid, anchor_grid
82
+
83
+
84
+ class Model(nn.Module):
85
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
86
+ super().__init__()
87
+ if isinstance(cfg, dict):
88
+ self.yaml = cfg # model dict
89
+ else: # is *.yaml
90
+ import yaml # for torch hub
91
+ self.yaml_file = Path(cfg).name
92
+ with open(cfg, encoding='ascii', errors='ignore') as f:
93
+ self.yaml = yaml.safe_load(f) # model dict
94
+
95
+ # Define model
96
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
97
+ if nc and nc != self.yaml['nc']:
98
+ LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
99
+ self.yaml['nc'] = nc # override yaml value
100
+ if anchors:
101
+ LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
102
+ self.yaml['anchors'] = round(anchors) # override yaml value
103
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
104
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
105
+ self.inplace = self.yaml.get('inplace', True)
106
+
107
+ # Build strides, anchors
108
+ m = self.model[-1] # Detect()
109
+ if isinstance(m, Detect):
110
+ s = 256 # 2x min stride
111
+ m.inplace = self.inplace
112
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
113
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
114
+ m.anchors /= m.stride.view(-1, 1, 1)
115
+ self.stride = m.stride
116
+ self._initialize_biases() # only run once
117
+
118
+ # Init weights, biases
119
+ initialize_weights(self)
120
+ self.info()
121
+ LOGGER.info('')
122
+
123
+ def forward(self, x, augment=False, profile=False, visualize=False):
124
+ if augment:
125
+ return self._forward_augment(x) # augmented inference, None
126
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
127
+
128
+ def _forward_augment(self, x):
129
+ img_size = x.shape[-2:] # height, width
130
+ s = [1, 0.83, 0.67] # scales
131
+ f = [None, 3, None] # flips (2-ud, 3-lr)
132
+ y = [] # outputs
133
+ for si, fi in zip(s, f):
134
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
135
+ yi = self._forward_once(xi)[0] # forward
136
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
137
+ yi = self._descale_pred(yi, fi, si, img_size)
138
+ y.append(yi)
139
+ y = self._clip_augmented(y) # clip augmented tails
140
+ return torch.cat(y, 1), None # augmented inference, train
141
+
142
+ def _forward_once(self, x, profile=False, visualize=False):
143
+ y, dt = [], [] # outputs
144
+ for m in self.model:
145
+ if m.f != -1: # if not from previous layer
146
+ 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
147
+ if profile:
148
+ self._profile_one_layer(m, x, dt)
149
+ x = m(x) # run
150
+ y.append(x if m.i in self.save else None) # save output
151
+ if visualize:
152
+ feature_visualization(x, m.type, m.i, save_dir=visualize)
153
+ return x
154
+
155
+ def _descale_pred(self, p, flips, scale, img_size):
156
+ # de-scale predictions following augmented inference (inverse operation)
157
+ if self.inplace:
158
+ p[..., :4] /= scale # de-scale
159
+ if flips == 2:
160
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
161
+ elif flips == 3:
162
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
163
+ else:
164
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
165
+ if flips == 2:
166
+ y = img_size[0] - y # de-flip ud
167
+ elif flips == 3:
168
+ x = img_size[1] - x # de-flip lr
169
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
170
+ return p
171
+
172
+ def _clip_augmented(self, y):
173
+ # Clip YOLOv5 augmented inference tails
174
+ nl = self.model[-1].nl # number of detection layers (P3-P5)
175
+ g = sum(4 ** x for x in range(nl)) # grid points
176
+ e = 1 # exclude layer count
177
+ i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
178
+ y[0] = y[0][:, :-i] # large
179
+ i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
180
+ y[-1] = y[-1][:, i:] # small
181
+ return y
182
+
183
+ def _profile_one_layer(self, m, x, dt):
184
+ c = isinstance(m, Detect) # is final layer, copy input as inplace fix
185
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
186
+ t = time_sync()
187
+ for _ in range(10):
188
+ m(x.copy() if c else x)
189
+ dt.append((time_sync() - t) * 100)
190
+ if m == self.model[0]:
191
+ LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
192
+ LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
193
+ if c:
194
+ LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
195
+
196
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
197
+ # https://arxiv.org/abs/1708.02002 section 3.3
198
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
199
+ m = self.model[-1] # Detect() module
200
+ for mi, s in zip(m.m, m.stride): # from
201
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
202
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
203
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
204
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
205
+
206
+ def _print_biases(self):
207
+ m = self.model[-1] # Detect() module
208
+ for mi in m.m: # from
209
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
210
+ LOGGER.info(
211
+ ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
212
+
213
+ # def _print_weights(self):
214
+ # for m in self.model.modules():
215
+ # if type(m) is Bottleneck:
216
+ # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
217
+
218
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
219
+ LOGGER.info('Fusing layers... ')
220
+ for m in self.model.modules():
221
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
222
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
223
+ delattr(m, 'bn') # remove batchnorm
224
+ m.forward = m.forward_fuse # update forward
225
+ self.info()
226
+ return self
227
+
228
+ def info(self, verbose=False, img_size=640): # print model information
229
+ model_info(self, verbose, img_size)
230
+
231
+ def _apply(self, fn):
232
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
233
+ self = super()._apply(fn)
234
+ m = self.model[-1] # Detect()
235
+ if isinstance(m, Detect):
236
+ m.stride = fn(m.stride)
237
+ m.grid = list(map(fn, m.grid))
238
+ if isinstance(m.anchor_grid, list):
239
+ m.anchor_grid = list(map(fn, m.anchor_grid))
240
+ return self
241
+
242
+
243
+ def parse_model(d, ch): # model_dict, input_channels(3)
244
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
245
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
246
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
247
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
248
+
249
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
250
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
251
+ m = eval(m) if isinstance(m, str) else m # eval strings
252
+ for j, a in enumerate(args):
253
+ try:
254
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
255
+ except NameError:
256
+ pass
257
+
258
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
259
+ if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
260
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
261
+ c1, c2 = ch[f], args[0]
262
+ if c2 != no: # if not output
263
+ c2 = make_divisible(c2 * gw, 8)
264
+
265
+ args = [c1, c2, *args[1:]]
266
+ if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
267
+ args.insert(2, n) # number of repeats
268
+ n = 1
269
+ elif m is nn.BatchNorm2d:
270
+ args = [ch[f]]
271
+ elif m is Concat:
272
+ c2 = sum(ch[x] for x in f)
273
+ elif m is Detect:
274
+ args.append([ch[x] for x in f])
275
+ if isinstance(args[1], int): # number of anchors
276
+ args[1] = [list(range(args[1] * 2))] * len(f)
277
+ elif m is Contract:
278
+ c2 = ch[f] * args[0] ** 2
279
+ elif m is Expand:
280
+ c2 = ch[f] // args[0] ** 2
281
+ else:
282
+ c2 = ch[f]
283
+
284
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
285
+ t = str(m)[8:-2].replace('__main__.', '') # module type
286
+ np = sum(x.numel() for x in m_.parameters()) # number params
287
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
288
+ LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
289
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
290
+ layers.append(m_)
291
+ if i == 0:
292
+ ch = []
293
+ ch.append(c2)
294
+ return nn.Sequential(*layers), sorted(save)
295
+
296
+
297
+ if __name__ == '__main__':
298
+ parser = argparse.ArgumentParser()
299
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
300
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
301
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
302
+ parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
303
+ opt = parser.parse_args()
304
+ opt.cfg = check_yaml(opt.cfg) # check YAML
305
+ print_args(FILE.stem, opt)
306
+ device = select_device(opt.device)
307
+
308
+ # Create model
309
+ model = Model(opt.cfg).to(device)
310
+ model.train()
311
+
312
+ # Profile
313
+ if opt.profile:
314
+ img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
315
+ y = model(img, profile=True)
316
+
317
+ # Test all models
318
+ if opt.test:
319
+ for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
320
+ try:
321
+ _ = Model(cfg)
322
+ except Exception as e:
323
+ print(f'Error in {cfg}: {e}')
324
+
325
+ # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
326
+ # from torch.utils.tensorboard import SummaryWriter
327
+ # tb_writer = SummaryWriter('.')
328
+ # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
329
+ # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/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
+ ]
ultralytics/yolov5/models/yolov5s.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 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
+ ]
ultralytics/yolov5/models/yolov5x.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.33 # model depth multiple
6
+ width_multiple: 1.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
+ ]
ultralytics/yolov5/utils/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ utils/initialization
4
+ """
5
+
6
+
7
+ def notebook_init(verbose=True):
8
+ # Check system software and hardware
9
+ print('Checking setup...')
10
+
11
+ import os
12
+ import shutil
13
+
14
+ from utils.general import check_requirements, emojis, is_colab
15
+ from utils.torch_utils import select_device # imports
16
+
17
+ check_requirements(('psutil', 'IPython'))
18
+ import psutil
19
+ from IPython import display # to display images and clear console output
20
+
21
+ if is_colab():
22
+ shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory
23
+
24
+ # System info
25
+ if verbose:
26
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
27
+ ram = psutil.virtual_memory().total
28
+ total, used, free = shutil.disk_usage("/")
29
+ display.clear_output()
30
+ s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)'
31
+ else:
32
+ s = ''
33
+
34
+ select_device(newline=False)
35
+ print(emojis(f'Setup complete ✅ {s}'))
36
+ return display
ultralytics/yolov5/utils/activations.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Activation functions
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+
11
+ # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
12
+ class SiLU(nn.Module): # export-friendly version of nn.SiLU()
13
+ @staticmethod
14
+ def forward(x):
15
+ return x * torch.sigmoid(x)
16
+
17
+
18
+ class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
19
+ @staticmethod
20
+ def forward(x):
21
+ # return x * F.hardsigmoid(x) # for TorchScript and CoreML
22
+ return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
23
+
24
+
25
+ # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
26
+ class Mish(nn.Module):
27
+ @staticmethod
28
+ def forward(x):
29
+ return x * F.softplus(x).tanh()
30
+
31
+
32
+ class MemoryEfficientMish(nn.Module):
33
+ class F(torch.autograd.Function):
34
+ @staticmethod
35
+ def forward(ctx, x):
36
+ ctx.save_for_backward(x)
37
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
38
+
39
+ @staticmethod
40
+ def backward(ctx, grad_output):
41
+ x = ctx.saved_tensors[0]
42
+ sx = torch.sigmoid(x)
43
+ fx = F.softplus(x).tanh()
44
+ return grad_output * (fx + x * sx * (1 - fx * fx))
45
+
46
+ def forward(self, x):
47
+ return self.F.apply(x)
48
+
49
+
50
+ # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
51
+ class FReLU(nn.Module):
52
+ def __init__(self, c1, k=3): # ch_in, kernel
53
+ super().__init__()
54
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
55
+ self.bn = nn.BatchNorm2d(c1)
56
+
57
+ def forward(self, x):
58
+ return torch.max(x, self.bn(self.conv(x)))
59
+
60
+
61
+ # ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
62
+ class AconC(nn.Module):
63
+ r""" ACON activation (activate or not).
64
+ AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
65
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
66
+ """
67
+
68
+ def __init__(self, c1):
69
+ super().__init__()
70
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
71
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
72
+ self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
73
+
74
+ def forward(self, x):
75
+ dpx = (self.p1 - self.p2) * x
76
+ return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
77
+
78
+
79
+ class MetaAconC(nn.Module):
80
+ r""" ACON activation (activate or not).
81
+ MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
82
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
83
+ """
84
+
85
+ def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
86
+ super().__init__()
87
+ c2 = max(r, c1 // r)
88
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
89
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
90
+ self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
91
+ self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
92
+ # self.bn1 = nn.BatchNorm2d(c2)
93
+ # self.bn2 = nn.BatchNorm2d(c1)
94
+
95
+ def forward(self, x):
96
+ y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
97
+ # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
98
+ # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
99
+ beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
100
+ dpx = (self.p1 - self.p2) * x
101
+ return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
ultralytics/yolov5/utils/augmentations.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Image augmentation functions
4
+ """
5
+
6
+ import math
7
+ import random
8
+
9
+ import cv2
10
+ import numpy as np
11
+
12
+ from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box
13
+ from utils.metrics import bbox_ioa
14
+
15
+
16
+ class Albumentations:
17
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
18
+ def __init__(self):
19
+ self.transform = None
20
+ try:
21
+ import albumentations as A
22
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
23
+
24
+ self.transform = A.Compose([
25
+ A.Blur(p=0.01),
26
+ A.MedianBlur(p=0.01),
27
+ A.ToGray(p=0.01),
28
+ A.CLAHE(p=0.01),
29
+ A.RandomBrightnessContrast(p=0.0),
30
+ A.RandomGamma(p=0.0),
31
+ A.ImageCompression(quality_lower=75, p=0.0)],
32
+ bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
33
+
34
+ LOGGER.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
35
+ except ImportError: # package not installed, skip
36
+ pass
37
+ except Exception as e:
38
+ LOGGER.info(colorstr('albumentations: ') + f'{e}')
39
+
40
+ def __call__(self, im, labels, p=1.0):
41
+ if self.transform and random.random() < p:
42
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
43
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
44
+ return im, labels
45
+
46
+
47
+ def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
48
+ # HSV color-space augmentation
49
+ if hgain or sgain or vgain:
50
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
51
+ hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
52
+ dtype = im.dtype # uint8
53
+
54
+ x = np.arange(0, 256, dtype=r.dtype)
55
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
56
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
57
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
58
+
59
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
60
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
61
+
62
+
63
+ def hist_equalize(im, clahe=True, bgr=False):
64
+ # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
65
+ yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
66
+ if clahe:
67
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
68
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
69
+ else:
70
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
71
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
72
+
73
+
74
+ def replicate(im, labels):
75
+ # Replicate labels
76
+ h, w = im.shape[:2]
77
+ boxes = labels[:, 1:].astype(int)
78
+ x1, y1, x2, y2 = boxes.T
79
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
80
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
81
+ x1b, y1b, x2b, y2b = boxes[i]
82
+ bh, bw = y2b - y1b, x2b - x1b
83
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
84
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
85
+ im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
86
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
87
+
88
+ return im, labels
89
+
90
+
91
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
92
+ # Resize and pad image while meeting stride-multiple constraints
93
+ shape = im.shape[:2] # current shape [height, width]
94
+ if isinstance(new_shape, int):
95
+ new_shape = (new_shape, new_shape)
96
+
97
+ # Scale ratio (new / old)
98
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
99
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
100
+ r = min(r, 1.0)
101
+
102
+ # Compute padding
103
+ ratio = r, r # width, height ratios
104
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
105
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
106
+ if auto: # minimum rectangle
107
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
108
+ elif scaleFill: # stretch
109
+ dw, dh = 0.0, 0.0
110
+ new_unpad = (new_shape[1], new_shape[0])
111
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
112
+
113
+ dw /= 2 # divide padding into 2 sides
114
+ dh /= 2
115
+
116
+ if shape[::-1] != new_unpad: # resize
117
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
118
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
119
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
120
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
121
+ return im, ratio, (dw, dh)
122
+
123
+
124
+ def random_perspective(im, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
125
+ border=(0, 0)):
126
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
127
+ # targets = [cls, xyxy]
128
+
129
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
130
+ width = im.shape[1] + border[1] * 2
131
+
132
+ # Center
133
+ C = np.eye(3)
134
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
135
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
136
+
137
+ # Perspective
138
+ P = np.eye(3)
139
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
140
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
141
+
142
+ # Rotation and Scale
143
+ R = np.eye(3)
144
+ a = random.uniform(-degrees, degrees)
145
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
146
+ s = random.uniform(1 - scale, 1 + scale)
147
+ # s = 2 ** random.uniform(-scale, scale)
148
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
149
+
150
+ # Shear
151
+ S = np.eye(3)
152
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
153
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
154
+
155
+ # Translation
156
+ T = np.eye(3)
157
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
158
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
159
+
160
+ # Combined rotation matrix
161
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
162
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
163
+ if perspective:
164
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
165
+ else: # affine
166
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
167
+
168
+ # Visualize
169
+ # import matplotlib.pyplot as plt
170
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
171
+ # ax[0].imshow(im[:, :, ::-1]) # base
172
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
173
+
174
+ # Transform label coordinates
175
+ n = len(targets)
176
+ if n:
177
+ use_segments = any(x.any() for x in segments)
178
+ new = np.zeros((n, 4))
179
+ if use_segments: # warp segments
180
+ segments = resample_segments(segments) # upsample
181
+ for i, segment in enumerate(segments):
182
+ xy = np.ones((len(segment), 3))
183
+ xy[:, :2] = segment
184
+ xy = xy @ M.T # transform
185
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
186
+
187
+ # clip
188
+ new[i] = segment2box(xy, width, height)
189
+
190
+ else: # warp boxes
191
+ xy = np.ones((n * 4, 3))
192
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
193
+ xy = xy @ M.T # transform
194
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
195
+
196
+ # create new boxes
197
+ x = xy[:, [0, 2, 4, 6]]
198
+ y = xy[:, [1, 3, 5, 7]]
199
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
200
+
201
+ # clip
202
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
203
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
204
+
205
+ # filter candidates
206
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
207
+ targets = targets[i]
208
+ targets[:, 1:5] = new[i]
209
+
210
+ return im, targets
211
+
212
+
213
+ def copy_paste(im, labels, segments, p=0.5):
214
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
215
+ n = len(segments)
216
+ if p and n:
217
+ h, w, c = im.shape # height, width, channels
218
+ im_new = np.zeros(im.shape, np.uint8)
219
+ for j in random.sample(range(n), k=round(p * n)):
220
+ l, s = labels[j], segments[j]
221
+ box = w - l[3], l[2], w - l[1], l[4]
222
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
223
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
224
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
225
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
226
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
227
+
228
+ result = cv2.bitwise_and(src1=im, src2=im_new)
229
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
230
+ i = result > 0 # pixels to replace
231
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
232
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
233
+
234
+ return im, labels, segments
235
+
236
+
237
+ def cutout(im, labels, p=0.5):
238
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
239
+ if random.random() < p:
240
+ h, w = im.shape[:2]
241
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
242
+ for s in scales:
243
+ mask_h = random.randint(1, int(h * s)) # create random masks
244
+ mask_w = random.randint(1, int(w * s))
245
+
246
+ # box
247
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
248
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
249
+ xmax = min(w, xmin + mask_w)
250
+ ymax = min(h, ymin + mask_h)
251
+
252
+ # apply random color mask
253
+ im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
254
+
255
+ # return unobscured labels
256
+ if len(labels) and s > 0.03:
257
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
258
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
259
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
260
+
261
+ return labels
262
+
263
+
264
+ def mixup(im, labels, im2, labels2):
265
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
266
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
267
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
268
+ labels = np.concatenate((labels, labels2), 0)
269
+ return im, labels
270
+
271
+
272
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
273
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
274
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
275
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
276
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
277
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
ultralytics/yolov5/utils/autoanchor.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ AutoAnchor utils
4
+ """
5
+
6
+ import random
7
+
8
+ import numpy as np
9
+ import torch
10
+ import yaml
11
+ from tqdm import tqdm
12
+
13
+ from utils.general import LOGGER, colorstr, emojis
14
+
15
+ PREFIX = colorstr('AutoAnchor: ')
16
+
17
+
18
+ def check_anchor_order(m):
19
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
20
+ a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer
21
+ da = a[-1] - a[0] # delta a
22
+ ds = m.stride[-1] - m.stride[0] # delta s
23
+ if da and (da.sign() != ds.sign()): # same order
24
+ LOGGER.info(f'{PREFIX}Reversing anchor order')
25
+ m.anchors[:] = m.anchors.flip(0)
26
+
27
+
28
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
29
+ # Check anchor fit to data, recompute if necessary
30
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
31
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
32
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
33
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
34
+
35
+ def metric(k): # compute metric
36
+ r = wh[:, None] / k[None]
37
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
38
+ best = x.max(1)[0] # best_x
39
+ aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
40
+ bpr = (best > 1 / thr).float().mean() # best possible recall
41
+ return bpr, aat
42
+
43
+ stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides
44
+ anchors = m.anchors.clone() * stride # current anchors
45
+ bpr, aat = metric(anchors.cpu().view(-1, 2))
46
+ s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '
47
+ if bpr > 0.98: # threshold to recompute
48
+ LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅'))
49
+ else:
50
+ LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...'))
51
+ na = m.anchors.numel() // 2 # number of anchors
52
+ try:
53
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
54
+ except Exception as e:
55
+ LOGGER.info(f'{PREFIX}ERROR: {e}')
56
+ new_bpr = metric(anchors)[0]
57
+ if new_bpr > bpr: # replace anchors
58
+ anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
59
+ m.anchors[:] = anchors.clone().view_as(m.anchors)
60
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
61
+ m.anchors /= stride
62
+ s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)'
63
+ else:
64
+ s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)'
65
+ LOGGER.info(emojis(s))
66
+
67
+
68
+ def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
69
+ """ Creates kmeans-evolved anchors from training dataset
70
+
71
+ Arguments:
72
+ dataset: path to data.yaml, or a loaded dataset
73
+ n: number of anchors
74
+ img_size: image size used for training
75
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
76
+ gen: generations to evolve anchors using genetic algorithm
77
+ verbose: print all results
78
+
79
+ Return:
80
+ k: kmeans evolved anchors
81
+
82
+ Usage:
83
+ from utils.autoanchor import *; _ = kmean_anchors()
84
+ """
85
+ from scipy.cluster.vq import kmeans
86
+
87
+ npr = np.random
88
+ thr = 1 / thr
89
+
90
+ def metric(k, wh): # compute metrics
91
+ r = wh[:, None] / k[None]
92
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
93
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
94
+ return x, x.max(1)[0] # x, best_x
95
+
96
+ def anchor_fitness(k): # mutation fitness
97
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
98
+ return (best * (best > thr).float()).mean() # fitness
99
+
100
+ def print_results(k, verbose=True):
101
+ k = k[np.argsort(k.prod(1))] # sort small to large
102
+ x, best = metric(k, wh0)
103
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
104
+ s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \
105
+ f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \
106
+ f'past_thr={x[x > thr].mean():.3f}-mean: '
107
+ for i, x in enumerate(k):
108
+ s += '%i,%i, ' % (round(x[0]), round(x[1]))
109
+ if verbose:
110
+ LOGGER.info(s[:-2])
111
+ return k
112
+
113
+ if isinstance(dataset, str): # *.yaml file
114
+ with open(dataset, errors='ignore') as f:
115
+ data_dict = yaml.safe_load(f) # model dict
116
+ from utils.datasets import LoadImagesAndLabels
117
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
118
+
119
+ # Get label wh
120
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
121
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
122
+
123
+ # Filter
124
+ i = (wh0 < 3.0).any(1).sum()
125
+ if i:
126
+ LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found: {i} of {len(wh0)} labels are < 3 pixels in size')
127
+ wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
128
+ # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
129
+
130
+ # Kmeans init
131
+ try:
132
+ LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')
133
+ assert n <= len(wh) # apply overdetermined constraint
134
+ s = wh.std(0) # sigmas for whitening
135
+ k = kmeans(wh / s, n, iter=30)[0] * s # points
136
+ assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar
137
+ except Exception:
138
+ LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init')
139
+ k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init
140
+ wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))
141
+ k = print_results(k, verbose=False)
142
+
143
+ # Plot
144
+ # k, d = [None] * 20, [None] * 20
145
+ # for i in tqdm(range(1, 21)):
146
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
147
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
148
+ # ax = ax.ravel()
149
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
150
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
151
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
152
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
153
+ # fig.savefig('wh.png', dpi=200)
154
+
155
+ # Evolve
156
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
157
+ pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
158
+ for _ in pbar:
159
+ v = np.ones(sh)
160
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
161
+ v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
162
+ kg = (k.copy() * v).clip(min=2.0)
163
+ fg = anchor_fitness(kg)
164
+ if fg > f:
165
+ f, k = fg, kg.copy()
166
+ pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
167
+ if verbose:
168
+ print_results(k, verbose)
169
+
170
+ return print_results(k)
ultralytics/yolov5/utils/autobatch.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Auto-batch utils
4
+ """
5
+
6
+ from copy import deepcopy
7
+
8
+ import numpy as np
9
+ import torch
10
+ from torch.cuda import amp
11
+
12
+ from utils.general import LOGGER, colorstr
13
+ from utils.torch_utils import profile
14
+
15
+
16
+ def check_train_batch_size(model, imgsz=640):
17
+ # Check YOLOv5 training batch size
18
+ with amp.autocast():
19
+ return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
20
+
21
+
22
+ def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):
23
+ # Automatically estimate best batch size to use `fraction` of available CUDA memory
24
+ # Usage:
25
+ # import torch
26
+ # from utils.autobatch import autobatch
27
+ # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
28
+ # print(autobatch(model))
29
+
30
+ prefix = colorstr('AutoBatch: ')
31
+ LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')
32
+ device = next(model.parameters()).device # get model device
33
+ if device.type == 'cpu':
34
+ LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')
35
+ return batch_size
36
+
37
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
38
+ d = str(device).upper() # 'CUDA:0'
39
+ properties = torch.cuda.get_device_properties(device) # device properties
40
+ t = properties.total_memory / gb # (GiB)
41
+ r = torch.cuda.memory_reserved(device) / gb # (GiB)
42
+ a = torch.cuda.memory_allocated(device) / gb # (GiB)
43
+ f = t - (r + a) # free inside reserved
44
+ LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
45
+
46
+ batch_sizes = [1, 2, 4, 8, 16]
47
+ try:
48
+ img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes]
49
+ y = profile(img, model, n=3, device=device)
50
+ except Exception as e:
51
+ LOGGER.warning(f'{prefix}{e}')
52
+
53
+ y = [x[2] for x in y if x] # memory [2]
54
+ batch_sizes = batch_sizes[:len(y)]
55
+ p = np.polyfit(batch_sizes, y, deg=1) # first degree polynomial fit
56
+ b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
57
+ LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%)')
58
+ return b
ultralytics/yolov5/utils/aws/__init__.py ADDED
File without changes
ultralytics/yolov5/utils/aws/mime.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/
2
+ # This script will run on every instance restart, not only on first start
3
+ # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---
4
+
5
+ Content-Type: multipart/mixed; boundary="//"
6
+ MIME-Version: 1.0
7
+
8
+ --//
9
+ Content-Type: text/cloud-config; charset="us-ascii"
10
+ MIME-Version: 1.0
11
+ Content-Transfer-Encoding: 7bit
12
+ Content-Disposition: attachment; filename="cloud-config.txt"
13
+
14
+ #cloud-config
15
+ cloud_final_modules:
16
+ - [scripts-user, always]
17
+
18
+ --//
19
+ Content-Type: text/x-shellscript; charset="us-ascii"
20
+ MIME-Version: 1.0
21
+ Content-Transfer-Encoding: 7bit
22
+ Content-Disposition: attachment; filename="userdata.txt"
23
+
24
+ #!/bin/bash
25
+ # --- paste contents of userdata.sh here ---
26
+ --//
ultralytics/yolov5/utils/aws/resume.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Resume all interrupted trainings in yolov5/ dir including DDP trainings
2
+ # Usage: $ python utils/aws/resume.py
3
+
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ import yaml
10
+
11
+ FILE = Path(__file__).resolve()
12
+ ROOT = FILE.parents[2] # YOLOv5 root directory
13
+ if str(ROOT) not in sys.path:
14
+ sys.path.append(str(ROOT)) # add ROOT to PATH
15
+
16
+ port = 0 # --master_port
17
+ path = Path('').resolve()
18
+ for last in path.rglob('*/**/last.pt'):
19
+ ckpt = torch.load(last)
20
+ if ckpt['optimizer'] is None:
21
+ continue
22
+
23
+ # Load opt.yaml
24
+ with open(last.parent.parent / 'opt.yaml', errors='ignore') as f:
25
+ opt = yaml.safe_load(f)
26
+
27
+ # Get device count
28
+ d = opt['device'].split(',') # devices
29
+ nd = len(d) # number of devices
30
+ ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
31
+
32
+ if ddp: # multi-GPU
33
+ port += 1
34
+ cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}'
35
+ else: # single-GPU
36
+ cmd = f'python train.py --resume {last}'
37
+
38
+ cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread
39
+ print(cmd)
40
+ os.system(cmd)
ultralytics/yolov5/utils/aws/userdata.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
3
+ # This script will run only once on first instance start (for a re-start script see mime.sh)
4
+ # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir
5
+ # Use >300 GB SSD
6
+
7
+ cd home/ubuntu
8
+ if [ ! -d yolov5 ]; then
9
+ echo "Running first-time script." # install dependencies, download COCO, pull Docker
10
+ git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5
11
+ cd yolov5
12
+ bash data/scripts/get_coco.sh && echo "COCO done." &
13
+ sudo docker pull ultralytics/yolov5:latest && echo "Docker done." &
14
+ python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." &
15
+ wait && echo "All tasks done." # finish background tasks
16
+ else
17
+ echo "Running re-start script." # resume interrupted runs
18
+ i=0
19
+ list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour'
20
+ while IFS= read -r id; do
21
+ ((i++))
22
+ echo "restarting container $i: $id"
23
+ sudo docker start $id
24
+ # sudo docker exec -it $id python train.py --resume # single-GPU
25
+ sudo docker exec -d $id python utils/aws/resume.py # multi-scenario
26
+ done <<<"$list"
27
+ fi
ultralytics/yolov5/utils/benchmarks.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Run YOLOv5 benchmarks on all supported export formats
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+ $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
23
+
24
+ Usage:
25
+ $ python utils/benchmarks.py --weights yolov5s.pt --img 640
26
+ """
27
+
28
+ import argparse
29
+ import sys
30
+ import time
31
+ from pathlib import Path
32
+
33
+ import pandas as pd
34
+
35
+ FILE = Path(__file__).resolve()
36
+ ROOT = FILE.parents[1] # YOLOv5 root directory
37
+ if str(ROOT) not in sys.path:
38
+ sys.path.append(str(ROOT)) # add ROOT to PATH
39
+ # ROOT = ROOT.relative_to(Path.cwd()) # relative
40
+
41
+ import export
42
+ import val
43
+ from utils import notebook_init
44
+ from utils.general import LOGGER, print_args
45
+ from utils.torch_utils import select_device
46
+
47
+
48
+ def run(weights=ROOT / 'yolov5s.pt', # weights path
49
+ imgsz=640, # inference size (pixels)
50
+ batch_size=1, # batch size
51
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
52
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
53
+ half=False, # use FP16 half-precision inference
54
+ ):
55
+ y, t = [], time.time()
56
+ formats = export.export_formats()
57
+ device = select_device(device)
58
+ for i, (name, f, suffix, gpu) in formats.iterrows(): # index, (name, file, suffix, gpu-capable)
59
+ try:
60
+ if device.type != 'cpu':
61
+ assert gpu, f'{name} inference not supported on GPU'
62
+ if f == '-':
63
+ w = weights # PyTorch format
64
+ else:
65
+ w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others
66
+ assert suffix in str(w), 'export failed'
67
+ result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half)
68
+ metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls))
69
+ speeds = result[2] # times (preprocess, inference, postprocess)
70
+ y.append([name, round(metrics[3], 4), round(speeds[1], 2)]) # mAP, t_inference
71
+ except Exception as e:
72
+ LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}')
73
+ y.append([name, None, None]) # mAP, t_inference
74
+
75
+ # Print results
76
+ LOGGER.info('\n')
77
+ parse_opt()
78
+ notebook_init() # print system info
79
+ py = pd.DataFrame(y, columns=['Format', 'mAP@0.5:0.95', 'Inference time (ms)'])
80
+ LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
81
+ LOGGER.info(str(py))
82
+ return py
83
+
84
+
85
+ def parse_opt():
86
+ parser = argparse.ArgumentParser()
87
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
88
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
89
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
90
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
91
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
92
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
93
+ opt = parser.parse_args()
94
+ print_args(FILE.stem, opt)
95
+ return opt
96
+
97
+
98
+ def main(opt):
99
+ run(**vars(opt))
100
+
101
+
102
+ if __name__ == "__main__":
103
+ opt = parse_opt()
104
+ main(opt)
ultralytics/yolov5/utils/callbacks.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Callback utils
4
+ """
5
+
6
+
7
+ class Callbacks:
8
+ """"
9
+ Handles all registered callbacks for YOLOv5 Hooks
10
+ """
11
+
12
+ def __init__(self):
13
+ # Define the available callbacks
14
+ self._callbacks = {
15
+ 'on_pretrain_routine_start': [],
16
+ 'on_pretrain_routine_end': [],
17
+
18
+ 'on_train_start': [],
19
+ 'on_train_epoch_start': [],
20
+ 'on_train_batch_start': [],
21
+ 'optimizer_step': [],
22
+ 'on_before_zero_grad': [],
23
+ 'on_train_batch_end': [],
24
+ 'on_train_epoch_end': [],
25
+
26
+ 'on_val_start': [],
27
+ 'on_val_batch_start': [],
28
+ 'on_val_image_end': [],
29
+ 'on_val_batch_end': [],
30
+ 'on_val_end': [],
31
+
32
+ 'on_fit_epoch_end': [], # fit = train + val
33
+ 'on_model_save': [],
34
+ 'on_train_end': [],
35
+ 'on_params_update': [],
36
+ 'teardown': [],
37
+ }
38
+ self.stop_training = False # set True to interrupt training
39
+
40
+ def register_action(self, hook, name='', callback=None):
41
+ """
42
+ Register a new action to a callback hook
43
+
44
+ Args:
45
+ hook The callback hook name to register the action to
46
+ name The name of the action for later reference
47
+ callback The callback to fire
48
+ """
49
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
50
+ assert callable(callback), f"callback '{callback}' is not callable"
51
+ self._callbacks[hook].append({'name': name, 'callback': callback})
52
+
53
+ def get_registered_actions(self, hook=None):
54
+ """"
55
+ Returns all the registered actions by callback hook
56
+
57
+ Args:
58
+ hook The name of the hook to check, defaults to all
59
+ """
60
+ if hook:
61
+ return self._callbacks[hook]
62
+ else:
63
+ return self._callbacks
64
+
65
+ def run(self, hook, *args, **kwargs):
66
+ """
67
+ Loop through the registered actions and fire all callbacks
68
+
69
+ Args:
70
+ hook The name of the hook to check, defaults to all
71
+ args Arguments to receive from YOLOv5
72
+ kwargs Keyword Arguments to receive from YOLOv5
73
+ """
74
+
75
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
76
+
77
+ for logger in self._callbacks[hook]:
78
+ logger['callback'](*args, **kwargs)
ultralytics/yolov5/utils/datasets.py ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Dataloaders and dataset utils
4
+ """
5
+
6
+ import glob
7
+ import hashlib
8
+ import json
9
+ import math
10
+ import os
11
+ import random
12
+ import shutil
13
+ import time
14
+ from itertools import repeat
15
+ from multiprocessing.pool import Pool, ThreadPool
16
+ from pathlib import Path
17
+ from threading import Thread
18
+ from urllib.parse import urlparse
19
+ from zipfile import ZipFile
20
+
21
+ import cv2
22
+ import numpy as np
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import yaml
26
+ from PIL import ExifTags, Image, ImageOps
27
+ from torch.utils.data import DataLoader, Dataset, dataloader, distributed
28
+ from tqdm import tqdm
29
+
30
+ from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
31
+ from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str,
32
+ segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
33
+ from utils.torch_utils import torch_distributed_zero_first
34
+
35
+ # Parameters
36
+ HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
37
+ IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' # include image suffixes
38
+ VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes
39
+ BAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}' # tqdm bar format
40
+
41
+ # Get orientation exif tag
42
+ for orientation in ExifTags.TAGS.keys():
43
+ if ExifTags.TAGS[orientation] == 'Orientation':
44
+ break
45
+
46
+
47
+ def get_hash(paths):
48
+ # Returns a single hash value of a list of paths (files or dirs)
49
+ size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
50
+ h = hashlib.md5(str(size).encode()) # hash sizes
51
+ h.update(''.join(paths).encode()) # hash paths
52
+ return h.hexdigest() # return hash
53
+
54
+
55
+ def exif_size(img):
56
+ # Returns exif-corrected PIL size
57
+ s = img.size # (width, height)
58
+ try:
59
+ rotation = dict(img._getexif().items())[orientation]
60
+ if rotation == 6: # rotation 270
61
+ s = (s[1], s[0])
62
+ elif rotation == 8: # rotation 90
63
+ s = (s[1], s[0])
64
+ except Exception:
65
+ pass
66
+
67
+ return s
68
+
69
+
70
+ def exif_transpose(image):
71
+ """
72
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
73
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
74
+
75
+ :param image: The image to transpose.
76
+ :return: An image.
77
+ """
78
+ exif = image.getexif()
79
+ orientation = exif.get(0x0112, 1) # default 1
80
+ if orientation > 1:
81
+ method = {2: Image.FLIP_LEFT_RIGHT,
82
+ 3: Image.ROTATE_180,
83
+ 4: Image.FLIP_TOP_BOTTOM,
84
+ 5: Image.TRANSPOSE,
85
+ 6: Image.ROTATE_270,
86
+ 7: Image.TRANSVERSE,
87
+ 8: Image.ROTATE_90,
88
+ }.get(orientation)
89
+ if method is not None:
90
+ image = image.transpose(method)
91
+ del exif[0x0112]
92
+ image.info["exif"] = exif.tobytes()
93
+ return image
94
+
95
+
96
+ def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,
97
+ rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='', shuffle=False):
98
+ if rect and shuffle:
99
+ LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')
100
+ shuffle = False
101
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
102
+ dataset = LoadImagesAndLabels(path, imgsz, batch_size,
103
+ augment=augment, # augmentation
104
+ hyp=hyp, # hyperparameters
105
+ rect=rect, # rectangular batches
106
+ cache_images=cache,
107
+ single_cls=single_cls,
108
+ stride=int(stride),
109
+ pad=pad,
110
+ image_weights=image_weights,
111
+ prefix=prefix)
112
+
113
+ batch_size = min(batch_size, len(dataset))
114
+ nd = torch.cuda.device_count() # number of CUDA devices
115
+ nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers
116
+ sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
117
+ loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
118
+ return loader(dataset,
119
+ batch_size=batch_size,
120
+ shuffle=shuffle and sampler is None,
121
+ num_workers=nw,
122
+ sampler=sampler,
123
+ pin_memory=True,
124
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset
125
+
126
+
127
+ class InfiniteDataLoader(dataloader.DataLoader):
128
+ """ Dataloader that reuses workers
129
+
130
+ Uses same syntax as vanilla DataLoader
131
+ """
132
+
133
+ def __init__(self, *args, **kwargs):
134
+ super().__init__(*args, **kwargs)
135
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
136
+ self.iterator = super().__iter__()
137
+
138
+ def __len__(self):
139
+ return len(self.batch_sampler.sampler)
140
+
141
+ def __iter__(self):
142
+ for i in range(len(self)):
143
+ yield next(self.iterator)
144
+
145
+
146
+ class _RepeatSampler:
147
+ """ Sampler that repeats forever
148
+
149
+ Args:
150
+ sampler (Sampler)
151
+ """
152
+
153
+ def __init__(self, sampler):
154
+ self.sampler = sampler
155
+
156
+ def __iter__(self):
157
+ while True:
158
+ yield from iter(self.sampler)
159
+
160
+
161
+ class LoadImages:
162
+ # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
163
+ def __init__(self, path, img_size=640, stride=32, auto=True):
164
+ p = str(Path(path).resolve()) # os-agnostic absolute path
165
+ if '*' in p:
166
+ files = sorted(glob.glob(p, recursive=True)) # glob
167
+ elif os.path.isdir(p):
168
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
169
+ elif os.path.isfile(p):
170
+ files = [p] # files
171
+ else:
172
+ raise Exception(f'ERROR: {p} does not exist')
173
+
174
+ images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
175
+ videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
176
+ ni, nv = len(images), len(videos)
177
+
178
+ self.img_size = img_size
179
+ self.stride = stride
180
+ self.files = images + videos
181
+ self.nf = ni + nv # number of files
182
+ self.video_flag = [False] * ni + [True] * nv
183
+ self.mode = 'image'
184
+ self.auto = auto
185
+ if any(videos):
186
+ self.new_video(videos[0]) # new video
187
+ else:
188
+ self.cap = None
189
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
190
+ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
191
+
192
+ def __iter__(self):
193
+ self.count = 0
194
+ return self
195
+
196
+ def __next__(self):
197
+ if self.count == self.nf:
198
+ raise StopIteration
199
+ path = self.files[self.count]
200
+
201
+ if self.video_flag[self.count]:
202
+ # Read video
203
+ self.mode = 'video'
204
+ ret_val, img0 = self.cap.read()
205
+ while not ret_val:
206
+ self.count += 1
207
+ self.cap.release()
208
+ if self.count == self.nf: # last video
209
+ raise StopIteration
210
+ else:
211
+ path = self.files[self.count]
212
+ self.new_video(path)
213
+ ret_val, img0 = self.cap.read()
214
+
215
+ self.frame += 1
216
+ s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
217
+
218
+ else:
219
+ # Read image
220
+ self.count += 1
221
+ img0 = cv2.imread(path) # BGR
222
+ assert img0 is not None, f'Image Not Found {path}'
223
+ s = f'image {self.count}/{self.nf} {path}: '
224
+
225
+ # Padded resize
226
+ img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]
227
+
228
+ # Convert
229
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
230
+ img = np.ascontiguousarray(img)
231
+
232
+ return path, img, img0, self.cap, s
233
+
234
+ def new_video(self, path):
235
+ self.frame = 0
236
+ self.cap = cv2.VideoCapture(path)
237
+ self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
238
+
239
+ def __len__(self):
240
+ return self.nf # number of files
241
+
242
+
243
+ class LoadWebcam: # for inference
244
+ # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0`
245
+ def __init__(self, pipe='0', img_size=640, stride=32):
246
+ self.img_size = img_size
247
+ self.stride = stride
248
+ self.pipe = eval(pipe) if pipe.isnumeric() else pipe
249
+ self.cap = cv2.VideoCapture(self.pipe) # video capture object
250
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
251
+
252
+ def __iter__(self):
253
+ self.count = -1
254
+ return self
255
+
256
+ def __next__(self):
257
+ self.count += 1
258
+ if cv2.waitKey(1) == ord('q'): # q to quit
259
+ self.cap.release()
260
+ cv2.destroyAllWindows()
261
+ raise StopIteration
262
+
263
+ # Read frame
264
+ ret_val, img0 = self.cap.read()
265
+ img0 = cv2.flip(img0, 1) # flip left-right
266
+
267
+ # Print
268
+ assert ret_val, f'Camera Error {self.pipe}'
269
+ img_path = 'webcam.jpg'
270
+ s = f'webcam {self.count}: '
271
+
272
+ # Padded resize
273
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
274
+
275
+ # Convert
276
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
277
+ img = np.ascontiguousarray(img)
278
+
279
+ return img_path, img, img0, None, s
280
+
281
+ def __len__(self):
282
+ return 0
283
+
284
+
285
+ class LoadStreams:
286
+ # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`
287
+ def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):
288
+ self.mode = 'stream'
289
+ self.img_size = img_size
290
+ self.stride = stride
291
+
292
+ if os.path.isfile(sources):
293
+ with open(sources) as f:
294
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
295
+ else:
296
+ sources = [sources]
297
+
298
+ n = len(sources)
299
+ self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
300
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
301
+ self.auto = auto
302
+ for i, s in enumerate(sources): # index, source
303
+ # Start thread to read frames from video stream
304
+ st = f'{i + 1}/{n}: {s}... '
305
+ if urlparse(s).hostname in ('youtube.com', 'youtu.be'): # if source is YouTube video
306
+ check_requirements(('pafy', 'youtube_dl==2020.12.2'))
307
+ import pafy
308
+ s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
309
+ s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
310
+ cap = cv2.VideoCapture(s)
311
+ assert cap.isOpened(), f'{st}Failed to open {s}'
312
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
313
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
314
+ fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan
315
+ self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
316
+ self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback
317
+
318
+ _, self.imgs[i] = cap.read() # guarantee first frame
319
+ self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)
320
+ LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
321
+ self.threads[i].start()
322
+ LOGGER.info('') # newline
323
+
324
+ # check for common shapes
325
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
326
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
327
+ if not self.rect:
328
+ LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.')
329
+
330
+ def update(self, i, cap, stream):
331
+ # Read stream `i` frames in daemon thread
332
+ n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
333
+ while cap.isOpened() and n < f:
334
+ n += 1
335
+ # _, self.imgs[index] = cap.read()
336
+ cap.grab()
337
+ if n % read == 0:
338
+ success, im = cap.retrieve()
339
+ if success:
340
+ self.imgs[i] = im
341
+ else:
342
+ LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.')
343
+ self.imgs[i] = np.zeros_like(self.imgs[i])
344
+ cap.open(stream) # re-open stream if signal was lost
345
+ time.sleep(1 / self.fps[i]) # wait time
346
+
347
+ def __iter__(self):
348
+ self.count = -1
349
+ return self
350
+
351
+ def __next__(self):
352
+ self.count += 1
353
+ if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
354
+ cv2.destroyAllWindows()
355
+ raise StopIteration
356
+
357
+ # Letterbox
358
+ img0 = self.imgs.copy()
359
+ img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]
360
+
361
+ # Stack
362
+ img = np.stack(img, 0)
363
+
364
+ # Convert
365
+ img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
366
+ img = np.ascontiguousarray(img)
367
+
368
+ return self.sources, img, img0, None, ''
369
+
370
+ def __len__(self):
371
+ return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
372
+
373
+
374
+ def img2label_paths(img_paths):
375
+ # Define label paths as a function of image paths
376
+ sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
377
+ return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
378
+
379
+
380
+ class LoadImagesAndLabels(Dataset):
381
+ # YOLOv5 train_loader/val_loader, loads images and labels for training and validation
382
+ cache_version = 0.6 # dataset labels *.cache version
383
+
384
+ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
385
+ cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
386
+ self.img_size = img_size
387
+ self.augment = augment
388
+ self.hyp = hyp
389
+ self.image_weights = image_weights
390
+ self.rect = False if image_weights else rect
391
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
392
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
393
+ self.stride = stride
394
+ self.path = path
395
+ self.albumentations = Albumentations() if augment else None
396
+
397
+ try:
398
+ f = [] # image files
399
+ for p in path if isinstance(path, list) else [path]:
400
+ p = Path(p) # os-agnostic
401
+ if p.is_dir(): # dir
402
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
403
+ # f = list(p.rglob('*.*')) # pathlib
404
+ elif p.is_file(): # file
405
+ with open(p) as t:
406
+ t = t.read().strip().splitlines()
407
+ parent = str(p.parent) + os.sep
408
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
409
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
410
+ else:
411
+ raise Exception(f'{prefix}{p} does not exist')
412
+ self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
413
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib
414
+ assert self.im_files, f'{prefix}No images found'
415
+ except Exception as e:
416
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}')
417
+
418
+ # Check cache
419
+ self.label_files = img2label_paths(self.im_files) # labels
420
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
421
+ try:
422
+ cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
423
+ assert cache['version'] == self.cache_version # same version
424
+ assert cache['hash'] == get_hash(self.label_files + self.im_files) # same hash
425
+ except Exception:
426
+ cache, exists = self.cache_labels(cache_path, prefix), False # cache
427
+
428
+ # Display cache
429
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total
430
+ if exists:
431
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt"
432
+ tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results
433
+ if cache['msgs']:
434
+ LOGGER.info('\n'.join(cache['msgs'])) # display warnings
435
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'
436
+
437
+ # Read cache
438
+ [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
439
+ labels, shapes, self.segments = zip(*cache.values())
440
+ self.labels = list(labels)
441
+ self.shapes = np.array(shapes, dtype=np.float64)
442
+ self.im_files = list(cache.keys()) # update
443
+ self.label_files = img2label_paths(cache.keys()) # update
444
+ n = len(shapes) # number of images
445
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
446
+ nb = bi[-1] + 1 # number of batches
447
+ self.batch = bi # batch index of image
448
+ self.n = n
449
+ self.indices = range(n)
450
+
451
+ # Update labels
452
+ include_class = [] # filter labels to include only these classes (optional)
453
+ include_class_array = np.array(include_class).reshape(1, -1)
454
+ for i, (label, segment) in enumerate(zip(self.labels, self.segments)):
455
+ if include_class:
456
+ j = (label[:, 0:1] == include_class_array).any(1)
457
+ self.labels[i] = label[j]
458
+ if segment:
459
+ self.segments[i] = segment[j]
460
+ if single_cls: # single-class training, merge all classes into 0
461
+ self.labels[i][:, 0] = 0
462
+ if segment:
463
+ self.segments[i][:, 0] = 0
464
+
465
+ # Rectangular Training
466
+ if self.rect:
467
+ # Sort by aspect ratio
468
+ s = self.shapes # wh
469
+ ar = s[:, 1] / s[:, 0] # aspect ratio
470
+ irect = ar.argsort()
471
+ self.im_files = [self.im_files[i] for i in irect]
472
+ self.label_files = [self.label_files[i] for i in irect]
473
+ self.labels = [self.labels[i] for i in irect]
474
+ self.shapes = s[irect] # wh
475
+ ar = ar[irect]
476
+
477
+ # Set training image shapes
478
+ shapes = [[1, 1]] * nb
479
+ for i in range(nb):
480
+ ari = ar[bi == i]
481
+ mini, maxi = ari.min(), ari.max()
482
+ if maxi < 1:
483
+ shapes[i] = [maxi, 1]
484
+ elif mini > 1:
485
+ shapes[i] = [1, 1 / mini]
486
+
487
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
488
+
489
+ # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources)
490
+ self.ims = [None] * n
491
+ self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]
492
+ if cache_images:
493
+ gb = 0 # Gigabytes of cached images
494
+ self.im_hw0, self.im_hw = [None] * n, [None] * n
495
+ fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image
496
+ results = ThreadPool(NUM_THREADS).imap(fcn, range(n))
497
+ pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT)
498
+ for i, x in pbar:
499
+ if cache_images == 'disk':
500
+ gb += self.npy_files[i].stat().st_size
501
+ else: # 'ram'
502
+ self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
503
+ gb += self.ims[i].nbytes
504
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'
505
+ pbar.close()
506
+
507
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
508
+ # Cache dataset labels, check images and read shapes
509
+ x = {} # dict
510
+ nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
511
+ desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
512
+ with Pool(NUM_THREADS) as pool:
513
+ pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),
514
+ desc=desc, total=len(self.im_files), bar_format=BAR_FORMAT)
515
+ for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
516
+ nm += nm_f
517
+ nf += nf_f
518
+ ne += ne_f
519
+ nc += nc_f
520
+ if im_file:
521
+ x[im_file] = [lb, shape, segments]
522
+ if msg:
523
+ msgs.append(msg)
524
+ pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt"
525
+
526
+ pbar.close()
527
+ if msgs:
528
+ LOGGER.info('\n'.join(msgs))
529
+ if nf == 0:
530
+ LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')
531
+ x['hash'] = get_hash(self.label_files + self.im_files)
532
+ x['results'] = nf, nm, ne, nc, len(self.im_files)
533
+ x['msgs'] = msgs # warnings
534
+ x['version'] = self.cache_version # cache version
535
+ try:
536
+ np.save(path, x) # save cache for next time
537
+ path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
538
+ LOGGER.info(f'{prefix}New cache created: {path}')
539
+ except Exception as e:
540
+ LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable
541
+ return x
542
+
543
+ def __len__(self):
544
+ return len(self.im_files)
545
+
546
+ # def __iter__(self):
547
+ # self.count = -1
548
+ # print('ran dataset iter')
549
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
550
+ # return self
551
+
552
+ def __getitem__(self, index):
553
+ index = self.indices[index] # linear, shuffled, or image_weights
554
+
555
+ hyp = self.hyp
556
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
557
+ if mosaic:
558
+ # Load mosaic
559
+ img, labels = self.load_mosaic(index)
560
+ shapes = None
561
+
562
+ # MixUp augmentation
563
+ if random.random() < hyp['mixup']:
564
+ img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1)))
565
+
566
+ else:
567
+ # Load image
568
+ img, (h0, w0), (h, w) = self.load_image(index)
569
+
570
+ # Letterbox
571
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
572
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
573
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
574
+
575
+ labels = self.labels[index].copy()
576
+ if labels.size: # normalized xywh to pixel xyxy format
577
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
578
+
579
+ if self.augment:
580
+ img, labels = random_perspective(img, labels,
581
+ degrees=hyp['degrees'],
582
+ translate=hyp['translate'],
583
+ scale=hyp['scale'],
584
+ shear=hyp['shear'],
585
+ perspective=hyp['perspective'])
586
+
587
+ nl = len(labels) # number of labels
588
+ if nl:
589
+ labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
590
+
591
+ if self.augment:
592
+ # Albumentations
593
+ img, labels = self.albumentations(img, labels)
594
+ nl = len(labels) # update after albumentations
595
+
596
+ # HSV color-space
597
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
598
+
599
+ # Flip up-down
600
+ if random.random() < hyp['flipud']:
601
+ img = np.flipud(img)
602
+ if nl:
603
+ labels[:, 2] = 1 - labels[:, 2]
604
+
605
+ # Flip left-right
606
+ if random.random() < hyp['fliplr']:
607
+ img = np.fliplr(img)
608
+ if nl:
609
+ labels[:, 1] = 1 - labels[:, 1]
610
+
611
+ # Cutouts
612
+ # labels = cutout(img, labels, p=0.5)
613
+ # nl = len(labels) # update after cutout
614
+
615
+ labels_out = torch.zeros((nl, 6))
616
+ if nl:
617
+ labels_out[:, 1:] = torch.from_numpy(labels)
618
+
619
+ # Convert
620
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
621
+ img = np.ascontiguousarray(img)
622
+
623
+ return torch.from_numpy(img), labels_out, self.im_files[index], shapes
624
+
625
+ def load_image(self, i):
626
+ # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw)
627
+ im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],
628
+ if im is None: # not cached in RAM
629
+ if fn.exists(): # load npy
630
+ im = np.load(fn)
631
+ else: # read image
632
+ im = cv2.imread(f) # BGR
633
+ assert im is not None, f'Image Not Found {f}'
634
+ h0, w0 = im.shape[:2] # orig hw
635
+ r = self.img_size / max(h0, w0) # ratio
636
+ if r != 1: # if sizes are not equal
637
+ im = cv2.resize(im,
638
+ (int(w0 * r), int(h0 * r)),
639
+ interpolation=cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA)
640
+ return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
641
+ else:
642
+ return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized
643
+
644
+ def cache_images_to_disk(self, i):
645
+ # Saves an image as an *.npy file for faster loading
646
+ f = self.npy_files[i]
647
+ if not f.exists():
648
+ np.save(f.as_posix(), cv2.imread(self.im_files[i]))
649
+
650
+ def load_mosaic(self, index):
651
+ # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
652
+ labels4, segments4 = [], []
653
+ s = self.img_size
654
+ yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
655
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
656
+ random.shuffle(indices)
657
+ for i, index in enumerate(indices):
658
+ # Load image
659
+ img, _, (h, w) = self.load_image(index)
660
+
661
+ # place img in img4
662
+ if i == 0: # top left
663
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
664
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
665
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
666
+ elif i == 1: # top right
667
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
668
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
669
+ elif i == 2: # bottom left
670
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
671
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
672
+ elif i == 3: # bottom right
673
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
674
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
675
+
676
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
677
+ padw = x1a - x1b
678
+ padh = y1a - y1b
679
+
680
+ # Labels
681
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
682
+ if labels.size:
683
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
684
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
685
+ labels4.append(labels)
686
+ segments4.extend(segments)
687
+
688
+ # Concat/clip labels
689
+ labels4 = np.concatenate(labels4, 0)
690
+ for x in (labels4[:, 1:], *segments4):
691
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
692
+ # img4, labels4 = replicate(img4, labels4) # replicate
693
+
694
+ # Augment
695
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
696
+ img4, labels4 = random_perspective(img4, labels4, segments4,
697
+ degrees=self.hyp['degrees'],
698
+ translate=self.hyp['translate'],
699
+ scale=self.hyp['scale'],
700
+ shear=self.hyp['shear'],
701
+ perspective=self.hyp['perspective'],
702
+ border=self.mosaic_border) # border to remove
703
+
704
+ return img4, labels4
705
+
706
+ def load_mosaic9(self, index):
707
+ # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic
708
+ labels9, segments9 = [], []
709
+ s = self.img_size
710
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
711
+ random.shuffle(indices)
712
+ hp, wp = -1, -1 # height, width previous
713
+ for i, index in enumerate(indices):
714
+ # Load image
715
+ img, _, (h, w) = self.load_image(index)
716
+
717
+ # place img in img9
718
+ if i == 0: # center
719
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
720
+ h0, w0 = h, w
721
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
722
+ elif i == 1: # top
723
+ c = s, s - h, s + w, s
724
+ elif i == 2: # top right
725
+ c = s + wp, s - h, s + wp + w, s
726
+ elif i == 3: # right
727
+ c = s + w0, s, s + w0 + w, s + h
728
+ elif i == 4: # bottom right
729
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
730
+ elif i == 5: # bottom
731
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
732
+ elif i == 6: # bottom left
733
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
734
+ elif i == 7: # left
735
+ c = s - w, s + h0 - h, s, s + h0
736
+ elif i == 8: # top left
737
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
738
+
739
+ padx, pady = c[:2]
740
+ x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
741
+
742
+ # Labels
743
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
744
+ if labels.size:
745
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
746
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
747
+ labels9.append(labels)
748
+ segments9.extend(segments)
749
+
750
+ # Image
751
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
752
+ hp, wp = h, w # height, width previous
753
+
754
+ # Offset
755
+ yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y
756
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
757
+
758
+ # Concat/clip labels
759
+ labels9 = np.concatenate(labels9, 0)
760
+ labels9[:, [1, 3]] -= xc
761
+ labels9[:, [2, 4]] -= yc
762
+ c = np.array([xc, yc]) # centers
763
+ segments9 = [x - c for x in segments9]
764
+
765
+ for x in (labels9[:, 1:], *segments9):
766
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
767
+ # img9, labels9 = replicate(img9, labels9) # replicate
768
+
769
+ # Augment
770
+ img9, labels9 = random_perspective(img9, labels9, segments9,
771
+ degrees=self.hyp['degrees'],
772
+ translate=self.hyp['translate'],
773
+ scale=self.hyp['scale'],
774
+ shear=self.hyp['shear'],
775
+ perspective=self.hyp['perspective'],
776
+ border=self.mosaic_border) # border to remove
777
+
778
+ return img9, labels9
779
+
780
+ @staticmethod
781
+ def collate_fn(batch):
782
+ im, label, path, shapes = zip(*batch) # transposed
783
+ for i, lb in enumerate(label):
784
+ lb[:, 0] = i # add target image index for build_targets()
785
+ return torch.stack(im, 0), torch.cat(label, 0), path, shapes
786
+
787
+ @staticmethod
788
+ def collate_fn4(batch):
789
+ img, label, path, shapes = zip(*batch) # transposed
790
+ n = len(shapes) // 4
791
+ im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
792
+
793
+ ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])
794
+ wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])
795
+ s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale
796
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
797
+ i *= 4
798
+ if random.random() < 0.5:
799
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', align_corners=False)[
800
+ 0].type(img[i].type())
801
+ lb = label[i]
802
+ else:
803
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
804
+ lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
805
+ im4.append(im)
806
+ label4.append(lb)
807
+
808
+ for i, lb in enumerate(label4):
809
+ lb[:, 0] = i # add target image index for build_targets()
810
+
811
+ return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4
812
+
813
+
814
+ # Ancillary functions --------------------------------------------------------------------------------------------------
815
+ def create_folder(path='./new'):
816
+ # Create folder
817
+ if os.path.exists(path):
818
+ shutil.rmtree(path) # delete output folder
819
+ os.makedirs(path) # make new output folder
820
+
821
+
822
+ def flatten_recursive(path=DATASETS_DIR / 'coco128'):
823
+ # Flatten a recursive directory by bringing all files to top level
824
+ new_path = Path(str(path) + '_flat')
825
+ create_folder(new_path)
826
+ for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
827
+ shutil.copyfile(file, new_path / Path(file).name)
828
+
829
+
830
+ def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.datasets import *; extract_boxes()
831
+ # Convert detection dataset into classification dataset, with one directory per class
832
+ path = Path(path) # images dir
833
+ shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
834
+ files = list(path.rglob('*.*'))
835
+ n = len(files) # number of files
836
+ for im_file in tqdm(files, total=n):
837
+ if im_file.suffix[1:] in IMG_FORMATS:
838
+ # image
839
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
840
+ h, w = im.shape[:2]
841
+
842
+ # labels
843
+ lb_file = Path(img2label_paths([str(im_file)])[0])
844
+ if Path(lb_file).exists():
845
+ with open(lb_file) as f:
846
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
847
+
848
+ for j, x in enumerate(lb):
849
+ c = int(x[0]) # class
850
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
851
+ if not f.parent.is_dir():
852
+ f.parent.mkdir(parents=True)
853
+
854
+ b = x[1:] * [w, h, w, h] # box
855
+ # b[2:] = b[2:].max() # rectangle to square
856
+ b[2:] = b[2:] * 1.2 + 3 # pad
857
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
858
+
859
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
860
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
861
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
862
+
863
+
864
+ def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
865
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
866
+ Usage: from utils.datasets import *; autosplit()
867
+ Arguments
868
+ path: Path to images directory
869
+ weights: Train, val, test weights (list, tuple)
870
+ annotated_only: Only use images with an annotated txt file
871
+ """
872
+ path = Path(path) # images dir
873
+ files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only
874
+ n = len(files) # number of files
875
+ random.seed(0) # for reproducibility
876
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
877
+
878
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
879
+ [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
880
+
881
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
882
+ for i, img in tqdm(zip(indices, files), total=n):
883
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
884
+ with open(path.parent / txt[i], 'a') as f:
885
+ f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file
886
+
887
+
888
+ def verify_image_label(args):
889
+ # Verify one image-label pair
890
+ im_file, lb_file, prefix = args
891
+ nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
892
+ try:
893
+ # verify images
894
+ im = Image.open(im_file)
895
+ im.verify() # PIL verify
896
+ shape = exif_size(im) # image size
897
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
898
+ assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
899
+ if im.format.lower() in ('jpg', 'jpeg'):
900
+ with open(im_file, 'rb') as f:
901
+ f.seek(-2, 2)
902
+ if f.read() != b'\xff\xd9': # corrupt JPEG
903
+ ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
904
+ msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
905
+
906
+ # verify labels
907
+ if os.path.isfile(lb_file):
908
+ nf = 1 # label found
909
+ with open(lb_file) as f:
910
+ lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
911
+ if any(len(x) > 6 for x in lb): # is segment
912
+ classes = np.array([x[0] for x in lb], dtype=np.float32)
913
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
914
+ lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
915
+ lb = np.array(lb, dtype=np.float32)
916
+ nl = len(lb)
917
+ if nl:
918
+ assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'
919
+ assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'
920
+ assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'
921
+ _, i = np.unique(lb, axis=0, return_index=True)
922
+ if len(i) < nl: # duplicate row check
923
+ lb = lb[i] # remove duplicates
924
+ if segments:
925
+ segments = segments[i]
926
+ msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'
927
+ else:
928
+ ne = 1 # label empty
929
+ lb = np.zeros((0, 5), dtype=np.float32)
930
+ else:
931
+ nm = 1 # label missing
932
+ lb = np.zeros((0, 5), dtype=np.float32)
933
+ return im_file, lb, shape, segments, nm, nf, ne, nc, msg
934
+ except Exception as e:
935
+ nc = 1
936
+ msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'
937
+ return [None, None, None, None, nm, nf, ne, nc, msg]
938
+
939
+
940
+ def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False):
941
+ """ Return dataset statistics dictionary with images and instances counts per split per class
942
+ To run in parent directory: export PYTHONPATH="$PWD/yolov5"
943
+ Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True)
944
+ Usage2: from utils.datasets import *; dataset_stats('path/to/coco128_with_yaml.zip')
945
+ Arguments
946
+ path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
947
+ autodownload: Attempt to download dataset if not found locally
948
+ verbose: Print stats dictionary
949
+ """
950
+
951
+ def round_labels(labels):
952
+ # Update labels to integer class and 6 decimal place floats
953
+ return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
954
+
955
+ def unzip(path):
956
+ # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/'
957
+ if str(path).endswith('.zip'): # path is data.zip
958
+ assert Path(path).is_file(), f'Error unzipping {path}, file not found'
959
+ ZipFile(path).extractall(path=path.parent) # unzip
960
+ dir = path.with_suffix('') # dataset directory == zip name
961
+ return True, str(dir), next(dir.rglob('*.yaml')) # zipped, data_dir, yaml_path
962
+ else: # path is data.yaml
963
+ return False, None, path
964
+
965
+ def hub_ops(f, max_dim=1920):
966
+ # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing
967
+ f_new = im_dir / Path(f).name # dataset-hub image filename
968
+ try: # use PIL
969
+ im = Image.open(f)
970
+ r = max_dim / max(im.height, im.width) # ratio
971
+ if r < 1.0: # image too large
972
+ im = im.resize((int(im.width * r), int(im.height * r)))
973
+ im.save(f_new, 'JPEG', quality=75, optimize=True) # save
974
+ except Exception as e: # use OpenCV
975
+ print(f'WARNING: HUB ops PIL failure {f}: {e}')
976
+ im = cv2.imread(f)
977
+ im_height, im_width = im.shape[:2]
978
+ r = max_dim / max(im_height, im_width) # ratio
979
+ if r < 1.0: # image too large
980
+ im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)
981
+ cv2.imwrite(str(f_new), im)
982
+
983
+ zipped, data_dir, yaml_path = unzip(Path(path))
984
+ with open(check_yaml(yaml_path), errors='ignore') as f:
985
+ data = yaml.safe_load(f) # data dict
986
+ if zipped:
987
+ data['path'] = data_dir # TODO: should this be dir.resolve()?
988
+ check_dataset(data, autodownload) # download dataset if missing
989
+ hub_dir = Path(data['path'] + ('-hub' if hub else ''))
990
+ stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary
991
+ for split in 'train', 'val', 'test':
992
+ if data.get(split) is None:
993
+ stats[split] = None # i.e. no test set
994
+ continue
995
+ x = []
996
+ dataset = LoadImagesAndLabels(data[split]) # load dataset
997
+ for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
998
+ x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))
999
+ x = np.array(x) # shape(128x80)
1000
+ stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},
1001
+ 'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),
1002
+ 'per_class': (x > 0).sum(0).tolist()},
1003
+ 'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in
1004
+ zip(dataset.im_files, dataset.labels)]}
1005
+
1006
+ if hub:
1007
+ im_dir = hub_dir / 'images'
1008
+ im_dir.mkdir(parents=True, exist_ok=True)
1009
+ for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.im_files), total=dataset.n, desc='HUB Ops'):
1010
+ pass
1011
+
1012
+ # Profile
1013
+ stats_path = hub_dir / 'stats.json'
1014
+ if profile:
1015
+ for _ in range(1):
1016
+ file = stats_path.with_suffix('.npy')
1017
+ t1 = time.time()
1018
+ np.save(file, stats)
1019
+ t2 = time.time()
1020
+ x = np.load(file, allow_pickle=True)
1021
+ print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
1022
+
1023
+ file = stats_path.with_suffix('.json')
1024
+ t1 = time.time()
1025
+ with open(file, 'w') as f:
1026
+ json.dump(stats, f) # save stats *.json
1027
+ t2 = time.time()
1028
+ with open(file) as f:
1029
+ x = json.load(f) # load hyps dict
1030
+ print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
1031
+
1032
+ # Save, print and return
1033
+ if hub:
1034
+ print(f'Saving {stats_path.resolve()}...')
1035
+ with open(stats_path, 'w') as f:
1036
+ json.dump(stats, f) # save stats.json
1037
+ if verbose:
1038
+ print(json.dumps(stats, indent=2, sort_keys=False))
1039
+ return stats
ultralytics/yolov5/utils/downloads.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Download utils
4
+ """
5
+
6
+ import os
7
+ import platform
8
+ import subprocess
9
+ import time
10
+ import urllib
11
+ from pathlib import Path
12
+ from zipfile import ZipFile
13
+
14
+ import requests
15
+ import torch
16
+
17
+
18
+ def gsutil_getsize(url=''):
19
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
20
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
21
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
22
+
23
+
24
+ def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
25
+ # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
26
+ file = Path(file)
27
+ assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
28
+ try: # url1
29
+ print(f'Downloading {url} to {file}...')
30
+ torch.hub.download_url_to_file(url, str(file))
31
+ assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
32
+ except Exception as e: # url2
33
+ file.unlink(missing_ok=True) # remove partial downloads
34
+ print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
35
+ os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
36
+ finally:
37
+ if not file.exists() or file.stat().st_size < min_bytes: # check
38
+ file.unlink(missing_ok=True) # remove partial downloads
39
+ print(f"ERROR: {assert_msg}\n{error_msg}")
40
+ print('')
41
+
42
+
43
+ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download()
44
+ # Attempt file download if does not exist
45
+ file = Path(str(file).strip().replace("'", ''))
46
+
47
+ if not file.exists():
48
+ # URL specified
49
+ name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
50
+ if str(file).startswith(('http:/', 'https:/')): # download
51
+ url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
52
+ file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
53
+ if Path(file).is_file():
54
+ print(f'Found {url} locally at {file}') # file already exists
55
+ else:
56
+ safe_download(file=file, url=url, min_bytes=1E5)
57
+ return file
58
+
59
+ # GitHub assets
60
+ file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
61
+ try:
62
+ response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
63
+ assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
64
+ tag = response['tag_name'] # i.e. 'v1.0'
65
+ except Exception: # fallback plan
66
+ assets = ['yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
67
+ 'yolov5n6.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
68
+ try:
69
+ tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
70
+ except Exception:
71
+ tag = 'v6.0' # current release
72
+
73
+ if name in assets:
74
+ safe_download(file,
75
+ url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
76
+ # url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional)
77
+ min_bytes=1E5,
78
+ error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/')
79
+
80
+ return str(file)
81
+
82
+
83
+ def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
84
+ # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
85
+ t = time.time()
86
+ file = Path(file)
87
+ cookie = Path('cookie') # gdrive cookie
88
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
89
+ file.unlink(missing_ok=True) # remove existing file
90
+ cookie.unlink(missing_ok=True) # remove existing cookie
91
+
92
+ # Attempt file download
93
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
94
+ os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
95
+ if os.path.exists('cookie'): # large file
96
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
97
+ else: # small file
98
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
99
+ r = os.system(s) # execute, capture return
100
+ cookie.unlink(missing_ok=True) # remove existing cookie
101
+
102
+ # Error check
103
+ if r != 0:
104
+ file.unlink(missing_ok=True) # remove partial
105
+ print('Download error ') # raise Exception('Download error')
106
+ return r
107
+
108
+ # Unzip if archive
109
+ if file.suffix == '.zip':
110
+ print('unzipping... ', end='')
111
+ ZipFile(file).extractall(path=file.parent) # unzip
112
+ file.unlink() # remove zip
113
+
114
+ print(f'Done ({time.time() - t:.1f}s)')
115
+ return r
116
+
117
+
118
+ def get_token(cookie="./cookie"):
119
+ with open(cookie) as f:
120
+ for line in f:
121
+ if "download" in line:
122
+ return line.split()[-1]
123
+ return ""
124
+
125
+ # Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------
126
+ #
127
+ #
128
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
129
+ # # Uploads a file to a bucket
130
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
131
+ #
132
+ # storage_client = storage.Client()
133
+ # bucket = storage_client.get_bucket(bucket_name)
134
+ # blob = bucket.blob(destination_blob_name)
135
+ #
136
+ # blob.upload_from_filename(source_file_name)
137
+ #
138
+ # print('File {} uploaded to {}.'.format(
139
+ # source_file_name,
140
+ # destination_blob_name))
141
+ #
142
+ #
143
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
144
+ # # Uploads a blob from a bucket
145
+ # storage_client = storage.Client()
146
+ # bucket = storage_client.get_bucket(bucket_name)
147
+ # blob = bucket.blob(source_blob_name)
148
+ #
149
+ # blob.download_to_filename(destination_file_name)
150
+ #
151
+ # print('Blob {} downloaded to {}.'.format(
152
+ # source_blob_name,
153
+ # destination_file_name))
ultralytics/yolov5/utils/flask_rest_api/README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Flask REST API
2
+
3
+ [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are
4
+ commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API
5
+ created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).
6
+
7
+ ## Requirements
8
+
9
+ [Flask](https://palletsprojects.com/p/flask/) is required. Install with:
10
+
11
+ ```shell
12
+ $ pip install Flask
13
+ ```
14
+
15
+ ## Run
16
+
17
+ After Flask installation run:
18
+
19
+ ```shell
20
+ $ python3 restapi.py --port 5000
21
+ ```
22
+
23
+ Then use [curl](https://curl.se/) to perform a request:
24
+
25
+ ```shell
26
+ $ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'
27
+ ```
28
+
29
+ The model inference results are returned as a JSON response:
30
+
31
+ ```json
32
+ [
33
+ {
34
+ "class": 0,
35
+ "confidence": 0.8900438547,
36
+ "height": 0.9318675399,
37
+ "name": "person",
38
+ "width": 0.3264600933,
39
+ "xcenter": 0.7438579798,
40
+ "ycenter": 0.5207948685
41
+ },
42
+ {
43
+ "class": 0,
44
+ "confidence": 0.8440024257,
45
+ "height": 0.7155083418,
46
+ "name": "person",
47
+ "width": 0.6546785235,
48
+ "xcenter": 0.427829951,
49
+ "ycenter": 0.6334488392
50
+ },
51
+ {
52
+ "class": 27,
53
+ "confidence": 0.3771208823,
54
+ "height": 0.3902671337,
55
+ "name": "tie",
56
+ "width": 0.0696444362,
57
+ "xcenter": 0.3675483763,
58
+ "ycenter": 0.7991207838
59
+ },
60
+ {
61
+ "class": 27,
62
+ "confidence": 0.3527112305,
63
+ "height": 0.1540903747,
64
+ "name": "tie",
65
+ "width": 0.0336618312,
66
+ "xcenter": 0.7814827561,
67
+ "ycenter": 0.5065554976
68
+ }
69
+ ]
70
+ ```
71
+
72
+ An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given
73
+ in `example_request.py`
ultralytics/yolov5/utils/flask_rest_api/example_request.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Perform test request"""
2
+ import pprint
3
+
4
+ import requests
5
+
6
+ DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s"
7
+ TEST_IMAGE = "zidane.jpg"
8
+
9
+ image_data = open(TEST_IMAGE, "rb").read()
10
+
11
+ response = requests.post(DETECTION_URL, files={"image": image_data}).json()
12
+
13
+ pprint.pprint(response)