Zengyf-CVer commited on
Commit
33e71b2
1 Parent(s): 495c1d3

app update

Browse files
.gitignore ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Streamlit YOLOv5 Model2X
2
+ # 创建人:曾逸夫
3
+ # 项目地址:https://gitee.com/CV_Lab/streamlit_yolov5_modle2x
4
+
5
+ # 图片格式
6
+ *.jpg
7
+ *.jpeg
8
+ *.png
9
+ *.svg
10
+ *.gif
11
+
12
+ # 视频格式
13
+ *.mp4
14
+ *.avi
15
+ .ipynb_checkpoints
16
+ /__pycache__
17
+ */__pycache__
18
+
19
+ # 日志格式
20
+ *.log
21
+ *.data
22
+ *.txt
23
+
24
+ # 生成文件
25
+ *.pdf
26
+ *.xlsx
27
+ *.csv
28
+
29
+ # 参数文件
30
+ *.yaml
31
+ *.json
32
+
33
+ # 压缩文件格式
34
+ *.zip
35
+ *.tar
36
+ *.tar.gz
37
+ *.rar
38
+
39
+ # 字体格式
40
+ *.ttc
41
+ *.ttf
42
+ *.otf
43
+ *.pkl
44
+
45
+ # 模型文件
46
+ *.pt
47
+ *.db
48
+ *.onnx
49
+ *.pb
50
+ *.torchscript
51
+ *.tflite
52
+ *.mlmodel
53
+ *.engine
54
+ /*_web_model
55
+ /*_saved_model
56
+ /*_openvino_model
57
+
58
+
59
+ /flagged
60
+ /run
61
+ !requirements.txt
62
+ !cls_name/*
63
+ !model_config/*
64
+ !img_examples/*
65
+
66
+ !requirements.txt
67
+ !.pre-commit-config.yaml
68
+
69
+ test.py
70
+ test*.py
71
+
72
+ model_download.py
73
+ /bak
74
+ /weights
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  title: Streamlit YOLOv5 Model2x
3
- emoji: 📚
4
  colorFrom: red
5
  colorTo: pink
6
  sdk: streamlit
 
1
  ---
2
  title: Streamlit YOLOv5 Model2x
3
+ emoji: 🚀
4
  colorFrom: red
5
  colorTo: pink
6
  sdk: streamlit
app_02.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Streamlit YOLOv5 Model2X v0.1
2
+ # 创建人:曾逸夫
3
+ # 创建时间:2022-07-14
4
+ # 功能描述:多选,多项模型转换和打包下载
5
+
6
+ import os
7
+ import shutil
8
+ import time
9
+ import zipfile
10
+
11
+ import streamlit as st
12
+
13
+
14
+ # 目录操作
15
+ def dir_opt(target_dir):
16
+ if os.path.exists(target_dir):
17
+ shutil.rmtree(target_dir)
18
+ os.mkdir(target_dir)
19
+ else:
20
+ os.mkdir(target_dir)
21
+
22
+
23
+ # 文件下载
24
+ def download_file(uploaded_file):
25
+ # --------------- 下载 ---------------
26
+ with open(f"{uploaded_file}", 'rb') as fmodel:
27
+ # 读取转换的模型文件(pt2x)
28
+ f_download_model = fmodel.read()
29
+ st.download_button(label='下载转换后的模型', data=f_download_model, file_name=f"{uploaded_file}")
30
+ fmodel.close()
31
+
32
+
33
+ # 文件压缩
34
+ def zipDir(origin_dir, compress_file):
35
+ # --------------- 压缩 ---------------
36
+ zip = zipfile.ZipFile(f"{compress_file}", "w", zipfile.ZIP_DEFLATED)
37
+ for path, dirnames, filenames in os.walk(f"{origin_dir}"):
38
+ fpath = path.replace(f"{origin_dir}", '')
39
+ for filename in filenames:
40
+ zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
41
+ zip.close()
42
+
43
+
44
+ # params_include_list = ["torchscript", "onnx", "openvino", "engine", "coreml", "saved_model", "pb", "tflite", "tfjs"]
45
+ def cb_opt(weight_name, btn_model_list, params_include_list):
46
+
47
+ for i in range(len(btn_model_list)):
48
+ if btn_model_list[i]:
49
+ st.info(f"正在转换{params_include_list[i]}......")
50
+ s = time.time()
51
+ if i == 3:
52
+ os.system(
53
+ f'python export.py --weights ./weights/{weight_name} --include {params_include_list[i]} --device 0')
54
+ else:
55
+ os.system(f'python export.py --weights ./weights/{weight_name} --include {params_include_list[i]}')
56
+ e = time.time()
57
+ st.success(f"{params_include_list[i]}转换完成,用时{round((e-s), 2)}秒")
58
+
59
+ zipDir("./weights", "convert_weights.zip") # 打包weights目录,包括原始权重和转换后的权重
60
+ download_file("convert_weights.zip") # 下载打包文件
61
+
62
+
63
+ def main():
64
+ with st.container():
65
+ st.title("Streamlit YOLOv5 Model2X")
66
+ st.subheader('创建人:曾逸夫(Zeng Yifu)')
67
+ st.text("基于Streamlit的YOLOv5模型转换工具")
68
+
69
+ st.write("-------------------------------------------------------------")
70
+
71
+ dir_opt("./weights")
72
+
73
+ uploaded_file = st.file_uploader("选择YOLOv5模型文件(.pt)")
74
+ if uploaded_file is not None:
75
+
76
+ # 读取上传的模型文件(.pt)
77
+ weight_name = uploaded_file.name
78
+
79
+ st.info(f"正在写入{weight_name}......")
80
+
81
+ bytes_data = uploaded_file.getvalue()
82
+ with open(f"./weights/{weight_name}", 'wb') as fb:
83
+ fb.write(bytes_data)
84
+ fb.close()
85
+ st.success(f"{weight_name}写入成功!")
86
+
87
+ st.text("请选择转换的类型:")
88
+ cb_torchscript = st.checkbox('TorchScript')
89
+ cb_onnx = st.checkbox('ONNX')
90
+ cb_openvino = st.checkbox('OpenVINO')
91
+ cb_engine = st.checkbox('TensorRT')
92
+ cb_coreml = st.checkbox('CoreML')
93
+ cb_saved_model = st.checkbox('TensorFlow SavedModel')
94
+ cb_pb = st.checkbox('TensorFlow GraphDef')
95
+ cb_tflite = st.checkbox('TensorFlow Lite')
96
+ # cb_edgetpu = st.checkbox('TensorFlow Edge TPU')
97
+ cb_tfjs = st.checkbox('TensorFlow.js')
98
+
99
+ btn_convert = st.button('转换')
100
+
101
+ btn_model_list = [
102
+ cb_torchscript, cb_onnx, cb_openvino, cb_engine, cb_coreml, cb_saved_model, cb_pb, cb_tflite, cb_tfjs]
103
+
104
+ params_include_list = [
105
+ "torchscript", "onnx", "openvino", "engine", "coreml", "saved_model", "pb", "tflite", "tfjs"]
106
+
107
+ if btn_convert:
108
+ cb_opt(weight_name, btn_model_list, params_include_list)
109
+
110
+ st.write("-------------------------------------------------------------")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
export.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+
23
+ Usage:
24
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
25
+
26
+ Inference:
27
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
28
+ yolov5s.torchscript # TorchScript
29
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
30
+ yolov5s.xml # OpenVINO
31
+ yolov5s.engine # TensorRT
32
+ yolov5s.mlmodel # CoreML (macOS-only)
33
+ yolov5s_saved_model # TensorFlow SavedModel
34
+ yolov5s.pb # TensorFlow GraphDef
35
+ yolov5s.tflite # TensorFlow Lite
36
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
37
+
38
+ TensorFlow.js:
39
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
40
+ $ npm install
41
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
42
+ $ npm start
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import platform
49
+ import subprocess
50
+ import sys
51
+ import time
52
+ import warnings
53
+ from pathlib import Path
54
+
55
+ import pandas as pd
56
+ import torch
57
+ import yaml
58
+ from torch.utils.mobile_optimizer import optimize_for_mobile
59
+
60
+ FILE = Path(__file__).resolve()
61
+ ROOT = FILE.parents[0] # YOLOv5 root directory
62
+ if str(ROOT) not in sys.path:
63
+ sys.path.append(str(ROOT)) # add ROOT to PATH
64
+ if platform.system() != 'Windows':
65
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
66
+
67
+ from models.experimental import attempt_load
68
+ from models.yolo import Detect
69
+ from utils.dataloaders import LoadImages
70
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
71
+ file_size, print_args, url2file)
72
+ from utils.torch_utils import select_device
73
+
74
+
75
+ def export_formats():
76
+ # YOLOv5 export formats
77
+ x = [
78
+ ['PyTorch', '-', '.pt', True, True],
79
+ ['TorchScript', 'torchscript', '.torchscript', True, True],
80
+ ['ONNX', 'onnx', '.onnx', True, True],
81
+ ['OpenVINO', 'openvino', '_openvino_model', True, False],
82
+ ['TensorRT', 'engine', '.engine', False, True],
83
+ ['CoreML', 'coreml', '.mlmodel', True, False],
84
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
85
+ ['TensorFlow GraphDef', 'pb', '.pb', True, True],
86
+ ['TensorFlow Lite', 'tflite', '.tflite', True, False],
87
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
88
+ ['TensorFlow.js', 'tfjs', '_web_model', False, False],]
89
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
90
+
91
+
92
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
93
+ # YOLOv5 TorchScript model export
94
+ try:
95
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
96
+ f = file.with_suffix('.torchscript')
97
+
98
+ ts = torch.jit.trace(model, im, strict=False)
99
+ d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
100
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
101
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
102
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
103
+ else:
104
+ ts.save(str(f), _extra_files=extra_files)
105
+
106
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
107
+ return f
108
+ except Exception as e:
109
+ LOGGER.info(f'{prefix} export failure: {e}')
110
+
111
+
112
+ def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
113
+ # YOLOv5 ONNX export
114
+ try:
115
+ check_requirements(('onnx',))
116
+ import onnx
117
+
118
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
119
+ f = file.with_suffix('.onnx')
120
+
121
+ torch.onnx.export(
122
+ model.cpu() if dynamic else model, # --dynamic only compatible with cpu
123
+ im.cpu() if dynamic else im,
124
+ f,
125
+ verbose=False,
126
+ opset_version=opset,
127
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
128
+ do_constant_folding=not train,
129
+ input_names=['images'],
130
+ output_names=['output'],
131
+ dynamic_axes={
132
+ 'images': {
133
+ 0: 'batch',
134
+ 2: 'height',
135
+ 3: 'width'}, # shape(1,3,640,640)
136
+ 'output': {
137
+ 0: 'batch',
138
+ 1: 'anchors'} # shape(1,25200,85)
139
+ } if dynamic else None)
140
+
141
+ # Checks
142
+ model_onnx = onnx.load(f) # load onnx model
143
+ onnx.checker.check_model(model_onnx) # check onnx model
144
+
145
+ # Metadata
146
+ d = {'stride': int(max(model.stride)), 'names': model.names}
147
+ for k, v in d.items():
148
+ meta = model_onnx.metadata_props.add()
149
+ meta.key, meta.value = k, str(v)
150
+ onnx.save(model_onnx, f)
151
+
152
+ # Simplify
153
+ if simplify:
154
+ try:
155
+ check_requirements(('onnx-simplifier',))
156
+ import onnxsim
157
+
158
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
159
+ model_onnx, check = onnxsim.simplify(model_onnx,
160
+ dynamic_input_shape=dynamic,
161
+ input_shapes={'images': list(im.shape)} if dynamic else None)
162
+ assert check, 'assert check failed'
163
+ onnx.save(model_onnx, f)
164
+ except Exception as e:
165
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
166
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
167
+ return f
168
+ except Exception as e:
169
+ LOGGER.info(f'{prefix} export failure: {e}')
170
+
171
+
172
+ def export_openvino(model, file, half, prefix=colorstr('OpenVINO:')):
173
+ # YOLOv5 OpenVINO export
174
+ try:
175
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
176
+ import openvino.inference_engine as ie
177
+
178
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
179
+ f = str(file).replace('.pt', f'_openvino_model{os.sep}')
180
+
181
+ cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
182
+ subprocess.check_output(cmd.split()) # export
183
+ with open(Path(f) / file.with_suffix('.yaml').name, 'w') as g:
184
+ yaml.dump({'stride': int(max(model.stride)), 'names': model.names}, g) # add metadata.yaml
185
+
186
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
187
+ return f
188
+ except Exception as e:
189
+ LOGGER.info(f'\n{prefix} export failure: {e}')
190
+
191
+
192
+ def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
193
+ # YOLOv5 CoreML export
194
+ try:
195
+ check_requirements(('coremltools',))
196
+ import coremltools as ct
197
+
198
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
199
+ f = file.with_suffix('.mlmodel')
200
+
201
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
202
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
203
+ bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
204
+ if bits < 32:
205
+ if platform.system() == 'Darwin': # quantization only supported on macOS
206
+ with warnings.catch_warnings():
207
+ warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
208
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
209
+ else:
210
+ print(f'{prefix} quantization only supported on macOS, skipping...')
211
+ ct_model.save(f)
212
+
213
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
214
+ return ct_model, f
215
+ except Exception as e:
216
+ LOGGER.info(f'\n{prefix} export failure: {e}')
217
+ return None, None
218
+
219
+
220
+ def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
221
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
222
+ try:
223
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
224
+ try:
225
+ import tensorrt as trt
226
+ except Exception:
227
+ if platform.system() == 'Linux':
228
+ check_requirements(('nvidia-tensorrt',), cmds=('-U --index-url https://pypi.ngc.nvidia.com',))
229
+ import tensorrt as trt
230
+
231
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
232
+ grid = model.model[-1].anchor_grid
233
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
234
+ export_onnx(model, im, file, 12, train, False, simplify) # opset 12
235
+ model.model[-1].anchor_grid = grid
236
+ else: # TensorRT >= 8
237
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
238
+ export_onnx(model, im, file, 13, train, False, simplify) # opset 13
239
+ onnx = file.with_suffix('.onnx')
240
+
241
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
242
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
243
+ f = file.with_suffix('.engine') # TensorRT engine file
244
+ logger = trt.Logger(trt.Logger.INFO)
245
+ if verbose:
246
+ logger.min_severity = trt.Logger.Severity.VERBOSE
247
+
248
+ builder = trt.Builder(logger)
249
+ config = builder.create_builder_config()
250
+ config.max_workspace_size = workspace * 1 << 30
251
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
252
+
253
+ flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
254
+ network = builder.create_network(flag)
255
+ parser = trt.OnnxParser(network, logger)
256
+ if not parser.parse_from_file(str(onnx)):
257
+ raise RuntimeError(f'failed to load ONNX file: {onnx}')
258
+
259
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
260
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
261
+ LOGGER.info(f'{prefix} Network Description:')
262
+ for inp in inputs:
263
+ LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
264
+ for out in outputs:
265
+ LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
266
+
267
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}')
268
+ if builder.platform_has_fast_fp16 and half:
269
+ config.set_flag(trt.BuilderFlag.FP16)
270
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
271
+ t.write(engine.serialize())
272
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
273
+ return f
274
+ except Exception as e:
275
+ LOGGER.info(f'\n{prefix} export failure: {e}')
276
+
277
+
278
+ def export_saved_model(model,
279
+ im,
280
+ file,
281
+ dynamic,
282
+ tf_nms=False,
283
+ agnostic_nms=False,
284
+ topk_per_class=100,
285
+ topk_all=100,
286
+ iou_thres=0.45,
287
+ conf_thres=0.25,
288
+ keras=False,
289
+ prefix=colorstr('TensorFlow SavedModel:')):
290
+ # YOLOv5 TensorFlow SavedModel export
291
+ try:
292
+ import tensorflow as tf
293
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
294
+
295
+ from models.tf import TFDetect, TFModel
296
+
297
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
298
+ f = str(file).replace('.pt', '_saved_model')
299
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
300
+
301
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
302
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
303
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
304
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
305
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
306
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
307
+ keras_model.trainable = False
308
+ keras_model.summary()
309
+ if keras:
310
+ keras_model.save(f, save_format='tf')
311
+ else:
312
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
313
+ m = tf.function(lambda x: keras_model(x)) # full model
314
+ m = m.get_concrete_function(spec)
315
+ frozen_func = convert_variables_to_constants_v2(m)
316
+ tfm = tf.Module()
317
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
318
+ tfm.__call__(im)
319
+ tf.saved_model.save(tfm,
320
+ f,
321
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
322
+ if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
323
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
324
+ return keras_model, f
325
+ except Exception as e:
326
+ LOGGER.info(f'\n{prefix} export failure: {e}')
327
+ return None, None
328
+
329
+
330
+ def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
331
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
332
+ try:
333
+ import tensorflow as tf
334
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
335
+
336
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
337
+ f = file.with_suffix('.pb')
338
+
339
+ m = tf.function(lambda x: keras_model(x)) # full model
340
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
341
+ frozen_func = convert_variables_to_constants_v2(m)
342
+ frozen_func.graph.as_graph_def()
343
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
344
+
345
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
346
+ return f
347
+ except Exception as e:
348
+ LOGGER.info(f'\n{prefix} export failure: {e}')
349
+
350
+
351
+ def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
352
+ # YOLOv5 TensorFlow Lite export
353
+ try:
354
+ import tensorflow as tf
355
+
356
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
357
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
358
+ f = str(file).replace('.pt', '-fp16.tflite')
359
+
360
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
361
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
362
+ converter.target_spec.supported_types = [tf.float16]
363
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
364
+ if int8:
365
+ from models.tf import representative_dataset_gen
366
+ dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
367
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
368
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
369
+ converter.target_spec.supported_types = []
370
+ converter.inference_input_type = tf.uint8 # or tf.int8
371
+ converter.inference_output_type = tf.uint8 # or tf.int8
372
+ converter.experimental_new_quantizer = True
373
+ f = str(file).replace('.pt', '-int8.tflite')
374
+ if nms or agnostic_nms:
375
+ converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
376
+
377
+ tflite_model = converter.convert()
378
+ open(f, "wb").write(tflite_model)
379
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
380
+ return f
381
+ except Exception as e:
382
+ LOGGER.info(f'\n{prefix} export failure: {e}')
383
+
384
+
385
+ def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
386
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
387
+ try:
388
+ cmd = 'edgetpu_compiler --version'
389
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
390
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
391
+ if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
392
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
393
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
394
+ for c in (
395
+ 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
396
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
397
+ 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
398
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
399
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
400
+
401
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
402
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
403
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
404
+
405
+ cmd = f"edgetpu_compiler -s -o {file.parent} {f_tfl}"
406
+ subprocess.run(cmd.split(), check=True)
407
+
408
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
409
+ return f
410
+ except Exception as e:
411
+ LOGGER.info(f'\n{prefix} export failure: {e}')
412
+
413
+
414
+ def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
415
+ # YOLOv5 TensorFlow.js export
416
+ try:
417
+ check_requirements(('tensorflowjs',))
418
+ import re
419
+
420
+ import tensorflowjs as tfjs
421
+
422
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
423
+ f = str(file).replace('.pt', '_web_model') # js dir
424
+ f_pb = file.with_suffix('.pb') # *.pb path
425
+ f_json = f'{f}/model.json' # *.json path
426
+
427
+ cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
428
+ f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
429
+ subprocess.run(cmd.split())
430
+
431
+ with open(f_json) as j:
432
+ json = j.read()
433
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
434
+ subst = re.sub(
435
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
436
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
437
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
438
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
439
+ r'"Identity_1": {"name": "Identity_1"}, '
440
+ r'"Identity_2": {"name": "Identity_2"}, '
441
+ r'"Identity_3": {"name": "Identity_3"}}}', json)
442
+ j.write(subst)
443
+
444
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
445
+ return f
446
+ except Exception as e:
447
+ LOGGER.info(f'\n{prefix} export failure: {e}')
448
+
449
+
450
+ @torch.no_grad()
451
+ def run(
452
+ data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
453
+ weights=ROOT / 'yolov5s.pt', # weights path
454
+ imgsz=(640, 640), # image (height, width)
455
+ batch_size=1, # batch size
456
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
457
+ include=('torchscript', 'onnx'), # include formats
458
+ half=False, # FP16 half-precision export
459
+ inplace=False, # set YOLOv5 Detect() inplace=True
460
+ train=False, # model.train() mode
461
+ keras=False, # use Keras
462
+ optimize=False, # TorchScript: optimize for mobile
463
+ int8=False, # CoreML/TF INT8 quantization
464
+ dynamic=False, # ONNX/TF: dynamic axes
465
+ simplify=False, # ONNX: simplify model
466
+ opset=12, # ONNX: opset version
467
+ verbose=False, # TensorRT: verbose log
468
+ workspace=4, # TensorRT: workspace size (GB)
469
+ nms=False, # TF: add NMS to model
470
+ agnostic_nms=False, # TF: add agnostic NMS to model
471
+ topk_per_class=100, # TF.js NMS: topk per class to keep
472
+ topk_all=100, # TF.js NMS: topk for all classes to keep
473
+ iou_thres=0.45, # TF.js NMS: IoU threshold
474
+ conf_thres=0.25, # TF.js NMS: confidence threshold
475
+ ):
476
+ t = time.time()
477
+ include = [x.lower() for x in include] # to lowercase
478
+ fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
479
+ flags = [x in include for x in fmts]
480
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
481
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
482
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
483
+
484
+ # Load PyTorch model
485
+ device = select_device(device)
486
+ if half:
487
+ assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
488
+ assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
489
+ model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
490
+ nc, names = model.nc, model.names # number of classes, class names
491
+
492
+ # Checks
493
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
494
+ assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
495
+
496
+ # Input
497
+ gs = int(max(model.stride)) # grid size (max stride)
498
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
499
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
500
+
501
+ # Update model
502
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
503
+ for k, m in model.named_modules():
504
+ if isinstance(m, Detect):
505
+ m.inplace = inplace
506
+ m.onnx_dynamic = dynamic
507
+ m.export = True
508
+
509
+ for _ in range(2):
510
+ y = model(im) # dry runs
511
+ if half and not coreml:
512
+ im, model = im.half(), model.half() # to FP16
513
+ shape = tuple(y[0].shape) # model output shape
514
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
515
+
516
+ # Exports
517
+ f = [''] * 10 # exported filenames
518
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
519
+ if jit:
520
+ f[0] = export_torchscript(model, im, file, optimize)
521
+ if engine: # TensorRT required before ONNX
522
+ f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
523
+ if onnx or xml: # OpenVINO requires ONNX
524
+ f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
525
+ if xml: # OpenVINO
526
+ f[3] = export_openvino(model, file, half)
527
+ if coreml:
528
+ _, f[4] = export_coreml(model, im, file, int8, half)
529
+
530
+ # TensorFlow Exports
531
+ if any((saved_model, pb, tflite, edgetpu, tfjs)):
532
+ if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
533
+ check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
534
+ assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
535
+ model, f[5] = export_saved_model(model.cpu(),
536
+ im,
537
+ file,
538
+ dynamic,
539
+ tf_nms=nms or agnostic_nms or tfjs,
540
+ agnostic_nms=agnostic_nms or tfjs,
541
+ topk_per_class=topk_per_class,
542
+ topk_all=topk_all,
543
+ iou_thres=iou_thres,
544
+ conf_thres=conf_thres,
545
+ keras=keras)
546
+ if pb or tfjs: # pb prerequisite to tfjs
547
+ f[6] = export_pb(model, file)
548
+ if tflite or edgetpu:
549
+ f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
550
+ if edgetpu:
551
+ f[8] = export_edgetpu(file)
552
+ if tfjs:
553
+ f[9] = export_tfjs(file)
554
+
555
+ # Finish
556
+ f = [str(x) for x in f if x] # filter out '' and None
557
+ if any(f):
558
+ h = '--half' if half else '' # --half FP16 inference arg
559
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
560
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
561
+ f"\nDetect: python detect.py --weights {f[-1]} {h}"
562
+ f"\nValidate: python val.py --weights {f[-1]} {h}"
563
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
564
+ f"\nVisualize: https://netron.app")
565
+ return f # return list of exported files/dirs
566
+
567
+
568
+ def parse_opt():
569
+ parser = argparse.ArgumentParser()
570
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
571
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
572
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
573
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
574
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
575
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
576
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
577
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
578
+ parser.add_argument('--keras', action='store_true', help='TF: use Keras')
579
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
580
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
581
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
582
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
583
+ parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
584
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
585
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
586
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
587
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
588
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
589
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
590
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
591
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
592
+ parser.add_argument('--include',
593
+ nargs='+',
594
+ default=['torchscript', 'onnx'],
595
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
596
+ opt = parser.parse_args()
597
+ print_args(vars(opt))
598
+ return opt
599
+
600
+
601
+ def main(opt):
602
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
603
+ run(**vars(opt))
604
+
605
+
606
+ if __name__ == "__main__":
607
+ opt = parse_opt()
608
+ main(opt)
models/__init__.py ADDED
File without changes
models/common.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.dataloaders 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 DWConvTranspose2d(nn.ConvTranspose2d):
60
+ # Depth-wise transpose convolution class
61
+ def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
62
+ super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
63
+
64
+
65
+ class TransformerLayer(nn.Module):
66
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
67
+ def __init__(self, c, num_heads):
68
+ super().__init__()
69
+ self.q = nn.Linear(c, c, bias=False)
70
+ self.k = nn.Linear(c, c, bias=False)
71
+ self.v = nn.Linear(c, c, bias=False)
72
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
73
+ self.fc1 = nn.Linear(c, c, bias=False)
74
+ self.fc2 = nn.Linear(c, c, bias=False)
75
+
76
+ def forward(self, x):
77
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
78
+ x = self.fc2(self.fc1(x)) + x
79
+ return x
80
+
81
+
82
+ class TransformerBlock(nn.Module):
83
+ # Vision Transformer https://arxiv.org/abs/2010.11929
84
+ def __init__(self, c1, c2, num_heads, num_layers):
85
+ super().__init__()
86
+ self.conv = None
87
+ if c1 != c2:
88
+ self.conv = Conv(c1, c2)
89
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
90
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
91
+ self.c2 = c2
92
+
93
+ def forward(self, x):
94
+ if self.conv is not None:
95
+ x = self.conv(x)
96
+ b, _, w, h = x.shape
97
+ p = x.flatten(2).permute(2, 0, 1)
98
+ return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
99
+
100
+
101
+ class Bottleneck(nn.Module):
102
+ # Standard bottleneck
103
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
104
+ super().__init__()
105
+ c_ = int(c2 * e) # hidden channels
106
+ self.cv1 = Conv(c1, c_, 1, 1)
107
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
108
+ self.add = shortcut and c1 == c2
109
+
110
+ def forward(self, x):
111
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
112
+
113
+
114
+ class BottleneckCSP(nn.Module):
115
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
116
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
117
+ super().__init__()
118
+ c_ = int(c2 * e) # hidden channels
119
+ self.cv1 = Conv(c1, c_, 1, 1)
120
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
121
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
122
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
123
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
124
+ self.act = nn.SiLU()
125
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
126
+
127
+ def forward(self, x):
128
+ y1 = self.cv3(self.m(self.cv1(x)))
129
+ y2 = self.cv2(x)
130
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
131
+
132
+
133
+ class CrossConv(nn.Module):
134
+ # Cross Convolution Downsample
135
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
136
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
137
+ super().__init__()
138
+ c_ = int(c2 * e) # hidden channels
139
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
140
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
141
+ self.add = shortcut and c1 == c2
142
+
143
+ def forward(self, x):
144
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
145
+
146
+
147
+ class C3(nn.Module):
148
+ # CSP Bottleneck with 3 convolutions
149
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
150
+ super().__init__()
151
+ c_ = int(c2 * e) # hidden channels
152
+ self.cv1 = Conv(c1, c_, 1, 1)
153
+ self.cv2 = Conv(c1, c_, 1, 1)
154
+ self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
155
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
156
+
157
+ def forward(self, x):
158
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
159
+
160
+
161
+ class C3x(C3):
162
+ # C3 module with cross-convolutions
163
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
164
+ super().__init__(c1, c2, n, shortcut, g, e)
165
+ c_ = int(c2 * e)
166
+ self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
167
+
168
+
169
+ class C3TR(C3):
170
+ # C3 module with TransformerBlock()
171
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
172
+ super().__init__(c1, c2, n, shortcut, g, e)
173
+ c_ = int(c2 * e)
174
+ self.m = TransformerBlock(c_, c_, 4, n)
175
+
176
+
177
+ class C3SPP(C3):
178
+ # C3 module with SPP()
179
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
180
+ super().__init__(c1, c2, n, shortcut, g, e)
181
+ c_ = int(c2 * e)
182
+ self.m = SPP(c_, c_, k)
183
+
184
+
185
+ class C3Ghost(C3):
186
+ # C3 module with GhostBottleneck()
187
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
188
+ super().__init__(c1, c2, n, shortcut, g, e)
189
+ c_ = int(c2 * e) # hidden channels
190
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
191
+
192
+
193
+ class SPP(nn.Module):
194
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
195
+ def __init__(self, c1, c2, k=(5, 9, 13)):
196
+ super().__init__()
197
+ c_ = c1 // 2 # hidden channels
198
+ self.cv1 = Conv(c1, c_, 1, 1)
199
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
200
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
201
+
202
+ def forward(self, x):
203
+ x = self.cv1(x)
204
+ with warnings.catch_warnings():
205
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
206
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
207
+
208
+
209
+ class SPPF(nn.Module):
210
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
211
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
212
+ super().__init__()
213
+ c_ = c1 // 2 # hidden channels
214
+ self.cv1 = Conv(c1, c_, 1, 1)
215
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
216
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
217
+
218
+ def forward(self, x):
219
+ x = self.cv1(x)
220
+ with warnings.catch_warnings():
221
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
222
+ y1 = self.m(x)
223
+ y2 = self.m(y1)
224
+ return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
225
+
226
+
227
+ class Focus(nn.Module):
228
+ # Focus wh information into c-space
229
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
230
+ super().__init__()
231
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
232
+ # self.contract = Contract(gain=2)
233
+
234
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
235
+ return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
236
+ # return self.conv(self.contract(x))
237
+
238
+
239
+ class GhostConv(nn.Module):
240
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
241
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
242
+ super().__init__()
243
+ c_ = c2 // 2 # hidden channels
244
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
245
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
246
+
247
+ def forward(self, x):
248
+ y = self.cv1(x)
249
+ return torch.cat((y, self.cv2(y)), 1)
250
+
251
+
252
+ class GhostBottleneck(nn.Module):
253
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
254
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
255
+ super().__init__()
256
+ c_ = c2 // 2
257
+ self.conv = nn.Sequential(
258
+ GhostConv(c1, c_, 1, 1), # pw
259
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
260
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
261
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,
262
+ act=False)) if s == 2 else nn.Identity()
263
+
264
+ def forward(self, x):
265
+ return self.conv(x) + self.shortcut(x)
266
+
267
+
268
+ class Contract(nn.Module):
269
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
270
+ def __init__(self, gain=2):
271
+ super().__init__()
272
+ self.gain = gain
273
+
274
+ def forward(self, x):
275
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
276
+ s = self.gain
277
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
278
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
279
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
280
+
281
+
282
+ class Expand(nn.Module):
283
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
284
+ def __init__(self, gain=2):
285
+ super().__init__()
286
+ self.gain = gain
287
+
288
+ def forward(self, x):
289
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
290
+ s = self.gain
291
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
292
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
293
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
294
+
295
+
296
+ class Concat(nn.Module):
297
+ # Concatenate a list of tensors along dimension
298
+ def __init__(self, dimension=1):
299
+ super().__init__()
300
+ self.d = dimension
301
+
302
+ def forward(self, x):
303
+ return torch.cat(x, self.d)
304
+
305
+
306
+ class DetectMultiBackend(nn.Module):
307
+ # YOLOv5 MultiBackend class for python inference on various backends
308
+ def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False):
309
+ # Usage:
310
+ # PyTorch: weights = *.pt
311
+ # TorchScript: *.torchscript
312
+ # ONNX Runtime: *.onnx
313
+ # ONNX OpenCV DNN: *.onnx with --dnn
314
+ # OpenVINO: *.xml
315
+ # CoreML: *.mlmodel
316
+ # TensorRT: *.engine
317
+ # TensorFlow SavedModel: *_saved_model
318
+ # TensorFlow GraphDef: *.pb
319
+ # TensorFlow Lite: *.tflite
320
+ # TensorFlow Edge TPU: *_edgetpu.tflite
321
+ from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
322
+
323
+ super().__init__()
324
+ w = str(weights[0] if isinstance(weights, list) else weights)
325
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = self.model_type(w) # get backend
326
+ w = attempt_download(w) # download if not local
327
+ fp16 &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16
328
+ stride, names = 32, [f'class{i}' for i in range(1000)] # assign defaults
329
+ if data: # assign class names (optional)
330
+ with open(data, errors='ignore') as f:
331
+ names = yaml.safe_load(f)['names']
332
+
333
+ if pt: # PyTorch
334
+ model = attempt_load(weights if isinstance(weights, list) else w, device=device)
335
+ stride = max(int(model.stride.max()), 32) # model stride
336
+ names = model.module.names if hasattr(model, 'module') else model.names # get class names
337
+ model.half() if fp16 else model.float()
338
+ self.model = model # explicitly assign for to(), cpu(), cuda(), half()
339
+ elif jit: # TorchScript
340
+ LOGGER.info(f'Loading {w} for TorchScript inference...')
341
+ extra_files = {'config.txt': ''} # model metadata
342
+ model = torch.jit.load(w, _extra_files=extra_files)
343
+ model.half() if fp16 else model.float()
344
+ if extra_files['config.txt']:
345
+ d = json.loads(extra_files['config.txt']) # extra_files dict
346
+ stride, names = int(d['stride']), d['names']
347
+ elif dnn: # ONNX OpenCV DNN
348
+ LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')
349
+ check_requirements(('opencv-python>=4.5.4',))
350
+ net = cv2.dnn.readNetFromONNX(w)
351
+ elif onnx: # ONNX Runtime
352
+ LOGGER.info(f'Loading {w} for ONNX Runtime inference...')
353
+ cuda = torch.cuda.is_available()
354
+ check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))
355
+ import onnxruntime
356
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
357
+ session = onnxruntime.InferenceSession(w, providers=providers)
358
+ meta = session.get_modelmeta().custom_metadata_map # metadata
359
+ if 'stride' in meta:
360
+ stride, names = int(meta['stride']), eval(meta['names'])
361
+ elif xml: # OpenVINO
362
+ LOGGER.info(f'Loading {w} for OpenVINO inference...')
363
+ check_requirements(('openvino',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
364
+ from openvino.runtime import Core, Layout, get_batch
365
+ ie = Core()
366
+ if not Path(w).is_file(): # if not *.xml
367
+ w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir
368
+ network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin'))
369
+ if network.get_parameters()[0].get_layout().empty:
370
+ network.get_parameters()[0].set_layout(Layout("NCHW"))
371
+ batch_dim = get_batch(network)
372
+ if batch_dim.is_static:
373
+ batch_size = batch_dim.get_length()
374
+ executable_network = ie.compile_model(network, device_name="CPU") # device_name="MYRIAD" for Intel NCS2
375
+ output_layer = next(iter(executable_network.outputs))
376
+ meta = Path(w).with_suffix('.yaml')
377
+ if meta.exists():
378
+ stride, names = self._load_metadata(meta) # load metadata
379
+ elif engine: # TensorRT
380
+ LOGGER.info(f'Loading {w} for TensorRT inference...')
381
+ import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
382
+ check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
383
+ Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))
384
+ logger = trt.Logger(trt.Logger.INFO)
385
+ with open(w, 'rb') as f, trt.Runtime(logger) as runtime:
386
+ model = runtime.deserialize_cuda_engine(f.read())
387
+ bindings = OrderedDict()
388
+ fp16 = False # default updated below
389
+ for index in range(model.num_bindings):
390
+ name = model.get_binding_name(index)
391
+ dtype = trt.nptype(model.get_binding_dtype(index))
392
+ shape = tuple(model.get_binding_shape(index))
393
+ data = torch.from_numpy(np.empty(shape, dtype=np.dtype(dtype))).to(device)
394
+ bindings[name] = Binding(name, dtype, shape, data, int(data.data_ptr()))
395
+ if model.binding_is_input(index) and dtype == np.float16:
396
+ fp16 = True
397
+ binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
398
+ context = model.create_execution_context()
399
+ batch_size = bindings['images'].shape[0]
400
+ elif coreml: # CoreML
401
+ LOGGER.info(f'Loading {w} for CoreML inference...')
402
+ import coremltools as ct
403
+ model = ct.models.MLModel(w)
404
+ else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
405
+ if saved_model: # SavedModel
406
+ LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')
407
+ import tensorflow as tf
408
+ keras = False # assume TF1 saved_model
409
+ model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
410
+ elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
411
+ LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')
412
+ import tensorflow as tf
413
+
414
+ def wrap_frozen_graph(gd, inputs, outputs):
415
+ x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
416
+ ge = x.graph.as_graph_element
417
+ return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
418
+
419
+ gd = tf.Graph().as_graph_def() # graph_def
420
+ with open(w, 'rb') as f:
421
+ gd.ParseFromString(f.read())
422
+ frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs="Identity:0")
423
+ elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
424
+ try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
425
+ from tflite_runtime.interpreter import Interpreter, load_delegate
426
+ except ImportError:
427
+ import tensorflow as tf
428
+ Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,
429
+ if edgetpu: # Edge TPU https://coral.ai/software/#edgetpu-runtime
430
+ LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')
431
+ delegate = {
432
+ 'Linux': 'libedgetpu.so.1',
433
+ 'Darwin': 'libedgetpu.1.dylib',
434
+ 'Windows': 'edgetpu.dll'}[platform.system()]
435
+ interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
436
+ else: # Lite
437
+ LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')
438
+ interpreter = Interpreter(model_path=w) # load TFLite model
439
+ interpreter.allocate_tensors() # allocate
440
+ input_details = interpreter.get_input_details() # inputs
441
+ output_details = interpreter.get_output_details() # outputs
442
+ elif tfjs:
443
+ raise Exception('ERROR: YOLOv5 TF.js inference is not supported')
444
+ self.__dict__.update(locals()) # assign all variables to self
445
+
446
+ def forward(self, im, augment=False, visualize=False, val=False):
447
+ # YOLOv5 MultiBackend inference
448
+ b, ch, h, w = im.shape # batch, channel, height, width
449
+ if self.fp16 and im.dtype != torch.float16:
450
+ im = im.half() # to FP16
451
+
452
+ if self.pt: # PyTorch
453
+ y = self.model(im, augment=augment, visualize=visualize)[0]
454
+ elif self.jit: # TorchScript
455
+ y = self.model(im)[0]
456
+ elif self.dnn: # ONNX OpenCV DNN
457
+ im = im.cpu().numpy() # torch to numpy
458
+ self.net.setInput(im)
459
+ y = self.net.forward()
460
+ elif self.onnx: # ONNX Runtime
461
+ im = im.cpu().numpy() # torch to numpy
462
+ y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0]
463
+ elif self.xml: # OpenVINO
464
+ im = im.cpu().numpy() # FP32
465
+ y = self.executable_network([im])[self.output_layer]
466
+ elif self.engine: # TensorRT
467
+ assert im.shape == self.bindings['images'].shape, (im.shape, self.bindings['images'].shape)
468
+ self.binding_addrs['images'] = int(im.data_ptr())
469
+ self.context.execute_v2(list(self.binding_addrs.values()))
470
+ y = self.bindings['output'].data
471
+ elif self.coreml: # CoreML
472
+ im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
473
+ im = Image.fromarray((im[0] * 255).astype('uint8'))
474
+ # im = im.resize((192, 320), Image.ANTIALIAS)
475
+ y = self.model.predict({'image': im}) # coordinates are xywh normalized
476
+ if 'confidence' in y:
477
+ box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
478
+ conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
479
+ y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
480
+ else:
481
+ k = 'var_' + str(sorted(int(k.replace('var_', '')) for k in y)[-1]) # output key
482
+ y = y[k] # output
483
+ else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
484
+ im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
485
+ if self.saved_model: # SavedModel
486
+ y = (self.model(im, training=False) if self.keras else self.model(im)).numpy()
487
+ elif self.pb: # GraphDef
488
+ y = self.frozen_func(x=self.tf.constant(im)).numpy()
489
+ else: # Lite or Edge TPU
490
+ input, output = self.input_details[0], self.output_details[0]
491
+ int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
492
+ if int8:
493
+ scale, zero_point = input['quantization']
494
+ im = (im / scale + zero_point).astype(np.uint8) # de-scale
495
+ self.interpreter.set_tensor(input['index'], im)
496
+ self.interpreter.invoke()
497
+ y = self.interpreter.get_tensor(output['index'])
498
+ if int8:
499
+ scale, zero_point = output['quantization']
500
+ y = (y.astype(np.float32) - zero_point) * scale # re-scale
501
+ y[..., :4] *= [w, h, w, h] # xywh normalized to pixels
502
+
503
+ if isinstance(y, np.ndarray):
504
+ y = torch.tensor(y, device=self.device)
505
+ return (y, []) if val else y
506
+
507
+ def warmup(self, imgsz=(1, 3, 640, 640)):
508
+ # Warmup model by running inference once
509
+ warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb
510
+ if any(warmup_types) and self.device.type != 'cpu':
511
+ im = torch.zeros(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
512
+ for _ in range(2 if self.jit else 1): #
513
+ self.forward(im) # warmup
514
+
515
+ @staticmethod
516
+ def model_type(p='path/to/model.pt'):
517
+ # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx
518
+ from export import export_formats
519
+ suffixes = list(export_formats().Suffix) + ['.xml'] # export suffixes
520
+ check_suffix(p, suffixes) # checks
521
+ p = Path(p).name # eliminate trailing separators
522
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes)
523
+ xml |= xml2 # *_openvino_model or *.xml
524
+ tflite &= not edgetpu # *.tflite
525
+ return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs
526
+
527
+ @staticmethod
528
+ def _load_metadata(f='path/to/meta.yaml'):
529
+ # Load metadata from meta.yaml if it exists
530
+ with open(f, errors='ignore') as f:
531
+ d = yaml.safe_load(f)
532
+ return d['stride'], d['names'] # assign stride, names
533
+
534
+
535
+ class AutoShape(nn.Module):
536
+ # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
537
+ conf = 0.25 # NMS confidence threshold
538
+ iou = 0.45 # NMS IoU threshold
539
+ agnostic = False # NMS class-agnostic
540
+ multi_label = False # NMS multiple labels per box
541
+ classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
542
+ max_det = 1000 # maximum number of detections per image
543
+ amp = False # Automatic Mixed Precision (AMP) inference
544
+
545
+ def __init__(self, model, verbose=True):
546
+ super().__init__()
547
+ if verbose:
548
+ LOGGER.info('Adding AutoShape... ')
549
+ copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
550
+ self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
551
+ self.pt = not self.dmb or model.pt # PyTorch model
552
+ self.model = model.eval()
553
+
554
+ def _apply(self, fn):
555
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
556
+ self = super()._apply(fn)
557
+ if self.pt:
558
+ m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
559
+ m.stride = fn(m.stride)
560
+ m.grid = list(map(fn, m.grid))
561
+ if isinstance(m.anchor_grid, list):
562
+ m.anchor_grid = list(map(fn, m.anchor_grid))
563
+ return self
564
+
565
+ @torch.no_grad()
566
+ def forward(self, imgs, size=640, augment=False, profile=False):
567
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
568
+ # file: imgs = 'data/images/zidane.jpg' # str or PosixPath
569
+ # URI: = 'https://ultralytics.com/images/zidane.jpg'
570
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
571
+ # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
572
+ # numpy: = np.zeros((640,1280,3)) # HWC
573
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
574
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
575
+
576
+ t = [time_sync()]
577
+ p = next(self.model.parameters()) if self.pt else torch.zeros(1, device=self.model.device) # for device, type
578
+ autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
579
+ if isinstance(imgs, torch.Tensor): # torch
580
+ with amp.autocast(autocast):
581
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
582
+
583
+ # Pre-process
584
+ n, imgs = (len(imgs), list(imgs)) if isinstance(imgs, (list, tuple)) else (1, [imgs]) # number, list of images
585
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
586
+ for i, im in enumerate(imgs):
587
+ f = f'image{i}' # filename
588
+ if isinstance(im, (str, Path)): # filename or uri
589
+ im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
590
+ im = np.asarray(exif_transpose(im))
591
+ elif isinstance(im, Image.Image): # PIL Image
592
+ im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
593
+ files.append(Path(f).with_suffix('.jpg').name)
594
+ if im.shape[0] < 5: # image in CHW
595
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
596
+ im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
597
+ s = im.shape[:2] # HWC
598
+ shape0.append(s) # image shape
599
+ g = (size / max(s)) # gain
600
+ shape1.append([y * g for y in s])
601
+ imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
602
+ shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)] # inf shape
603
+ x = [letterbox(im, shape1, auto=False)[0] for im in imgs] # pad
604
+ x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
605
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
606
+ t.append(time_sync())
607
+
608
+ with amp.autocast(autocast):
609
+ # Inference
610
+ y = self.model(x, augment, profile) # forward
611
+ t.append(time_sync())
612
+
613
+ # Post-process
614
+ y = non_max_suppression(y if self.dmb else y[0],
615
+ self.conf,
616
+ self.iou,
617
+ self.classes,
618
+ self.agnostic,
619
+ self.multi_label,
620
+ max_det=self.max_det) # NMS
621
+ for i in range(n):
622
+ scale_coords(shape1, y[i][:, :4], shape0[i])
623
+
624
+ t.append(time_sync())
625
+ return Detections(imgs, y, files, t, self.names, x.shape)
626
+
627
+
628
+ class Detections:
629
+ # YOLOv5 detections class for inference results
630
+ def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None):
631
+ super().__init__()
632
+ d = pred[0].device # device
633
+ gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations
634
+ self.imgs = imgs # list of images as numpy arrays
635
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
636
+ self.names = names # class names
637
+ self.files = files # image filenames
638
+ self.times = times # profiling times
639
+ self.xyxy = pred # xyxy pixels
640
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
641
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
642
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
643
+ self.n = len(self.pred) # number of images (batch size)
644
+ self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
645
+ self.s = shape # inference BCHW shape
646
+
647
+ def display(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
648
+ crops = []
649
+ for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
650
+ s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
651
+ if pred.shape[0]:
652
+ for c in pred[:, -1].unique():
653
+ n = (pred[:, -1] == c).sum() # detections per class
654
+ s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
655
+ if show or save or render or crop:
656
+ annotator = Annotator(im, example=str(self.names))
657
+ for *box, conf, cls in reversed(pred): # xyxy, confidence, class
658
+ label = f'{self.names[int(cls)]} {conf:.2f}'
659
+ if crop:
660
+ file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
661
+ crops.append({
662
+ 'box': box,
663
+ 'conf': conf,
664
+ 'cls': cls,
665
+ 'label': label,
666
+ 'im': save_one_box(box, im, file=file, save=save)})
667
+ else: # all others
668
+ annotator.box_label(box, label if labels else '', color=colors(cls))
669
+ im = annotator.im
670
+ else:
671
+ s += '(no detections)'
672
+
673
+ im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
674
+ if pprint:
675
+ print(s.rstrip(', '))
676
+ if show:
677
+ im.show(self.files[i]) # show
678
+ if save:
679
+ f = self.files[i]
680
+ im.save(save_dir / f) # save
681
+ if i == self.n - 1:
682
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
683
+ if render:
684
+ self.imgs[i] = np.asarray(im)
685
+ if crop:
686
+ if save:
687
+ LOGGER.info(f'Saved results to {save_dir}\n')
688
+ return crops
689
+
690
+ def print(self):
691
+ self.display(pprint=True) # print results
692
+ print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)
693
+
694
+ def show(self, labels=True):
695
+ self.display(show=True, labels=labels) # show results
696
+
697
+ def save(self, labels=True, save_dir='runs/detect/exp'):
698
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
699
+ self.display(save=True, labels=labels, save_dir=save_dir) # save results
700
+
701
+ def crop(self, save=True, save_dir='runs/detect/exp'):
702
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
703
+ return self.display(crop=True, save=save, save_dir=save_dir) # crop results
704
+
705
+ def render(self, labels=True):
706
+ self.display(render=True, labels=labels) # render results
707
+ return self.imgs
708
+
709
+ def pandas(self):
710
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
711
+ new = copy(self) # return copy
712
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
713
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
714
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
715
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
716
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
717
+ return new
718
+
719
+ def tolist(self):
720
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
721
+ r = range(self.n) # iterable
722
+ x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
723
+ # for d in x:
724
+ # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
725
+ # setattr(d, k, getattr(d, k)[0]) # pop out of list
726
+ return x
727
+
728
+ def __len__(self):
729
+ return self.n # override len(results)
730
+
731
+ def __str__(self):
732
+ self.print() # override print(results)
733
+ return ''
734
+
735
+
736
+ class Classify(nn.Module):
737
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
738
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
739
+ super().__init__()
740
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
741
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
742
+ self.flat = nn.Flatten()
743
+
744
+ def forward(self, x):
745
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
746
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
models/experimental.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Sum(nn.Module):
16
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
17
+ def __init__(self, n, weight=False): # n: number of inputs
18
+ super().__init__()
19
+ self.weight = weight # apply weights boolean
20
+ self.iter = range(n - 1) # iter object
21
+ if weight:
22
+ self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
23
+
24
+ def forward(self, x):
25
+ y = x[0] # no weight
26
+ if self.weight:
27
+ w = torch.sigmoid(self.w) * 2
28
+ for i in self.iter:
29
+ y = y + x[i + 1] * w[i]
30
+ else:
31
+ for i in self.iter:
32
+ y = y + x[i + 1]
33
+ return y
34
+
35
+
36
+ class MixConv2d(nn.Module):
37
+ # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
38
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
39
+ super().__init__()
40
+ n = len(k) # number of convolutions
41
+ if equal_ch: # equal c_ per group
42
+ i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
43
+ c_ = [(i == g).sum() for g in range(n)] # intermediate channels
44
+ else: # equal weight.numel() per group
45
+ b = [c2] + [0] * n
46
+ a = np.eye(n + 1, n, k=-1)
47
+ a -= np.roll(a, 1, axis=1)
48
+ a *= np.array(k) ** 2
49
+ a[0] = 1
50
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
51
+
52
+ self.m = nn.ModuleList([
53
+ nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
54
+ self.bn = nn.BatchNorm2d(c2)
55
+ self.act = nn.SiLU()
56
+
57
+ def forward(self, x):
58
+ return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
59
+
60
+
61
+ class Ensemble(nn.ModuleList):
62
+ # Ensemble of models
63
+ def __init__(self):
64
+ super().__init__()
65
+
66
+ def forward(self, x, augment=False, profile=False, visualize=False):
67
+ y = [module(x, augment, profile, visualize)[0] for module in self]
68
+ # y = torch.stack(y).max(0)[0] # max ensemble
69
+ # y = torch.stack(y).mean(0) # mean ensemble
70
+ y = torch.cat(y, 1) # nms ensemble
71
+ return y, None # inference, train output
72
+
73
+
74
+ def attempt_load(weights, device=None, inplace=True, fuse=True):
75
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
76
+ from models.yolo import Detect, Model
77
+
78
+ model = Ensemble()
79
+ for w in weights if isinstance(weights, list) else [weights]:
80
+ ckpt = torch.load(attempt_download(w), map_location='cpu') # load
81
+ ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
82
+ model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode
83
+
84
+ # Compatibility updates
85
+ for m in model.modules():
86
+ t = type(m)
87
+ if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
88
+ m.inplace = inplace # torch 1.7.0 compatibility
89
+ if t is Detect and not isinstance(m.anchor_grid, list):
90
+ delattr(m, 'anchor_grid')
91
+ setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
92
+ elif t is Conv:
93
+ m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility
94
+ elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
95
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
96
+
97
+ if len(model) == 1:
98
+ return model[-1] # return model
99
+ print(f'Ensemble created with {weights}\n')
100
+ for k in 'names', 'nc', 'yaml':
101
+ setattr(model, k, getattr(model[0], k))
102
+ model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
103
+ assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
104
+ return model # return ensemble
models/tf.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, C3x, Concat, Conv, CrossConv, DWConv,
31
+ DWConvTranspose2d, Focus, autopad)
32
+ from models.experimental import MixConv2d, attempt_load
33
+ from models.yolo import Detect
34
+ from utils.activations import SiLU
35
+ from utils.general import LOGGER, make_divisible, print_args
36
+
37
+
38
+ class TFBN(keras.layers.Layer):
39
+ # TensorFlow BatchNormalization wrapper
40
+ def __init__(self, w=None):
41
+ super().__init__()
42
+ self.bn = keras.layers.BatchNormalization(
43
+ beta_initializer=keras.initializers.Constant(w.bias.numpy()),
44
+ gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
45
+ moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
46
+ moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
47
+ epsilon=w.eps)
48
+
49
+ def call(self, inputs):
50
+ return self.bn(inputs)
51
+
52
+
53
+ class TFPad(keras.layers.Layer):
54
+ # Pad inputs in spatial dimensions 1 and 2
55
+ def __init__(self, pad):
56
+ super().__init__()
57
+ if isinstance(pad, int):
58
+ self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
59
+ else: # tuple/list
60
+ self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]])
61
+
62
+ def call(self, inputs):
63
+ return tf.pad(inputs, self.pad, mode='constant', constant_values=0)
64
+
65
+
66
+ class TFConv(keras.layers.Layer):
67
+ # Standard convolution
68
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
69
+ # ch_in, ch_out, weights, kernel, stride, padding, groups
70
+ super().__init__()
71
+ assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
72
+ # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
73
+ # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
74
+ conv = keras.layers.Conv2D(
75
+ filters=c2,
76
+ kernel_size=k,
77
+ strides=s,
78
+ padding='SAME' if s == 1 else 'VALID',
79
+ use_bias=not hasattr(w, 'bn'),
80
+ kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
81
+ bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
82
+ self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
83
+ self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
84
+ self.act = activations(w.act) if act else tf.identity
85
+
86
+ def call(self, inputs):
87
+ return self.act(self.bn(self.conv(inputs)))
88
+
89
+
90
+ class TFDWConv(keras.layers.Layer):
91
+ # Depthwise convolution
92
+ def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
93
+ # ch_in, ch_out, weights, kernel, stride, padding, groups
94
+ super().__init__()
95
+ assert c2 % c1 == 0, f'TFDWConv() output={c2} must be a multiple of input={c1} channels'
96
+ conv = keras.layers.DepthwiseConv2D(
97
+ kernel_size=k,
98
+ depth_multiplier=c2 // c1,
99
+ strides=s,
100
+ padding='SAME' if s == 1 else 'VALID',
101
+ use_bias=not hasattr(w, 'bn'),
102
+ depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
103
+ bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
104
+ self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
105
+ self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
106
+ self.act = activations(w.act) if act else tf.identity
107
+
108
+ def call(self, inputs):
109
+ return self.act(self.bn(self.conv(inputs)))
110
+
111
+
112
+ class TFDWConvTranspose2d(keras.layers.Layer):
113
+ # Depthwise ConvTranspose2d
114
+ def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
115
+ # ch_in, ch_out, weights, kernel, stride, padding, groups
116
+ super().__init__()
117
+ assert c1 == c2, f'TFDWConv() output={c2} must be equal to input={c1} channels'
118
+ assert k == 4 and p1 == 1, 'TFDWConv() only valid for k=4 and p1=1'
119
+ weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy()
120
+ self.c1 = c1
121
+ self.conv = [
122
+ keras.layers.Conv2DTranspose(filters=1,
123
+ kernel_size=k,
124
+ strides=s,
125
+ padding='VALID',
126
+ output_padding=p2,
127
+ use_bias=True,
128
+ kernel_initializer=keras.initializers.Constant(weight[..., i:i + 1]),
129
+ bias_initializer=keras.initializers.Constant(bias[i])) for i in range(c1)]
130
+
131
+ def call(self, inputs):
132
+ return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1]
133
+
134
+
135
+ class TFFocus(keras.layers.Layer):
136
+ # Focus wh information into c-space
137
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
138
+ # ch_in, ch_out, kernel, stride, padding, groups
139
+ super().__init__()
140
+ self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
141
+
142
+ def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
143
+ # inputs = inputs / 255 # normalize 0-255 to 0-1
144
+ inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]]
145
+ return self.conv(tf.concat(inputs, 3))
146
+
147
+
148
+ class TFBottleneck(keras.layers.Layer):
149
+ # Standard bottleneck
150
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion
151
+ super().__init__()
152
+ c_ = int(c2 * e) # hidden channels
153
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
154
+ self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
155
+ self.add = shortcut and c1 == c2
156
+
157
+ def call(self, inputs):
158
+ return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
159
+
160
+
161
+ class TFCrossConv(keras.layers.Layer):
162
+ # Cross Convolution
163
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
164
+ super().__init__()
165
+ c_ = int(c2 * e) # hidden channels
166
+ self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1)
167
+ self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2)
168
+ self.add = shortcut and c1 == c2
169
+
170
+ def call(self, inputs):
171
+ return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
172
+
173
+
174
+ class TFConv2d(keras.layers.Layer):
175
+ # Substitution for PyTorch nn.Conv2D
176
+ def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
177
+ super().__init__()
178
+ assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
179
+ self.conv = keras.layers.Conv2D(filters=c2,
180
+ kernel_size=k,
181
+ strides=s,
182
+ padding='VALID',
183
+ use_bias=bias,
184
+ kernel_initializer=keras.initializers.Constant(
185
+ w.weight.permute(2, 3, 1, 0).numpy()),
186
+ bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None)
187
+
188
+ def call(self, inputs):
189
+ return self.conv(inputs)
190
+
191
+
192
+ class TFBottleneckCSP(keras.layers.Layer):
193
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
194
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
195
+ # ch_in, ch_out, number, shortcut, groups, expansion
196
+ super().__init__()
197
+ c_ = int(c2 * e) # hidden channels
198
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
199
+ self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
200
+ self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
201
+ self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
202
+ self.bn = TFBN(w.bn)
203
+ self.act = lambda x: keras.activations.swish(x)
204
+ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
205
+
206
+ def call(self, inputs):
207
+ y1 = self.cv3(self.m(self.cv1(inputs)))
208
+ y2 = self.cv2(inputs)
209
+ return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
210
+
211
+
212
+ class TFC3(keras.layers.Layer):
213
+ # CSP Bottleneck with 3 convolutions
214
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
215
+ # ch_in, ch_out, number, shortcut, groups, expansion
216
+ super().__init__()
217
+ c_ = int(c2 * e) # hidden channels
218
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
219
+ self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
220
+ self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
221
+ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
222
+
223
+ def call(self, inputs):
224
+ return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
225
+
226
+
227
+ class TFC3x(keras.layers.Layer):
228
+ # 3 module with cross-convolutions
229
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
230
+ # ch_in, ch_out, number, shortcut, groups, expansion
231
+ super().__init__()
232
+ c_ = int(c2 * e) # hidden channels
233
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
234
+ self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
235
+ self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
236
+ self.m = keras.Sequential([
237
+ TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)])
238
+
239
+ def call(self, inputs):
240
+ return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
241
+
242
+
243
+ class TFSPP(keras.layers.Layer):
244
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
245
+ def __init__(self, c1, c2, k=(5, 9, 13), w=None):
246
+ super().__init__()
247
+ c_ = c1 // 2 # hidden channels
248
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
249
+ self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
250
+ self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]
251
+
252
+ def call(self, inputs):
253
+ x = self.cv1(inputs)
254
+ return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
255
+
256
+
257
+ class TFSPPF(keras.layers.Layer):
258
+ # Spatial pyramid pooling-Fast layer
259
+ def __init__(self, c1, c2, k=5, w=None):
260
+ super().__init__()
261
+ c_ = c1 // 2 # hidden channels
262
+ self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
263
+ self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
264
+ self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')
265
+
266
+ def call(self, inputs):
267
+ x = self.cv1(inputs)
268
+ y1 = self.m(x)
269
+ y2 = self.m(y1)
270
+ return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
271
+
272
+
273
+ class TFDetect(keras.layers.Layer):
274
+ # TF YOLOv5 Detect layer
275
+ def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer
276
+ super().__init__()
277
+ self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
278
+ self.nc = nc # number of classes
279
+ self.no = nc + 5 # number of outputs per anchor
280
+ self.nl = len(anchors) # number of detection layers
281
+ self.na = len(anchors[0]) // 2 # number of anchors
282
+ self.grid = [tf.zeros(1)] * self.nl # init grid
283
+ self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
284
+ self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2])
285
+ self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
286
+ self.training = False # set to False after building model
287
+ self.imgsz = imgsz
288
+ for i in range(self.nl):
289
+ ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
290
+ self.grid[i] = self._make_grid(nx, ny)
291
+
292
+ def call(self, inputs):
293
+ z = [] # inference output
294
+ x = []
295
+ for i in range(self.nl):
296
+ x.append(self.m[i](inputs[i]))
297
+ # x(bs,20,20,255) to x(bs,3,20,20,85)
298
+ ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
299
+ x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])
300
+
301
+ if not self.training: # inference
302
+ y = tf.sigmoid(x[i])
303
+ grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5
304
+ anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4
305
+ xy = (y[..., 0:2] * 2 + grid) * self.stride[i] # xy
306
+ wh = y[..., 2:4] ** 2 * anchor_grid
307
+ # Normalize xywh to 0-1 to reduce calibration error
308
+ xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
309
+ wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
310
+ y = tf.concat([xy, wh, y[..., 4:]], -1)
311
+ z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))
312
+
313
+ return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1), x)
314
+
315
+ @staticmethod
316
+ def _make_grid(nx=20, ny=20):
317
+ # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
318
+ # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
319
+ xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
320
+ return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
321
+
322
+
323
+ class TFUpsample(keras.layers.Layer):
324
+ # TF version of torch.nn.Upsample()
325
+ def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'
326
+ super().__init__()
327
+ assert scale_factor == 2, "scale_factor must be 2"
328
+ self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode)
329
+ # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
330
+ # with default arguments: align_corners=False, half_pixel_centers=False
331
+ # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
332
+ # size=(x.shape[1] * 2, x.shape[2] * 2))
333
+
334
+ def call(self, inputs):
335
+ return self.upsample(inputs)
336
+
337
+
338
+ class TFConcat(keras.layers.Layer):
339
+ # TF version of torch.concat()
340
+ def __init__(self, dimension=1, w=None):
341
+ super().__init__()
342
+ assert dimension == 1, "convert only NCHW to NHWC concat"
343
+ self.d = 3
344
+
345
+ def call(self, inputs):
346
+ return tf.concat(inputs, self.d)
347
+
348
+
349
+ def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
350
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
351
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
352
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
353
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
354
+
355
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
356
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
357
+ m_str = m
358
+ m = eval(m) if isinstance(m, str) else m # eval strings
359
+ for j, a in enumerate(args):
360
+ try:
361
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
362
+ except NameError:
363
+ pass
364
+
365
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
366
+ if m in [
367
+ nn.Conv2d, Conv, DWConv, DWConvTranspose2d, Bottleneck, SPP, SPPF, MixConv2d, Focus, CrossConv,
368
+ BottleneckCSP, C3, C3x]:
369
+ c1, c2 = ch[f], args[0]
370
+ c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
371
+
372
+ args = [c1, c2, *args[1:]]
373
+ if m in [BottleneckCSP, C3, C3x]:
374
+ args.insert(2, n)
375
+ n = 1
376
+ elif m is nn.BatchNorm2d:
377
+ args = [ch[f]]
378
+ elif m is Concat:
379
+ c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
380
+ elif m is Detect:
381
+ args.append([ch[x + 1] for x in f])
382
+ if isinstance(args[1], int): # number of anchors
383
+ args[1] = [list(range(args[1] * 2))] * len(f)
384
+ args.append(imgsz)
385
+ else:
386
+ c2 = ch[f]
387
+
388
+ tf_m = eval('TF' + m_str.replace('nn.', ''))
389
+ m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \
390
+ else tf_m(*args, w=model.model[i]) # module
391
+
392
+ torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
393
+ t = str(m)[8:-2].replace('__main__.', '') # module type
394
+ np = sum(x.numel() for x in torch_m_.parameters()) # number params
395
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
396
+ LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print
397
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
398
+ layers.append(m_)
399
+ ch.append(c2)
400
+ return keras.Sequential(layers), sorted(save)
401
+
402
+
403
+ class TFModel:
404
+ # TF YOLOv5 model
405
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes
406
+ super().__init__()
407
+ if isinstance(cfg, dict):
408
+ self.yaml = cfg # model dict
409
+ else: # is *.yaml
410
+ import yaml # for torch hub
411
+ self.yaml_file = Path(cfg).name
412
+ with open(cfg) as f:
413
+ self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
414
+
415
+ # Define model
416
+ if nc and nc != self.yaml['nc']:
417
+ LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
418
+ self.yaml['nc'] = nc # override yaml value
419
+ self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
420
+
421
+ def predict(self,
422
+ inputs,
423
+ tf_nms=False,
424
+ agnostic_nms=False,
425
+ topk_per_class=100,
426
+ topk_all=100,
427
+ iou_thres=0.45,
428
+ conf_thres=0.25):
429
+ y = [] # outputs
430
+ x = inputs
431
+ for m in self.model.layers:
432
+ if m.f != -1: # if not from previous layer
433
+ 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
434
+
435
+ x = m(x) # run
436
+ y.append(x if m.i in self.savelist else None) # save output
437
+
438
+ # Add TensorFlow NMS
439
+ if tf_nms:
440
+ boxes = self._xywh2xyxy(x[0][..., :4])
441
+ probs = x[0][:, :, 4:5]
442
+ classes = x[0][:, :, 5:]
443
+ scores = probs * classes
444
+ if agnostic_nms:
445
+ nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
446
+ else:
447
+ boxes = tf.expand_dims(boxes, 2)
448
+ nms = tf.image.combined_non_max_suppression(boxes,
449
+ scores,
450
+ topk_per_class,
451
+ topk_all,
452
+ iou_thres,
453
+ conf_thres,
454
+ clip_boxes=False)
455
+ return nms, x[1]
456
+ return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]
457
+ # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85)
458
+ # xywh = x[..., :4] # x(6300,4) boxes
459
+ # conf = x[..., 4:5] # x(6300,1) confidences
460
+ # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
461
+ # return tf.concat([conf, cls, xywh], 1)
462
+
463
+ @staticmethod
464
+ def _xywh2xyxy(xywh):
465
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
466
+ x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
467
+ return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
468
+
469
+
470
+ class AgnosticNMS(keras.layers.Layer):
471
+ # TF Agnostic NMS
472
+ def call(self, input, topk_all, iou_thres, conf_thres):
473
+ # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450
474
+ return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres),
475
+ input,
476
+ fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
477
+ name='agnostic_nms')
478
+
479
+ @staticmethod
480
+ def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
481
+ boxes, classes, scores = x
482
+ class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
483
+ scores_inp = tf.reduce_max(scores, -1)
484
+ selected_inds = tf.image.non_max_suppression(boxes,
485
+ scores_inp,
486
+ max_output_size=topk_all,
487
+ iou_threshold=iou_thres,
488
+ score_threshold=conf_thres)
489
+ selected_boxes = tf.gather(boxes, selected_inds)
490
+ padded_boxes = tf.pad(selected_boxes,
491
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
492
+ mode="CONSTANT",
493
+ constant_values=0.0)
494
+ selected_scores = tf.gather(scores_inp, selected_inds)
495
+ padded_scores = tf.pad(selected_scores,
496
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
497
+ mode="CONSTANT",
498
+ constant_values=-1.0)
499
+ selected_classes = tf.gather(class_inds, selected_inds)
500
+ padded_classes = tf.pad(selected_classes,
501
+ paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
502
+ mode="CONSTANT",
503
+ constant_values=-1.0)
504
+ valid_detections = tf.shape(selected_inds)[0]
505
+ return padded_boxes, padded_scores, padded_classes, valid_detections
506
+
507
+
508
+ def activations(act=nn.SiLU):
509
+ # Returns TF activation from input PyTorch activation
510
+ if isinstance(act, nn.LeakyReLU):
511
+ return lambda x: keras.activations.relu(x, alpha=0.1)
512
+ elif isinstance(act, nn.Hardswish):
513
+ return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667
514
+ elif isinstance(act, (nn.SiLU, SiLU)):
515
+ return lambda x: keras.activations.swish(x)
516
+ else:
517
+ raise Exception(f'no matching TensorFlow activation found for PyTorch activation {act}')
518
+
519
+
520
+ def representative_dataset_gen(dataset, ncalib=100):
521
+ # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
522
+ for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
523
+ im = np.transpose(img, [1, 2, 0])
524
+ im = np.expand_dims(im, axis=0).astype(np.float32)
525
+ im /= 255
526
+ yield [im]
527
+ if n >= ncalib:
528
+ break
529
+
530
+
531
+ def run(
532
+ weights=ROOT / 'yolov5s.pt', # weights path
533
+ imgsz=(640, 640), # inference size h,w
534
+ batch_size=1, # batch size
535
+ dynamic=False, # dynamic batch size
536
+ ):
537
+ # PyTorch model
538
+ im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
539
+ model = attempt_load(weights, device=torch.device('cpu'), inplace=True, fuse=False)
540
+ _ = model(im) # inference
541
+ model.info()
542
+
543
+ # TensorFlow model
544
+ im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
545
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
546
+ _ = tf_model.predict(im) # inference
547
+
548
+ # Keras model
549
+ im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
550
+ keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
551
+ keras_model.summary()
552
+
553
+ LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.')
554
+
555
+
556
+ def parse_opt():
557
+ parser = argparse.ArgumentParser()
558
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
559
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
560
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
561
+ parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')
562
+ opt = parser.parse_args()
563
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
564
+ print_args(vars(opt))
565
+ return opt
566
+
567
+
568
+ def main(opt):
569
+ run(**vars(opt))
570
+
571
+
572
+ if __name__ == "__main__":
573
+ opt = parse_opt()
574
+ main(opt)
models/yolo.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
11
+ import platform
12
+ import sys
13
+ from copy import deepcopy
14
+ from pathlib import Path
15
+
16
+ FILE = Path(__file__).resolve()
17
+ ROOT = FILE.parents[1] # YOLOv5 root directory
18
+ if str(ROOT) not in sys.path:
19
+ sys.path.append(str(ROOT)) # add ROOT to PATH
20
+ if platform.system() != 'Windows':
21
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
22
+
23
+ from models.common import *
24
+ from models.experimental import *
25
+ from utils.autoanchor import check_anchor_order
26
+ from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
27
+ from utils.plots import feature_visualization
28
+ from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
29
+ time_sync)
30
+
31
+ try:
32
+ import thop # for FLOPs computation
33
+ except ImportError:
34
+ thop = None
35
+
36
+
37
+ class Detect(nn.Module):
38
+ stride = None # strides computed during build
39
+ onnx_dynamic = False # ONNX export parameter
40
+ export = False # export mode
41
+
42
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
43
+ super().__init__()
44
+ self.nc = nc # number of classes
45
+ self.no = nc + 5 # number of outputs per anchor
46
+ self.nl = len(anchors) # number of detection layers
47
+ self.na = len(anchors[0]) // 2 # number of anchors
48
+ self.grid = [torch.zeros(1)] * self.nl # init grid
49
+ self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
50
+ self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
51
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
52
+ self.inplace = inplace # use in-place ops (e.g. slice assignment)
53
+
54
+ def forward(self, x):
55
+ z = [] # inference output
56
+ for i in range(self.nl):
57
+ x[i] = self.m[i](x[i]) # conv
58
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
59
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
60
+
61
+ if not self.training: # inference
62
+ if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
63
+ self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
64
+
65
+ y = x[i].sigmoid()
66
+ if self.inplace:
67
+ y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy
68
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
69
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
70
+ xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
71
+ xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
72
+ wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
73
+ y = torch.cat((xy, wh, conf), 4)
74
+ z.append(y.view(bs, -1, self.no))
75
+
76
+ return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
77
+
78
+ def _make_grid(self, nx=20, ny=20, i=0):
79
+ d = self.anchors[i].device
80
+ t = self.anchors[i].dtype
81
+ shape = 1, self.na, ny, nx, 2 # grid shape
82
+ y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
83
+ if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
84
+ yv, xv = torch.meshgrid(y, x, indexing='ij')
85
+ else:
86
+ yv, xv = torch.meshgrid(y, x)
87
+ grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
88
+ anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
89
+ return grid, anchor_grid
90
+
91
+
92
+ class Model(nn.Module):
93
+ # YOLOv5 model
94
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
95
+ super().__init__()
96
+ if isinstance(cfg, dict):
97
+ self.yaml = cfg # model dict
98
+ else: # is *.yaml
99
+ import yaml # for torch hub
100
+ self.yaml_file = Path(cfg).name
101
+ with open(cfg, encoding='ascii', errors='ignore') as f:
102
+ self.yaml = yaml.safe_load(f) # model dict
103
+
104
+ # Define model
105
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
106
+ if nc and nc != self.yaml['nc']:
107
+ LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
108
+ self.yaml['nc'] = nc # override yaml value
109
+ if anchors:
110
+ LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
111
+ self.yaml['anchors'] = round(anchors) # override yaml value
112
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
113
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
114
+ self.inplace = self.yaml.get('inplace', True)
115
+
116
+ # Build strides, anchors
117
+ m = self.model[-1] # Detect()
118
+ if isinstance(m, Detect):
119
+ s = 256 # 2x min stride
120
+ m.inplace = self.inplace
121
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
122
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
123
+ m.anchors /= m.stride.view(-1, 1, 1)
124
+ self.stride = m.stride
125
+ self._initialize_biases() # only run once
126
+
127
+ # Init weights, biases
128
+ initialize_weights(self)
129
+ self.info()
130
+ LOGGER.info('')
131
+
132
+ def forward(self, x, augment=False, profile=False, visualize=False):
133
+ if augment:
134
+ return self._forward_augment(x) # augmented inference, None
135
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
136
+
137
+ def _forward_augment(self, x):
138
+ img_size = x.shape[-2:] # height, width
139
+ s = [1, 0.83, 0.67] # scales
140
+ f = [None, 3, None] # flips (2-ud, 3-lr)
141
+ y = [] # outputs
142
+ for si, fi in zip(s, f):
143
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
144
+ yi = self._forward_once(xi)[0] # forward
145
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
146
+ yi = self._descale_pred(yi, fi, si, img_size)
147
+ y.append(yi)
148
+ y = self._clip_augmented(y) # clip augmented tails
149
+ return torch.cat(y, 1), None # augmented inference, train
150
+
151
+ def _forward_once(self, x, profile=False, visualize=False):
152
+ y, dt = [], [] # outputs
153
+ for m in self.model:
154
+ if m.f != -1: # if not from previous layer
155
+ 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
156
+ if profile:
157
+ self._profile_one_layer(m, x, dt)
158
+ x = m(x) # run
159
+ y.append(x if m.i in self.save else None) # save output
160
+ if visualize:
161
+ feature_visualization(x, m.type, m.i, save_dir=visualize)
162
+ return x
163
+
164
+ def _descale_pred(self, p, flips, scale, img_size):
165
+ # de-scale predictions following augmented inference (inverse operation)
166
+ if self.inplace:
167
+ p[..., :4] /= scale # de-scale
168
+ if flips == 2:
169
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
170
+ elif flips == 3:
171
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
172
+ else:
173
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
174
+ if flips == 2:
175
+ y = img_size[0] - y # de-flip ud
176
+ elif flips == 3:
177
+ x = img_size[1] - x # de-flip lr
178
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
179
+ return p
180
+
181
+ def _clip_augmented(self, y):
182
+ # Clip YOLOv5 augmented inference tails
183
+ nl = self.model[-1].nl # number of detection layers (P3-P5)
184
+ g = sum(4 ** x for x in range(nl)) # grid points
185
+ e = 1 # exclude layer count
186
+ i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
187
+ y[0] = y[0][:, :-i] # large
188
+ i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
189
+ y[-1] = y[-1][:, i:] # small
190
+ return y
191
+
192
+ def _profile_one_layer(self, m, x, dt):
193
+ c = isinstance(m, Detect) # is final layer, copy input as inplace fix
194
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
195
+ t = time_sync()
196
+ for _ in range(10):
197
+ m(x.copy() if c else x)
198
+ dt.append((time_sync() - t) * 100)
199
+ if m == self.model[0]:
200
+ LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
201
+ LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
202
+ if c:
203
+ LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
204
+
205
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
206
+ # https://arxiv.org/abs/1708.02002 section 3.3
207
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
208
+ m = self.model[-1] # Detect() module
209
+ for mi, s in zip(m.m, m.stride): # from
210
+ b = mi.bias.view(m.na, -1).detach() # conv.bias(255) to (3,85)
211
+ b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
212
+ b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
213
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
214
+
215
+ def _print_biases(self):
216
+ m = self.model[-1] # Detect() module
217
+ for mi in m.m: # from
218
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
219
+ LOGGER.info(
220
+ ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
221
+
222
+ # def _print_weights(self):
223
+ # for m in self.model.modules():
224
+ # if type(m) is Bottleneck:
225
+ # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
226
+
227
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
228
+ LOGGER.info('Fusing layers... ')
229
+ for m in self.model.modules():
230
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
231
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
232
+ delattr(m, 'bn') # remove batchnorm
233
+ m.forward = m.forward_fuse # update forward
234
+ self.info()
235
+ return self
236
+
237
+ def info(self, verbose=False, img_size=640): # print model information
238
+ model_info(self, verbose, img_size)
239
+
240
+ def _apply(self, fn):
241
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
242
+ self = super()._apply(fn)
243
+ m = self.model[-1] # Detect()
244
+ if isinstance(m, Detect):
245
+ m.stride = fn(m.stride)
246
+ m.grid = list(map(fn, m.grid))
247
+ if isinstance(m.anchor_grid, list):
248
+ m.anchor_grid = list(map(fn, m.anchor_grid))
249
+ return self
250
+
251
+
252
+ def parse_model(d, ch): # model_dict, input_channels(3)
253
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
254
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
255
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
256
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
257
+
258
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
259
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
260
+ m = eval(m) if isinstance(m, str) else m # eval strings
261
+ for j, a in enumerate(args):
262
+ try:
263
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
264
+ except NameError:
265
+ pass
266
+
267
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
268
+ if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
269
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x):
270
+ c1, c2 = ch[f], args[0]
271
+ if c2 != no: # if not output
272
+ c2 = make_divisible(c2 * gw, 8)
273
+
274
+ args = [c1, c2, *args[1:]]
275
+ if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]:
276
+ args.insert(2, n) # number of repeats
277
+ n = 1
278
+ elif m is nn.BatchNorm2d:
279
+ args = [ch[f]]
280
+ elif m is Concat:
281
+ c2 = sum(ch[x] for x in f)
282
+ elif m is Detect:
283
+ args.append([ch[x] for x in f])
284
+ if isinstance(args[1], int): # number of anchors
285
+ args[1] = [list(range(args[1] * 2))] * len(f)
286
+ elif m is Contract:
287
+ c2 = ch[f] * args[0] ** 2
288
+ elif m is Expand:
289
+ c2 = ch[f] // args[0] ** 2
290
+ else:
291
+ c2 = ch[f]
292
+
293
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
294
+ t = str(m)[8:-2].replace('__main__.', '') # module type
295
+ np = sum(x.numel() for x in m_.parameters()) # number params
296
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
297
+ LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
298
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
299
+ layers.append(m_)
300
+ if i == 0:
301
+ ch = []
302
+ ch.append(c2)
303
+ return nn.Sequential(*layers), sorted(save)
304
+
305
+
306
+ if __name__ == '__main__':
307
+ parser = argparse.ArgumentParser()
308
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
309
+ parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
310
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
311
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
312
+ parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
313
+ parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
314
+ opt = parser.parse_args()
315
+ opt.cfg = check_yaml(opt.cfg) # check YAML
316
+ print_args(vars(opt))
317
+ device = select_device(opt.device)
318
+
319
+ # Create model
320
+ im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
321
+ model = Model(opt.cfg).to(device)
322
+
323
+ # Options
324
+ if opt.line_profile: # profile layer by layer
325
+ _ = model(im, profile=True)
326
+
327
+ elif opt.profile: # profile forward-backward
328
+ results = profile(input=im, ops=[model], n=3)
329
+
330
+ elif opt.test: # test all models
331
+ for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
332
+ try:
333
+ _ = Model(cfg)
334
+ except Exception as e:
335
+ print(f'Error in {cfg}: {e}')
336
+
337
+ else: # report fused model summary
338
+ model.fuse()
requirements.txt ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 参考:https://github.com/ultralytics/yolov5/blob/master/requirements.txt
2
+ # pip install -r requirements.txt
3
+ # pip 22.1.2
4
+
5
+ # Base ----------------------------------------
6
+ matplotlib==3.5.2
7
+ numpy==1.19.5
8
+ opencv-python==4.5.5.64
9
+ Pillow==9.2.0
10
+ PyYAML==6.0
11
+ requests==2.28.1
12
+ scipy==1.5.4 # Google Colab version
13
+ torch==1.11.0 # https://github.com/ultralytics/yolov5/issues/8395
14
+ torchvision>=0.12.0 # https://github.com/ultralytics/yolov5/issues/8395
15
+ tqdm==4.64.0
16
+ protobuf==3.19.4 # https://github.com/ultralytics/yolov5/issues/8012
17
+
18
+
19
+ # Streamlit YOLOv5 Model2X
20
+ streamlit==1.10.0
21
+
22
+
23
+ # Logging -------------------------------------
24
+ tensorboard==2.9.1
25
+ # wandb
26
+
27
+ # Plotting ------------------------------------
28
+ pandas==1.1.5
29
+ seaborn==0.11.2
30
+
31
+ # Export --------------------------------------
32
+ coremltools==5.2.0 # CoreML export
33
+ onnx==1.12.0 # ONNX export
34
+ onnx-simplifier==0.4.0 # ONNX simplifier
35
+ onnxruntime-gpu==1.11.1
36
+ nvidia-pyindex==1.0.9
37
+ nvidia-tensorrt==8.4.1.5
38
+ scikit-learn==0.24.2 # CoreML quantization
39
+ tensorflow==2.4.1 # TFLite export
40
+ tensorflowjs==3.18.0 # TF.js export
41
+ openvino-dev==2022.1.0 # OpenVINO export
42
+
43
+ # Extras --------------------------------------
44
+ ipython==8.4.0 # interactive notebook
45
+ psutil==5.9.1 # system utilization
46
+ thop==0.1.0.post2207010342 # FLOPs computation
47
+ # albumentations>=1.0.3
48
+ # pycocotools>=2.0 # COCO mAP
49
+ # roboflow
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
utils/activations.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class SiLU(nn.Module):
12
+ # SiLU activation https://arxiv.org/pdf/1606.08415.pdf
13
+ @staticmethod
14
+ def forward(x):
15
+ return x * torch.sigmoid(x)
16
+
17
+
18
+ class Hardswish(nn.Module):
19
+ # Hard-SiLU activation
20
+ @staticmethod
21
+ def forward(x):
22
+ # return x * F.hardsigmoid(x) # for TorchScript and CoreML
23
+ return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
24
+
25
+
26
+ class Mish(nn.Module):
27
+ # Mish activation https://github.com/digantamisra98/Mish
28
+ @staticmethod
29
+ def forward(x):
30
+ return x * F.softplus(x).tanh()
31
+
32
+
33
+ class MemoryEfficientMish(nn.Module):
34
+ # Mish activation memory-efficient
35
+ class F(torch.autograd.Function):
36
+
37
+ @staticmethod
38
+ def forward(ctx, x):
39
+ ctx.save_for_backward(x)
40
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
41
+
42
+ @staticmethod
43
+ def backward(ctx, grad_output):
44
+ x = ctx.saved_tensors[0]
45
+ sx = torch.sigmoid(x)
46
+ fx = F.softplus(x).tanh()
47
+ return grad_output * (fx + x * sx * (1 - fx * fx))
48
+
49
+ def forward(self, x):
50
+ return self.F.apply(x)
51
+
52
+
53
+ class FReLU(nn.Module):
54
+ # FReLU activation https://arxiv.org/abs/2007.11824
55
+ def __init__(self, c1, k=3): # ch_in, kernel
56
+ super().__init__()
57
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
58
+ self.bn = nn.BatchNorm2d(c1)
59
+
60
+ def forward(self, x):
61
+ return torch.max(x, self.bn(self.conv(x)))
62
+
63
+
64
+ class AconC(nn.Module):
65
+ r""" ACON activation (activate or not)
66
+ AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
67
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
68
+ """
69
+
70
+ def __init__(self, c1):
71
+ super().__init__()
72
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
73
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
74
+ self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
75
+
76
+ def forward(self, x):
77
+ dpx = (self.p1 - self.p2) * x
78
+ return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
79
+
80
+
81
+ class MetaAconC(nn.Module):
82
+ r""" ACON activation (activate or not)
83
+ MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
84
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
85
+ """
86
+
87
+ def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
88
+ super().__init__()
89
+ c2 = max(r, c1 // r)
90
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
91
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
92
+ self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
93
+ self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
94
+ # self.bn1 = nn.BatchNorm2d(c2)
95
+ # self.bn2 = nn.BatchNorm2d(c1)
96
+
97
+ def forward(self, x):
98
+ y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
99
+ # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
100
+ # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
101
+ beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
102
+ dpx = (self.p1 - self.p2) * x
103
+ return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
utils/augmentations.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ T = [
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)] # transforms
32
+ self.transform = A.Compose(T, 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,
125
+ targets=(),
126
+ segments=(),
127
+ degrees=10,
128
+ translate=.1,
129
+ scale=.1,
130
+ shear=10,
131
+ perspective=0.0,
132
+ border=(0, 0)):
133
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
134
+ # targets = [cls, xyxy]
135
+
136
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
137
+ width = im.shape[1] + border[1] * 2
138
+
139
+ # Center
140
+ C = np.eye(3)
141
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
142
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
143
+
144
+ # Perspective
145
+ P = np.eye(3)
146
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
147
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
148
+
149
+ # Rotation and Scale
150
+ R = np.eye(3)
151
+ a = random.uniform(-degrees, degrees)
152
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
153
+ s = random.uniform(1 - scale, 1 + scale)
154
+ # s = 2 ** random.uniform(-scale, scale)
155
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
156
+
157
+ # Shear
158
+ S = np.eye(3)
159
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
160
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
161
+
162
+ # Translation
163
+ T = np.eye(3)
164
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
165
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
166
+
167
+ # Combined rotation matrix
168
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
169
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
170
+ if perspective:
171
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
172
+ else: # affine
173
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
174
+
175
+ # Visualize
176
+ # import matplotlib.pyplot as plt
177
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
178
+ # ax[0].imshow(im[:, :, ::-1]) # base
179
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
180
+
181
+ # Transform label coordinates
182
+ n = len(targets)
183
+ if n:
184
+ use_segments = any(x.any() for x in segments)
185
+ new = np.zeros((n, 4))
186
+ if use_segments: # warp segments
187
+ segments = resample_segments(segments) # upsample
188
+ for i, segment in enumerate(segments):
189
+ xy = np.ones((len(segment), 3))
190
+ xy[:, :2] = segment
191
+ xy = xy @ M.T # transform
192
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
193
+
194
+ # clip
195
+ new[i] = segment2box(xy, width, height)
196
+
197
+ else: # warp boxes
198
+ xy = np.ones((n * 4, 3))
199
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
200
+ xy = xy @ M.T # transform
201
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
202
+
203
+ # create new boxes
204
+ x = xy[:, [0, 2, 4, 6]]
205
+ y = xy[:, [1, 3, 5, 7]]
206
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
207
+
208
+ # clip
209
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
210
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
211
+
212
+ # filter candidates
213
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
214
+ targets = targets[i]
215
+ targets[:, 1:5] = new[i]
216
+
217
+ return im, targets
218
+
219
+
220
+ def copy_paste(im, labels, segments, p=0.5):
221
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
222
+ n = len(segments)
223
+ if p and n:
224
+ h, w, c = im.shape # height, width, channels
225
+ im_new = np.zeros(im.shape, np.uint8)
226
+ for j in random.sample(range(n), k=round(p * n)):
227
+ l, s = labels[j], segments[j]
228
+ box = w - l[3], l[2], w - l[1], l[4]
229
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
230
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
231
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
232
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
233
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
234
+
235
+ result = cv2.bitwise_and(src1=im, src2=im_new)
236
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
237
+ i = result > 0 # pixels to replace
238
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
239
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
240
+
241
+ return im, labels, segments
242
+
243
+
244
+ def cutout(im, labels, p=0.5):
245
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
246
+ if random.random() < p:
247
+ h, w = im.shape[:2]
248
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
249
+ for s in scales:
250
+ mask_h = random.randint(1, int(h * s)) # create random masks
251
+ mask_w = random.randint(1, int(w * s))
252
+
253
+ # box
254
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
255
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
256
+ xmax = min(w, xmin + mask_w)
257
+ ymax = min(h, ymin + mask_h)
258
+
259
+ # apply random color mask
260
+ im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
261
+
262
+ # return unobscured labels
263
+ if len(labels) and s > 0.03:
264
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
265
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
266
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
267
+
268
+ return labels
269
+
270
+
271
+ def mixup(im, labels, im2, labels2):
272
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
273
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
274
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
275
+ labels = np.concatenate((labels, labels2), 0)
276
+ return im, labels
277
+
278
+
279
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
280
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
281
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
282
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
283
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
284
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
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 x in 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.dataloaders 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)
utils/autobatch.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ from utils.general import LOGGER, colorstr, emojis
12
+ from utils.torch_utils import profile
13
+
14
+
15
+ def check_train_batch_size(model, imgsz=640, amp=True):
16
+ # Check YOLOv5 training batch size
17
+ with torch.cuda.amp.autocast(amp):
18
+ return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
19
+
20
+
21
+ def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):
22
+ # Automatically estimate best batch size to use `fraction` of available CUDA memory
23
+ # Usage:
24
+ # import torch
25
+ # from utils.autobatch import autobatch
26
+ # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
27
+ # print(autobatch(model))
28
+
29
+ # Check device
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
+ # Inspect CUDA memory
38
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
39
+ d = str(device).upper() # 'CUDA:0'
40
+ properties = torch.cuda.get_device_properties(device) # device properties
41
+ t = properties.total_memory / gb # GiB total
42
+ r = torch.cuda.memory_reserved(device) / gb # GiB reserved
43
+ a = torch.cuda.memory_allocated(device) / gb # GiB allocated
44
+ f = t - (r + a) # GiB free
45
+ LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
46
+
47
+ # Profile batch sizes
48
+ batch_sizes = [1, 2, 4, 8, 16]
49
+ try:
50
+ img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes]
51
+ results = profile(img, model, n=3, device=device)
52
+ except Exception as e:
53
+ LOGGER.warning(f'{prefix}{e}')
54
+
55
+ # Fit a solution
56
+ y = [x[2] for x in results if x] # memory [2]
57
+ p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit
58
+ b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
59
+ if None in results: # some sizes failed
60
+ i = results.index(None) # first fail index
61
+ if b >= batch_sizes[i]: # y intercept above failure point
62
+ b = batch_sizes[max(i - 1, 0)] # select prior safe point
63
+
64
+ fraction = np.polyval(p, b) / t # actual fraction predicted
65
+ LOGGER.info(emojis(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅'))
66
+ return b
utils/benchmarks.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 platform
30
+ import sys
31
+ import time
32
+ from pathlib import Path
33
+
34
+ import pandas as pd
35
+
36
+ FILE = Path(__file__).resolve()
37
+ ROOT = FILE.parents[1] # YOLOv5 root directory
38
+ if str(ROOT) not in sys.path:
39
+ sys.path.append(str(ROOT)) # add ROOT to PATH
40
+ # ROOT = ROOT.relative_to(Path.cwd()) # relative
41
+
42
+ import export
43
+ import val
44
+ from utils import notebook_init
45
+ from utils.general import LOGGER, check_yaml, file_size, print_args
46
+ from utils.torch_utils import select_device
47
+
48
+
49
+ def run(
50
+ weights=ROOT / 'yolov5s.pt', # weights path
51
+ imgsz=640, # inference size (pixels)
52
+ batch_size=1, # batch size
53
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
54
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
55
+ half=False, # use FP16 half-precision inference
56
+ test=False, # test exports only
57
+ pt_only=False, # test PyTorch only
58
+ hard_fail=False, # throw error on benchmark failure
59
+ ):
60
+ y, t = [], time.time()
61
+ device = select_device(device)
62
+ for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
63
+ try:
64
+ assert i not in (9, 10), 'inference not supported' # Edge TPU and TF.js are unsupported
65
+ assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13' # CoreML
66
+ if 'cpu' in device.type:
67
+ assert cpu, 'inference not supported on CPU'
68
+ if 'cuda' in device.type:
69
+ assert gpu, 'inference not supported on GPU'
70
+
71
+ # Export
72
+ if f == '-':
73
+ w = weights # PyTorch format
74
+ else:
75
+ w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others
76
+ assert suffix in str(w), 'export failed'
77
+
78
+ # Validate
79
+ result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half)
80
+ metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls))
81
+ speeds = result[2] # times (preprocess, inference, postprocess)
82
+ y.append([name, round(file_size(w), 1), round(metrics[3], 4), round(speeds[1], 2)]) # MB, mAP, t_inference
83
+ except Exception as e:
84
+ if hard_fail:
85
+ assert type(e) is AssertionError, f'Benchmark --hard-fail for {name}: {e}'
86
+ LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}')
87
+ y.append([name, None, None, None]) # mAP, t_inference
88
+ if pt_only and i == 0:
89
+ break # break after PyTorch
90
+
91
+ # Print results
92
+ LOGGER.info('\n')
93
+ parse_opt()
94
+ notebook_init() # print system info
95
+ c = ['Format', 'Size (MB)', 'mAP@0.5:0.95', 'Inference time (ms)'] if map else ['Format', 'Export', '', '']
96
+ py = pd.DataFrame(y, columns=c)
97
+ LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
98
+ LOGGER.info(str(py if map else py.iloc[:, :2]))
99
+ return py
100
+
101
+
102
+ def test(
103
+ weights=ROOT / 'yolov5s.pt', # weights path
104
+ imgsz=640, # inference size (pixels)
105
+ batch_size=1, # batch size
106
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
107
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
108
+ half=False, # use FP16 half-precision inference
109
+ test=False, # test exports only
110
+ pt_only=False, # test PyTorch only
111
+ hard_fail=False, # throw error on benchmark failure
112
+ ):
113
+ y, t = [], time.time()
114
+ device = select_device(device)
115
+ for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
116
+ try:
117
+ w = weights if f == '-' else \
118
+ export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights
119
+ assert suffix in str(w), 'export failed'
120
+ y.append([name, True])
121
+ except Exception:
122
+ y.append([name, False]) # mAP, t_inference
123
+
124
+ # Print results
125
+ LOGGER.info('\n')
126
+ parse_opt()
127
+ notebook_init() # print system info
128
+ py = pd.DataFrame(y, columns=['Format', 'Export'])
129
+ LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)')
130
+ LOGGER.info(str(py))
131
+ return py
132
+
133
+
134
+ def parse_opt():
135
+ parser = argparse.ArgumentParser()
136
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
137
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
138
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
139
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
140
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
141
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
142
+ parser.add_argument('--test', action='store_true', help='test exports only')
143
+ parser.add_argument('--pt-only', action='store_true', help='test PyTorch only')
144
+ parser.add_argument('--hard-fail', action='store_true', help='throw error on benchmark failure')
145
+ opt = parser.parse_args()
146
+ opt.data = check_yaml(opt.data) # check YAML
147
+ print_args(vars(opt))
148
+ return opt
149
+
150
+
151
+ def main(opt):
152
+ test(**vars(opt)) if opt.test else run(**vars(opt))
153
+
154
+
155
+ if __name__ == "__main__":
156
+ opt = parse_opt()
157
+ main(opt)
utils/callbacks.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 'on_train_start': [],
18
+ 'on_train_epoch_start': [],
19
+ 'on_train_batch_start': [],
20
+ 'optimizer_step': [],
21
+ 'on_before_zero_grad': [],
22
+ 'on_train_batch_end': [],
23
+ 'on_train_epoch_end': [],
24
+ 'on_val_start': [],
25
+ 'on_val_batch_start': [],
26
+ 'on_val_image_end': [],
27
+ 'on_val_batch_end': [],
28
+ 'on_val_end': [],
29
+ 'on_fit_epoch_end': [], # fit = train + val
30
+ 'on_model_save': [],
31
+ 'on_train_end': [],
32
+ 'on_params_update': [],
33
+ 'teardown': [],}
34
+ self.stop_training = False # set True to interrupt training
35
+
36
+ def register_action(self, hook, name='', callback=None):
37
+ """
38
+ Register a new action to a callback hook
39
+
40
+ Args:
41
+ hook: The callback hook name to register the action to
42
+ name: The name of the action for later reference
43
+ callback: The callback to fire
44
+ """
45
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
46
+ assert callable(callback), f"callback '{callback}' is not callable"
47
+ self._callbacks[hook].append({'name': name, 'callback': callback})
48
+
49
+ def get_registered_actions(self, hook=None):
50
+ """"
51
+ Returns all the registered actions by callback hook
52
+
53
+ Args:
54
+ hook: The name of the hook to check, defaults to all
55
+ """
56
+ return self._callbacks[hook] if hook else self._callbacks
57
+
58
+ def run(self, hook, *args, **kwargs):
59
+ """
60
+ Loop through the registered actions and fire all callbacks
61
+
62
+ Args:
63
+ hook: The name of the hook to check, defaults to all
64
+ args: Arguments to receive from YOLOv5
65
+ kwargs: Keyword Arguments to receive from YOLOv5
66
+ """
67
+
68
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
69
+
70
+ for logger in self._callbacks[hook]:
71
+ logger['callback'](*args, **kwargs)
utils/dataloaders.py ADDED
@@ -0,0 +1,1096 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 numpy as np
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import yaml
25
+ from PIL import ExifTags, Image, ImageOps
26
+ from torch.utils.data import DataLoader, Dataset, dataloader, distributed
27
+ from tqdm import tqdm
28
+
29
+ from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
30
+ from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str,
31
+ cv2, is_colab, is_kaggle, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
32
+ from utils.torch_utils import torch_distributed_zero_first
33
+
34
+ # Parameters
35
+ HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
36
+ IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' # include image suffixes
37
+ VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes
38
+ BAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}' # tqdm bar format
39
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
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 in [6, 8]: # rotation 270 or 90
61
+ s = (s[1], s[0])
62
+ except Exception:
63
+ pass
64
+
65
+ return s
66
+
67
+
68
+ def exif_transpose(image):
69
+ """
70
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
71
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
72
+
73
+ :param image: The image to transpose.
74
+ :return: An image.
75
+ """
76
+ exif = image.getexif()
77
+ orientation = exif.get(0x0112, 1) # default 1
78
+ if orientation > 1:
79
+ method = {
80
+ 2: Image.FLIP_LEFT_RIGHT,
81
+ 3: Image.ROTATE_180,
82
+ 4: Image.FLIP_TOP_BOTTOM,
83
+ 5: Image.TRANSPOSE,
84
+ 6: Image.ROTATE_270,
85
+ 7: Image.TRANSVERSE,
86
+ 8: Image.ROTATE_90,}.get(orientation)
87
+ if method is not None:
88
+ image = image.transpose(method)
89
+ del exif[0x0112]
90
+ image.info["exif"] = exif.tobytes()
91
+ return image
92
+
93
+
94
+ def create_dataloader(path,
95
+ imgsz,
96
+ batch_size,
97
+ stride,
98
+ single_cls=False,
99
+ hyp=None,
100
+ augment=False,
101
+ cache=False,
102
+ pad=0.0,
103
+ rect=False,
104
+ rank=-1,
105
+ workers=8,
106
+ image_weights=False,
107
+ quad=False,
108
+ prefix='',
109
+ shuffle=False):
110
+ if rect and shuffle:
111
+ LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')
112
+ shuffle = False
113
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
114
+ dataset = LoadImagesAndLabels(
115
+ path,
116
+ imgsz,
117
+ batch_size,
118
+ augment=augment, # augmentation
119
+ hyp=hyp, # hyperparameters
120
+ rect=rect, # rectangular batches
121
+ cache_images=cache,
122
+ single_cls=single_cls,
123
+ stride=int(stride),
124
+ pad=pad,
125
+ image_weights=image_weights,
126
+ prefix=prefix)
127
+
128
+ batch_size = min(batch_size, len(dataset))
129
+ nd = torch.cuda.device_count() # number of CUDA devices
130
+ nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers
131
+ sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
132
+ loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
133
+ return loader(dataset,
134
+ batch_size=batch_size,
135
+ shuffle=shuffle and sampler is None,
136
+ num_workers=nw,
137
+ sampler=sampler,
138
+ pin_memory=True,
139
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset
140
+
141
+
142
+ class InfiniteDataLoader(dataloader.DataLoader):
143
+ """ Dataloader that reuses workers
144
+
145
+ Uses same syntax as vanilla DataLoader
146
+ """
147
+
148
+ def __init__(self, *args, **kwargs):
149
+ super().__init__(*args, **kwargs)
150
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
151
+ self.iterator = super().__iter__()
152
+
153
+ def __len__(self):
154
+ return len(self.batch_sampler.sampler)
155
+
156
+ def __iter__(self):
157
+ for _ in range(len(self)):
158
+ yield next(self.iterator)
159
+
160
+
161
+ class _RepeatSampler:
162
+ """ Sampler that repeats forever
163
+
164
+ Args:
165
+ sampler (Sampler)
166
+ """
167
+
168
+ def __init__(self, sampler):
169
+ self.sampler = sampler
170
+
171
+ def __iter__(self):
172
+ while True:
173
+ yield from iter(self.sampler)
174
+
175
+
176
+ class LoadImages:
177
+ # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
178
+ def __init__(self, path, img_size=640, stride=32, auto=True):
179
+ files = []
180
+ for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
181
+ p = str(Path(p).resolve())
182
+ if '*' in p:
183
+ files.extend(sorted(glob.glob(p, recursive=True))) # glob
184
+ elif os.path.isdir(p):
185
+ files.extend(sorted(glob.glob(os.path.join(p, '*.*')))) # dir
186
+ elif os.path.isfile(p):
187
+ files.append(p) # files
188
+ else:
189
+ raise FileNotFoundError(f'{p} does not exist')
190
+
191
+ images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
192
+ videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
193
+ ni, nv = len(images), len(videos)
194
+
195
+ self.img_size = img_size
196
+ self.stride = stride
197
+ self.files = images + videos
198
+ self.nf = ni + nv # number of files
199
+ self.video_flag = [False] * ni + [True] * nv
200
+ self.mode = 'image'
201
+ self.auto = auto
202
+ if any(videos):
203
+ self.new_video(videos[0]) # new video
204
+ else:
205
+ self.cap = None
206
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
207
+ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
208
+
209
+ def __iter__(self):
210
+ self.count = 0
211
+ return self
212
+
213
+ def __next__(self):
214
+ if self.count == self.nf:
215
+ raise StopIteration
216
+ path = self.files[self.count]
217
+
218
+ if self.video_flag[self.count]:
219
+ # Read video
220
+ self.mode = 'video'
221
+ ret_val, img0 = self.cap.read()
222
+ while not ret_val:
223
+ self.count += 1
224
+ self.cap.release()
225
+ if self.count == self.nf: # last video
226
+ raise StopIteration
227
+ path = self.files[self.count]
228
+ self.new_video(path)
229
+ ret_val, img0 = self.cap.read()
230
+
231
+ self.frame += 1
232
+ s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
233
+
234
+ else:
235
+ # Read image
236
+ self.count += 1
237
+ img0 = cv2.imread(path) # BGR
238
+ assert img0 is not None, f'Image Not Found {path}'
239
+ s = f'image {self.count}/{self.nf} {path}: '
240
+
241
+ # Padded resize
242
+ img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]
243
+
244
+ # Convert
245
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
246
+ img = np.ascontiguousarray(img)
247
+
248
+ return path, img, img0, self.cap, s
249
+
250
+ def new_video(self, path):
251
+ self.frame = 0
252
+ self.cap = cv2.VideoCapture(path)
253
+ self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
254
+
255
+ def __len__(self):
256
+ return self.nf # number of files
257
+
258
+
259
+ class LoadWebcam: # for inference
260
+ # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0`
261
+ def __init__(self, pipe='0', img_size=640, stride=32):
262
+ self.img_size = img_size
263
+ self.stride = stride
264
+ self.pipe = eval(pipe) if pipe.isnumeric() else pipe
265
+ self.cap = cv2.VideoCapture(self.pipe) # video capture object
266
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
267
+
268
+ def __iter__(self):
269
+ self.count = -1
270
+ return self
271
+
272
+ def __next__(self):
273
+ self.count += 1
274
+ if cv2.waitKey(1) == ord('q'): # q to quit
275
+ self.cap.release()
276
+ cv2.destroyAllWindows()
277
+ raise StopIteration
278
+
279
+ # Read frame
280
+ ret_val, img0 = self.cap.read()
281
+ img0 = cv2.flip(img0, 1) # flip left-right
282
+
283
+ # Print
284
+ assert ret_val, f'Camera Error {self.pipe}'
285
+ img_path = 'webcam.jpg'
286
+ s = f'webcam {self.count}: '
287
+
288
+ # Padded resize
289
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
290
+
291
+ # Convert
292
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
293
+ img = np.ascontiguousarray(img)
294
+
295
+ return img_path, img, img0, None, s
296
+
297
+ def __len__(self):
298
+ return 0
299
+
300
+
301
+ class LoadStreams:
302
+ # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`
303
+ def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):
304
+ self.mode = 'stream'
305
+ self.img_size = img_size
306
+ self.stride = stride
307
+
308
+ if os.path.isfile(sources):
309
+ with open(sources) as f:
310
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
311
+ else:
312
+ sources = [sources]
313
+
314
+ n = len(sources)
315
+ self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
316
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
317
+ self.auto = auto
318
+ for i, s in enumerate(sources): # index, source
319
+ # Start thread to read frames from video stream
320
+ st = f'{i + 1}/{n}: {s}... '
321
+ if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'): # if source is YouTube video
322
+ check_requirements(('pafy', 'youtube_dl==2020.12.2'))
323
+ import pafy
324
+ s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
325
+ s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
326
+ if s == 0:
327
+ assert not is_colab(), '--source 0 webcam unsupported on Colab. Rerun command in a local environment.'
328
+ assert not is_kaggle(), '--source 0 webcam unsupported on Kaggle. Rerun command in a local environment.'
329
+ cap = cv2.VideoCapture(s)
330
+ assert cap.isOpened(), f'{st}Failed to open {s}'
331
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
332
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
333
+ fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan
334
+ self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
335
+ self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback
336
+
337
+ _, self.imgs[i] = cap.read() # guarantee first frame
338
+ self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)
339
+ LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
340
+ self.threads[i].start()
341
+ LOGGER.info('') # newline
342
+
343
+ # check for common shapes
344
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
345
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
346
+ if not self.rect:
347
+ LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.')
348
+
349
+ def update(self, i, cap, stream):
350
+ # Read stream `i` frames in daemon thread
351
+ n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
352
+ while cap.isOpened() and n < f:
353
+ n += 1
354
+ # _, self.imgs[index] = cap.read()
355
+ cap.grab()
356
+ if n % read == 0:
357
+ success, im = cap.retrieve()
358
+ if success:
359
+ self.imgs[i] = im
360
+ else:
361
+ LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.')
362
+ self.imgs[i] = np.zeros_like(self.imgs[i])
363
+ cap.open(stream) # re-open stream if signal was lost
364
+ time.sleep(0.0) # wait time
365
+
366
+ def __iter__(self):
367
+ self.count = -1
368
+ return self
369
+
370
+ def __next__(self):
371
+ self.count += 1
372
+ if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
373
+ cv2.destroyAllWindows()
374
+ raise StopIteration
375
+
376
+ # Letterbox
377
+ img0 = self.imgs.copy()
378
+ img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]
379
+
380
+ # Stack
381
+ img = np.stack(img, 0)
382
+
383
+ # Convert
384
+ img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
385
+ img = np.ascontiguousarray(img)
386
+
387
+ return self.sources, img, img0, None, ''
388
+
389
+ def __len__(self):
390
+ return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
391
+
392
+
393
+ def img2label_paths(img_paths):
394
+ # Define label paths as a function of image paths
395
+ sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings
396
+ return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
397
+
398
+
399
+ class LoadImagesAndLabels(Dataset):
400
+ # YOLOv5 train_loader/val_loader, loads images and labels for training and validation
401
+ cache_version = 0.6 # dataset labels *.cache version
402
+ rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
403
+
404
+ def __init__(self,
405
+ path,
406
+ img_size=640,
407
+ batch_size=16,
408
+ augment=False,
409
+ hyp=None,
410
+ rect=False,
411
+ image_weights=False,
412
+ cache_images=False,
413
+ single_cls=False,
414
+ stride=32,
415
+ pad=0.0,
416
+ prefix=''):
417
+ self.img_size = img_size
418
+ self.augment = augment
419
+ self.hyp = hyp
420
+ self.image_weights = image_weights
421
+ self.rect = False if image_weights else rect
422
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
423
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
424
+ self.stride = stride
425
+ self.path = path
426
+ self.albumentations = Albumentations() if augment else None
427
+
428
+ try:
429
+ f = [] # image files
430
+ for p in path if isinstance(path, list) else [path]:
431
+ p = Path(p) # os-agnostic
432
+ if p.is_dir(): # dir
433
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
434
+ # f = list(p.rglob('*.*')) # pathlib
435
+ elif p.is_file(): # file
436
+ with open(p) as t:
437
+ t = t.read().strip().splitlines()
438
+ parent = str(p.parent) + os.sep
439
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
440
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
441
+ else:
442
+ raise FileNotFoundError(f'{prefix}{p} does not exist')
443
+ self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
444
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib
445
+ assert self.im_files, f'{prefix}No images found'
446
+ except Exception as e:
447
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}')
448
+
449
+ # Check cache
450
+ self.label_files = img2label_paths(self.im_files) # labels
451
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
452
+ try:
453
+ cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
454
+ assert cache['version'] == self.cache_version # matches current version
455
+ assert cache['hash'] == get_hash(self.label_files + self.im_files) # identical hash
456
+ except Exception:
457
+ cache, exists = self.cache_labels(cache_path, prefix), False # run cache ops
458
+
459
+ # Display cache
460
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total
461
+ if exists and LOCAL_RANK in {-1, 0}:
462
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt"
463
+ tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results
464
+ if cache['msgs']:
465
+ LOGGER.info('\n'.join(cache['msgs'])) # display warnings
466
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'
467
+
468
+ # Read cache
469
+ [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
470
+ labels, shapes, self.segments = zip(*cache.values())
471
+ self.labels = list(labels)
472
+ self.shapes = np.array(shapes, dtype=np.float64)
473
+ self.im_files = list(cache.keys()) # update
474
+ self.label_files = img2label_paths(cache.keys()) # update
475
+ n = len(shapes) # number of images
476
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
477
+ nb = bi[-1] + 1 # number of batches
478
+ self.batch = bi # batch index of image
479
+ self.n = n
480
+ self.indices = range(n)
481
+
482
+ # Update labels
483
+ include_class = [] # filter labels to include only these classes (optional)
484
+ include_class_array = np.array(include_class).reshape(1, -1)
485
+ for i, (label, segment) in enumerate(zip(self.labels, self.segments)):
486
+ if include_class:
487
+ j = (label[:, 0:1] == include_class_array).any(1)
488
+ self.labels[i] = label[j]
489
+ if segment:
490
+ self.segments[i] = segment[j]
491
+ if single_cls: # single-class training, merge all classes into 0
492
+ self.labels[i][:, 0] = 0
493
+ if segment:
494
+ self.segments[i][:, 0] = 0
495
+
496
+ # Rectangular Training
497
+ if self.rect:
498
+ # Sort by aspect ratio
499
+ s = self.shapes # wh
500
+ ar = s[:, 1] / s[:, 0] # aspect ratio
501
+ irect = ar.argsort()
502
+ self.im_files = [self.im_files[i] for i in irect]
503
+ self.label_files = [self.label_files[i] for i in irect]
504
+ self.labels = [self.labels[i] for i in irect]
505
+ self.shapes = s[irect] # wh
506
+ ar = ar[irect]
507
+
508
+ # Set training image shapes
509
+ shapes = [[1, 1]] * nb
510
+ for i in range(nb):
511
+ ari = ar[bi == i]
512
+ mini, maxi = ari.min(), ari.max()
513
+ if maxi < 1:
514
+ shapes[i] = [maxi, 1]
515
+ elif mini > 1:
516
+ shapes[i] = [1, 1 / mini]
517
+
518
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
519
+
520
+ # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources)
521
+ self.ims = [None] * n
522
+ self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]
523
+ if cache_images:
524
+ gb = 0 # Gigabytes of cached images
525
+ self.im_hw0, self.im_hw = [None] * n, [None] * n
526
+ fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image
527
+ results = ThreadPool(NUM_THREADS).imap(fcn, range(n))
528
+ pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT, disable=LOCAL_RANK > 0)
529
+ for i, x in pbar:
530
+ if cache_images == 'disk':
531
+ gb += self.npy_files[i].stat().st_size
532
+ else: # 'ram'
533
+ self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
534
+ gb += self.ims[i].nbytes
535
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'
536
+ pbar.close()
537
+
538
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
539
+ # Cache dataset labels, check images and read shapes
540
+ x = {} # dict
541
+ nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
542
+ desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
543
+ with Pool(NUM_THREADS) as pool:
544
+ pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),
545
+ desc=desc,
546
+ total=len(self.im_files),
547
+ bar_format=BAR_FORMAT)
548
+ for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
549
+ nm += nm_f
550
+ nf += nf_f
551
+ ne += ne_f
552
+ nc += nc_f
553
+ if im_file:
554
+ x[im_file] = [lb, shape, segments]
555
+ if msg:
556
+ msgs.append(msg)
557
+ pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt"
558
+
559
+ pbar.close()
560
+ if msgs:
561
+ LOGGER.info('\n'.join(msgs))
562
+ if nf == 0:
563
+ LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')
564
+ x['hash'] = get_hash(self.label_files + self.im_files)
565
+ x['results'] = nf, nm, ne, nc, len(self.im_files)
566
+ x['msgs'] = msgs # warnings
567
+ x['version'] = self.cache_version # cache version
568
+ try:
569
+ np.save(path, x) # save cache for next time
570
+ path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
571
+ LOGGER.info(f'{prefix}New cache created: {path}')
572
+ except Exception as e:
573
+ LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable
574
+ return x
575
+
576
+ def __len__(self):
577
+ return len(self.im_files)
578
+
579
+ # def __iter__(self):
580
+ # self.count = -1
581
+ # print('ran dataset iter')
582
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
583
+ # return self
584
+
585
+ def __getitem__(self, index):
586
+ index = self.indices[index] # linear, shuffled, or image_weights
587
+
588
+ hyp = self.hyp
589
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
590
+ if mosaic:
591
+ # Load mosaic
592
+ img, labels = self.load_mosaic(index)
593
+ shapes = None
594
+
595
+ # MixUp augmentation
596
+ if random.random() < hyp['mixup']:
597
+ img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1)))
598
+
599
+ else:
600
+ # Load image
601
+ img, (h0, w0), (h, w) = self.load_image(index)
602
+
603
+ # Letterbox
604
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
605
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
606
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
607
+
608
+ labels = self.labels[index].copy()
609
+ if labels.size: # normalized xywh to pixel xyxy format
610
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
611
+
612
+ if self.augment:
613
+ img, labels = random_perspective(img,
614
+ labels,
615
+ degrees=hyp['degrees'],
616
+ translate=hyp['translate'],
617
+ scale=hyp['scale'],
618
+ shear=hyp['shear'],
619
+ perspective=hyp['perspective'])
620
+
621
+ nl = len(labels) # number of labels
622
+ if nl:
623
+ labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
624
+
625
+ if self.augment:
626
+ # Albumentations
627
+ img, labels = self.albumentations(img, labels)
628
+ nl = len(labels) # update after albumentations
629
+
630
+ # HSV color-space
631
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
632
+
633
+ # Flip up-down
634
+ if random.random() < hyp['flipud']:
635
+ img = np.flipud(img)
636
+ if nl:
637
+ labels[:, 2] = 1 - labels[:, 2]
638
+
639
+ # Flip left-right
640
+ if random.random() < hyp['fliplr']:
641
+ img = np.fliplr(img)
642
+ if nl:
643
+ labels[:, 1] = 1 - labels[:, 1]
644
+
645
+ # Cutouts
646
+ # labels = cutout(img, labels, p=0.5)
647
+ # nl = len(labels) # update after cutout
648
+
649
+ labels_out = torch.zeros((nl, 6))
650
+ if nl:
651
+ labels_out[:, 1:] = torch.from_numpy(labels)
652
+
653
+ # Convert
654
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
655
+ img = np.ascontiguousarray(img)
656
+
657
+ return torch.from_numpy(img), labels_out, self.im_files[index], shapes
658
+
659
+ def load_image(self, i):
660
+ # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw)
661
+ im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],
662
+ if im is None: # not cached in RAM
663
+ if fn.exists(): # load npy
664
+ im = np.load(fn)
665
+ else: # read image
666
+ im = cv2.imread(f) # BGR
667
+ assert im is not None, f'Image Not Found {f}'
668
+ h0, w0 = im.shape[:2] # orig hw
669
+ r = self.img_size / max(h0, w0) # ratio
670
+ if r != 1: # if sizes are not equal
671
+ interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA
672
+ im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=interp)
673
+ return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
674
+ else:
675
+ return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized
676
+
677
+ def cache_images_to_disk(self, i):
678
+ # Saves an image as an *.npy file for faster loading
679
+ f = self.npy_files[i]
680
+ if not f.exists():
681
+ np.save(f.as_posix(), cv2.imread(self.im_files[i]))
682
+
683
+ def load_mosaic(self, index):
684
+ # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
685
+ labels4, segments4 = [], []
686
+ s = self.img_size
687
+ yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
688
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
689
+ random.shuffle(indices)
690
+ for i, index in enumerate(indices):
691
+ # Load image
692
+ img, _, (h, w) = self.load_image(index)
693
+
694
+ # place img in img4
695
+ if i == 0: # top left
696
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
697
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
698
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
699
+ elif i == 1: # top right
700
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
701
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
702
+ elif i == 2: # bottom left
703
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
704
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
705
+ elif i == 3: # bottom right
706
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
707
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
708
+
709
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
710
+ padw = x1a - x1b
711
+ padh = y1a - y1b
712
+
713
+ # Labels
714
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
715
+ if labels.size:
716
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
717
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
718
+ labels4.append(labels)
719
+ segments4.extend(segments)
720
+
721
+ # Concat/clip labels
722
+ labels4 = np.concatenate(labels4, 0)
723
+ for x in (labels4[:, 1:], *segments4):
724
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
725
+ # img4, labels4 = replicate(img4, labels4) # replicate
726
+
727
+ # Augment
728
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
729
+ img4, labels4 = random_perspective(img4,
730
+ labels4,
731
+ segments4,
732
+ degrees=self.hyp['degrees'],
733
+ translate=self.hyp['translate'],
734
+ scale=self.hyp['scale'],
735
+ shear=self.hyp['shear'],
736
+ perspective=self.hyp['perspective'],
737
+ border=self.mosaic_border) # border to remove
738
+
739
+ return img4, labels4
740
+
741
+ def load_mosaic9(self, index):
742
+ # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic
743
+ labels9, segments9 = [], []
744
+ s = self.img_size
745
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
746
+ random.shuffle(indices)
747
+ hp, wp = -1, -1 # height, width previous
748
+ for i, index in enumerate(indices):
749
+ # Load image
750
+ img, _, (h, w) = self.load_image(index)
751
+
752
+ # place img in img9
753
+ if i == 0: # center
754
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
755
+ h0, w0 = h, w
756
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
757
+ elif i == 1: # top
758
+ c = s, s - h, s + w, s
759
+ elif i == 2: # top right
760
+ c = s + wp, s - h, s + wp + w, s
761
+ elif i == 3: # right
762
+ c = s + w0, s, s + w0 + w, s + h
763
+ elif i == 4: # bottom right
764
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
765
+ elif i == 5: # bottom
766
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
767
+ elif i == 6: # bottom left
768
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
769
+ elif i == 7: # left
770
+ c = s - w, s + h0 - h, s, s + h0
771
+ elif i == 8: # top left
772
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
773
+
774
+ padx, pady = c[:2]
775
+ x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
776
+
777
+ # Labels
778
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
779
+ if labels.size:
780
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
781
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
782
+ labels9.append(labels)
783
+ segments9.extend(segments)
784
+
785
+ # Image
786
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
787
+ hp, wp = h, w # height, width previous
788
+
789
+ # Offset
790
+ yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y
791
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
792
+
793
+ # Concat/clip labels
794
+ labels9 = np.concatenate(labels9, 0)
795
+ labels9[:, [1, 3]] -= xc
796
+ labels9[:, [2, 4]] -= yc
797
+ c = np.array([xc, yc]) # centers
798
+ segments9 = [x - c for x in segments9]
799
+
800
+ for x in (labels9[:, 1:], *segments9):
801
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
802
+ # img9, labels9 = replicate(img9, labels9) # replicate
803
+
804
+ # Augment
805
+ img9, labels9 = random_perspective(img9,
806
+ labels9,
807
+ segments9,
808
+ degrees=self.hyp['degrees'],
809
+ translate=self.hyp['translate'],
810
+ scale=self.hyp['scale'],
811
+ shear=self.hyp['shear'],
812
+ perspective=self.hyp['perspective'],
813
+ border=self.mosaic_border) # border to remove
814
+
815
+ return img9, labels9
816
+
817
+ @staticmethod
818
+ def collate_fn(batch):
819
+ im, label, path, shapes = zip(*batch) # transposed
820
+ for i, lb in enumerate(label):
821
+ lb[:, 0] = i # add target image index for build_targets()
822
+ return torch.stack(im, 0), torch.cat(label, 0), path, shapes
823
+
824
+ @staticmethod
825
+ def collate_fn4(batch):
826
+ img, label, path, shapes = zip(*batch) # transposed
827
+ n = len(shapes) // 4
828
+ im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
829
+
830
+ ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])
831
+ wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])
832
+ s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale
833
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
834
+ i *= 4
835
+ if random.random() < 0.5:
836
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear',
837
+ align_corners=False)[0].type(img[i].type())
838
+ lb = label[i]
839
+ else:
840
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
841
+ lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
842
+ im4.append(im)
843
+ label4.append(lb)
844
+
845
+ for i, lb in enumerate(label4):
846
+ lb[:, 0] = i # add target image index for build_targets()
847
+
848
+ return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4
849
+
850
+
851
+ # Ancillary functions --------------------------------------------------------------------------------------------------
852
+ def create_folder(path='./new'):
853
+ # Create folder
854
+ if os.path.exists(path):
855
+ shutil.rmtree(path) # delete output folder
856
+ os.makedirs(path) # make new output folder
857
+
858
+
859
+ def flatten_recursive(path=DATASETS_DIR / 'coco128'):
860
+ # Flatten a recursive directory by bringing all files to top level
861
+ new_path = Path(str(path) + '_flat')
862
+ create_folder(new_path)
863
+ for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
864
+ shutil.copyfile(file, new_path / Path(file).name)
865
+
866
+
867
+ def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.dataloaders import *; extract_boxes()
868
+ # Convert detection dataset into classification dataset, with one directory per class
869
+ path = Path(path) # images dir
870
+ shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
871
+ files = list(path.rglob('*.*'))
872
+ n = len(files) # number of files
873
+ for im_file in tqdm(files, total=n):
874
+ if im_file.suffix[1:] in IMG_FORMATS:
875
+ # image
876
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
877
+ h, w = im.shape[:2]
878
+
879
+ # labels
880
+ lb_file = Path(img2label_paths([str(im_file)])[0])
881
+ if Path(lb_file).exists():
882
+ with open(lb_file) as f:
883
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
884
+
885
+ for j, x in enumerate(lb):
886
+ c = int(x[0]) # class
887
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
888
+ if not f.parent.is_dir():
889
+ f.parent.mkdir(parents=True)
890
+
891
+ b = x[1:] * [w, h, w, h] # box
892
+ # b[2:] = b[2:].max() # rectangle to square
893
+ b[2:] = b[2:] * 1.2 + 3 # pad
894
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
895
+
896
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
897
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
898
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
899
+
900
+
901
+ def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
902
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
903
+ Usage: from utils.dataloaders import *; autosplit()
904
+ Arguments
905
+ path: Path to images directory
906
+ weights: Train, val, test weights (list, tuple)
907
+ annotated_only: Only use images with an annotated txt file
908
+ """
909
+ path = Path(path) # images dir
910
+ files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only
911
+ n = len(files) # number of files
912
+ random.seed(0) # for reproducibility
913
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
914
+
915
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
916
+ [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
917
+
918
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
919
+ for i, img in tqdm(zip(indices, files), total=n):
920
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
921
+ with open(path.parent / txt[i], 'a') as f:
922
+ f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file
923
+
924
+
925
+ def verify_image_label(args):
926
+ # Verify one image-label pair
927
+ im_file, lb_file, prefix = args
928
+ nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
929
+ try:
930
+ # verify images
931
+ im = Image.open(im_file)
932
+ im.verify() # PIL verify
933
+ shape = exif_size(im) # image size
934
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
935
+ assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
936
+ if im.format.lower() in ('jpg', 'jpeg'):
937
+ with open(im_file, 'rb') as f:
938
+ f.seek(-2, 2)
939
+ if f.read() != b'\xff\xd9': # corrupt JPEG
940
+ ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
941
+ msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
942
+
943
+ # verify labels
944
+ if os.path.isfile(lb_file):
945
+ nf = 1 # label found
946
+ with open(lb_file) as f:
947
+ lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
948
+ if any(len(x) > 6 for x in lb): # is segment
949
+ classes = np.array([x[0] for x in lb], dtype=np.float32)
950
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
951
+ lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
952
+ lb = np.array(lb, dtype=np.float32)
953
+ nl = len(lb)
954
+ if nl:
955
+ assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'
956
+ assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'
957
+ assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'
958
+ _, i = np.unique(lb, axis=0, return_index=True)
959
+ if len(i) < nl: # duplicate row check
960
+ lb = lb[i] # remove duplicates
961
+ if segments:
962
+ segments = segments[i]
963
+ msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'
964
+ else:
965
+ ne = 1 # label empty
966
+ lb = np.zeros((0, 5), dtype=np.float32)
967
+ else:
968
+ nm = 1 # label missing
969
+ lb = np.zeros((0, 5), dtype=np.float32)
970
+ return im_file, lb, shape, segments, nm, nf, ne, nc, msg
971
+ except Exception as e:
972
+ nc = 1
973
+ msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'
974
+ return [None, None, None, None, nm, nf, ne, nc, msg]
975
+
976
+
977
+ def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False):
978
+ """ Return dataset statistics dictionary with images and instances counts per split per class
979
+ To run in parent directory: export PYTHONPATH="$PWD/yolov5"
980
+ Usage1: from utils.dataloaders import *; dataset_stats('coco128.yaml', autodownload=True)
981
+ Usage2: from utils.dataloaders import *; dataset_stats('path/to/coco128_with_yaml.zip')
982
+ Arguments
983
+ path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
984
+ autodownload: Attempt to download dataset if not found locally
985
+ verbose: Print stats dictionary
986
+ """
987
+
988
+ def _round_labels(labels):
989
+ # Update labels to integer class and 6 decimal place floats
990
+ return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
991
+
992
+ def _find_yaml(dir):
993
+ # Return data.yaml file
994
+ files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml')) # try root level first and then recursive
995
+ assert files, f'No *.yaml file found in {dir}'
996
+ if len(files) > 1:
997
+ files = [f for f in files if f.stem == dir.stem] # prefer *.yaml files that match dir name
998
+ assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed'
999
+ assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}'
1000
+ return files[0]
1001
+
1002
+ def _unzip(path):
1003
+ # Unzip data.zip
1004
+ if str(path).endswith('.zip'): # path is data.zip
1005
+ assert Path(path).is_file(), f'Error unzipping {path}, file not found'
1006
+ ZipFile(path).extractall(path=path.parent) # unzip
1007
+ dir = path.with_suffix('') # dataset directory == zip name
1008
+ assert dir.is_dir(), f'Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/'
1009
+ return True, str(dir), _find_yaml(dir) # zipped, data_dir, yaml_path
1010
+ else: # path is data.yaml
1011
+ return False, None, path
1012
+
1013
+ def _hub_ops(f, max_dim=1920):
1014
+ # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing
1015
+ f_new = im_dir / Path(f).name # dataset-hub image filename
1016
+ try: # use PIL
1017
+ im = Image.open(f)
1018
+ r = max_dim / max(im.height, im.width) # ratio
1019
+ if r < 1.0: # image too large
1020
+ im = im.resize((int(im.width * r), int(im.height * r)))
1021
+ im.save(f_new, 'JPEG', quality=75, optimize=True) # save
1022
+ except Exception as e: # use OpenCV
1023
+ print(f'WARNING: HUB ops PIL failure {f}: {e}')
1024
+ im = cv2.imread(f)
1025
+ im_height, im_width = im.shape[:2]
1026
+ r = max_dim / max(im_height, im_width) # ratio
1027
+ if r < 1.0: # image too large
1028
+ im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)
1029
+ cv2.imwrite(str(f_new), im)
1030
+
1031
+ zipped, data_dir, yaml_path = _unzip(Path(path))
1032
+ try:
1033
+ with open(check_yaml(yaml_path), errors='ignore') as f:
1034
+ data = yaml.safe_load(f) # data dict
1035
+ if zipped:
1036
+ data['path'] = data_dir # TODO: should this be dir.resolve()?`
1037
+ except Exception:
1038
+ raise Exception("error/HUB/dataset_stats/yaml_load")
1039
+
1040
+ check_dataset(data, autodownload) # download dataset if missing
1041
+ hub_dir = Path(data['path'] + ('-hub' if hub else ''))
1042
+ stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary
1043
+ for split in 'train', 'val', 'test':
1044
+ if data.get(split) is None:
1045
+ stats[split] = None # i.e. no test set
1046
+ continue
1047
+ x = []
1048
+ dataset = LoadImagesAndLabels(data[split]) # load dataset
1049
+ for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
1050
+ x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))
1051
+ x = np.array(x) # shape(128x80)
1052
+ stats[split] = {
1053
+ 'instance_stats': {
1054
+ 'total': int(x.sum()),
1055
+ 'per_class': x.sum(0).tolist()},
1056
+ 'image_stats': {
1057
+ 'total': dataset.n,
1058
+ 'unlabelled': int(np.all(x == 0, 1).sum()),
1059
+ 'per_class': (x > 0).sum(0).tolist()},
1060
+ 'labels': [{
1061
+ str(Path(k).name): _round_labels(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)]}
1062
+
1063
+ if hub:
1064
+ im_dir = hub_dir / 'images'
1065
+ im_dir.mkdir(parents=True, exist_ok=True)
1066
+ for _ in tqdm(ThreadPool(NUM_THREADS).imap(_hub_ops, dataset.im_files), total=dataset.n, desc='HUB Ops'):
1067
+ pass
1068
+
1069
+ # Profile
1070
+ stats_path = hub_dir / 'stats.json'
1071
+ if profile:
1072
+ for _ in range(1):
1073
+ file = stats_path.with_suffix('.npy')
1074
+ t1 = time.time()
1075
+ np.save(file, stats)
1076
+ t2 = time.time()
1077
+ x = np.load(file, allow_pickle=True)
1078
+ print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
1079
+
1080
+ file = stats_path.with_suffix('.json')
1081
+ t1 = time.time()
1082
+ with open(file, 'w') as f:
1083
+ json.dump(stats, f) # save stats *.json
1084
+ t2 = time.time()
1085
+ with open(file) as f:
1086
+ x = json.load(f) # load hyps dict
1087
+ print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
1088
+
1089
+ # Save, print and return
1090
+ if hub:
1091
+ print(f'Saving {stats_path.resolve()}...')
1092
+ with open(stats_path, 'w') as f:
1093
+ json.dump(stats, f) # save stats.json
1094
+ if verbose:
1095
+ print(json.dumps(stats, indent=2, sort_keys=False))
1096
+ return stats
utils/downloads.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Download utils
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ import platform
9
+ import subprocess
10
+ import time
11
+ import urllib
12
+ from pathlib import Path
13
+ from zipfile import ZipFile
14
+
15
+ import requests
16
+ import torch
17
+
18
+
19
+ def is_url(url):
20
+ # Check if online file exists
21
+ try:
22
+ r = urllib.request.urlopen(url) # response
23
+ return r.getcode() == 200
24
+ except urllib.request.HTTPError:
25
+ return False
26
+
27
+
28
+ def gsutil_getsize(url=''):
29
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
30
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
31
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
32
+
33
+
34
+ def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
35
+ # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
36
+ from utils.general import LOGGER
37
+
38
+ file = Path(file)
39
+ assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
40
+ try: # url1
41
+ LOGGER.info(f'Downloading {url} to {file}...')
42
+ torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
43
+ assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
44
+ except Exception as e: # url2
45
+ file.unlink(missing_ok=True) # remove partial downloads
46
+ LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
47
+ os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
48
+ finally:
49
+ if not file.exists() or file.stat().st_size < min_bytes: # check
50
+ file.unlink(missing_ok=True) # remove partial downloads
51
+ LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
52
+ LOGGER.info('')
53
+
54
+
55
+ def attempt_download(file, repo='ultralytics/yolov5', release='v6.1'):
56
+ # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.1', etc.
57
+ from utils.general import LOGGER
58
+
59
+ def github_assets(repository, version='latest'):
60
+ # Return GitHub repo tag (i.e. 'v6.1') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...])
61
+ if version != 'latest':
62
+ version = f'tags/{version}' # i.e. tags/v6.1
63
+ response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api
64
+ return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets
65
+
66
+ file = Path(str(file).strip().replace("'", ''))
67
+ if not file.exists():
68
+ # URL specified
69
+ name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
70
+ if str(file).startswith(('http:/', 'https:/')): # download
71
+ url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
72
+ file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
73
+ if Path(file).is_file():
74
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
75
+ else:
76
+ safe_download(file=file, url=url, min_bytes=1E5)
77
+ return file
78
+
79
+ # GitHub assets
80
+ assets = [
81
+ 'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt',
82
+ 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
83
+ try:
84
+ tag, assets = github_assets(repo, release)
85
+ except Exception:
86
+ try:
87
+ tag, assets = github_assets(repo) # latest release
88
+ except Exception:
89
+ try:
90
+ tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
91
+ except Exception:
92
+ tag = release
93
+
94
+ file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
95
+ if name in assets:
96
+ url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror
97
+ safe_download(
98
+ file,
99
+ url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
100
+ url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}', # backup url (optional)
101
+ min_bytes=1E5,
102
+ error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}')
103
+
104
+ return str(file)
105
+
106
+
107
+ def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
108
+ # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
109
+ t = time.time()
110
+ file = Path(file)
111
+ cookie = Path('cookie') # gdrive cookie
112
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
113
+ file.unlink(missing_ok=True) # remove existing file
114
+ cookie.unlink(missing_ok=True) # remove existing cookie
115
+
116
+ # Attempt file download
117
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
118
+ os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
119
+ if os.path.exists('cookie'): # large file
120
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
121
+ else: # small file
122
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
123
+ r = os.system(s) # execute, capture return
124
+ cookie.unlink(missing_ok=True) # remove existing cookie
125
+
126
+ # Error check
127
+ if r != 0:
128
+ file.unlink(missing_ok=True) # remove partial
129
+ print('Download error ') # raise Exception('Download error')
130
+ return r
131
+
132
+ # Unzip if archive
133
+ if file.suffix == '.zip':
134
+ print('unzipping... ', end='')
135
+ ZipFile(file).extractall(path=file.parent) # unzip
136
+ file.unlink() # remove zip
137
+
138
+ print(f'Done ({time.time() - t:.1f}s)')
139
+ return r
140
+
141
+
142
+ def get_token(cookie="./cookie"):
143
+ with open(cookie) as f:
144
+ for line in f:
145
+ if "download" in line:
146
+ return line.split()[-1]
147
+ return ""
148
+
149
+
150
+ # Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------
151
+ #
152
+ #
153
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
154
+ # # Uploads a file to a bucket
155
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
156
+ #
157
+ # storage_client = storage.Client()
158
+ # bucket = storage_client.get_bucket(bucket_name)
159
+ # blob = bucket.blob(destination_blob_name)
160
+ #
161
+ # blob.upload_from_filename(source_file_name)
162
+ #
163
+ # print('File {} uploaded to {}.'.format(
164
+ # source_file_name,
165
+ # destination_blob_name))
166
+ #
167
+ #
168
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
169
+ # # Uploads a blob from a bucket
170
+ # storage_client = storage.Client()
171
+ # bucket = storage_client.get_bucket(bucket_name)
172
+ # blob = bucket.blob(source_blob_name)
173
+ #
174
+ # blob.download_to_filename(destination_file_name)
175
+ #
176
+ # print('Blob {} downloaded to {}.'.format(
177
+ # source_blob_name,
178
+ # destination_file_name))
utils/general.py ADDED
@@ -0,0 +1,1026 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ General utils
4
+ """
5
+
6
+ import contextlib
7
+ import glob
8
+ import inspect
9
+ import logging
10
+ import math
11
+ import os
12
+ import platform
13
+ import random
14
+ import re
15
+ import shutil
16
+ import signal
17
+ import threading
18
+ import time
19
+ import urllib
20
+ from datetime import datetime
21
+ from itertools import repeat
22
+ from multiprocessing.pool import ThreadPool
23
+ from pathlib import Path
24
+ from subprocess import check_output
25
+ from typing import Optional
26
+ from zipfile import ZipFile
27
+
28
+ import cv2
29
+ import numpy as np
30
+ import pandas as pd
31
+ import pkg_resources as pkg
32
+ import torch
33
+ import torchvision
34
+ import yaml
35
+
36
+ from utils.downloads import gsutil_getsize
37
+ from utils.metrics import box_iou, fitness
38
+
39
+ FILE = Path(__file__).resolve()
40
+ ROOT = FILE.parents[1] # YOLOv5 root directory
41
+ RANK = int(os.getenv('RANK', -1))
42
+
43
+ # Settings
44
+ DATASETS_DIR = ROOT.parent / 'datasets' # YOLOv5 datasets directory
45
+ NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads
46
+ AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode
47
+ VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode
48
+ FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf
49
+
50
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
51
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
52
+ pd.options.display.max_columns = 10
53
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
54
+ os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads
55
+ os.environ['OMP_NUM_THREADS'] = str(NUM_THREADS) # OpenMP max threads (PyTorch and SciPy)
56
+
57
+
58
+ def is_kaggle():
59
+ # Is environment a Kaggle Notebook?
60
+ try:
61
+ assert os.environ.get('PWD') == '/kaggle/working'
62
+ assert os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'
63
+ return True
64
+ except AssertionError:
65
+ return False
66
+
67
+
68
+ def is_writeable(dir, test=False):
69
+ # Return True if directory has write permissions, test opening a file with write permissions if test=True
70
+ if not test:
71
+ return os.access(dir, os.R_OK) # possible issues on Windows
72
+ file = Path(dir) / 'tmp.txt'
73
+ try:
74
+ with open(file, 'w'): # open file with write permissions
75
+ pass
76
+ file.unlink() # remove file
77
+ return True
78
+ except OSError:
79
+ return False
80
+
81
+
82
+ def set_logging(name=None, verbose=VERBOSE):
83
+ # Sets level and returns logger
84
+ if is_kaggle():
85
+ for h in logging.root.handlers:
86
+ logging.root.removeHandler(h) # remove all handlers associated with the root logger object
87
+ rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
88
+ level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
89
+ log = logging.getLogger(name)
90
+ log.setLevel(level)
91
+ handler = logging.StreamHandler()
92
+ handler.setFormatter(logging.Formatter("%(message)s"))
93
+ handler.setLevel(level)
94
+ log.addHandler(handler)
95
+
96
+
97
+ set_logging() # run before defining LOGGER
98
+ LOGGER = logging.getLogger("yolov5") # define globally (used in train.py, val.py, detect.py, etc.)
99
+
100
+
101
+ def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):
102
+ # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.
103
+ env = os.getenv(env_var)
104
+ if env:
105
+ path = Path(env) # use environment variable
106
+ else:
107
+ cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs
108
+ path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir
109
+ path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable
110
+ path.mkdir(exist_ok=True) # make if required
111
+ return path
112
+
113
+
114
+ CONFIG_DIR = user_config_dir() # Ultralytics settings dir
115
+
116
+
117
+ class Profile(contextlib.ContextDecorator):
118
+ # Usage: @Profile() decorator or 'with Profile():' context manager
119
+ def __enter__(self):
120
+ self.start = time.time()
121
+
122
+ def __exit__(self, type, value, traceback):
123
+ print(f'Profile results: {time.time() - self.start:.5f}s')
124
+
125
+
126
+ class Timeout(contextlib.ContextDecorator):
127
+ # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
128
+ def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):
129
+ self.seconds = int(seconds)
130
+ self.timeout_message = timeout_msg
131
+ self.suppress = bool(suppress_timeout_errors)
132
+
133
+ def _timeout_handler(self, signum, frame):
134
+ raise TimeoutError(self.timeout_message)
135
+
136
+ def __enter__(self):
137
+ if platform.system() != 'Windows': # not supported on Windows
138
+ signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM
139
+ signal.alarm(self.seconds) # start countdown for SIGALRM to be raised
140
+
141
+ def __exit__(self, exc_type, exc_val, exc_tb):
142
+ if platform.system() != 'Windows':
143
+ signal.alarm(0) # Cancel SIGALRM if it's scheduled
144
+ if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError
145
+ return True
146
+
147
+
148
+ class WorkingDirectory(contextlib.ContextDecorator):
149
+ # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager
150
+ def __init__(self, new_dir):
151
+ self.dir = new_dir # new dir
152
+ self.cwd = Path.cwd().resolve() # current dir
153
+
154
+ def __enter__(self):
155
+ os.chdir(self.dir)
156
+
157
+ def __exit__(self, exc_type, exc_val, exc_tb):
158
+ os.chdir(self.cwd)
159
+
160
+
161
+ def try_except(func):
162
+ # try-except function. Usage: @try_except decorator
163
+ def handler(*args, **kwargs):
164
+ try:
165
+ func(*args, **kwargs)
166
+ except Exception as e:
167
+ print(e)
168
+
169
+ return handler
170
+
171
+
172
+ def threaded(func):
173
+ # Multi-threads a target function and returns thread. Usage: @threaded decorator
174
+ def wrapper(*args, **kwargs):
175
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
176
+ thread.start()
177
+ return thread
178
+
179
+ return wrapper
180
+
181
+
182
+ def methods(instance):
183
+ # Get class/instance methods
184
+ return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]
185
+
186
+
187
+ def print_args(args: Optional[dict] = None, show_file=True, show_fcn=False):
188
+ # Print function arguments (optional args dict)
189
+ x = inspect.currentframe().f_back # previous frame
190
+ file, _, fcn, _, _ = inspect.getframeinfo(x)
191
+ if args is None: # get args automatically
192
+ args, _, _, frm = inspect.getargvalues(x)
193
+ args = {k: v for k, v in frm.items() if k in args}
194
+ s = (f'{Path(file).stem}: ' if show_file else '') + (f'{fcn}: ' if show_fcn else '')
195
+ LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items()))
196
+
197
+
198
+ def init_seeds(seed=0, deterministic=False):
199
+ # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html
200
+ # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible
201
+ import torch.backends.cudnn as cudnn
202
+
203
+ if deterministic and check_version(torch.__version__, '1.12.0'): # https://github.com/ultralytics/yolov5/pull/8213
204
+ torch.use_deterministic_algorithms(True)
205
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
206
+ # os.environ['PYTHONHASHSEED'] = str(seed)
207
+
208
+ random.seed(seed)
209
+ np.random.seed(seed)
210
+ torch.manual_seed(seed)
211
+ cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False)
212
+ # torch.cuda.manual_seed(seed)
213
+ # torch.cuda.manual_seed_all(seed) # for multi GPU, exception safe
214
+
215
+
216
+ def intersect_dicts(da, db, exclude=()):
217
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
218
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
219
+
220
+
221
+ def get_latest_run(search_dir='.'):
222
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
223
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
224
+ return max(last_list, key=os.path.getctime) if last_list else ''
225
+
226
+
227
+ def is_docker():
228
+ # Is environment a Docker container?
229
+ return Path('/workspace').exists() # or Path('/.dockerenv').exists()
230
+
231
+
232
+ def is_colab():
233
+ # Is environment a Google Colab instance?
234
+ try:
235
+ import google.colab
236
+ return True
237
+ except ImportError:
238
+ return False
239
+
240
+
241
+ def is_pip():
242
+ # Is file in a pip package?
243
+ return 'site-packages' in Path(__file__).resolve().parts
244
+
245
+
246
+ def is_ascii(s=''):
247
+ # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7)
248
+ s = str(s) # convert list, tuple, None, etc. to str
249
+ return len(s.encode().decode('ascii', 'ignore')) == len(s)
250
+
251
+
252
+ def is_chinese(s='人工智能'):
253
+ # Is string composed of any Chinese characters?
254
+ return bool(re.search('[\u4e00-\u9fff]', str(s)))
255
+
256
+
257
+ def emojis(str=''):
258
+ # Return platform-dependent emoji-safe version of string
259
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
260
+
261
+
262
+ def file_age(path=__file__):
263
+ # Return days since last file update
264
+ dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)) # delta
265
+ return dt.days # + dt.seconds / 86400 # fractional days
266
+
267
+
268
+ def file_date(path=__file__):
269
+ # Return human-readable file modification date, i.e. '2021-3-26'
270
+ t = datetime.fromtimestamp(Path(path).stat().st_mtime)
271
+ return f'{t.year}-{t.month}-{t.day}'
272
+
273
+
274
+ def file_size(path):
275
+ # Return file/dir size (MB)
276
+ mb = 1 << 20 # bytes to MiB (1024 ** 2)
277
+ path = Path(path)
278
+ if path.is_file():
279
+ return path.stat().st_size / mb
280
+ elif path.is_dir():
281
+ return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb
282
+ else:
283
+ return 0.0
284
+
285
+
286
+ def check_online():
287
+ # Check internet connectivity
288
+ import socket
289
+ try:
290
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility
291
+ return True
292
+ except OSError:
293
+ return False
294
+
295
+
296
+ def git_describe(path=ROOT): # path must be a directory
297
+ # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
298
+ try:
299
+ assert (Path(path) / '.git').is_dir()
300
+ return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]
301
+ except Exception:
302
+ return ''
303
+
304
+
305
+ @try_except
306
+ @WorkingDirectory(ROOT)
307
+ def check_git_status():
308
+ # Recommend 'git pull' if code is out of date
309
+ msg = ', for updates see https://github.com/ultralytics/yolov5'
310
+ s = colorstr('github: ') # string
311
+ assert Path('.git').exists(), s + 'skipping check (not a git repository)' + msg
312
+ assert not is_docker(), s + 'skipping check (Docker image)' + msg
313
+ assert check_online(), s + 'skipping check (offline)' + msg
314
+
315
+ cmd = 'git fetch && git config --get remote.origin.url'
316
+ url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip('.git') # git fetch
317
+ branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
318
+ n = int(check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind
319
+ if n > 0:
320
+ s += f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update."
321
+ else:
322
+ s += f'up to date with {url} ✅'
323
+ LOGGER.info(emojis(s)) # emoji-safe
324
+
325
+
326
+ def check_python(minimum='3.7.0'):
327
+ # Check current python version vs. required python version
328
+ check_version(platform.python_version(), minimum, name='Python ', hard=True)
329
+
330
+
331
+ def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):
332
+ # Check version vs. required version
333
+ current, minimum = (pkg.parse_version(x) for x in (current, minimum))
334
+ result = (current == minimum) if pinned else (current >= minimum) # bool
335
+ s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string
336
+ if hard:
337
+ assert result, s # assert min requirements met
338
+ if verbose and not result:
339
+ LOGGER.warning(s)
340
+ return result
341
+
342
+
343
+ @try_except
344
+ def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=()):
345
+ # Check installed dependencies meet requirements (pass *.txt file or list of packages)
346
+ prefix = colorstr('red', 'bold', 'requirements:')
347
+ check_python() # check python version
348
+ if isinstance(requirements, (str, Path)): # requirements.txt file
349
+ file = Path(requirements)
350
+ assert file.exists(), f"{prefix} {file.resolve()} not found, check failed."
351
+ with file.open() as f:
352
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]
353
+ else: # list or tuple of packages
354
+ requirements = [x for x in requirements if x not in exclude]
355
+
356
+ n = 0 # number of packages updates
357
+ for i, r in enumerate(requirements):
358
+ try:
359
+ pkg.require(r)
360
+ except Exception: # DistributionNotFound or VersionConflict if requirements not met
361
+ s = f"{prefix} {r} not found and is required by YOLOv5"
362
+ if install and AUTOINSTALL: # check environment variable
363
+ LOGGER.info(f"{s}, attempting auto-update...")
364
+ try:
365
+ assert check_online(), f"'pip install {r}' skipped (offline)"
366
+ LOGGER.info(check_output(f'pip install "{r}" {cmds[i] if cmds else ""}', shell=True).decode())
367
+ n += 1
368
+ except Exception as e:
369
+ LOGGER.warning(f'{prefix} {e}')
370
+ else:
371
+ LOGGER.info(f'{s}. Please install and rerun your command.')
372
+
373
+ if n: # if packages updated
374
+ source = file.resolve() if 'file' in locals() else requirements
375
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
376
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
377
+ LOGGER.info(emojis(s))
378
+
379
+
380
+ def check_img_size(imgsz, s=32, floor=0):
381
+ # Verify image size is a multiple of stride s in each dimension
382
+ if isinstance(imgsz, int): # integer i.e. img_size=640
383
+ new_size = max(make_divisible(imgsz, int(s)), floor)
384
+ else: # list i.e. img_size=[640, 480]
385
+ imgsz = list(imgsz) # convert to list if tuple
386
+ new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]
387
+ if new_size != imgsz:
388
+ LOGGER.warning(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')
389
+ return new_size
390
+
391
+
392
+ def check_imshow():
393
+ # Check if environment supports image displays
394
+ try:
395
+ assert not is_docker(), 'cv2.imshow() is disabled in Docker environments'
396
+ assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments'
397
+ cv2.imshow('test', np.zeros((1, 1, 3)))
398
+ cv2.waitKey(1)
399
+ cv2.destroyAllWindows()
400
+ cv2.waitKey(1)
401
+ return True
402
+ except Exception as e:
403
+ LOGGER.warning(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')
404
+ return False
405
+
406
+
407
+ def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''):
408
+ # Check file(s) for acceptable suffix
409
+ if file and suffix:
410
+ if isinstance(suffix, str):
411
+ suffix = [suffix]
412
+ for f in file if isinstance(file, (list, tuple)) else [file]:
413
+ s = Path(f).suffix.lower() # file suffix
414
+ if len(s):
415
+ assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}"
416
+
417
+
418
+ def check_yaml(file, suffix=('.yaml', '.yml')):
419
+ # Search/download YAML file (if necessary) and return path, checking suffix
420
+ return check_file(file, suffix)
421
+
422
+
423
+ def check_file(file, suffix=''):
424
+ # Search/download file (if necessary) and return path
425
+ check_suffix(file, suffix) # optional
426
+ file = str(file) # convert to str()
427
+ if Path(file).is_file() or not file: # exists
428
+ return file
429
+ elif file.startswith(('http:/', 'https:/')): # download
430
+ url = file # warning: Pathlib turns :// -> :/
431
+ file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth
432
+ if Path(file).is_file():
433
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
434
+ else:
435
+ LOGGER.info(f'Downloading {url} to {file}...')
436
+ torch.hub.download_url_to_file(url, file)
437
+ assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check
438
+ return file
439
+ else: # search
440
+ files = []
441
+ for d in 'data', 'models', 'utils': # search directories
442
+ files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file
443
+ assert len(files), f'File not found: {file}' # assert file was found
444
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
445
+ return files[0] # return file
446
+
447
+
448
+ def check_font(font=FONT, progress=False):
449
+ # Download font to CONFIG_DIR if necessary
450
+ font = Path(font)
451
+ file = CONFIG_DIR / font.name
452
+ if not font.exists() and not file.exists():
453
+ url = "https://ultralytics.com/assets/" + font.name
454
+ LOGGER.info(f'Downloading {url} to {file}...')
455
+ torch.hub.download_url_to_file(url, str(file), progress=progress)
456
+
457
+
458
+ def check_dataset(data, autodownload=True):
459
+ # Download, check and/or unzip dataset if not found locally
460
+
461
+ # Download (optional)
462
+ extract_dir = ''
463
+ if isinstance(data, (str, Path)) and str(data).endswith('.zip'): # i.e. gs://bucket/dir/coco128.zip
464
+ download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False, threads=1)
465
+ data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml'))
466
+ extract_dir, autodownload = data.parent, False
467
+
468
+ # Read yaml (optional)
469
+ if isinstance(data, (str, Path)):
470
+ with open(data, errors='ignore') as f:
471
+ data = yaml.safe_load(f) # dictionary
472
+
473
+ # Checks
474
+ for k in 'train', 'val', 'nc':
475
+ assert k in data, emojis(f"data.yaml '{k}:' field missing ❌")
476
+ if 'names' not in data:
477
+ LOGGER.warning(emojis("data.yaml 'names:' field missing ⚠, assigning default names 'class0', 'class1', etc."))
478
+ data['names'] = [f'class{i}' for i in range(data['nc'])] # default names
479
+
480
+ # Resolve paths
481
+ path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.'
482
+ if not path.is_absolute():
483
+ path = (ROOT / path).resolve()
484
+ for k in 'train', 'val', 'test':
485
+ if data.get(k): # prepend path
486
+ data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]]
487
+
488
+ # Parse yaml
489
+ train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))
490
+ if val:
491
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
492
+ if not all(x.exists() for x in val):
493
+ LOGGER.info(emojis('\nDataset not found ⚠, missing paths %s' % [str(x) for x in val if not x.exists()]))
494
+ if not s or not autodownload:
495
+ raise Exception(emojis('Dataset not found ❌'))
496
+ t = time.time()
497
+ root = path.parent if 'path' in data else '..' # unzip directory i.e. '../'
498
+ if s.startswith('http') and s.endswith('.zip'): # URL
499
+ f = Path(s).name # filename
500
+ LOGGER.info(f'Downloading {s} to {f}...')
501
+ torch.hub.download_url_to_file(s, f)
502
+ Path(root).mkdir(parents=True, exist_ok=True) # create root
503
+ ZipFile(f).extractall(path=root) # unzip
504
+ Path(f).unlink() # remove zip
505
+ r = None # success
506
+ elif s.startswith('bash '): # bash script
507
+ LOGGER.info(f'Running {s} ...')
508
+ r = os.system(s)
509
+ else: # python script
510
+ r = exec(s, {'yaml': data}) # return None
511
+ dt = f'({round(time.time() - t, 1)}s)'
512
+ s = f"success ✅ {dt}, saved to {colorstr('bold', root)}" if r in (0, None) else f"failure {dt} ❌"
513
+ LOGGER.info(emojis(f"Dataset download {s}"))
514
+ check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts
515
+ return data # dictionary
516
+
517
+
518
+ def check_amp(model):
519
+ # Check PyTorch Automatic Mixed Precision (AMP) functionality. Return True on correct operation
520
+ from models.common import AutoShape, DetectMultiBackend
521
+
522
+ def amp_allclose(model, im):
523
+ # All close FP32 vs AMP results
524
+ m = AutoShape(model, verbose=False) # model
525
+ a = m(im).xywhn[0] # FP32 inference
526
+ m.amp = True
527
+ b = m(im).xywhn[0] # AMP inference
528
+ return a.shape == b.shape and torch.allclose(a, b, atol=0.1) # close to 10% absolute tolerance
529
+
530
+ prefix = colorstr('AMP: ')
531
+ device = next(model.parameters()).device # get model device
532
+ if device.type == 'cpu':
533
+ return False # AMP disabled on CPU
534
+ f = ROOT / 'data' / 'images' / 'bus.jpg' # image to check
535
+ im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if check_online() else np.ones((640, 640, 3))
536
+ try:
537
+ assert amp_allclose(model, im) or amp_allclose(DetectMultiBackend('yolov5n.pt', device), im)
538
+ LOGGER.info(emojis(f'{prefix}checks passed ✅'))
539
+ return True
540
+ except Exception:
541
+ help_url = 'https://github.com/ultralytics/yolov5/issues/7908'
542
+ LOGGER.warning(emojis(f'{prefix}checks failed ❌, disabling Automatic Mixed Precision. See {help_url}'))
543
+ return False
544
+
545
+
546
+ def url2file(url):
547
+ # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt
548
+ url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/
549
+ return Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth
550
+
551
+
552
+ def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3):
553
+ # Multi-threaded file download and unzip function, used in data.yaml for autodownload
554
+ def download_one(url, dir):
555
+ # Download 1 file
556
+ success = True
557
+ f = dir / Path(url).name # filename
558
+ if Path(url).is_file(): # exists in current path
559
+ Path(url).rename(f) # move to dir
560
+ elif not f.exists():
561
+ LOGGER.info(f'Downloading {url} to {f}...')
562
+ for i in range(retry + 1):
563
+ if curl:
564
+ s = 'sS' if threads > 1 else '' # silent
565
+ r = os.system(f'curl -{s}L "{url}" -o "{f}" --retry 9 -C -') # curl download with retry, continue
566
+ success = r == 0
567
+ else:
568
+ torch.hub.download_url_to_file(url, f, progress=threads == 1) # torch download
569
+ success = f.is_file()
570
+ if success:
571
+ break
572
+ elif i < retry:
573
+ LOGGER.warning(f'Download failure, retrying {i + 1}/{retry} {url}...')
574
+ else:
575
+ LOGGER.warning(f'Failed to download {url}...')
576
+
577
+ if unzip and success and f.suffix in ('.zip', '.gz'):
578
+ LOGGER.info(f'Unzipping {f}...')
579
+ if f.suffix == '.zip':
580
+ ZipFile(f).extractall(path=dir) # unzip
581
+ elif f.suffix == '.gz':
582
+ os.system(f'tar xfz {f} --directory {f.parent}') # unzip
583
+ if delete:
584
+ f.unlink() # remove zip
585
+
586
+ dir = Path(dir)
587
+ dir.mkdir(parents=True, exist_ok=True) # make directory
588
+ if threads > 1:
589
+ pool = ThreadPool(threads)
590
+ pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded
591
+ pool.close()
592
+ pool.join()
593
+ else:
594
+ for u in [url] if isinstance(url, (str, Path)) else url:
595
+ download_one(u, dir)
596
+
597
+
598
+ def make_divisible(x, divisor):
599
+ # Returns nearest x divisible by divisor
600
+ if isinstance(divisor, torch.Tensor):
601
+ divisor = int(divisor.max()) # to int
602
+ return math.ceil(x / divisor) * divisor
603
+
604
+
605
+ def clean_str(s):
606
+ # Cleans a string by replacing special characters with underscore _
607
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
608
+
609
+
610
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
611
+ # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf
612
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
613
+
614
+
615
+ def colorstr(*input):
616
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
617
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
618
+ colors = {
619
+ 'black': '\033[30m', # basic colors
620
+ 'red': '\033[31m',
621
+ 'green': '\033[32m',
622
+ 'yellow': '\033[33m',
623
+ 'blue': '\033[34m',
624
+ 'magenta': '\033[35m',
625
+ 'cyan': '\033[36m',
626
+ 'white': '\033[37m',
627
+ 'bright_black': '\033[90m', # bright colors
628
+ 'bright_red': '\033[91m',
629
+ 'bright_green': '\033[92m',
630
+ 'bright_yellow': '\033[93m',
631
+ 'bright_blue': '\033[94m',
632
+ 'bright_magenta': '\033[95m',
633
+ 'bright_cyan': '\033[96m',
634
+ 'bright_white': '\033[97m',
635
+ 'end': '\033[0m', # misc
636
+ 'bold': '\033[1m',
637
+ 'underline': '\033[4m'}
638
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
639
+
640
+
641
+ def labels_to_class_weights(labels, nc=80):
642
+ # Get class weights (inverse frequency) from training labels
643
+ if labels[0] is None: # no labels loaded
644
+ return torch.Tensor()
645
+
646
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
647
+ classes = labels[:, 0].astype(int) # labels = [class xywh]
648
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
649
+
650
+ # Prepend gridpoint count (for uCE training)
651
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
652
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
653
+
654
+ weights[weights == 0] = 1 # replace empty bins with 1
655
+ weights = 1 / weights # number of targets per class
656
+ weights /= weights.sum() # normalize
657
+ return torch.from_numpy(weights).float()
658
+
659
+
660
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
661
+ # Produces image weights based on class_weights and image contents
662
+ # Usage: index = random.choices(range(n), weights=image_weights, k=1) # weighted image sample
663
+ class_counts = np.array([np.bincount(x[:, 0].astype(int), minlength=nc) for x in labels])
664
+ return (class_weights.reshape(1, nc) * class_counts).sum(1)
665
+
666
+
667
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
668
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
669
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
670
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
671
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
672
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
673
+ return [
674
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
675
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
676
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
677
+
678
+
679
+ def xyxy2xywh(x):
680
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
681
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
682
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
683
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
684
+ y[:, 2] = x[:, 2] - x[:, 0] # width
685
+ y[:, 3] = x[:, 3] - x[:, 1] # height
686
+ return y
687
+
688
+
689
+ def xywh2xyxy(x):
690
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
691
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
692
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
693
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
694
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
695
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
696
+ return y
697
+
698
+
699
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
700
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
701
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
702
+ y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
703
+ y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
704
+ y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
705
+ y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
706
+ return y
707
+
708
+
709
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
710
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
711
+ if clip:
712
+ clip_coords(x, (h - eps, w - eps)) # warning: inplace clip
713
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
714
+ y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center
715
+ y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center
716
+ y[:, 2] = (x[:, 2] - x[:, 0]) / w # width
717
+ y[:, 3] = (x[:, 3] - x[:, 1]) / h # height
718
+ return y
719
+
720
+
721
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
722
+ # Convert normalized segments into pixel segments, shape (n,2)
723
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
724
+ y[:, 0] = w * x[:, 0] + padw # top left x
725
+ y[:, 1] = h * x[:, 1] + padh # top left y
726
+ return y
727
+
728
+
729
+ def segment2box(segment, width=640, height=640):
730
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
731
+ x, y = segment.T # segment xy
732
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
733
+ x, y, = x[inside], y[inside]
734
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
735
+
736
+
737
+ def segments2boxes(segments):
738
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
739
+ boxes = []
740
+ for s in segments:
741
+ x, y = s.T # segment xy
742
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
743
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
744
+
745
+
746
+ def resample_segments(segments, n=1000):
747
+ # Up-sample an (n,2) segment
748
+ for i, s in enumerate(segments):
749
+ s = np.concatenate((s, s[0:1, :]), axis=0)
750
+ x = np.linspace(0, len(s) - 1, n)
751
+ xp = np.arange(len(s))
752
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
753
+ return segments
754
+
755
+
756
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
757
+ # Rescale coords (xyxy) from img1_shape to img0_shape
758
+ if ratio_pad is None: # calculate from img0_shape
759
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
760
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
761
+ else:
762
+ gain = ratio_pad[0][0]
763
+ pad = ratio_pad[1]
764
+
765
+ coords[:, [0, 2]] -= pad[0] # x padding
766
+ coords[:, [1, 3]] -= pad[1] # y padding
767
+ coords[:, :4] /= gain
768
+ clip_coords(coords, img0_shape)
769
+ return coords
770
+
771
+
772
+ def clip_coords(boxes, shape):
773
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
774
+ if isinstance(boxes, torch.Tensor): # faster individually
775
+ boxes[:, 0].clamp_(0, shape[1]) # x1
776
+ boxes[:, 1].clamp_(0, shape[0]) # y1
777
+ boxes[:, 2].clamp_(0, shape[1]) # x2
778
+ boxes[:, 3].clamp_(0, shape[0]) # y2
779
+ else: # np.array (faster grouped)
780
+ boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2
781
+ boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2
782
+
783
+
784
+ def non_max_suppression(prediction,
785
+ conf_thres=0.25,
786
+ iou_thres=0.45,
787
+ classes=None,
788
+ agnostic=False,
789
+ multi_label=False,
790
+ labels=(),
791
+ max_det=300):
792
+ """Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes
793
+
794
+ Returns:
795
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
796
+ """
797
+
798
+ bs = prediction.shape[0] # batch size
799
+ nc = prediction.shape[2] - 5 # number of classes
800
+ xc = prediction[..., 4] > conf_thres # candidates
801
+
802
+ # Checks
803
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
804
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
805
+
806
+ # Settings
807
+ # min_wh = 2 # (pixels) minimum box width and height
808
+ max_wh = 7680 # (pixels) maximum box width and height
809
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
810
+ time_limit = 0.3 + 0.03 * bs # seconds to quit after
811
+ redundant = True # require redundant detections
812
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
813
+ merge = False # use merge-NMS
814
+
815
+ t = time.time()
816
+ output = [torch.zeros((0, 6), device=prediction.device)] * bs
817
+ for xi, x in enumerate(prediction): # image index, image inference
818
+ # Apply constraints
819
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
820
+ x = x[xc[xi]] # confidence
821
+
822
+ # Cat apriori labels if autolabelling
823
+ if labels and len(labels[xi]):
824
+ lb = labels[xi]
825
+ v = torch.zeros((len(lb), nc + 5), device=x.device)
826
+ v[:, :4] = lb[:, 1:5] # box
827
+ v[:, 4] = 1.0 # conf
828
+ v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls
829
+ x = torch.cat((x, v), 0)
830
+
831
+ # If none remain process next image
832
+ if not x.shape[0]:
833
+ continue
834
+
835
+ # Compute conf
836
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
837
+
838
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
839
+ box = xywh2xyxy(x[:, :4])
840
+
841
+ # Detections matrix nx6 (xyxy, conf, cls)
842
+ if multi_label:
843
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
844
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
845
+ else: # best class only
846
+ conf, j = x[:, 5:].max(1, keepdim=True)
847
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
848
+
849
+ # Filter by class
850
+ if classes is not None:
851
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
852
+
853
+ # Apply finite constraint
854
+ # if not torch.isfinite(x).all():
855
+ # x = x[torch.isfinite(x).all(1)]
856
+
857
+ # Check shape
858
+ n = x.shape[0] # number of boxes
859
+ if not n: # no boxes
860
+ continue
861
+ elif n > max_nms: # excess boxes
862
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
863
+
864
+ # Batched NMS
865
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
866
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
867
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
868
+ if i.shape[0] > max_det: # limit detections
869
+ i = i[:max_det]
870
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
871
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
872
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
873
+ weights = iou * scores[None] # box weights
874
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
875
+ if redundant:
876
+ i = i[iou.sum(1) > 1] # require redundancy
877
+
878
+ output[xi] = x[i]
879
+ if (time.time() - t) > time_limit:
880
+ LOGGER.warning(f'WARNING: NMS time limit {time_limit:.3f}s exceeded')
881
+ break # time limit exceeded
882
+
883
+ return output
884
+
885
+
886
+ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
887
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
888
+ x = torch.load(f, map_location=torch.device('cpu'))
889
+ if x.get('ema'):
890
+ x['model'] = x['ema'] # replace model with ema
891
+ for k in 'optimizer', 'best_fitness', 'wandb_id', 'ema', 'updates': # keys
892
+ x[k] = None
893
+ x['epoch'] = -1
894
+ x['model'].half() # to FP16
895
+ for p in x['model'].parameters():
896
+ p.requires_grad = False
897
+ torch.save(x, s or f)
898
+ mb = os.path.getsize(s or f) / 1E6 # filesize
899
+ LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB")
900
+
901
+
902
+ def print_mutation(results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')):
903
+ evolve_csv = save_dir / 'evolve.csv'
904
+ evolve_yaml = save_dir / 'hyp_evolve.yaml'
905
+ keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss',
906
+ 'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys()) # [results + hyps]
907
+ keys = tuple(x.strip() for x in keys)
908
+ vals = results + tuple(hyp.values())
909
+ n = len(keys)
910
+
911
+ # Download (optional)
912
+ if bucket:
913
+ url = f'gs://{bucket}/evolve.csv'
914
+ if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0):
915
+ os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local
916
+
917
+ # Log to evolve.csv
918
+ s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header
919
+ with open(evolve_csv, 'a') as f:
920
+ f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n')
921
+
922
+ # Save yaml
923
+ with open(evolve_yaml, 'w') as f:
924
+ data = pd.read_csv(evolve_csv)
925
+ data = data.rename(columns=lambda x: x.strip()) # strip keys
926
+ i = np.argmax(fitness(data.values[:, :4])) #
927
+ generations = len(data)
928
+ f.write('# YOLOv5 Hyperparameter Evolution Results\n' + f'# Best generation: {i}\n' +
929
+ f'# Last generation: {generations - 1}\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) +
930
+ '\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n')
931
+ yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False)
932
+
933
+ # Print to screen
934
+ LOGGER.info(prefix + f'{generations} generations finished, current result:\n' + prefix +
935
+ ', '.join(f'{x.strip():>20s}' for x in keys) + '\n' + prefix + ', '.join(f'{x:20.5g}'
936
+ for x in vals) + '\n\n')
937
+
938
+ if bucket:
939
+ os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload
940
+
941
+
942
+ def apply_classifier(x, model, img, im0):
943
+ # Apply a second stage classifier to YOLO outputs
944
+ # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval()
945
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
946
+ for i, d in enumerate(x): # per image
947
+ if d is not None and len(d):
948
+ d = d.clone()
949
+
950
+ # Reshape and pad cutouts
951
+ b = xyxy2xywh(d[:, :4]) # boxes
952
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
953
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
954
+ d[:, :4] = xywh2xyxy(b).long()
955
+
956
+ # Rescale boxes from img_size to im0 size
957
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
958
+
959
+ # Classes
960
+ pred_cls1 = d[:, 5].long()
961
+ ims = []
962
+ for a in d:
963
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
964
+ im = cv2.resize(cutout, (224, 224)) # BGR
965
+
966
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
967
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
968
+ im /= 255 # 0 - 255 to 0.0 - 1.0
969
+ ims.append(im)
970
+
971
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
972
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
973
+
974
+ return x
975
+
976
+
977
+ def increment_path(path, exist_ok=False, sep='', mkdir=False):
978
+ # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
979
+ path = Path(path) # os-agnostic
980
+ if path.exists() and not exist_ok:
981
+ path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
982
+
983
+ # Method 1
984
+ for n in range(2, 9999):
985
+ p = f'{path}{sep}{n}{suffix}' # increment path
986
+ if not os.path.exists(p): #
987
+ break
988
+ path = Path(p)
989
+
990
+ # Method 2 (deprecated)
991
+ # dirs = glob.glob(f"{path}{sep}*") # similar paths
992
+ # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs]
993
+ # i = [int(m.groups()[0]) for m in matches if m] # indices
994
+ # n = max(i) + 1 if i else 2 # increment number
995
+ # path = Path(f"{path}{sep}{n}{suffix}") # increment path
996
+
997
+ if mkdir:
998
+ path.mkdir(parents=True, exist_ok=True) # make directory
999
+
1000
+ return path
1001
+
1002
+
1003
+ # OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------
1004
+ imshow_ = cv2.imshow # copy to avoid recursion errors
1005
+
1006
+
1007
+ def imread(path, flags=cv2.IMREAD_COLOR):
1008
+ return cv2.imdecode(np.fromfile(path, np.uint8), flags)
1009
+
1010
+
1011
+ def imwrite(path, im):
1012
+ try:
1013
+ cv2.imencode(Path(path).suffix, im)[1].tofile(path)
1014
+ return True
1015
+ except Exception:
1016
+ return False
1017
+
1018
+
1019
+ def imshow(path, im):
1020
+ imshow_(path.encode('unicode_escape').decode(), im)
1021
+
1022
+
1023
+ cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow # redefine
1024
+
1025
+ # Variables ------------------------------------------------------------------------------------------------------------
1026
+ NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm
utils/loss.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Loss functions
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ from utils.metrics import bbox_iou
10
+ from utils.torch_utils import de_parallel
11
+
12
+
13
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
14
+ # return positive, negative label smoothing BCE targets
15
+ return 1.0 - 0.5 * eps, 0.5 * eps
16
+
17
+
18
+ class BCEBlurWithLogitsLoss(nn.Module):
19
+ # BCEwithLogitLoss() with reduced missing label effects.
20
+ def __init__(self, alpha=0.05):
21
+ super().__init__()
22
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
23
+ self.alpha = alpha
24
+
25
+ def forward(self, pred, true):
26
+ loss = self.loss_fcn(pred, true)
27
+ pred = torch.sigmoid(pred) # prob from logits
28
+ dx = pred - true # reduce only missing label effects
29
+ # dx = (pred - true).abs() # reduce missing label and false label effects
30
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
31
+ loss *= alpha_factor
32
+ return loss.mean()
33
+
34
+
35
+ class FocalLoss(nn.Module):
36
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
37
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
38
+ super().__init__()
39
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
40
+ self.gamma = gamma
41
+ self.alpha = alpha
42
+ self.reduction = loss_fcn.reduction
43
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
44
+
45
+ def forward(self, pred, true):
46
+ loss = self.loss_fcn(pred, true)
47
+ # p_t = torch.exp(-loss)
48
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
49
+
50
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
51
+ pred_prob = torch.sigmoid(pred) # prob from logits
52
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
53
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
54
+ modulating_factor = (1.0 - p_t) ** self.gamma
55
+ loss *= alpha_factor * modulating_factor
56
+
57
+ if self.reduction == 'mean':
58
+ return loss.mean()
59
+ elif self.reduction == 'sum':
60
+ return loss.sum()
61
+ else: # 'none'
62
+ return loss
63
+
64
+
65
+ class QFocalLoss(nn.Module):
66
+ # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
67
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
68
+ super().__init__()
69
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
70
+ self.gamma = gamma
71
+ self.alpha = alpha
72
+ self.reduction = loss_fcn.reduction
73
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
74
+
75
+ def forward(self, pred, true):
76
+ loss = self.loss_fcn(pred, true)
77
+
78
+ pred_prob = torch.sigmoid(pred) # prob from logits
79
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
80
+ modulating_factor = torch.abs(true - pred_prob) ** self.gamma
81
+ loss *= alpha_factor * modulating_factor
82
+
83
+ if self.reduction == 'mean':
84
+ return loss.mean()
85
+ elif self.reduction == 'sum':
86
+ return loss.sum()
87
+ else: # 'none'
88
+ return loss
89
+
90
+
91
+ class ComputeLoss:
92
+ sort_obj_iou = False
93
+
94
+ # Compute losses
95
+ def __init__(self, model, autobalance=False):
96
+ device = next(model.parameters()).device # get model device
97
+ h = model.hyp # hyperparameters
98
+
99
+ # Define criteria
100
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
101
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
102
+
103
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
104
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
105
+
106
+ # Focal loss
107
+ g = h['fl_gamma'] # focal loss gamma
108
+ if g > 0:
109
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
110
+
111
+ m = de_parallel(model).model[-1] # Detect() module
112
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
113
+ self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
114
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
115
+ self.na = m.na # number of anchors
116
+ self.nc = m.nc # number of classes
117
+ self.nl = m.nl # number of layers
118
+ self.anchors = m.anchors
119
+ self.device = device
120
+
121
+ def __call__(self, p, targets): # predictions, targets
122
+ lcls = torch.zeros(1, device=self.device) # class loss
123
+ lbox = torch.zeros(1, device=self.device) # box loss
124
+ lobj = torch.zeros(1, device=self.device) # object loss
125
+ tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
126
+
127
+ # Losses
128
+ for i, pi in enumerate(p): # layer index, layer predictions
129
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
130
+ tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
131
+
132
+ n = b.shape[0] # number of targets
133
+ if n:
134
+ # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
135
+ pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
136
+
137
+ # Regression
138
+ pxy = pxy.sigmoid() * 2 - 0.5
139
+ pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
140
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
141
+ iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
142
+ lbox += (1.0 - iou).mean() # iou loss
143
+
144
+ # Objectness
145
+ iou = iou.detach().clamp(0).type(tobj.dtype)
146
+ if self.sort_obj_iou:
147
+ j = iou.argsort()
148
+ b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
149
+ if self.gr < 1:
150
+ iou = (1.0 - self.gr) + self.gr * iou
151
+ tobj[b, a, gj, gi] = iou # iou ratio
152
+
153
+ # Classification
154
+ if self.nc > 1: # cls loss (only if multiple classes)
155
+ t = torch.full_like(pcls, self.cn, device=self.device) # targets
156
+ t[range(n), tcls[i]] = self.cp
157
+ lcls += self.BCEcls(pcls, t) # BCE
158
+
159
+ # Append targets to text file
160
+ # with open('targets.txt', 'a') as file:
161
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
162
+
163
+ obji = self.BCEobj(pi[..., 4], tobj)
164
+ lobj += obji * self.balance[i] # obj loss
165
+ if self.autobalance:
166
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
167
+
168
+ if self.autobalance:
169
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
170
+ lbox *= self.hyp['box']
171
+ lobj *= self.hyp['obj']
172
+ lcls *= self.hyp['cls']
173
+ bs = tobj.shape[0] # batch size
174
+
175
+ return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
176
+
177
+ def build_targets(self, p, targets):
178
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
179
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
180
+ tcls, tbox, indices, anch = [], [], [], []
181
+ gain = torch.ones(7, device=self.device) # normalized to gridspace gain
182
+ ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
183
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
184
+
185
+ g = 0.5 # bias
186
+ off = torch.tensor(
187
+ [
188
+ [0, 0],
189
+ [1, 0],
190
+ [0, 1],
191
+ [-1, 0],
192
+ [0, -1], # j,k,l,m
193
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
194
+ ],
195
+ device=self.device).float() * g # offsets
196
+
197
+ for i in range(self.nl):
198
+ anchors, shape = self.anchors[i], p[i].shape
199
+ gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
200
+
201
+ # Match targets to anchors
202
+ t = targets * gain # shape(3,n,7)
203
+ if nt:
204
+ # Matches
205
+ r = t[..., 4:6] / anchors[:, None] # wh ratio
206
+ j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
207
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
208
+ t = t[j] # filter
209
+
210
+ # Offsets
211
+ gxy = t[:, 2:4] # grid xy
212
+ gxi = gain[[2, 3]] - gxy # inverse
213
+ j, k = ((gxy % 1 < g) & (gxy > 1)).T
214
+ l, m = ((gxi % 1 < g) & (gxi > 1)).T
215
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
216
+ t = t.repeat((5, 1, 1))[j]
217
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
218
+ else:
219
+ t = targets[0]
220
+ offsets = 0
221
+
222
+ # Define
223
+ bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
224
+ a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
225
+ gij = (gxy - offsets).long()
226
+ gi, gj = gij.T # grid indices
227
+
228
+ # Append
229
+ indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
230
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
231
+ anch.append(anchors[a]) # anchors
232
+ tcls.append(c) # class
233
+
234
+ return tcls, tbox, indices, anch
utils/metrics.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Model validation metrics
4
+ """
5
+
6
+ import math
7
+ import warnings
8
+ from pathlib import Path
9
+
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import torch
13
+
14
+
15
+ def fitness(x):
16
+ # Model fitness as a weighted combination of metrics
17
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
18
+ return (x[:, :4] * w).sum(1)
19
+
20
+
21
+ def smooth(y, f=0.05):
22
+ # Box filter of fraction f
23
+ nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
24
+ p = np.ones(nf // 2) # ones padding
25
+ yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
26
+ return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
27
+
28
+
29
+ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16):
30
+ """ Compute the average precision, given the recall and precision curves.
31
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
32
+ # Arguments
33
+ tp: True positives (nparray, nx1 or nx10).
34
+ conf: Objectness value from 0-1 (nparray).
35
+ pred_cls: Predicted object classes (nparray).
36
+ target_cls: True object classes (nparray).
37
+ plot: Plot precision-recall curve at mAP@0.5
38
+ save_dir: Plot save directory
39
+ # Returns
40
+ The average precision as computed in py-faster-rcnn.
41
+ """
42
+
43
+ # Sort by objectness
44
+ i = np.argsort(-conf)
45
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
46
+
47
+ # Find unique classes
48
+ unique_classes, nt = np.unique(target_cls, return_counts=True)
49
+ nc = unique_classes.shape[0] # number of classes, number of detections
50
+
51
+ # Create Precision-Recall curve and compute AP for each class
52
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
53
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
54
+ for ci, c in enumerate(unique_classes):
55
+ i = pred_cls == c
56
+ n_l = nt[ci] # number of labels
57
+ n_p = i.sum() # number of predictions
58
+ if n_p == 0 or n_l == 0:
59
+ continue
60
+
61
+ # Accumulate FPs and TPs
62
+ fpc = (1 - tp[i]).cumsum(0)
63
+ tpc = tp[i].cumsum(0)
64
+
65
+ # Recall
66
+ recall = tpc / (n_l + eps) # recall curve
67
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
68
+
69
+ # Precision
70
+ precision = tpc / (tpc + fpc) # precision curve
71
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
72
+
73
+ # AP from recall-precision curve
74
+ for j in range(tp.shape[1]):
75
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
76
+ if plot and j == 0:
77
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
78
+
79
+ # Compute F1 (harmonic mean of precision and recall)
80
+ f1 = 2 * p * r / (p + r + eps)
81
+ names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
82
+ names = dict(enumerate(names)) # to dict
83
+ if plot:
84
+ plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
85
+ plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
86
+ plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
87
+ plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
88
+
89
+ i = smooth(f1.mean(0), 0.1).argmax() # max F1 index
90
+ p, r, f1 = p[:, i], r[:, i], f1[:, i]
91
+ tp = (r * nt).round() # true positives
92
+ fp = (tp / (p + eps) - tp).round() # false positives
93
+ return tp, fp, p, r, f1, ap, unique_classes.astype(int)
94
+
95
+
96
+ def compute_ap(recall, precision):
97
+ """ Compute the average precision, given the recall and precision curves
98
+ # Arguments
99
+ recall: The recall curve (list)
100
+ precision: The precision curve (list)
101
+ # Returns
102
+ Average precision, precision curve, recall curve
103
+ """
104
+
105
+ # Append sentinel values to beginning and end
106
+ mrec = np.concatenate(([0.0], recall, [1.0]))
107
+ mpre = np.concatenate(([1.0], precision, [0.0]))
108
+
109
+ # Compute the precision envelope
110
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
111
+
112
+ # Integrate area under curve
113
+ method = 'interp' # methods: 'continuous', 'interp'
114
+ if method == 'interp':
115
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
116
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
117
+ else: # 'continuous'
118
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
119
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
120
+
121
+ return ap, mpre, mrec
122
+
123
+
124
+ class ConfusionMatrix:
125
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
126
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
127
+ self.matrix = np.zeros((nc + 1, nc + 1))
128
+ self.nc = nc # number of classes
129
+ self.conf = conf
130
+ self.iou_thres = iou_thres
131
+
132
+ def process_batch(self, detections, labels):
133
+ """
134
+ Return intersection-over-union (Jaccard index) of boxes.
135
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
136
+ Arguments:
137
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
138
+ labels (Array[M, 5]), class, x1, y1, x2, y2
139
+ Returns:
140
+ None, updates confusion matrix accordingly
141
+ """
142
+ detections = detections[detections[:, 4] > self.conf]
143
+ gt_classes = labels[:, 0].int()
144
+ detection_classes = detections[:, 5].int()
145
+ iou = box_iou(labels[:, 1:], detections[:, :4])
146
+
147
+ x = torch.where(iou > self.iou_thres)
148
+ if x[0].shape[0]:
149
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
150
+ if x[0].shape[0] > 1:
151
+ matches = matches[matches[:, 2].argsort()[::-1]]
152
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
153
+ matches = matches[matches[:, 2].argsort()[::-1]]
154
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
155
+ else:
156
+ matches = np.zeros((0, 3))
157
+
158
+ n = matches.shape[0] > 0
159
+ m0, m1, _ = matches.transpose().astype(int)
160
+ for i, gc in enumerate(gt_classes):
161
+ j = m0 == i
162
+ if n and sum(j) == 1:
163
+ self.matrix[detection_classes[m1[j]], gc] += 1 # correct
164
+ else:
165
+ self.matrix[self.nc, gc] += 1 # background FP
166
+
167
+ if n:
168
+ for i, dc in enumerate(detection_classes):
169
+ if not any(m1 == i):
170
+ self.matrix[dc, self.nc] += 1 # background FN
171
+
172
+ def matrix(self):
173
+ return self.matrix
174
+
175
+ def tp_fp(self):
176
+ tp = self.matrix.diagonal() # true positives
177
+ fp = self.matrix.sum(1) - tp # false positives
178
+ # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
179
+ return tp[:-1], fp[:-1] # remove background class
180
+
181
+ def plot(self, normalize=True, save_dir='', names=()):
182
+ try:
183
+ import seaborn as sn
184
+
185
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns
186
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
187
+
188
+ fig = plt.figure(figsize=(12, 9), tight_layout=True)
189
+ nc, nn = self.nc, len(names) # number of classes, names
190
+ sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
191
+ labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
192
+ with warnings.catch_warnings():
193
+ warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
194
+ sn.heatmap(array,
195
+ annot=nc < 30,
196
+ annot_kws={
197
+ "size": 8},
198
+ cmap='Blues',
199
+ fmt='.2f',
200
+ square=True,
201
+ vmin=0.0,
202
+ xticklabels=names + ['background FP'] if labels else "auto",
203
+ yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
204
+ fig.axes[0].set_xlabel('True')
205
+ fig.axes[0].set_ylabel('Predicted')
206
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
207
+ plt.close()
208
+ except Exception as e:
209
+ print(f'WARNING: ConfusionMatrix plot failure: {e}')
210
+
211
+ def print(self):
212
+ for i in range(self.nc + 1):
213
+ print(' '.join(map(str, self.matrix[i])))
214
+
215
+
216
+ def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
217
+ # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
218
+
219
+ # Get the coordinates of bounding boxes
220
+ if xywh: # transform from xywh to xyxy
221
+ (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, 1), box2.chunk(4, 1)
222
+ w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
223
+ b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
224
+ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
225
+ else: # x1, y1, x2, y2 = box1
226
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, 1)
227
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, 1)
228
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
229
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
230
+
231
+ # Intersection area
232
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
233
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
234
+
235
+ # Union Area
236
+ union = w1 * h1 + w2 * h2 - inter + eps
237
+
238
+ # IoU
239
+ iou = inter / union
240
+ if CIoU or DIoU or GIoU:
241
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
242
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
243
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
244
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
245
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
246
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
247
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / (h2 + eps)) - torch.atan(w1 / (h1 + eps)), 2)
248
+ with torch.no_grad():
249
+ alpha = v / (v - iou + (1 + eps))
250
+ return iou - (rho2 / c2 + v * alpha) # CIoU
251
+ return iou - rho2 / c2 # DIoU
252
+ c_area = cw * ch + eps # convex area
253
+ return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
254
+ return iou # IoU
255
+
256
+
257
+ def box_area(box):
258
+ # box = xyxy(4,n)
259
+ return (box[2] - box[0]) * (box[3] - box[1])
260
+
261
+
262
+ def box_iou(box1, box2, eps=1e-7):
263
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
264
+ """
265
+ Return intersection-over-union (Jaccard index) of boxes.
266
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
267
+ Arguments:
268
+ box1 (Tensor[N, 4])
269
+ box2 (Tensor[M, 4])
270
+ Returns:
271
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
272
+ IoU values for every element in boxes1 and boxes2
273
+ """
274
+
275
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
276
+ (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1)
277
+ inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)
278
+
279
+ # IoU = inter / (area1 + area2 - inter)
280
+ return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter + eps)
281
+
282
+
283
+ def bbox_ioa(box1, box2, eps=1e-7):
284
+ """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
285
+ box1: np.array of shape(4)
286
+ box2: np.array of shape(nx4)
287
+ returns: np.array of shape(n)
288
+ """
289
+
290
+ # Get the coordinates of bounding boxes
291
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1
292
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
293
+
294
+ # Intersection area
295
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
296
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
297
+
298
+ # box2 area
299
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
300
+
301
+ # Intersection over box2 area
302
+ return inter_area / box2_area
303
+
304
+
305
+ def wh_iou(wh1, wh2, eps=1e-7):
306
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
307
+ wh1 = wh1[:, None] # [N,1,2]
308
+ wh2 = wh2[None] # [1,M,2]
309
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
310
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter + eps) # iou = inter / (area1 + area2 - inter)
311
+
312
+
313
+ # Plots ----------------------------------------------------------------------------------------------------------------
314
+
315
+
316
+ def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
317
+ # Precision-recall curve
318
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
319
+ py = np.stack(py, axis=1)
320
+
321
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
322
+ for i, y in enumerate(py.T):
323
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
324
+ else:
325
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
326
+
327
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
328
+ ax.set_xlabel('Recall')
329
+ ax.set_ylabel('Precision')
330
+ ax.set_xlim(0, 1)
331
+ ax.set_ylim(0, 1)
332
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
333
+ fig.savefig(save_dir, dpi=250)
334
+ plt.close()
335
+
336
+
337
+ def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'):
338
+ # Metric-confidence curve
339
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
340
+
341
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
342
+ for i, y in enumerate(py):
343
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
344
+ else:
345
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
346
+
347
+ y = smooth(py.mean(0), 0.05)
348
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
349
+ ax.set_xlabel(xlabel)
350
+ ax.set_ylabel(ylabel)
351
+ ax.set_xlim(0, 1)
352
+ ax.set_ylim(0, 1)
353
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
354
+ fig.savefig(save_dir, dpi=250)
355
+ plt.close()
utils/plots.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Plotting utils
4
+ """
5
+
6
+ import math
7
+ import os
8
+ from copy import copy
9
+ from pathlib import Path
10
+ from urllib.error import URLError
11
+
12
+ import cv2
13
+ import matplotlib
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ import pandas as pd
17
+ import seaborn as sn
18
+ import torch
19
+ from PIL import Image, ImageDraw, ImageFont
20
+
21
+ from utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords,
22
+ increment_path, is_ascii, threaded, try_except, xywh2xyxy, xyxy2xywh)
23
+ from utils.metrics import fitness
24
+
25
+ # Settings
26
+ RANK = int(os.getenv('RANK', -1))
27
+ matplotlib.rc('font', **{'size': 11})
28
+ matplotlib.use('Agg') # for writing to files only
29
+
30
+
31
+ class Colors:
32
+ # Ultralytics color palette https://ultralytics.com/
33
+ def __init__(self):
34
+ # hex = matplotlib.colors.TABLEAU_COLORS.values()
35
+ hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
36
+ '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
37
+ self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
38
+ self.n = len(self.palette)
39
+
40
+ def __call__(self, i, bgr=False):
41
+ c = self.palette[int(i) % self.n]
42
+ return (c[2], c[1], c[0]) if bgr else c
43
+
44
+ @staticmethod
45
+ def hex2rgb(h): # rgb order (PIL)
46
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
47
+
48
+
49
+ colors = Colors() # create instance for 'from utils.plots import colors'
50
+
51
+
52
+ def check_pil_font(font=FONT, size=10):
53
+ # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary
54
+ font = Path(font)
55
+ font = font if font.exists() else (CONFIG_DIR / font.name)
56
+ try:
57
+ return ImageFont.truetype(str(font) if font.exists() else font.name, size)
58
+ except Exception: # download if missing
59
+ try:
60
+ check_font(font)
61
+ return ImageFont.truetype(str(font), size)
62
+ except TypeError:
63
+ check_requirements('Pillow>=8.4.0') # known issue https://github.com/ultralytics/yolov5/issues/5374
64
+ except URLError: # not online
65
+ return ImageFont.load_default()
66
+
67
+
68
+ class Annotator:
69
+ # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations
70
+ def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'):
71
+ assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'
72
+ non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic
73
+ self.pil = pil or non_ascii
74
+ if self.pil: # use PIL
75
+ self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
76
+ self.draw = ImageDraw.Draw(self.im)
77
+ self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font,
78
+ size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))
79
+ else: # use cv2
80
+ self.im = im
81
+ self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width
82
+
83
+ def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
84
+ # Add one xyxy box to image with label
85
+ if self.pil or not is_ascii(label):
86
+ self.draw.rectangle(box, width=self.lw, outline=color) # box
87
+ if label:
88
+ w, h = self.font.getsize(label) # text width, height
89
+ outside = box[1] - h >= 0 # label fits outside box
90
+ self.draw.rectangle(
91
+ (box[0], box[1] - h if outside else box[1], box[0] + w + 1,
92
+ box[1] + 1 if outside else box[1] + h + 1),
93
+ fill=color,
94
+ )
95
+ # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0
96
+ self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)
97
+ else: # cv2
98
+ p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
99
+ cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)
100
+ if label:
101
+ tf = max(self.lw - 1, 1) # font thickness
102
+ w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height
103
+ outside = p1[1] - h >= 3
104
+ p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
105
+ cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled
106
+ cv2.putText(self.im,
107
+ label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
108
+ 0,
109
+ self.lw / 3,
110
+ txt_color,
111
+ thickness=tf,
112
+ lineType=cv2.LINE_AA)
113
+
114
+ def rectangle(self, xy, fill=None, outline=None, width=1):
115
+ # Add rectangle to image (PIL-only)
116
+ self.draw.rectangle(xy, fill, outline, width)
117
+
118
+ def text(self, xy, text, txt_color=(255, 255, 255)):
119
+ # Add text to image (PIL-only)
120
+ w, h = self.font.getsize(text) # text width, height
121
+ self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font)
122
+
123
+ def result(self):
124
+ # Return annotated image as array
125
+ return np.asarray(self.im)
126
+
127
+
128
+ def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
129
+ """
130
+ x: Features to be visualized
131
+ module_type: Module type
132
+ stage: Module stage within model
133
+ n: Maximum number of feature maps to plot
134
+ save_dir: Directory to save results
135
+ """
136
+ if 'Detect' not in module_type:
137
+ batch, channels, height, width = x.shape # batch, channels, height, width
138
+ if height > 1 and width > 1:
139
+ f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
140
+
141
+ blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
142
+ n = min(n, channels) # number of plots
143
+ fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
144
+ ax = ax.ravel()
145
+ plt.subplots_adjust(wspace=0.05, hspace=0.05)
146
+ for i in range(n):
147
+ ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
148
+ ax[i].axis('off')
149
+
150
+ LOGGER.info(f'Saving {f}... ({n}/{channels})')
151
+ plt.savefig(f, dpi=300, bbox_inches='tight')
152
+ plt.close()
153
+ np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save
154
+
155
+
156
+ def hist2d(x, y, n=100):
157
+ # 2d histogram used in labels.png and evolve.png
158
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
159
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
160
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
161
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
162
+ return np.log(hist[xidx, yidx])
163
+
164
+
165
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
166
+ from scipy.signal import butter, filtfilt
167
+
168
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
169
+ def butter_lowpass(cutoff, fs, order):
170
+ nyq = 0.5 * fs
171
+ normal_cutoff = cutoff / nyq
172
+ return butter(order, normal_cutoff, btype='low', analog=False)
173
+
174
+ b, a = butter_lowpass(cutoff, fs, order=order)
175
+ return filtfilt(b, a, data) # forward-backward filter
176
+
177
+
178
+ def output_to_target(output):
179
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
180
+ targets = []
181
+ for i, o in enumerate(output):
182
+ for *box, conf, cls in o.cpu().numpy():
183
+ targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
184
+ return np.array(targets)
185
+
186
+
187
+ @threaded
188
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):
189
+ # Plot image grid with labels
190
+ if isinstance(images, torch.Tensor):
191
+ images = images.cpu().float().numpy()
192
+ if isinstance(targets, torch.Tensor):
193
+ targets = targets.cpu().numpy()
194
+ if np.max(images[0]) <= 1:
195
+ images *= 255 # de-normalise (optional)
196
+ bs, _, h, w = images.shape # batch size, _, height, width
197
+ bs = min(bs, max_subplots) # limit plot images
198
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
199
+
200
+ # Build Image
201
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
202
+ for i, im in enumerate(images):
203
+ if i == max_subplots: # if last batch has fewer images than we expect
204
+ break
205
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
206
+ im = im.transpose(1, 2, 0)
207
+ mosaic[y:y + h, x:x + w, :] = im
208
+
209
+ # Resize (optional)
210
+ scale = max_size / ns / max(h, w)
211
+ if scale < 1:
212
+ h = math.ceil(scale * h)
213
+ w = math.ceil(scale * w)
214
+ mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
215
+
216
+ # Annotate
217
+ fs = int((h + w) * ns * 0.01) # font size
218
+ annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)
219
+ for i in range(i + 1):
220
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
221
+ annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
222
+ if paths:
223
+ annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
224
+ if len(targets) > 0:
225
+ ti = targets[targets[:, 0] == i] # image targets
226
+ boxes = xywh2xyxy(ti[:, 2:6]).T
227
+ classes = ti[:, 1].astype('int')
228
+ labels = ti.shape[1] == 6 # labels if no conf column
229
+ conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
230
+
231
+ if boxes.shape[1]:
232
+ if boxes.max() <= 1.01: # if normalized with tolerance 0.01
233
+ boxes[[0, 2]] *= w # scale to pixels
234
+ boxes[[1, 3]] *= h
235
+ elif scale < 1: # absolute coords need scale if image scales
236
+ boxes *= scale
237
+ boxes[[0, 2]] += x
238
+ boxes[[1, 3]] += y
239
+ for j, box in enumerate(boxes.T.tolist()):
240
+ cls = classes[j]
241
+ color = colors(cls)
242
+ cls = names[cls] if names else cls
243
+ if labels or conf[j] > 0.25: # 0.25 conf thresh
244
+ label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'
245
+ annotator.box_label(box, label, color=color)
246
+ annotator.im.save(fname) # save
247
+
248
+
249
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
250
+ # Plot LR simulating training for full epochs
251
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
252
+ y = []
253
+ for _ in range(epochs):
254
+ scheduler.step()
255
+ y.append(optimizer.param_groups[0]['lr'])
256
+ plt.plot(y, '.-', label='LR')
257
+ plt.xlabel('epoch')
258
+ plt.ylabel('LR')
259
+ plt.grid()
260
+ plt.xlim(0, epochs)
261
+ plt.ylim(0)
262
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
263
+ plt.close()
264
+
265
+
266
+ def plot_val_txt(): # from utils.plots import *; plot_val()
267
+ # Plot val.txt histograms
268
+ x = np.loadtxt('val.txt', dtype=np.float32)
269
+ box = xyxy2xywh(x[:, :4])
270
+ cx, cy = box[:, 0], box[:, 1]
271
+
272
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
273
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
274
+ ax.set_aspect('equal')
275
+ plt.savefig('hist2d.png', dpi=300)
276
+
277
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
278
+ ax[0].hist(cx, bins=600)
279
+ ax[1].hist(cy, bins=600)
280
+ plt.savefig('hist1d.png', dpi=200)
281
+
282
+
283
+ def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
284
+ # Plot targets.txt histograms
285
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
286
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
287
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
288
+ ax = ax.ravel()
289
+ for i in range(4):
290
+ ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}')
291
+ ax[i].legend()
292
+ ax[i].set_title(s[i])
293
+ plt.savefig('targets.jpg', dpi=200)
294
+
295
+
296
+ def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()
297
+ # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)
298
+ save_dir = Path(file).parent if file else Path(dir)
299
+ plot2 = False # plot additional results
300
+ if plot2:
301
+ ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
302
+
303
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
304
+ # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
305
+ for f in sorted(save_dir.glob('study*.txt')):
306
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
307
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
308
+ if plot2:
309
+ s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
310
+ for i in range(7):
311
+ ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
312
+ ax[i].set_title(s[i])
313
+
314
+ j = y[3].argmax() + 1
315
+ ax2.plot(y[5, 1:j],
316
+ y[3, 1:j] * 1E2,
317
+ '.-',
318
+ linewidth=2,
319
+ markersize=8,
320
+ label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
321
+
322
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
323
+ 'k.-',
324
+ linewidth=2,
325
+ markersize=8,
326
+ alpha=.25,
327
+ label='EfficientDet')
328
+
329
+ ax2.grid(alpha=0.2)
330
+ ax2.set_yticks(np.arange(20, 60, 5))
331
+ ax2.set_xlim(0, 57)
332
+ ax2.set_ylim(25, 55)
333
+ ax2.set_xlabel('GPU Speed (ms/img)')
334
+ ax2.set_ylabel('COCO AP val')
335
+ ax2.legend(loc='lower right')
336
+ f = save_dir / 'study.png'
337
+ print(f'Saving {f}...')
338
+ plt.savefig(f, dpi=300)
339
+
340
+
341
+ @try_except # known issue https://github.com/ultralytics/yolov5/issues/5395
342
+ @Timeout(30) # known issue https://github.com/ultralytics/yolov5/issues/5611
343
+ def plot_labels(labels, names=(), save_dir=Path('')):
344
+ # plot dataset labels
345
+ LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
346
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
347
+ nc = int(c.max() + 1) # number of classes
348
+ x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
349
+
350
+ # seaborn correlogram
351
+ sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
352
+ plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
353
+ plt.close()
354
+
355
+ # matplotlib labels
356
+ matplotlib.use('svg') # faster
357
+ ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
358
+ y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
359
+ try: # color histogram bars by class
360
+ [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195
361
+ except Exception:
362
+ pass
363
+ ax[0].set_ylabel('instances')
364
+ if 0 < len(names) < 30:
365
+ ax[0].set_xticks(range(len(names)))
366
+ ax[0].set_xticklabels(names, rotation=90, fontsize=10)
367
+ else:
368
+ ax[0].set_xlabel('classes')
369
+ sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
370
+ sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
371
+
372
+ # rectangles
373
+ labels[:, 1:3] = 0.5 # center
374
+ labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
375
+ img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
376
+ for cls, *box in labels[:1000]:
377
+ ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
378
+ ax[1].imshow(img)
379
+ ax[1].axis('off')
380
+
381
+ for a in [0, 1, 2, 3]:
382
+ for s in ['top', 'right', 'left', 'bottom']:
383
+ ax[a].spines[s].set_visible(False)
384
+
385
+ plt.savefig(save_dir / 'labels.jpg', dpi=200)
386
+ matplotlib.use('Agg')
387
+ plt.close()
388
+
389
+
390
+ def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve()
391
+ # Plot evolve.csv hyp evolution results
392
+ evolve_csv = Path(evolve_csv)
393
+ data = pd.read_csv(evolve_csv)
394
+ keys = [x.strip() for x in data.columns]
395
+ x = data.values
396
+ f = fitness(x)
397
+ j = np.argmax(f) # max fitness index
398
+ plt.figure(figsize=(10, 12), tight_layout=True)
399
+ matplotlib.rc('font', **{'size': 8})
400
+ print(f'Best results from row {j} of {evolve_csv}:')
401
+ for i, k in enumerate(keys[7:]):
402
+ v = x[:, 7 + i]
403
+ mu = v[j] # best single result
404
+ plt.subplot(6, 5, i + 1)
405
+ plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
406
+ plt.plot(mu, f.max(), 'k+', markersize=15)
407
+ plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9}) # limit to 40 characters
408
+ if i % 5 != 0:
409
+ plt.yticks([])
410
+ print(f'{k:>15}: {mu:.3g}')
411
+ f = evolve_csv.with_suffix('.png') # filename
412
+ plt.savefig(f, dpi=200)
413
+ plt.close()
414
+ print(f'Saved {f}')
415
+
416
+
417
+ def plot_results(file='path/to/results.csv', dir=''):
418
+ # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
419
+ save_dir = Path(file).parent if file else Path(dir)
420
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
421
+ ax = ax.ravel()
422
+ files = list(save_dir.glob('results*.csv'))
423
+ assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
424
+ for f in files:
425
+ try:
426
+ data = pd.read_csv(f)
427
+ s = [x.strip() for x in data.columns]
428
+ x = data.values[:, 0]
429
+ for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
430
+ y = data.values[:, j].astype('float')
431
+ # y[y == 0] = np.nan # don't show zero values
432
+ ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)
433
+ ax[i].set_title(s[j], fontsize=12)
434
+ # if j in [8, 9, 10]: # share train and val loss y axes
435
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
436
+ except Exception as e:
437
+ LOGGER.info(f'Warning: Plotting error for {f}: {e}')
438
+ ax[1].legend()
439
+ fig.savefig(save_dir / 'results.png', dpi=200)
440
+ plt.close()
441
+
442
+
443
+ def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
444
+ # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
445
+ ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
446
+ s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
447
+ files = list(Path(save_dir).glob('frames*.txt'))
448
+ for fi, f in enumerate(files):
449
+ try:
450
+ results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
451
+ n = results.shape[1] # number of rows
452
+ x = np.arange(start, min(stop, n) if stop else n)
453
+ results = results[:, x]
454
+ t = (results[0] - results[0].min()) # set t0=0s
455
+ results[0] = x
456
+ for i, a in enumerate(ax):
457
+ if i < len(results):
458
+ label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
459
+ a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
460
+ a.set_title(s[i])
461
+ a.set_xlabel('time (s)')
462
+ # if fi == len(files) - 1:
463
+ # a.set_ylim(bottom=0)
464
+ for side in ['top', 'right']:
465
+ a.spines[side].set_visible(False)
466
+ else:
467
+ a.remove()
468
+ except Exception as e:
469
+ print(f'Warning: Plotting error for {f}; {e}')
470
+ ax[1].legend()
471
+ plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
472
+
473
+
474
+ def save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True):
475
+ # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop
476
+ xyxy = torch.tensor(xyxy).view(-1, 4)
477
+ b = xyxy2xywh(xyxy) # boxes
478
+ if square:
479
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
480
+ b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
481
+ xyxy = xywh2xyxy(b).long()
482
+ clip_coords(xyxy, im.shape)
483
+ crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]
484
+ if save:
485
+ file.parent.mkdir(parents=True, exist_ok=True) # make directory
486
+ f = str(increment_path(file).with_suffix('.jpg'))
487
+ # cv2.imwrite(f, crop) # https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue
488
+ Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)).save(f, quality=95, subsampling=0)
489
+ return crop
utils/torch_utils.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ PyTorch utils
4
+ """
5
+
6
+ import math
7
+ import os
8
+ import platform
9
+ import subprocess
10
+ import time
11
+ import warnings
12
+ from contextlib import contextmanager
13
+ from copy import deepcopy
14
+ from pathlib import Path
15
+
16
+ import torch
17
+ import torch.distributed as dist
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from utils.general import LOGGER, file_date, git_describe
22
+
23
+ try:
24
+ import thop # for FLOPs computation
25
+ except ImportError:
26
+ thop = None
27
+
28
+ # Suppress PyTorch warnings
29
+ warnings.filterwarnings('ignore', message='User provided device_type of \'cuda\', but CUDA is not available. Disabling')
30
+
31
+
32
+ @contextmanager
33
+ def torch_distributed_zero_first(local_rank: int):
34
+ # Decorator to make all processes in distributed training wait for each local_master to do something
35
+ if local_rank not in [-1, 0]:
36
+ dist.barrier(device_ids=[local_rank])
37
+ yield
38
+ if local_rank == 0:
39
+ dist.barrier(device_ids=[0])
40
+
41
+
42
+ def device_count():
43
+ # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Supports Linux and Windows
44
+ assert platform.system() in ('Linux', 'Windows'), 'device_count() only supported on Linux or Windows'
45
+ try:
46
+ cmd = 'nvidia-smi -L | wc -l' if platform.system() == 'Linux' else 'nvidia-smi -L | find /c /v ""' # Windows
47
+ return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1])
48
+ except Exception:
49
+ return 0
50
+
51
+
52
+ def select_device(device='', batch_size=0, newline=True):
53
+ # device = None or 'cpu' or 0 or '0' or '0,1,2,3'
54
+ s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} '
55
+ device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0'
56
+ cpu = device == 'cpu'
57
+ mps = device == 'mps' # Apple Metal Performance Shaders (MPS)
58
+ if cpu or mps:
59
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
60
+ elif device: # non-cpu device requested
61
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available()
62
+ assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \
63
+ f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)"
64
+
65
+ if not (cpu or mps) and torch.cuda.is_available(): # prefer GPU if available
66
+ devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7
67
+ n = len(devices) # device count
68
+ if n > 1 and batch_size > 0: # check batch_size is divisible by device_count
69
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
70
+ space = ' ' * (len(s) + 1)
71
+ for i, d in enumerate(devices):
72
+ p = torch.cuda.get_device_properties(i)
73
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB
74
+ arg = 'cuda:0'
75
+ elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available(): # prefer MPS if available
76
+ s += 'MPS\n'
77
+ arg = 'mps'
78
+ else: # revert to CPU
79
+ s += 'CPU\n'
80
+ arg = 'cpu'
81
+
82
+ if not newline:
83
+ s = s.rstrip()
84
+ LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
85
+ return torch.device(arg)
86
+
87
+
88
+ def time_sync():
89
+ # PyTorch-accurate time
90
+ if torch.cuda.is_available():
91
+ torch.cuda.synchronize()
92
+ return time.time()
93
+
94
+
95
+ def profile(input, ops, n=10, device=None):
96
+ # YOLOv5 speed/memory/FLOPs profiler
97
+ #
98
+ # Usage:
99
+ # input = torch.randn(16, 3, 640, 640)
100
+ # m1 = lambda x: x * torch.sigmoid(x)
101
+ # m2 = nn.SiLU()
102
+ # profile(input, [m1, m2], n=100) # profile over 100 iterations
103
+
104
+ results = []
105
+ if not isinstance(device, torch.device):
106
+ device = select_device(device)
107
+ print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}"
108
+ f"{'input':>24s}{'output':>24s}")
109
+
110
+ for x in input if isinstance(input, list) else [input]:
111
+ x = x.to(device)
112
+ x.requires_grad = True
113
+ for m in ops if isinstance(ops, list) else [ops]:
114
+ m = m.to(device) if hasattr(m, 'to') else m # device
115
+ m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m
116
+ tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward
117
+ try:
118
+ flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs
119
+ except Exception:
120
+ flops = 0
121
+
122
+ try:
123
+ for _ in range(n):
124
+ t[0] = time_sync()
125
+ y = m(x)
126
+ t[1] = time_sync()
127
+ try:
128
+ _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()
129
+ t[2] = time_sync()
130
+ except Exception: # no backward method
131
+ # print(e) # for debug
132
+ t[2] = float('nan')
133
+ tf += (t[1] - t[0]) * 1000 / n # ms per op forward
134
+ tb += (t[2] - t[1]) * 1000 / n # ms per op backward
135
+ mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB)
136
+ s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y)) # shapes
137
+ p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters
138
+ print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')
139
+ results.append([p, flops, mem, tf, tb, s_in, s_out])
140
+ except Exception as e:
141
+ print(e)
142
+ results.append(None)
143
+ torch.cuda.empty_cache()
144
+ return results
145
+
146
+
147
+ def is_parallel(model):
148
+ # Returns True if model is of type DP or DDP
149
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
150
+
151
+
152
+ def de_parallel(model):
153
+ # De-parallelize a model: returns single-GPU model if model is of type DP or DDP
154
+ return model.module if is_parallel(model) else model
155
+
156
+
157
+ def initialize_weights(model):
158
+ for m in model.modules():
159
+ t = type(m)
160
+ if t is nn.Conv2d:
161
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
162
+ elif t is nn.BatchNorm2d:
163
+ m.eps = 1e-3
164
+ m.momentum = 0.03
165
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
166
+ m.inplace = True
167
+
168
+
169
+ def find_modules(model, mclass=nn.Conv2d):
170
+ # Finds layer indices matching module class 'mclass'
171
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
172
+
173
+
174
+ def sparsity(model):
175
+ # Return global model sparsity
176
+ a, b = 0, 0
177
+ for p in model.parameters():
178
+ a += p.numel()
179
+ b += (p == 0).sum()
180
+ return b / a
181
+
182
+
183
+ def prune(model, amount=0.3):
184
+ # Prune model to requested global sparsity
185
+ import torch.nn.utils.prune as prune
186
+ print('Pruning model... ', end='')
187
+ for name, m in model.named_modules():
188
+ if isinstance(m, nn.Conv2d):
189
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
190
+ prune.remove(m, 'weight') # make permanent
191
+ print(' %.3g global sparsity' % sparsity(model))
192
+
193
+
194
+ def fuse_conv_and_bn(conv, bn):
195
+ # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
196
+ fusedconv = nn.Conv2d(conv.in_channels,
197
+ conv.out_channels,
198
+ kernel_size=conv.kernel_size,
199
+ stride=conv.stride,
200
+ padding=conv.padding,
201
+ groups=conv.groups,
202
+ bias=True).requires_grad_(False).to(conv.weight.device)
203
+
204
+ # Prepare filters
205
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
206
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
207
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
208
+
209
+ # Prepare spatial bias
210
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
211
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
212
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
213
+
214
+ return fusedconv
215
+
216
+
217
+ def model_info(model, verbose=False, img_size=640):
218
+ # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
219
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
220
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
221
+ if verbose:
222
+ print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}")
223
+ for i, (name, p) in enumerate(model.named_parameters()):
224
+ name = name.replace('module_list.', '')
225
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
226
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
227
+
228
+ try: # FLOPs
229
+ from thop import profile
230
+ stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
231
+ img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
232
+ flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs
233
+ img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
234
+ fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs
235
+ except Exception:
236
+ fs = ''
237
+
238
+ name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model'
239
+ LOGGER.info(f"{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
240
+
241
+
242
+ def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
243
+ # Scales img(bs,3,y,x) by ratio constrained to gs-multiple
244
+ if ratio == 1.0:
245
+ return img
246
+ h, w = img.shape[2:]
247
+ s = (int(h * ratio), int(w * ratio)) # new size
248
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
249
+ if not same_shape: # pad/crop img
250
+ h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
251
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
252
+
253
+
254
+ def copy_attr(a, b, include=(), exclude=()):
255
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
256
+ for k, v in b.__dict__.items():
257
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
258
+ continue
259
+ else:
260
+ setattr(a, k, v)
261
+
262
+
263
+ class EarlyStopping:
264
+ # YOLOv5 simple early stopper
265
+ def __init__(self, patience=30):
266
+ self.best_fitness = 0.0 # i.e. mAP
267
+ self.best_epoch = 0
268
+ self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop
269
+ self.possible_stop = False # possible stop may occur next epoch
270
+
271
+ def __call__(self, epoch, fitness):
272
+ if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training
273
+ self.best_epoch = epoch
274
+ self.best_fitness = fitness
275
+ delta = epoch - self.best_epoch # epochs without improvement
276
+ self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch
277
+ stop = delta >= self.patience # stop training if patience exceeded
278
+ if stop:
279
+ LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. '
280
+ f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n'
281
+ f'To update EarlyStopping(patience={self.patience}) pass a new patience value, '
282
+ f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.')
283
+ return stop
284
+
285
+
286
+ class ModelEMA:
287
+ """ Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models
288
+ Keeps a moving average of everything in the model state_dict (parameters and buffers)
289
+ For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
290
+ """
291
+
292
+ def __init__(self, model, decay=0.9999, tau=2000, updates=0):
293
+ # Create EMA
294
+ self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA
295
+ # if next(model.parameters()).device.type != 'cpu':
296
+ # self.ema.half() # FP16 EMA
297
+ self.updates = updates # number of EMA updates
298
+ self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
299
+ for p in self.ema.parameters():
300
+ p.requires_grad_(False)
301
+
302
+ def update(self, model):
303
+ # Update EMA parameters
304
+ with torch.no_grad():
305
+ self.updates += 1
306
+ d = self.decay(self.updates)
307
+
308
+ msd = de_parallel(model).state_dict() # model state_dict
309
+ for k, v in self.ema.state_dict().items():
310
+ if v.dtype.is_floating_point:
311
+ v *= d
312
+ v += (1 - d) * msd[k].detach()
313
+
314
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
315
+ # Update EMA attributes
316
+ copy_attr(self.ema, model, include, exclude)
val.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Validate a trained YOLOv5 model accuracy on a custom dataset
4
+
5
+ Usage:
6
+ $ python path/to/val.py --weights yolov5s.pt --data coco128.yaml --img 640
7
+
8
+ Usage - formats:
9
+ $ python path/to/val.py --weights yolov5s.pt # PyTorch
10
+ yolov5s.torchscript # TorchScript
11
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
12
+ yolov5s.xml # OpenVINO
13
+ yolov5s.engine # TensorRT
14
+ yolov5s.mlmodel # CoreML (macOS-only)
15
+ yolov5s_saved_model # TensorFlow SavedModel
16
+ yolov5s.pb # TensorFlow GraphDef
17
+ yolov5s.tflite # TensorFlow Lite
18
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
19
+ """
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import torch
29
+ from tqdm import tqdm
30
+
31
+ FILE = Path(__file__).resolve()
32
+ ROOT = FILE.parents[0] # YOLOv5 root directory
33
+ if str(ROOT) not in sys.path:
34
+ sys.path.append(str(ROOT)) # add ROOT to PATH
35
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
36
+
37
+ from models.common import DetectMultiBackend
38
+ from utils.callbacks import Callbacks
39
+ from utils.dataloaders import create_dataloader
40
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_yaml,
41
+ coco80_to_coco91_class, colorstr, emojis, increment_path, non_max_suppression, print_args,
42
+ scale_coords, xywh2xyxy, xyxy2xywh)
43
+ from utils.metrics import ConfusionMatrix, ap_per_class, box_iou
44
+ from utils.plots import output_to_target, plot_images, plot_val_study
45
+ from utils.torch_utils import select_device, time_sync
46
+
47
+
48
+ def save_one_txt(predn, save_conf, shape, file):
49
+ # Save one txt result
50
+ gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
51
+ for *xyxy, conf, cls in predn.tolist():
52
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
53
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
54
+ with open(file, 'a') as f:
55
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
56
+
57
+
58
+ def save_one_json(predn, jdict, path, class_map):
59
+ # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
60
+ image_id = int(path.stem) if path.stem.isnumeric() else path.stem
61
+ box = xyxy2xywh(predn[:, :4]) # xywh
62
+ box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
63
+ for p, b in zip(predn.tolist(), box.tolist()):
64
+ jdict.append({
65
+ 'image_id': image_id,
66
+ 'category_id': class_map[int(p[5])],
67
+ 'bbox': [round(x, 3) for x in b],
68
+ 'score': round(p[4], 5)})
69
+
70
+
71
+ def process_batch(detections, labels, iouv):
72
+ """
73
+ Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format.
74
+ Arguments:
75
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
76
+ labels (Array[M, 5]), class, x1, y1, x2, y2
77
+ Returns:
78
+ correct (Array[N, 10]), for 10 IoU levels
79
+ """
80
+ correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool)
81
+ iou = box_iou(labels[:, 1:], detections[:, :4])
82
+ correct_class = labels[:, 0:1] == detections[:, 5]
83
+ for i in range(len(iouv)):
84
+ x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match
85
+ if x[0].shape[0]:
86
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou]
87
+ if x[0].shape[0] > 1:
88
+ matches = matches[matches[:, 2].argsort()[::-1]]
89
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
90
+ # matches = matches[matches[:, 2].argsort()[::-1]]
91
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
92
+ correct[matches[:, 1].astype(int), i] = True
93
+ return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
94
+
95
+
96
+ @torch.no_grad()
97
+ def run(
98
+ data,
99
+ weights=None, # model.pt path(s)
100
+ batch_size=32, # batch size
101
+ imgsz=640, # inference size (pixels)
102
+ conf_thres=0.001, # confidence threshold
103
+ iou_thres=0.6, # NMS IoU threshold
104
+ task='val', # train, val, test, speed or study
105
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
106
+ workers=8, # max dataloader workers (per RANK in DDP mode)
107
+ single_cls=False, # treat as single-class dataset
108
+ augment=False, # augmented inference
109
+ verbose=False, # verbose output
110
+ save_txt=False, # save results to *.txt
111
+ save_hybrid=False, # save label+prediction hybrid results to *.txt
112
+ save_conf=False, # save confidences in --save-txt labels
113
+ save_json=False, # save a COCO-JSON results file
114
+ project=ROOT / 'runs/val', # save to project/name
115
+ name='exp', # save to project/name
116
+ exist_ok=False, # existing project/name ok, do not increment
117
+ half=True, # use FP16 half-precision inference
118
+ dnn=False, # use OpenCV DNN for ONNX inference
119
+ model=None,
120
+ dataloader=None,
121
+ save_dir=Path(''),
122
+ plots=True,
123
+ callbacks=Callbacks(),
124
+ compute_loss=None,
125
+ ):
126
+ # Initialize/load model and set device
127
+ training = model is not None
128
+ if training: # called by train.py
129
+ device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
130
+ half &= device.type != 'cpu' # half precision only supported on CUDA
131
+ model.half() if half else model.float()
132
+ else: # called directly
133
+ device = select_device(device, batch_size=batch_size)
134
+
135
+ # Directories
136
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
137
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
138
+
139
+ # Load model
140
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
141
+ stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
142
+ imgsz = check_img_size(imgsz, s=stride) # check image size
143
+ half = model.fp16 # FP16 supported on limited backends with CUDA
144
+ if engine:
145
+ batch_size = model.batch_size
146
+ else:
147
+ device = model.device
148
+ if not (pt or jit):
149
+ batch_size = 1 # export.py models default to batch-size 1
150
+ LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
151
+
152
+ # Data
153
+ data = check_dataset(data) # check
154
+
155
+ # Configure
156
+ model.eval()
157
+ cuda = device.type != 'cpu'
158
+ is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset
159
+ nc = 1 if single_cls else int(data['nc']) # number of classes
160
+ iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95
161
+ niou = iouv.numel()
162
+
163
+ # Dataloader
164
+ if not training:
165
+ if pt and not single_cls: # check --weights are trained on --data
166
+ ncm = model.model.nc
167
+ assert ncm == nc, f'{weights} ({ncm} classes) trained on different --data than what you passed ({nc} ' \
168
+ f'classes). Pass correct combination of --weights and --data that are trained together.'
169
+ model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup
170
+ pad = 0.0 if task in ('speed', 'benchmark') else 0.5
171
+ rect = False if task == 'benchmark' else pt # square inference for benchmarks
172
+ task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
173
+ dataloader = create_dataloader(data[task],
174
+ imgsz,
175
+ batch_size,
176
+ stride,
177
+ single_cls,
178
+ pad=pad,
179
+ rect=rect,
180
+ workers=workers,
181
+ prefix=colorstr(f'{task}: '))[0]
182
+
183
+ seen = 0
184
+ confusion_matrix = ConfusionMatrix(nc=nc)
185
+ names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
186
+ class_map = coco80_to_coco91_class() if is_coco else list(range(1000))
187
+ s = ('%20s' + '%11s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
188
+ dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
189
+ loss = torch.zeros(3, device=device)
190
+ jdict, stats, ap, ap_class = [], [], [], []
191
+ callbacks.run('on_val_start')
192
+ pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
193
+ for batch_i, (im, targets, paths, shapes) in enumerate(pbar):
194
+ callbacks.run('on_val_batch_start')
195
+ t1 = time_sync()
196
+ if cuda:
197
+ im = im.to(device, non_blocking=True)
198
+ targets = targets.to(device)
199
+ im = im.half() if half else im.float() # uint8 to fp16/32
200
+ im /= 255 # 0 - 255 to 0.0 - 1.0
201
+ nb, _, height, width = im.shape # batch size, channels, height, width
202
+ t2 = time_sync()
203
+ dt[0] += t2 - t1
204
+
205
+ # Inference
206
+ out, train_out = model(im) if training else model(im, augment=augment, val=True) # inference, loss outputs
207
+ dt[1] += time_sync() - t2
208
+
209
+ # Loss
210
+ if compute_loss:
211
+ loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls
212
+
213
+ # NMS
214
+ targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels
215
+ lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
216
+ t3 = time_sync()
217
+ out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls)
218
+ dt[2] += time_sync() - t3
219
+
220
+ # Metrics
221
+ for si, pred in enumerate(out):
222
+ labels = targets[targets[:, 0] == si, 1:]
223
+ nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions
224
+ path, shape = Path(paths[si]), shapes[si][0]
225
+ correct = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init
226
+ seen += 1
227
+
228
+ if npr == 0:
229
+ if nl:
230
+ stats.append((correct, *torch.zeros((2, 0), device=device), labels[:, 0]))
231
+ continue
232
+
233
+ # Predictions
234
+ if single_cls:
235
+ pred[:, 5] = 0
236
+ predn = pred.clone()
237
+ scale_coords(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred
238
+
239
+ # Evaluate
240
+ if nl:
241
+ tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
242
+ scale_coords(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels
243
+ labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
244
+ correct = process_batch(predn, labelsn, iouv)
245
+ if plots:
246
+ confusion_matrix.process_batch(predn, labelsn)
247
+ stats.append((correct, pred[:, 4], pred[:, 5], labels[:, 0])) # (correct, conf, pcls, tcls)
248
+
249
+ # Save/log
250
+ if save_txt:
251
+ save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / (path.stem + '.txt'))
252
+ if save_json:
253
+ save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary
254
+ callbacks.run('on_val_image_end', pred, predn, path, names, im[si])
255
+
256
+ # Plot images
257
+ if plots and batch_i < 3:
258
+ plot_images(im, targets, paths, save_dir / f'val_batch{batch_i}_labels.jpg', names) # labels
259
+ plot_images(im, output_to_target(out), paths, save_dir / f'val_batch{batch_i}_pred.jpg', names) # pred
260
+
261
+ callbacks.run('on_val_batch_end')
262
+
263
+ # Compute metrics
264
+ stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpy
265
+ if len(stats) and stats[0].any():
266
+ tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
267
+ ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
268
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
269
+ nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class
270
+ else:
271
+ nt = torch.zeros(1)
272
+
273
+ # Print results
274
+ pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format
275
+ LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
276
+
277
+ # Print results per class
278
+ if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
279
+ for i, c in enumerate(ap_class):
280
+ LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
281
+
282
+ # Print speeds
283
+ t = tuple(x / seen * 1E3 for x in dt) # speeds per image
284
+ if not training:
285
+ shape = (batch_size, 3, imgsz, imgsz)
286
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t)
287
+
288
+ # Plots
289
+ if plots:
290
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
291
+ callbacks.run('on_val_end')
292
+
293
+ # Save JSON
294
+ if save_json and len(jdict):
295
+ w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
296
+ anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json
297
+ pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
298
+ LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...')
299
+ with open(pred_json, 'w') as f:
300
+ json.dump(jdict, f)
301
+
302
+ try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
303
+ check_requirements(['pycocotools'])
304
+ from pycocotools.coco import COCO
305
+ from pycocotools.cocoeval import COCOeval
306
+
307
+ anno = COCO(anno_json) # init annotations api
308
+ pred = anno.loadRes(pred_json) # init predictions api
309
+ eval = COCOeval(anno, pred, 'bbox')
310
+ if is_coco:
311
+ eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluate
312
+ eval.evaluate()
313
+ eval.accumulate()
314
+ eval.summarize()
315
+ map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
316
+ except Exception as e:
317
+ LOGGER.info(f'pycocotools unable to run: {e}')
318
+
319
+ # Return results
320
+ model.float() # for training
321
+ if not training:
322
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
323
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
324
+ maps = np.zeros(nc) + map
325
+ for i, c in enumerate(ap_class):
326
+ maps[c] = ap[i]
327
+ return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
328
+
329
+
330
+ def parse_opt():
331
+ parser = argparse.ArgumentParser()
332
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
333
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
334
+ parser.add_argument('--batch-size', type=int, default=32, help='batch size')
335
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
336
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold')
337
+ parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold')
338
+ parser.add_argument('--task', default='val', help='train, val, test, speed or study')
339
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
340
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
341
+ parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
342
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
343
+ parser.add_argument('--verbose', action='store_true', help='report mAP by class')
344
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
345
+ parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
346
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
347
+ parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file')
348
+ parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name')
349
+ parser.add_argument('--name', default='exp', help='save to project/name')
350
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
351
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
352
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
353
+ opt = parser.parse_args()
354
+ opt.data = check_yaml(opt.data) # check YAML
355
+ opt.save_json |= opt.data.endswith('coco.yaml')
356
+ opt.save_txt |= opt.save_hybrid
357
+ print_args(vars(opt))
358
+ return opt
359
+
360
+
361
+ def main(opt):
362
+ check_requirements(requirements=ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
363
+
364
+ if opt.task in ('train', 'val', 'test'): # run normally
365
+ if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466
366
+ LOGGER.info(emojis(f'WARNING: confidence threshold {opt.conf_thres} > 0.001 produces invalid results ⚠️'))
367
+ run(**vars(opt))
368
+
369
+ else:
370
+ weights = opt.weights if isinstance(opt.weights, list) else [opt.weights]
371
+ opt.half = True # FP16 for fastest results
372
+ if opt.task == 'speed': # speed benchmarks
373
+ # python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt...
374
+ opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False
375
+ for opt.weights in weights:
376
+ run(**vars(opt), plots=False)
377
+
378
+ elif opt.task == 'study': # speed vs mAP benchmarks
379
+ # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt...
380
+ for opt.weights in weights:
381
+ f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt' # filename to save to
382
+ x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis
383
+ for opt.imgsz in x: # img-size
384
+ LOGGER.info(f'\nRunning {f} --imgsz {opt.imgsz}...')
385
+ r, _, t = run(**vars(opt), plots=False)
386
+ y.append(r + t) # results and times
387
+ np.savetxt(f, y, fmt='%10.4g') # save
388
+ os.system('zip -r study.zip study_*.txt')
389
+ plot_val_study(x=x) # plot
390
+
391
+
392
+ if __name__ == "__main__":
393
+ opt = parse_opt()
394
+ main(opt)
yolov5_model_p5_p6_all.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 P5 P6模型下载脚本
2
+ # 创建人:曾逸夫
3
+ # 创建时间:2022-06-01
4
+
5
+ cd ./models
6
+
7
+ yolov5_version="v6.1"
8
+ wget_download="wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/"
9
+ model_list=(yolov5n yolov5s yolov5m yolov5l yolov5x yolov5n6 yolov5s6 yolov5m6 yolov5l6 yolov5x6)
10
+
11
+ for i in ${model_list[*]}; do
12
+ $wget_download$yolov5_version$"/"$i$".pt"
13
+ echo $i"模型下载成功!"
14
+ done