pyesonekyaw commited on
Commit
80288b5
1 Parent(s): 73e18ee

added ultralytics prereqs

Browse files
Files changed (46) hide show
  1. hubconf.py +143 -0
  2. models/__init__.py +0 -0
  3. models/common.py +623 -0
  4. models/experimental.py +108 -0
  5. models/hub/anchors.yaml +59 -0
  6. models/hub/yolov5-bifpn.yaml +48 -0
  7. models/hub/yolov5-fpn.yaml +42 -0
  8. models/hub/yolov5-p2.yaml +54 -0
  9. models/hub/yolov5-p34.yaml +41 -0
  10. models/hub/yolov5-p6.yaml +56 -0
  11. models/hub/yolov5-p7.yaml +67 -0
  12. models/hub/yolov5-panet.yaml +48 -0
  13. models/hub/yolov5l6.yaml +60 -0
  14. models/hub/yolov5m6.yaml +60 -0
  15. models/hub/yolov5n6.yaml +60 -0
  16. models/hub/yolov5s-LeakyReLU.yaml +49 -0
  17. models/hub/yolov5s-ghost.yaml +48 -0
  18. models/hub/yolov5s-transformer.yaml +48 -0
  19. models/hub/yolov5s6.yaml +60 -0
  20. models/hub/yolov5x6.yaml +60 -0
  21. models/yolo.py +391 -0
  22. models/yolov5l.yaml +48 -0
  23. models/yolov5m.yaml +48 -0
  24. models/yolov5n.yaml +48 -0
  25. models/yolov5s.yaml +48 -0
  26. models/yolov5x.yaml +48 -0
  27. utils/__init__.py +80 -0
  28. utils/__pycache__/__init__.cpython-38.pyc +0 -0
  29. utils/__pycache__/augmentations.cpython-38.pyc +0 -0
  30. utils/__pycache__/autoanchor.cpython-38.pyc +0 -0
  31. utils/__pycache__/dataloaders.cpython-38.pyc +0 -0
  32. utils/__pycache__/general.cpython-38.pyc +0 -0
  33. utils/__pycache__/metrics.cpython-38.pyc +0 -0
  34. utils/__pycache__/plots.cpython-38.pyc +0 -0
  35. utils/__pycache__/torch_utils.cpython-38.pyc +0 -0
  36. utils/activations.py +103 -0
  37. utils/augmentations.py +397 -0
  38. utils/autoanchor.py +169 -0
  39. utils/autobatch.py +72 -0
  40. utils/callbacks.py +76 -0
  41. utils/dataloaders.py +331 -0
  42. utils/general.py +1083 -0
  43. utils/loss.py +234 -0
  44. utils/metrics.py +360 -0
  45. utils/plots.py +560 -0
  46. utils/torch_utils.py +432 -0
hubconf.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
4
+
5
+ Usage:
6
+ import torch
7
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
8
+ model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch
9
+ """
10
+
11
+ import torch
12
+
13
+
14
+ def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
15
+ """Creates or loads a YOLOv5 model
16
+
17
+ Arguments:
18
+ name (str): model name 'yolov5s' or path 'path/to/best.pt'
19
+ pretrained (bool): load pretrained weights into the model
20
+ channels (int): number of input channels
21
+ classes (int): number of model classes
22
+ autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
23
+ verbose (bool): print all information to screen
24
+ device (str, torch.device, None): device to use for model parameters
25
+
26
+ Returns:
27
+ YOLOv5 model
28
+ """
29
+ from pathlib import Path
30
+
31
+ from models.common import AutoShape, DetectMultiBackend
32
+ from models.yolo import Model
33
+ #from utils.downloads import attempt_download
34
+ from utils.general import LOGGER, check_requirements, intersect_dicts, logging
35
+ from utils.torch_utils import select_device
36
+
37
+ if not verbose:
38
+ LOGGER.setLevel(logging.WARNING)
39
+ check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
40
+ name = Path(name)
41
+ path = name.with_suffix('.pt') if name.suffix == '' else name # checkpoint path
42
+ try:
43
+ device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device)
44
+ #device = 'mps'
45
+ if pretrained and channels == 3 and classes == 80:
46
+ model = DetectMultiBackend(path, device=device) # download/load FP32 model
47
+ # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model
48
+ else:
49
+ cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
50
+ model = Model(cfg, channels, classes) # create model
51
+ if pretrained:
52
+ ckpt = torch.load(path, map_location=device) # load
53
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
54
+ csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
55
+ model.load_state_dict(csd, strict=False) # load
56
+ if len(ckpt['model'].names) == classes:
57
+ model.names = ckpt['model'].names # set class names attribute
58
+ if autoshape:
59
+ model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
60
+ return model.to(device)
61
+
62
+ except Exception as e:
63
+ help_url = 'https://github.com/ultralytics/yolov5/issues/36'
64
+ s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
65
+ raise Exception(s) from e
66
+
67
+
68
+ def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None):
69
+ # YOLOv5 custom or local model
70
+ return _create(path, autoshape=autoshape, verbose=verbose, device=device)
71
+
72
+
73
+ def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
74
+ # YOLOv5-nano model https://github.com/ultralytics/yolov5
75
+ return _create('yolov5n', pretrained, channels, classes, autoshape, verbose, device)
76
+
77
+
78
+ def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
79
+ # YOLOv5-small model https://github.com/ultralytics/yolov5
80
+ return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device)
81
+
82
+
83
+ def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
84
+ # YOLOv5-medium model https://github.com/ultralytics/yolov5
85
+ return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device)
86
+
87
+
88
+ def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
89
+ # YOLOv5-large model https://github.com/ultralytics/yolov5
90
+ return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device)
91
+
92
+
93
+ def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
94
+ # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
95
+ return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device)
96
+
97
+
98
+ def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
99
+ # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
100
+ return _create('yolov5n6', pretrained, channels, classes, autoshape, verbose, device)
101
+
102
+
103
+ def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
104
+ # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
105
+ return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device)
106
+
107
+
108
+ def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
109
+ # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
110
+ return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device)
111
+
112
+
113
+ def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
114
+ # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
115
+ return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device)
116
+
117
+
118
+ def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
119
+ # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
120
+ return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device)
121
+
122
+
123
+ if __name__ == '__main__':
124
+ model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
125
+ # model = custom(path='path/to/model.pt') # custom
126
+
127
+ # Verify inference
128
+ from pathlib import Path
129
+
130
+ import cv2
131
+ import numpy as np
132
+ from PIL import Image
133
+
134
+ imgs = ['data/images/zidane.jpg', # filename
135
+ Path('data/images/zidane.jpg'), # Path
136
+ 'https://ultralytics.com/images/zidane.jpg', # URI
137
+ cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
138
+ Image.open('data/images/bus.jpg'), # PIL
139
+ np.zeros((320, 640, 3))] # numpy
140
+
141
+ results = model(imgs, size=320) # batched inference
142
+ results.print()
143
+ results.save()
models/__init__.py ADDED
File without changes
models/common.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Common modules
4
+ """
5
+
6
+ import math
7
+ import warnings
8
+ from copy import copy
9
+ from pathlib import Path
10
+ from urllib.parse import urlparse
11
+
12
+ import cv2
13
+ import numpy as np
14
+ import pandas as pd
15
+ import requests
16
+ import torch
17
+ import torch.nn as nn
18
+ from IPython.display import display
19
+ from PIL import Image
20
+ from torch.cuda import amp
21
+
22
+ from utils import TryExcept
23
+ from utils.dataloaders import exif_transpose, letterbox
24
+ from utils.general import (LOGGER, ROOT, Profile, colorstr,
25
+ increment_path, is_notebook, make_divisible, non_max_suppression, scale_boxes, xyxy2xywh, yaml_load)
26
+ from utils.plots import Annotator, colors, save_one_box
27
+ from utils.torch_utils import copy_attr, smart_inference_mode
28
+
29
+
30
+ def autopad(k, p=None, d=1): # kernel, padding, dilation
31
+ # Pad to 'same' shape outputs
32
+ if d > 1:
33
+ k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
34
+ if p is None:
35
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
36
+ return p
37
+
38
+
39
+ class Conv(nn.Module):
40
+ # Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
41
+ default_act = nn.SiLU() # default activation
42
+
43
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
44
+ super().__init__()
45
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
46
+ self.bn = nn.BatchNorm2d(c2)
47
+ self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
48
+
49
+ def forward(self, x):
50
+ return self.act(self.bn(self.conv(x)))
51
+
52
+ def forward_fuse(self, x):
53
+ return self.act(self.conv(x))
54
+
55
+
56
+ class DWConv(Conv):
57
+ # Depth-wise convolution
58
+ def __init__(self, c1, c2, k=1, s=1, d=1, act=True): # ch_in, ch_out, kernel, stride, dilation, activation
59
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
60
+
61
+
62
+ class DWConvTranspose2d(nn.ConvTranspose2d):
63
+ # Depth-wise transpose convolution
64
+ def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
65
+ super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
66
+
67
+
68
+ class TransformerLayer(nn.Module):
69
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
70
+ def __init__(self, c, num_heads):
71
+ super().__init__()
72
+ self.q = nn.Linear(c, c, bias=False)
73
+ self.k = nn.Linear(c, c, bias=False)
74
+ self.v = nn.Linear(c, c, bias=False)
75
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
76
+ self.fc1 = nn.Linear(c, c, bias=False)
77
+ self.fc2 = nn.Linear(c, c, bias=False)
78
+
79
+ def forward(self, x):
80
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
81
+ x = self.fc2(self.fc1(x)) + x
82
+ return x
83
+
84
+
85
+ class TransformerBlock(nn.Module):
86
+ # Vision Transformer https://arxiv.org/abs/2010.11929
87
+ def __init__(self, c1, c2, num_heads, num_layers):
88
+ super().__init__()
89
+ self.conv = None
90
+ if c1 != c2:
91
+ self.conv = Conv(c1, c2)
92
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
93
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
94
+ self.c2 = c2
95
+
96
+ def forward(self, x):
97
+ if self.conv is not None:
98
+ x = self.conv(x)
99
+ b, _, w, h = x.shape
100
+ p = x.flatten(2).permute(2, 0, 1)
101
+ return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
102
+
103
+
104
+ class Bottleneck(nn.Module):
105
+ # Standard bottleneck
106
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
107
+ super().__init__()
108
+ c_ = int(c2 * e) # hidden channels
109
+ self.cv1 = Conv(c1, c_, 1, 1)
110
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
111
+ self.add = shortcut and c1 == c2
112
+
113
+ def forward(self, x):
114
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
115
+
116
+
117
+ class BottleneckCSP(nn.Module):
118
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
119
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
120
+ super().__init__()
121
+ c_ = int(c2 * e) # hidden channels
122
+ self.cv1 = Conv(c1, c_, 1, 1)
123
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
124
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
125
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
126
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
127
+ self.act = nn.SiLU()
128
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
129
+
130
+ def forward(self, x):
131
+ y1 = self.cv3(self.m(self.cv1(x)))
132
+ y2 = self.cv2(x)
133
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
134
+
135
+
136
+ class CrossConv(nn.Module):
137
+ # Cross Convolution Downsample
138
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
139
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
140
+ super().__init__()
141
+ c_ = int(c2 * e) # hidden channels
142
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
143
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
144
+ self.add = shortcut and c1 == c2
145
+
146
+ def forward(self, x):
147
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
148
+
149
+
150
+ class C3(nn.Module):
151
+ # CSP Bottleneck with 3 convolutions
152
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
153
+ super().__init__()
154
+ c_ = int(c2 * e) # hidden channels
155
+ self.cv1 = Conv(c1, c_, 1, 1)
156
+ self.cv2 = Conv(c1, c_, 1, 1)
157
+ self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
158
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
159
+
160
+ def forward(self, x):
161
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
162
+
163
+
164
+ class C3x(C3):
165
+ # C3 module with cross-convolutions
166
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
167
+ super().__init__(c1, c2, n, shortcut, g, e)
168
+ c_ = int(c2 * e)
169
+ self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
170
+
171
+
172
+ class C3TR(C3):
173
+ # C3 module with TransformerBlock()
174
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
175
+ super().__init__(c1, c2, n, shortcut, g, e)
176
+ c_ = int(c2 * e)
177
+ self.m = TransformerBlock(c_, c_, 4, n)
178
+
179
+
180
+ class C3SPP(C3):
181
+ # C3 module with SPP()
182
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
183
+ super().__init__(c1, c2, n, shortcut, g, e)
184
+ c_ = int(c2 * e)
185
+ self.m = SPP(c_, c_, k)
186
+
187
+
188
+ class C3Ghost(C3):
189
+ # C3 module with GhostBottleneck()
190
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
191
+ super().__init__(c1, c2, n, shortcut, g, e)
192
+ c_ = int(c2 * e) # hidden channels
193
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
194
+
195
+
196
+ class SPP(nn.Module):
197
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
198
+ def __init__(self, c1, c2, k=(5, 9, 13)):
199
+ super().__init__()
200
+ c_ = c1 // 2 # hidden channels
201
+ self.cv1 = Conv(c1, c_, 1, 1)
202
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
203
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
204
+
205
+ def forward(self, x):
206
+ x = self.cv1(x)
207
+ with warnings.catch_warnings():
208
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
209
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
210
+
211
+
212
+ class SPPF(nn.Module):
213
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
214
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
215
+ super().__init__()
216
+ c_ = c1 // 2 # hidden channels
217
+ self.cv1 = Conv(c1, c_, 1, 1)
218
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
219
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
220
+
221
+ def forward(self, x):
222
+ x = self.cv1(x)
223
+ with warnings.catch_warnings():
224
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
225
+ y1 = self.m(x)
226
+ y2 = self.m(y1)
227
+ return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
228
+
229
+
230
+ class Focus(nn.Module):
231
+ # Focus wh information into c-space
232
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
233
+ super().__init__()
234
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
235
+ # self.contract = Contract(gain=2)
236
+
237
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
238
+ return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
239
+ # return self.conv(self.contract(x))
240
+
241
+
242
+ class GhostConv(nn.Module):
243
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
244
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
245
+ super().__init__()
246
+ c_ = c2 // 2 # hidden channels
247
+ self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
248
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
249
+
250
+ def forward(self, x):
251
+ y = self.cv1(x)
252
+ return torch.cat((y, self.cv2(y)), 1)
253
+
254
+
255
+ class GhostBottleneck(nn.Module):
256
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
257
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
258
+ super().__init__()
259
+ c_ = c2 // 2
260
+ self.conv = nn.Sequential(
261
+ GhostConv(c1, c_, 1, 1), # pw
262
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
263
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
264
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,
265
+ act=False)) if s == 2 else nn.Identity()
266
+
267
+ def forward(self, x):
268
+ return self.conv(x) + self.shortcut(x)
269
+
270
+
271
+ class Contract(nn.Module):
272
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
273
+ def __init__(self, gain=2):
274
+ super().__init__()
275
+ self.gain = gain
276
+
277
+ def forward(self, x):
278
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
279
+ s = self.gain
280
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
281
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
282
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
283
+
284
+
285
+ class Expand(nn.Module):
286
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
287
+ def __init__(self, gain=2):
288
+ super().__init__()
289
+ self.gain = gain
290
+
291
+ def forward(self, x):
292
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
293
+ s = self.gain
294
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
295
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
296
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
297
+
298
+
299
+ class Concat(nn.Module):
300
+ # Concatenate a list of tensors along dimension
301
+ def __init__(self, dimension=1):
302
+ super().__init__()
303
+ self.d = dimension
304
+
305
+ def forward(self, x):
306
+ return torch.cat(x, self.d)
307
+
308
+
309
+ class DetectMultiBackend(nn.Module):
310
+ # YOLOv5 MultiBackend class for python inference on various backends
311
+ def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):
312
+ # Usage:
313
+ # PyTorch: weights = *.pt
314
+ from models.experimental import attempt_load # scoped to avoid circular import
315
+
316
+ super().__init__()
317
+ w = str(weights[0] if isinstance(weights, list) else weights)
318
+ pt = self._model_type(w)[0]
319
+ fp16 = True # FP16
320
+ nhwc = False # BHWC formats (vs torch BCWH)
321
+ stride = 32 # default stride
322
+ cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA
323
+ model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
324
+ stride = max(int(model.stride.max()), 32) # model stride
325
+ names = model.module.names if hasattr(model, 'module') else model.names # get class names
326
+ model.half() if fp16 else model.float()
327
+ self.model = model # explicitly assign for to(), cpu(), cuda(), half()
328
+
329
+ # class names
330
+ if 'names' not in locals():
331
+ names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}
332
+ if names[0] == 'n01440764' and len(names) == 1000: # ImageNet
333
+ names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names
334
+
335
+ self.__dict__.update(locals()) # assign all variables to self
336
+
337
+ def forward(self, im, augment=False, visualize=False):
338
+ # YOLOv5 MultiBackend inference
339
+ b, ch, h, w = im.shape # batch, channel, height, width
340
+ if self.fp16 and im.dtype != torch.float16:
341
+ im = im.half() # to FP16
342
+ if self.nhwc:
343
+ im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)
344
+
345
+ if self.pt: # PyTorch
346
+ y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
347
+
348
+ if isinstance(y, (list, tuple)):
349
+ return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]
350
+ else:
351
+ return self.from_numpy(y)
352
+
353
+ def from_numpy(self, x):
354
+ return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x
355
+
356
+ def warmup(self, imgsz=(1, 3, 640, 640)):
357
+ # Warmup model by running inference once
358
+ warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton
359
+ if any(warmup_types) and (self.device.type != 'cpu' or self.triton):
360
+ im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
361
+ for _ in range(2 if self.jit else 1): #
362
+ self.forward(im) # warmup
363
+
364
+ @staticmethod
365
+ def _model_type(p='path/to/model.pt'):
366
+
367
+ def export_formats():
368
+ x = [['PyTorch', '-', '.pt', True, True],]
369
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
370
+
371
+ sf = list(export_formats().Suffix) # export suffixes
372
+ url = urlparse(p) # if url may be Triton inference server
373
+ types = [s in Path(p).name for s in sf]
374
+ triton = False
375
+ return types + [triton]
376
+
377
+ @staticmethod
378
+ def _load_metadata(f=Path('path/to/meta.yaml')):
379
+ # Load metadata from meta.yaml if it exists
380
+ if f.exists():
381
+ d = yaml_load(f)
382
+ return d['stride'], d['names'] # assign stride, names
383
+ return None, None
384
+
385
+
386
+ class AutoShape(nn.Module):
387
+ # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
388
+ conf = 0.25 # NMS confidence threshold
389
+ iou = 0.45 # NMS IoU threshold
390
+ agnostic = False # NMS class-agnostic
391
+ multi_label = False # NMS multiple labels per box
392
+ classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
393
+ max_det = 1000 # maximum number of detections per image
394
+ amp = False # Automatic Mixed Precision (AMP) inference
395
+
396
+ def __init__(self, model, verbose=True):
397
+ super().__init__()
398
+ if verbose:
399
+ LOGGER.info('Adding AutoShape... ')
400
+ copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
401
+ self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
402
+ self.pt = not self.dmb or model.pt # PyTorch model
403
+ self.model = model.eval()
404
+ if self.pt:
405
+ m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
406
+ m.inplace = False # Detect.inplace=False for safe multithread inference
407
+ m.export = True # do not output loss values
408
+
409
+ def _apply(self, fn):
410
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
411
+ self = super()._apply(fn)
412
+ if self.pt:
413
+ m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
414
+ m.stride = fn(m.stride)
415
+ m.grid = list(map(fn, m.grid))
416
+ if isinstance(m.anchor_grid, list):
417
+ m.anchor_grid = list(map(fn, m.anchor_grid))
418
+ return self
419
+
420
+ @smart_inference_mode()
421
+ def forward(self, ims, size=640, augment=False, profile=False):
422
+ # Inference from various sources. For size(height=640, width=1280), RGB images example inputs are:
423
+ # file: ims = 'data/images/zidane.jpg' # str or PosixPath
424
+ # URI: = 'https://ultralytics.com/images/zidane.jpg'
425
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
426
+ # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
427
+ # numpy: = np.zeros((640,1280,3)) # HWC
428
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
429
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
430
+
431
+ dt = (Profile(), Profile(), Profile())
432
+ with dt[0]:
433
+ if isinstance(size, int): # expand
434
+ size = (size, size)
435
+ p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) # param
436
+ autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
437
+ if isinstance(ims, torch.Tensor): # torch
438
+ with amp.autocast(autocast):
439
+ return self.model(ims.to(p.device).type_as(p), augment=augment) # inference
440
+
441
+ # Pre-process
442
+ n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of images
443
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
444
+ for i, im in enumerate(ims):
445
+ f = f'image{i}' # filename
446
+ if isinstance(im, (str, Path)): # filename or uri
447
+ im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
448
+ im = np.asarray(exif_transpose(im))
449
+ elif isinstance(im, Image.Image): # PIL Image
450
+ im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
451
+ files.append(Path(f).with_suffix('.jpg').name)
452
+ if im.shape[0] < 5: # image in CHW
453
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
454
+ im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch input
455
+ s = im.shape[:2] # HWC
456
+ shape0.append(s) # image shape
457
+ g = max(size) / max(s) # gain
458
+ shape1.append([int(y * g) for y in s])
459
+ ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
460
+ shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] # inf shape
461
+ x = [letterbox(im, shape1, auto=False)[0] for im in ims] # pad
462
+ x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
463
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
464
+
465
+ with amp.autocast(autocast):
466
+ # Inference
467
+ with dt[1]:
468
+ y = self.model(x, augment=augment) # forward
469
+
470
+ # Post-process
471
+ with dt[2]:
472
+ y = non_max_suppression(y if self.dmb else y[0],
473
+ self.conf,
474
+ self.iou,
475
+ self.classes,
476
+ self.agnostic,
477
+ self.multi_label,
478
+ max_det=self.max_det) # NMS
479
+ for i in range(n):
480
+ scale_boxes(shape1, y[i][:, :4], shape0[i])
481
+
482
+ return Detections(ims, y, files, dt, self.names, x.shape)
483
+
484
+
485
+ class Detections:
486
+ # YOLOv5 detections class for inference results
487
+ def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
488
+ super().__init__()
489
+ d = pred[0].device # device
490
+ gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] # normalizations
491
+ self.ims = ims # list of images as numpy arrays
492
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
493
+ self.names = names # class names
494
+ self.files = files # image filenames
495
+ self.times = times # profiling times
496
+ self.xyxy = pred # xyxy pixels
497
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
498
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
499
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
500
+ self.n = len(self.pred) # number of images (batch size)
501
+ self.t = tuple(x.t / self.n * 1E3 for x in times) # timestamps (ms)
502
+ self.s = tuple(shape) # inference BCHW shape
503
+
504
+ def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
505
+ s, crops = '', []
506
+ for i, (im, pred) in enumerate(zip(self.ims, self.pred)):
507
+ s += f'\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
508
+ if pred.shape[0]:
509
+ for c in pred[:, -1].unique():
510
+ n = (pred[:, -1] == c).sum() # detections per class
511
+ s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
512
+ s = s.rstrip(', ')
513
+ if show or save or render or crop:
514
+ annotator = Annotator(im, example=str(self.names))
515
+ for *box, conf, cls in reversed(pred): # xyxy, confidence, class
516
+ label = f'{self.names[int(cls)]} {conf:.2f}'
517
+ if crop:
518
+ file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
519
+ crops.append({
520
+ 'box': box,
521
+ 'conf': conf,
522
+ 'cls': cls,
523
+ 'label': label,
524
+ 'im': save_one_box(box, im, file=file, save=save)})
525
+ else: # all others
526
+ annotator.box_label(box, label if labels else '', color=colors(cls))
527
+ im = annotator.im
528
+ else:
529
+ s += '(no detections)'
530
+
531
+ im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
532
+ if show:
533
+ display(im) if is_notebook() else im.show(self.files[i])
534
+ if save:
535
+ f = self.files[i]
536
+ im.save(save_dir / f) # save
537
+ if i == self.n - 1:
538
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
539
+ if render:
540
+ self.ims[i] = np.asarray(im)
541
+ if pprint:
542
+ s = s.lstrip('\n')
543
+ return f'{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t
544
+ if crop:
545
+ if save:
546
+ LOGGER.info(f'Saved results to {save_dir}\n')
547
+ return crops
548
+
549
+ @TryExcept('Showing images is not supported in this environment')
550
+ def show(self, labels=True):
551
+ self._run(show=True, labels=labels) # show results
552
+
553
+ def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):
554
+ save_dir = increment_path(save_dir, exist_ok, mkdir=True) # increment save_dir
555
+ self._run(save=True, labels=labels, save_dir=save_dir) # save results
556
+
557
+ def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):
558
+ save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
559
+ return self._run(crop=True, save=save, save_dir=save_dir) # crop results
560
+
561
+ def render(self, labels=True):
562
+ self._run(render=True, labels=labels) # render results
563
+ return self.ims
564
+
565
+ def pandas(self):
566
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
567
+ new = copy(self) # return copy
568
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
569
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
570
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
571
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
572
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
573
+ return new
574
+
575
+ def tolist(self):
576
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
577
+ r = range(self.n) # iterable
578
+ x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
579
+ # for d in x:
580
+ # for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
581
+ # setattr(d, k, getattr(d, k)[0]) # pop out of list
582
+ return x
583
+
584
+ def print(self):
585
+ LOGGER.info(self.__str__())
586
+
587
+ def __len__(self): # override len(results)
588
+ return self.n
589
+
590
+ def __str__(self): # override print(results)
591
+ return self._run(pprint=True) # print results
592
+
593
+ def __repr__(self):
594
+ return f'YOLOv5 {self.__class__} instance\n' + self.__str__()
595
+
596
+
597
+ class Proto(nn.Module):
598
+ # YOLOv5 mask Proto module for segmentation models
599
+ def __init__(self, c1, c_=256, c2=32): # ch_in, number of protos, number of masks
600
+ super().__init__()
601
+ self.cv1 = Conv(c1, c_, k=3)
602
+ self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
603
+ self.cv2 = Conv(c_, c_, k=3)
604
+ self.cv3 = Conv(c_, c2)
605
+
606
+ def forward(self, x):
607
+ return self.cv3(self.cv2(self.upsample(self.cv1(x))))
608
+
609
+
610
+ class Classify(nn.Module):
611
+ # YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2)
612
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
613
+ super().__init__()
614
+ c_ = 1280 # efficientnet_b0 size
615
+ self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
616
+ self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
617
+ self.drop = nn.Dropout(p=0.0, inplace=True)
618
+ self.linear = nn.Linear(c_, c2) # to x(b,c2)
619
+
620
+ def forward(self, x):
621
+ if isinstance(x, list):
622
+ x = torch.cat(x, 1)
623
+ return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
models/experimental.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class Sum(nn.Module):
12
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
13
+ def __init__(self, n, weight=False): # n: number of inputs
14
+ super().__init__()
15
+ self.weight = weight # apply weights boolean
16
+ self.iter = range(n - 1) # iter object
17
+ if weight:
18
+ self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
19
+
20
+ def forward(self, x):
21
+ y = x[0] # no weight
22
+ if self.weight:
23
+ w = torch.sigmoid(self.w) * 2
24
+ for i in self.iter:
25
+ y = y + x[i + 1] * w[i]
26
+ else:
27
+ for i in self.iter:
28
+ y = y + x[i + 1]
29
+ return y
30
+
31
+
32
+ class MixConv2d(nn.Module):
33
+ # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
34
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
35
+ super().__init__()
36
+ n = len(k) # number of convolutions
37
+ if equal_ch: # equal c_ per group
38
+ i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
39
+ c_ = [(i == g).sum() for g in range(n)] # intermediate channels
40
+ else: # equal weight.numel() per group
41
+ b = [c2] + [0] * n
42
+ a = np.eye(n + 1, n, k=-1)
43
+ a -= np.roll(a, 1, axis=1)
44
+ a *= np.array(k) ** 2
45
+ a[0] = 1
46
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
47
+
48
+ self.m = nn.ModuleList([
49
+ nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
50
+ self.bn = nn.BatchNorm2d(c2)
51
+ self.act = nn.SiLU()
52
+
53
+ def forward(self, x):
54
+ return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
55
+
56
+
57
+ class Ensemble(nn.ModuleList):
58
+ # Ensemble of models
59
+ def __init__(self):
60
+ super().__init__()
61
+
62
+ def forward(self, x, augment=False, profile=False, visualize=False):
63
+ y = [module(x, augment, profile, visualize)[0] for module in self]
64
+ # y = torch.stack(y).max(0)[0] # max ensemble
65
+ # y = torch.stack(y).mean(0) # mean ensemble
66
+ y = torch.cat(y, 1) # nms ensemble
67
+ return y, None # inference, train output
68
+
69
+
70
+ def attempt_load(weights, device=None, inplace=True, fuse=True):
71
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
72
+ from models.yolo import Detect, Model
73
+
74
+ model = Ensemble()
75
+ for w in weights if isinstance(weights, list) else [weights]:
76
+ ckpt = torch.load(w, map_location='cpu') # load
77
+ ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
78
+
79
+ # Model compatibility updates
80
+ if not hasattr(ckpt, 'stride'):
81
+ ckpt.stride = torch.tensor([32.])
82
+ if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):
83
+ ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
84
+
85
+ model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode
86
+
87
+ # Module compatibility updates
88
+ for m in model.modules():
89
+ t = type(m)
90
+ if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
91
+ m.inplace = inplace # torch 1.7.0 compatibility
92
+ if t is Detect and not isinstance(m.anchor_grid, list):
93
+ delattr(m, 'anchor_grid')
94
+ setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
95
+ elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
96
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
97
+
98
+ # Return model
99
+ if len(model) == 1:
100
+ return model[-1]
101
+
102
+ # Return detection ensemble
103
+ print(f'Ensemble created with {weights}\n')
104
+ for k in 'names', 'nc', 'yaml':
105
+ setattr(model, k, getattr(model[0], k))
106
+ model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
107
+ assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
108
+ return model
models/hub/anchors.yaml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ # Default anchors for COCO data
3
+
4
+
5
+ # P5 -------------------------------------------------------------------------------------------------------------------
6
+ # P5-640:
7
+ anchors_p5_640:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+
13
+ # P6 -------------------------------------------------------------------------------------------------------------------
14
+ # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
15
+ anchors_p6_640:
16
+ - [9,11, 21,19, 17,41] # P3/8
17
+ - [43,32, 39,70, 86,64] # P4/16
18
+ - [65,131, 134,130, 120,265] # P5/32
19
+ - [282,180, 247,354, 512,387] # P6/64
20
+
21
+ # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
22
+ anchors_p6_1280:
23
+ - [19,27, 44,40, 38,94] # P3/8
24
+ - [96,68, 86,152, 180,137] # P4/16
25
+ - [140,301, 303,264, 238,542] # P5/32
26
+ - [436,615, 739,380, 925,792] # P6/64
27
+
28
+ # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
29
+ anchors_p6_1920:
30
+ - [28,41, 67,59, 57,141] # P3/8
31
+ - [144,103, 129,227, 270,205] # P4/16
32
+ - [209,452, 455,396, 358,812] # P5/32
33
+ - [653,922, 1109,570, 1387,1187] # P6/64
34
+
35
+
36
+ # P7 -------------------------------------------------------------------------------------------------------------------
37
+ # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
38
+ anchors_p7_640:
39
+ - [11,11, 13,30, 29,20] # P3/8
40
+ - [30,46, 61,38, 39,92] # P4/16
41
+ - [78,80, 146,66, 79,163] # P5/32
42
+ - [149,150, 321,143, 157,303] # P6/64
43
+ - [257,402, 359,290, 524,372] # P7/128
44
+
45
+ # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
46
+ anchors_p7_1280:
47
+ - [19,22, 54,36, 32,77] # P3/8
48
+ - [70,83, 138,71, 75,173] # P4/16
49
+ - [165,159, 148,334, 375,151] # P5/32
50
+ - [334,317, 251,626, 499,474] # P6/64
51
+ - [750,326, 534,814, 1079,818] # P7/128
52
+
53
+ # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
54
+ anchors_p7_1920:
55
+ - [29,34, 81,55, 47,115] # P3/8
56
+ - [105,124, 207,107, 113,259] # P4/16
57
+ - [247,238, 222,500, 563,227] # P5/32
58
+ - [501,476, 376,939, 749,711] # P6/64
59
+ - [1126,489, 801,1222, 1618,1227] # P7/128
models/hub/yolov5-bifpn.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 BiFPN head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/hub/yolov5-fpn.yaml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 FPN head
28
+ head:
29
+ [[-1, 3, C3, [1024, False]], # 10 (P5/32-large)
30
+
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 3, C3, [512, False]], # 14 (P4/16-medium)
35
+
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 3, C3, [256, False]], # 18 (P3/8-small)
40
+
41
+ [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42
+ ]
models/hub/yolov5-p2.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 6, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [1024]],
21
+ [-1, 1, SPPF, [1024, 5]], # 9
22
+ ]
23
+
24
+ # YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs
25
+ head:
26
+ [[-1, 1, Conv, [512, 1, 1]],
27
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
28
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
29
+ [-1, 3, C3, [512, False]], # 13
30
+
31
+ [-1, 1, Conv, [256, 1, 1]],
32
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
34
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
35
+
36
+ [-1, 1, Conv, [128, 1, 1]],
37
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38
+ [[-1, 2], 1, Concat, [1]], # cat backbone P2
39
+ [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall)
40
+
41
+ [-1, 1, Conv, [128, 3, 2]],
42
+ [[-1, 18], 1, Concat, [1]], # cat head P3
43
+ [-1, 3, C3, [256, False]], # 24 (P3/8-small)
44
+
45
+ [-1, 1, Conv, [256, 3, 2]],
46
+ [[-1, 14], 1, Concat, [1]], # cat head P4
47
+ [-1, 3, C3, [512, False]], # 27 (P4/16-medium)
48
+
49
+ [-1, 1, Conv, [512, 3, 2]],
50
+ [[-1, 10], 1, Concat, [1]], # cat head P5
51
+ [-1, 3, C3, [1024, False]], # 30 (P5/32-large)
52
+
53
+ [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
54
+ ]
models/hub/yolov5-p34.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 0-P1/2
13
+ [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14
+ [ -1, 3, C3, [ 128 ] ],
15
+ [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16
+ [ -1, 6, C3, [ 256 ] ],
17
+ [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18
+ [ -1, 9, C3, [ 512 ] ],
19
+ [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32
20
+ [ -1, 3, C3, [ 1024 ] ],
21
+ [ -1, 1, SPPF, [ 1024, 5 ] ], # 9
22
+ ]
23
+
24
+ # YOLOv5 v6.0 head with (P3, P4) outputs
25
+ head:
26
+ [ [ -1, 1, Conv, [ 512, 1, 1 ] ],
27
+ [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
28
+ [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
29
+ [ -1, 3, C3, [ 512, False ] ], # 13
30
+
31
+ [ -1, 1, Conv, [ 256, 1, 1 ] ],
32
+ [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
33
+ [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
34
+ [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
35
+
36
+ [ -1, 1, Conv, [ 256, 3, 2 ] ],
37
+ [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
38
+ [ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium)
39
+
40
+ [ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4)
41
+ ]
models/hub/yolov5-p6.yaml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 6, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [768]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22
+ [-1, 3, C3, [1024]],
23
+ [-1, 1, SPPF, [1024, 5]], # 11
24
+ ]
25
+
26
+ # YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs
27
+ head:
28
+ [[-1, 1, Conv, [768, 1, 1]],
29
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
30
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
31
+ [-1, 3, C3, [768, False]], # 15
32
+
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
35
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
36
+ [-1, 3, C3, [512, False]], # 19
37
+
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
40
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
41
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
42
+
43
+ [-1, 1, Conv, [256, 3, 2]],
44
+ [[-1, 20], 1, Concat, [1]], # cat head P4
45
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
46
+
47
+ [-1, 1, Conv, [512, 3, 2]],
48
+ [[-1, 16], 1, Concat, [1]], # cat head P5
49
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
50
+
51
+ [-1, 1, Conv, [768, 3, 2]],
52
+ [[-1, 12], 1, Concat, [1]], # cat head P6
53
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
54
+
55
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
56
+ ]
models/hub/yolov5-p7.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
8
+
9
+ # YOLOv5 v6.0 backbone
10
+ backbone:
11
+ # [from, number, module, args]
12
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
13
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14
+ [-1, 3, C3, [128]],
15
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16
+ [-1, 6, C3, [256]],
17
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18
+ [-1, 9, C3, [512]],
19
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20
+ [-1, 3, C3, [768]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22
+ [-1, 3, C3, [1024]],
23
+ [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128
24
+ [-1, 3, C3, [1280]],
25
+ [-1, 1, SPPF, [1280, 5]], # 13
26
+ ]
27
+
28
+ # YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs
29
+ head:
30
+ [[-1, 1, Conv, [1024, 1, 1]],
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 10], 1, Concat, [1]], # cat backbone P6
33
+ [-1, 3, C3, [1024, False]], # 17
34
+
35
+ [-1, 1, Conv, [768, 1, 1]],
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
38
+ [-1, 3, C3, [768, False]], # 21
39
+
40
+ [-1, 1, Conv, [512, 1, 1]],
41
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
42
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
43
+ [-1, 3, C3, [512, False]], # 25
44
+
45
+ [-1, 1, Conv, [256, 1, 1]],
46
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
47
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
48
+ [-1, 3, C3, [256, False]], # 29 (P3/8-small)
49
+
50
+ [-1, 1, Conv, [256, 3, 2]],
51
+ [[-1, 26], 1, Concat, [1]], # cat head P4
52
+ [-1, 3, C3, [512, False]], # 32 (P4/16-medium)
53
+
54
+ [-1, 1, Conv, [512, 3, 2]],
55
+ [[-1, 22], 1, Concat, [1]], # cat head P5
56
+ [-1, 3, C3, [768, False]], # 35 (P5/32-large)
57
+
58
+ [-1, 1, Conv, [768, 3, 2]],
59
+ [[-1, 18], 1, Concat, [1]], # cat head P6
60
+ [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge)
61
+
62
+ [-1, 1, Conv, [1024, 3, 2]],
63
+ [[-1, 14], 1, Concat, [1]], # cat head P7
64
+ [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge)
65
+
66
+ [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7)
67
+ ]
models/hub/yolov5-panet.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 PANet head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/hub/yolov5l6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/hub/yolov5m6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.67 # model depth multiple
6
+ width_multiple: 0.75 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/hub/yolov5n6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.25 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/hub/yolov5s-LeakyReLU.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ activation: nn.LeakyReLU(0.1) # <----- Conv() activation used throughout entire YOLOv5 model
6
+ depth_multiple: 0.33 # model depth multiple
7
+ width_multiple: 0.50 # layer channel multiple
8
+ anchors:
9
+ - [10,13, 16,30, 33,23] # P3/8
10
+ - [30,61, 62,45, 59,119] # P4/16
11
+ - [116,90, 156,198, 373,326] # P5/32
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [1024]],
25
+ [-1, 1, SPPF, [1024, 5]], # 9
26
+ ]
27
+
28
+ # YOLOv5 v6.0 head
29
+ head:
30
+ [[-1, 1, Conv, [512, 1, 1]],
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
33
+ [-1, 3, C3, [512, False]], # 13
34
+
35
+ [-1, 1, Conv, [256, 1, 1]],
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
38
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
39
+
40
+ [-1, 1, Conv, [256, 3, 2]],
41
+ [[-1, 14], 1, Concat, [1]], # cat head P4
42
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
43
+
44
+ [-1, 1, Conv, [512, 3, 2]],
45
+ [[-1, 10], 1, Concat, [1]], # cat head P5
46
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
47
+
48
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
49
+ ]
models/hub/yolov5s-ghost.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3Ghost, [128]],
18
+ [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3Ghost, [256]],
20
+ [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3Ghost, [512]],
22
+ [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3Ghost, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, GhostConv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3Ghost, [512, False]], # 13
33
+
34
+ [-1, 1, GhostConv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, GhostConv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, GhostConv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/hub/yolov5s-transformer.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3TR, [1024]], # 9 <--- C3TR() Transformer module
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/hub/yolov5s6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/hub/yolov5x6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.33 # model depth multiple
6
+ width_multiple: 1.25 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 v6.0 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 6, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 3, C3, [1024]],
27
+ [-1, 1, SPPF, [1024, 5]], # 11
28
+ ]
29
+
30
+ # YOLOv5 v6.0 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/yolo.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ YOLO-specific modules
4
+
5
+ Usage:
6
+ $ python models/yolo.py --cfg yolov5s.yaml
7
+ """
8
+
9
+ import argparse
10
+ import contextlib
11
+ import os
12
+ import platform
13
+ import sys
14
+ from copy import deepcopy
15
+ from pathlib import Path
16
+
17
+ FILE = Path(__file__).resolve()
18
+ ROOT = FILE.parents[1] # YOLOv5 root directory
19
+ if str(ROOT) not in sys.path:
20
+ sys.path.append(str(ROOT)) # add ROOT to PATH
21
+ if platform.system() != 'Windows':
22
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
23
+
24
+ from models.common import *
25
+ from models.experimental import *
26
+ from utils.autoanchor import check_anchor_order
27
+ from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
28
+ from utils.plots import feature_visualization
29
+ from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
30
+ time_sync)
31
+
32
+ try:
33
+ import thop # for FLOPs computation
34
+ except ImportError:
35
+ thop = None
36
+
37
+
38
+ class Detect(nn.Module):
39
+ # YOLOv5 Detect head for detection models
40
+ stride = None # strides computed during build
41
+ dynamic = False # force grid reconstruction
42
+ export = False # export mode
43
+
44
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
45
+ super().__init__()
46
+ self.nc = nc # number of classes
47
+ self.no = nc + 5 # number of outputs per anchor
48
+ self.nl = len(anchors) # number of detection layers
49
+ self.na = len(anchors[0]) // 2 # number of anchors
50
+ self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
51
+ self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
52
+ self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
53
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
54
+ self.inplace = inplace # use inplace ops (e.g. slice assignment)
55
+
56
+ def forward(self, x):
57
+ z = [] # inference output
58
+ for i in range(self.nl):
59
+ x[i] = self.m[i](x[i]) # conv
60
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
61
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
62
+
63
+ if not self.training: # inference
64
+ if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
65
+ self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
66
+
67
+ if isinstance(self, Segment): # (boxes + masks)
68
+ xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
69
+ xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
70
+ wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
71
+ y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
72
+ else: # Detect (boxes only)
73
+ xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
74
+ xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
75
+ wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
76
+ y = torch.cat((xy, wh, conf), 4)
77
+ z.append(y.view(bs, self.na * nx * ny, self.no))
78
+
79
+ return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
80
+
81
+ def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):
82
+ d = self.anchors[i].device
83
+ t = self.anchors[i].dtype
84
+ shape = 1, self.na, ny, nx, 2 # grid shape
85
+ y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
86
+ yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
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 Segment(Detect):
93
+ # YOLOv5 Segment head for segmentation models
94
+ def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
95
+ super().__init__(nc, anchors, ch, inplace)
96
+ self.nm = nm # number of masks
97
+ self.npr = npr # number of protos
98
+ self.no = 5 + nc + self.nm # number of outputs per anchor
99
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
100
+ self.proto = Proto(ch[0], self.npr, self.nm) # protos
101
+ self.detect = Detect.forward
102
+
103
+ def forward(self, x):
104
+ p = self.proto(x[0])
105
+ x = self.detect(self, x)
106
+ return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
107
+
108
+
109
+ class BaseModel(nn.Module):
110
+ # YOLOv5 base model
111
+ def forward(self, x, profile=False, visualize=False):
112
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
113
+
114
+ def _forward_once(self, x, profile=False, visualize=False):
115
+ y, dt = [], [] # outputs
116
+ for m in self.model:
117
+ if m.f != -1: # if not from previous layer
118
+ 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
119
+ if profile:
120
+ self._profile_one_layer(m, x, dt)
121
+ x = m(x) # run
122
+ y.append(x if m.i in self.save else None) # save output
123
+ if visualize:
124
+ feature_visualization(x, m.type, m.i, save_dir=visualize)
125
+ return x
126
+
127
+ def _profile_one_layer(self, m, x, dt):
128
+ c = m == self.model[-1] # is final layer, copy input as inplace fix
129
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
130
+ t = time_sync()
131
+ for _ in range(10):
132
+ m(x.copy() if c else x)
133
+ dt.append((time_sync() - t) * 100)
134
+ if m == self.model[0]:
135
+ LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
136
+ LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
137
+ if c:
138
+ LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
139
+
140
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
141
+ LOGGER.info('Fusing layers... ')
142
+ for m in self.model.modules():
143
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
144
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
145
+ delattr(m, 'bn') # remove batchnorm
146
+ m.forward = m.forward_fuse # update forward
147
+ self.info()
148
+ return self
149
+
150
+ def info(self, verbose=False, img_size=640): # print model information
151
+ model_info(self, verbose, img_size)
152
+
153
+ def _apply(self, fn):
154
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
155
+ self = super()._apply(fn)
156
+ m = self.model[-1] # Detect()
157
+ if isinstance(m, (Detect, Segment)):
158
+ m.stride = fn(m.stride)
159
+ m.grid = list(map(fn, m.grid))
160
+ if isinstance(m.anchor_grid, list):
161
+ m.anchor_grid = list(map(fn, m.anchor_grid))
162
+ return self
163
+
164
+
165
+ class DetectionModel(BaseModel):
166
+ # YOLOv5 detection model
167
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
168
+ super().__init__()
169
+ if isinstance(cfg, dict):
170
+ self.yaml = cfg # model dict
171
+ else: # is *.yaml
172
+ import yaml # for torch hub
173
+ self.yaml_file = Path(cfg).name
174
+ with open(cfg, encoding='ascii', errors='ignore') as f:
175
+ self.yaml = yaml.safe_load(f) # model dict
176
+
177
+ # Define model
178
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
179
+ if nc and nc != self.yaml['nc']:
180
+ LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
181
+ self.yaml['nc'] = nc # override yaml value
182
+ if anchors:
183
+ LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
184
+ self.yaml['anchors'] = round(anchors) # override yaml value
185
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
186
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
187
+ self.inplace = self.yaml.get('inplace', True)
188
+
189
+ # Build strides, anchors
190
+ m = self.model[-1] # Detect()
191
+ if isinstance(m, (Detect, Segment)):
192
+ s = 256 # 2x min stride
193
+ m.inplace = self.inplace
194
+ forward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
195
+ m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward
196
+ check_anchor_order(m)
197
+ m.anchors /= m.stride.view(-1, 1, 1)
198
+ self.stride = m.stride
199
+ self._initialize_biases() # only run once
200
+
201
+ # Init weights, biases
202
+ initialize_weights(self)
203
+ self.info()
204
+ LOGGER.info('')
205
+
206
+ def forward(self, x, augment=False, profile=False, visualize=False):
207
+ if augment:
208
+ return self._forward_augment(x) # augmented inference, None
209
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
210
+
211
+ def _forward_augment(self, x):
212
+ img_size = x.shape[-2:] # height, width
213
+ s = [1, 0.83, 0.67] # scales
214
+ f = [None, 3, None] # flips (2-ud, 3-lr)
215
+ y = [] # outputs
216
+ for si, fi in zip(s, f):
217
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
218
+ yi = self._forward_once(xi)[0] # forward
219
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
220
+ yi = self._descale_pred(yi, fi, si, img_size)
221
+ y.append(yi)
222
+ y = self._clip_augmented(y) # clip augmented tails
223
+ return torch.cat(y, 1), None # augmented inference, train
224
+
225
+ def _descale_pred(self, p, flips, scale, img_size):
226
+ # de-scale predictions following augmented inference (inverse operation)
227
+ if self.inplace:
228
+ p[..., :4] /= scale # de-scale
229
+ if flips == 2:
230
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
231
+ elif flips == 3:
232
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
233
+ else:
234
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
235
+ if flips == 2:
236
+ y = img_size[0] - y # de-flip ud
237
+ elif flips == 3:
238
+ x = img_size[1] - x # de-flip lr
239
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
240
+ return p
241
+
242
+ def _clip_augmented(self, y):
243
+ # Clip YOLOv5 augmented inference tails
244
+ nl = self.model[-1].nl # number of detection layers (P3-P5)
245
+ g = sum(4 ** x for x in range(nl)) # grid points
246
+ e = 1 # exclude layer count
247
+ i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
248
+ y[0] = y[0][:, :-i] # large
249
+ i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
250
+ y[-1] = y[-1][:, i:] # small
251
+ return y
252
+
253
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
254
+ # https://arxiv.org/abs/1708.02002 section 3.3
255
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
256
+ m = self.model[-1] # Detect() module
257
+ for mi, s in zip(m.m, m.stride): # from
258
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
259
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
260
+ b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # cls
261
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
262
+
263
+
264
+ Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility
265
+
266
+
267
+ class SegmentationModel(DetectionModel):
268
+ # YOLOv5 segmentation model
269
+ def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None):
270
+ super().__init__(cfg, ch, nc, anchors)
271
+
272
+
273
+ class ClassificationModel(BaseModel):
274
+ # YOLOv5 classification model
275
+ def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index
276
+ super().__init__()
277
+ self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
278
+
279
+ def _from_detection_model(self, model, nc=1000, cutoff=10):
280
+ # Create a YOLOv5 classification model from a YOLOv5 detection model
281
+ if isinstance(model, DetectMultiBackend):
282
+ model = model.model # unwrap DetectMultiBackend
283
+ model.model = model.model[:cutoff] # backbone
284
+ m = model.model[-1] # last layer
285
+ ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module
286
+ c = Classify(ch, nc) # Classify()
287
+ c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type
288
+ model.model[-1] = c # replace
289
+ self.model = model.model
290
+ self.stride = model.stride
291
+ self.save = []
292
+ self.nc = nc
293
+
294
+ def _from_yaml(self, cfg):
295
+ # Create a YOLOv5 classification model from a *.yaml file
296
+ self.model = None
297
+
298
+
299
+ def parse_model(d, ch): # model_dict, input_channels(3)
300
+ # Parse a YOLOv5 model.yaml dictionary
301
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
302
+ anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation')
303
+ if act:
304
+ Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
305
+ LOGGER.info(f"{colorstr('activation:')} {act}") # print
306
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
307
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
308
+
309
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
310
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
311
+ m = eval(m) if isinstance(m, str) else m # eval strings
312
+ for j, a in enumerate(args):
313
+ with contextlib.suppress(NameError):
314
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
315
+
316
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
317
+ if m in {
318
+ Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
319
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:
320
+ c1, c2 = ch[f], args[0]
321
+ if c2 != no: # if not output
322
+ c2 = make_divisible(c2 * gw, 8)
323
+
324
+ args = [c1, c2, *args[1:]]
325
+ if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
326
+ args.insert(2, n) # number of repeats
327
+ n = 1
328
+ elif m is nn.BatchNorm2d:
329
+ args = [ch[f]]
330
+ elif m is Concat:
331
+ c2 = sum(ch[x] for x in f)
332
+ # TODO: channel, gw, gd
333
+ elif m in {Detect, Segment}:
334
+ args.append([ch[x] for x in f])
335
+ if isinstance(args[1], int): # number of anchors
336
+ args[1] = [list(range(args[1] * 2))] * len(f)
337
+ if m is Segment:
338
+ args[3] = make_divisible(args[3] * gw, 8)
339
+ elif m is Contract:
340
+ c2 = ch[f] * args[0] ** 2
341
+ elif m is Expand:
342
+ c2 = ch[f] // args[0] ** 2
343
+ else:
344
+ c2 = ch[f]
345
+
346
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
347
+ t = str(m)[8:-2].replace('__main__.', '') # module type
348
+ np = sum(x.numel() for x in m_.parameters()) # number params
349
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
350
+ LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
351
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
352
+ layers.append(m_)
353
+ if i == 0:
354
+ ch = []
355
+ ch.append(c2)
356
+ return nn.Sequential(*layers), sorted(save)
357
+
358
+
359
+ if __name__ == '__main__':
360
+ parser = argparse.ArgumentParser()
361
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
362
+ parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
363
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
364
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
365
+ parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
366
+ parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
367
+ opt = parser.parse_args()
368
+ opt.cfg = check_yaml(opt.cfg) # check YAML
369
+ print_args(vars(opt))
370
+ device = select_device(opt.device)
371
+
372
+ # Create model
373
+ im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
374
+ model = Model(opt.cfg).to(device)
375
+
376
+ # Options
377
+ if opt.line_profile: # profile layer by layer
378
+ model(im, profile=True)
379
+
380
+ elif opt.profile: # profile forward-backward
381
+ results = profile(input=im, ops=[model], n=3)
382
+
383
+ elif opt.test: # test all models
384
+ for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
385
+ try:
386
+ _ = Model(cfg)
387
+ except Exception as e:
388
+ print(f'Error in {cfg}: {e}')
389
+
390
+ else: # report fused model summary
391
+ model.fuse()
models/yolov5l.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5m.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.67 # model depth multiple
6
+ width_multiple: 0.75 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5n.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.25 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5s.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5x.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.33 # model depth multiple
6
+ width_multiple: 1.25 # layer channel multiple
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 v6.0 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, C3, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 6, C3, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, C3, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 3, C3, [1024]],
24
+ [-1, 1, SPPF, [1024, 5]], # 9
25
+ ]
26
+
27
+ # YOLOv5 v6.0 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, C3, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
utils/__init__.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ utils/initialization
4
+ """
5
+
6
+ import contextlib
7
+ import platform
8
+ import threading
9
+
10
+
11
+ def emojis(str=''):
12
+ # Return platform-dependent emoji-safe version of string
13
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
14
+
15
+
16
+ class TryExcept(contextlib.ContextDecorator):
17
+ # YOLOv5 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager
18
+ def __init__(self, msg=''):
19
+ self.msg = msg
20
+
21
+ def __enter__(self):
22
+ pass
23
+
24
+ def __exit__(self, exc_type, value, traceback):
25
+ if value:
26
+ print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
27
+ return True
28
+
29
+
30
+ def threaded(func):
31
+ # Multi-threads a target function and returns thread. Usage: @threaded decorator
32
+ def wrapper(*args, **kwargs):
33
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
34
+ thread.start()
35
+ return thread
36
+
37
+ return wrapper
38
+
39
+
40
+ def join_threads(verbose=False):
41
+ # Join all daemon threads, i.e. atexit.register(lambda: join_threads())
42
+ main_thread = threading.current_thread()
43
+ for t in threading.enumerate():
44
+ if t is not main_thread:
45
+ if verbose:
46
+ print(f'Joining thread {t.name}')
47
+ t.join()
48
+
49
+
50
+ def notebook_init(verbose=True):
51
+ # Check system software and hardware
52
+ print('Checking setup...')
53
+
54
+ import os
55
+ import shutil
56
+
57
+ from utils.general import check_font, check_requirements, is_colab
58
+ from utils.torch_utils import select_device # imports
59
+
60
+ check_font()
61
+
62
+ import psutil
63
+ from IPython import display # to display images and clear console output
64
+
65
+ if is_colab():
66
+ shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory
67
+
68
+ # System info
69
+ if verbose:
70
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
71
+ ram = psutil.virtual_memory().total
72
+ total, used, free = shutil.disk_usage("/")
73
+ display.clear_output()
74
+ s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)'
75
+ else:
76
+ s = ''
77
+
78
+ select_device(newline=False)
79
+ print(emojis(f'Setup complete ✅ {s}'))
80
+ return display
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (2.51 kB). View file
 
utils/__pycache__/augmentations.cpython-38.pyc ADDED
Binary file (13.7 kB). View file
 
utils/__pycache__/autoanchor.cpython-38.pyc ADDED
Binary file (6.45 kB). View file
 
utils/__pycache__/dataloaders.cpython-38.pyc ADDED
Binary file (12.7 kB). View file
 
utils/__pycache__/general.cpython-38.pyc ADDED
Binary file (36.7 kB). View file
 
utils/__pycache__/metrics.cpython-38.pyc ADDED
Binary file (11.3 kB). View file
 
utils/__pycache__/plots.cpython-38.pyc ADDED
Binary file (20.2 kB). View file
 
utils/__pycache__/torch_utils.cpython-38.pyc ADDED
Binary file (16.8 kB). View file
 
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,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch
12
+ import torchvision.transforms as T
13
+ import torchvision.transforms.functional as TF
14
+
15
+ from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
16
+ from utils.metrics import bbox_ioa
17
+
18
+ IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
19
+ IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
20
+
21
+
22
+ class Albumentations:
23
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
24
+ def __init__(self, size=640):
25
+ self.transform = None
26
+ prefix = colorstr('albumentations: ')
27
+ try:
28
+ import albumentations as A
29
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
30
+
31
+ T = [
32
+ A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),
33
+ A.Blur(p=0.01),
34
+ A.MedianBlur(p=0.01),
35
+ A.ToGray(p=0.01),
36
+ A.CLAHE(p=0.01),
37
+ A.RandomBrightnessContrast(p=0.0),
38
+ A.RandomGamma(p=0.0),
39
+ A.ImageCompression(quality_lower=75, p=0.0)] # transforms
40
+ self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
41
+
42
+ LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
43
+ except ImportError: # package not installed, skip
44
+ pass
45
+ except Exception as e:
46
+ LOGGER.info(f'{prefix}{e}')
47
+
48
+ def __call__(self, im, labels, p=1.0):
49
+ if self.transform and random.random() < p:
50
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
51
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
52
+ return im, labels
53
+
54
+
55
+ def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
56
+ # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std
57
+ return TF.normalize(x, mean, std, inplace=inplace)
58
+
59
+
60
+ def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
61
+ # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean
62
+ for i in range(3):
63
+ x[:, i] = x[:, i] * std[i] + mean[i]
64
+ return x
65
+
66
+
67
+ def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
68
+ # HSV color-space augmentation
69
+ if hgain or sgain or vgain:
70
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
71
+ hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
72
+ dtype = im.dtype # uint8
73
+
74
+ x = np.arange(0, 256, dtype=r.dtype)
75
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
76
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
77
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
78
+
79
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
80
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
81
+
82
+
83
+ def hist_equalize(im, clahe=True, bgr=False):
84
+ # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
85
+ yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
86
+ if clahe:
87
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
88
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
89
+ else:
90
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
91
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
92
+
93
+
94
+ def replicate(im, labels):
95
+ # Replicate labels
96
+ h, w = im.shape[:2]
97
+ boxes = labels[:, 1:].astype(int)
98
+ x1, y1, x2, y2 = boxes.T
99
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
100
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
101
+ x1b, y1b, x2b, y2b = boxes[i]
102
+ bh, bw = y2b - y1b, x2b - x1b
103
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
104
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
105
+ im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
106
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
107
+
108
+ return im, labels
109
+
110
+
111
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
112
+ # Resize and pad image while meeting stride-multiple constraints
113
+ shape = im.shape[:2] # current shape [height, width]
114
+ if isinstance(new_shape, int):
115
+ new_shape = (new_shape, new_shape)
116
+
117
+ # Scale ratio (new / old)
118
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
119
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
120
+ r = min(r, 1.0)
121
+
122
+ # Compute padding
123
+ ratio = r, r # width, height ratios
124
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
125
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
126
+ if auto: # minimum rectangle
127
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
128
+ elif scaleFill: # stretch
129
+ dw, dh = 0.0, 0.0
130
+ new_unpad = (new_shape[1], new_shape[0])
131
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
132
+
133
+ dw /= 2 # divide padding into 2 sides
134
+ dh /= 2
135
+
136
+ if shape[::-1] != new_unpad: # resize
137
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
138
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
139
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
140
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
141
+ return im, ratio, (dw, dh)
142
+
143
+
144
+ def random_perspective(im,
145
+ targets=(),
146
+ segments=(),
147
+ degrees=10,
148
+ translate=.1,
149
+ scale=.1,
150
+ shear=10,
151
+ perspective=0.0,
152
+ border=(0, 0)):
153
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
154
+ # targets = [cls, xyxy]
155
+
156
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
157
+ width = im.shape[1] + border[1] * 2
158
+
159
+ # Center
160
+ C = np.eye(3)
161
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
162
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
163
+
164
+ # Perspective
165
+ P = np.eye(3)
166
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
167
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
168
+
169
+ # Rotation and Scale
170
+ R = np.eye(3)
171
+ a = random.uniform(-degrees, degrees)
172
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
173
+ s = random.uniform(1 - scale, 1 + scale)
174
+ # s = 2 ** random.uniform(-scale, scale)
175
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
176
+
177
+ # Shear
178
+ S = np.eye(3)
179
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
180
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
181
+
182
+ # Translation
183
+ T = np.eye(3)
184
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
185
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
186
+
187
+ # Combined rotation matrix
188
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
189
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
190
+ if perspective:
191
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
192
+ else: # affine
193
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
194
+
195
+ # Visualize
196
+ # import matplotlib.pyplot as plt
197
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
198
+ # ax[0].imshow(im[:, :, ::-1]) # base
199
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
200
+
201
+ # Transform label coordinates
202
+ n = len(targets)
203
+ if n:
204
+ use_segments = any(x.any() for x in segments)
205
+ new = np.zeros((n, 4))
206
+ if use_segments: # warp segments
207
+ segments = resample_segments(segments) # upsample
208
+ for i, segment in enumerate(segments):
209
+ xy = np.ones((len(segment), 3))
210
+ xy[:, :2] = segment
211
+ xy = xy @ M.T # transform
212
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
213
+
214
+ # clip
215
+ new[i] = segment2box(xy, width, height)
216
+
217
+ else: # warp boxes
218
+ xy = np.ones((n * 4, 3))
219
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
220
+ xy = xy @ M.T # transform
221
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
222
+
223
+ # create new boxes
224
+ x = xy[:, [0, 2, 4, 6]]
225
+ y = xy[:, [1, 3, 5, 7]]
226
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
227
+
228
+ # clip
229
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
230
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
231
+
232
+ # filter candidates
233
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
234
+ targets = targets[i]
235
+ targets[:, 1:5] = new[i]
236
+
237
+ return im, targets
238
+
239
+
240
+ def copy_paste(im, labels, segments, p=0.5):
241
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
242
+ n = len(segments)
243
+ if p and n:
244
+ h, w, c = im.shape # height, width, channels
245
+ im_new = np.zeros(im.shape, np.uint8)
246
+ for j in random.sample(range(n), k=round(p * n)):
247
+ l, s = labels[j], segments[j]
248
+ box = w - l[3], l[2], w - l[1], l[4]
249
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
250
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
251
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
252
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
253
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
254
+
255
+ result = cv2.flip(im, 1) # augment segments (flip left-right)
256
+ i = cv2.flip(im_new, 1).astype(bool)
257
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
258
+
259
+ return im, labels, segments
260
+
261
+
262
+ def cutout(im, labels, p=0.5):
263
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
264
+ if random.random() < p:
265
+ h, w = im.shape[:2]
266
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
267
+ for s in scales:
268
+ mask_h = random.randint(1, int(h * s)) # create random masks
269
+ mask_w = random.randint(1, int(w * s))
270
+
271
+ # box
272
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
273
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
274
+ xmax = min(w, xmin + mask_w)
275
+ ymax = min(h, ymin + mask_h)
276
+
277
+ # apply random color mask
278
+ im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
279
+
280
+ # return unobscured labels
281
+ if len(labels) and s > 0.03:
282
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
283
+ ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h)) # intersection over area
284
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
285
+
286
+ return labels
287
+
288
+
289
+ def mixup(im, labels, im2, labels2):
290
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
291
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
292
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
293
+ labels = np.concatenate((labels, labels2), 0)
294
+ return im, labels
295
+
296
+
297
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
298
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
299
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
300
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
301
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
302
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
303
+
304
+
305
+ def classify_albumentations(
306
+ augment=True,
307
+ size=224,
308
+ scale=(0.08, 1.0),
309
+ ratio=(0.75, 1.0 / 0.75), # 0.75, 1.33
310
+ hflip=0.5,
311
+ vflip=0.0,
312
+ jitter=0.4,
313
+ mean=IMAGENET_MEAN,
314
+ std=IMAGENET_STD,
315
+ auto_aug=False):
316
+ # YOLOv5 classification Albumentations (optional, only used if package is installed)
317
+ prefix = colorstr('albumentations: ')
318
+ try:
319
+ import albumentations as A
320
+ from albumentations.pytorch import ToTensorV2
321
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
322
+ if augment: # Resize and crop
323
+ T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]
324
+ if auto_aug:
325
+ # TODO: implement AugMix, AutoAug & RandAug in albumentation
326
+ LOGGER.info(f'{prefix}auto augmentations are currently not supported')
327
+ else:
328
+ if hflip > 0:
329
+ T += [A.HorizontalFlip(p=hflip)]
330
+ if vflip > 0:
331
+ T += [A.VerticalFlip(p=vflip)]
332
+ if jitter > 0:
333
+ color_jitter = (float(jitter),) * 3 # repeat value for brightness, contrast, satuaration, 0 hue
334
+ T += [A.ColorJitter(*color_jitter, 0)]
335
+ else: # Use fixed crop for eval set (reproducibility)
336
+ T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
337
+ T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
338
+ LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
339
+ return A.Compose(T)
340
+
341
+ except ImportError: # package not installed, skip
342
+ LOGGER.warning(f'{prefix}⚠️ not found, install with `pip install albumentations` (recommended)')
343
+ except Exception as e:
344
+ LOGGER.info(f'{prefix}{e}')
345
+
346
+
347
+ def classify_transforms(size=224):
348
+ # Transforms to apply if albumentations not installed
349
+ assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'
350
+ # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
351
+ return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
352
+
353
+
354
+ class LetterBox:
355
+ # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
356
+ def __init__(self, size=(640, 640), auto=False, stride=32):
357
+ super().__init__()
358
+ self.h, self.w = (size, size) if isinstance(size, int) else size
359
+ self.auto = auto # pass max size integer, automatically solve for short side using stride
360
+ self.stride = stride # used with auto
361
+
362
+ def __call__(self, im): # im = np.array HWC
363
+ imh, imw = im.shape[:2]
364
+ r = min(self.h / imh, self.w / imw) # ratio of new/old
365
+ h, w = round(imh * r), round(imw * r) # resized image
366
+ hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
367
+ top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
368
+ im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
369
+ im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
370
+ return im_out
371
+
372
+
373
+ class CenterCrop:
374
+ # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])
375
+ def __init__(self, size=640):
376
+ super().__init__()
377
+ self.h, self.w = (size, size) if isinstance(size, int) else size
378
+
379
+ def __call__(self, im): # im = np.array HWC
380
+ imh, imw = im.shape[:2]
381
+ m = min(imh, imw) # min dimension
382
+ top, left = (imh - m) // 2, (imw - m) // 2
383
+ return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
384
+
385
+
386
+ class ToTensor:
387
+ # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
388
+ def __init__(self, half=False):
389
+ super().__init__()
390
+ self.half = half
391
+
392
+ def __call__(self, im): # im = np.array HWC in BGR order
393
+ im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
394
+ im = torch.from_numpy(im) # to torch
395
+ im = im.half() if self.half else im.float() # uint8 to fp16/32
396
+ im /= 255.0 # 0-255 to 0.0-1.0
397
+ return im
utils/autoanchor.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 import TryExcept
14
+ from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr
15
+
16
+ PREFIX = colorstr('AutoAnchor: ')
17
+
18
+
19
+ def check_anchor_order(m):
20
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
21
+ a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer
22
+ da = a[-1] - a[0] # delta a
23
+ ds = m.stride[-1] - m.stride[0] # delta s
24
+ if da and (da.sign() != ds.sign()): # same order
25
+ LOGGER.info(f'{PREFIX}Reversing anchor order')
26
+ m.anchors[:] = m.anchors.flip(0)
27
+
28
+
29
+ @TryExcept(f'{PREFIX}ERROR')
30
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
31
+ # Check anchor fit to data, recompute if necessary
32
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
33
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
34
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
35
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
36
+
37
+ def metric(k): # compute metric
38
+ r = wh[:, None] / k[None]
39
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
40
+ best = x.max(1)[0] # best_x
41
+ aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
42
+ bpr = (best > 1 / thr).float().mean() # best possible recall
43
+ return bpr, aat
44
+
45
+ stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides
46
+ anchors = m.anchors.clone() * stride # current anchors
47
+ bpr, aat = metric(anchors.cpu().view(-1, 2))
48
+ s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '
49
+ if bpr > 0.98: # threshold to recompute
50
+ LOGGER.info(f'{s}Current anchors are a good fit to dataset ✅')
51
+ else:
52
+ LOGGER.info(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...')
53
+ na = m.anchors.numel() // 2 # number of anchors
54
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
55
+ new_bpr = metric(anchors)[0]
56
+ if new_bpr > bpr: # replace anchors
57
+ anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
58
+ m.anchors[:] = anchors.clone().view_as(m.anchors)
59
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
60
+ m.anchors /= stride
61
+ s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)'
62
+ else:
63
+ s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)'
64
+ LOGGER.info(s)
65
+
66
+
67
+ def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
68
+ """ Creates kmeans-evolved anchors from training dataset
69
+
70
+ Arguments:
71
+ dataset: path to data.yaml, or a loaded dataset
72
+ n: number of anchors
73
+ img_size: image size used for training
74
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
75
+ gen: generations to evolve anchors using genetic algorithm
76
+ verbose: print all results
77
+
78
+ Return:
79
+ k: kmeans evolved anchors
80
+
81
+ Usage:
82
+ from utils.autoanchor import *; _ = kmean_anchors()
83
+ """
84
+ from scipy.cluster.vq import kmeans
85
+
86
+ npr = np.random
87
+ thr = 1 / thr
88
+
89
+ def metric(k, wh): # compute metrics
90
+ r = wh[:, None] / k[None]
91
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
92
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
93
+ return x, x.max(1)[0] # x, best_x
94
+
95
+ def anchor_fitness(k): # mutation fitness
96
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
97
+ return (best * (best > thr).float()).mean() # fitness
98
+
99
+ def print_results(k, verbose=True):
100
+ k = k[np.argsort(k.prod(1))] # sort small to large
101
+ x, best = metric(k, wh0)
102
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
103
+ s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \
104
+ f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \
105
+ f'past_thr={x[x > thr].mean():.3f}-mean: '
106
+ for x in k:
107
+ s += '%i,%i, ' % (round(x[0]), round(x[1]))
108
+ if verbose:
109
+ LOGGER.info(s[:-2])
110
+ return k
111
+
112
+ if isinstance(dataset, str): # *.yaml file
113
+ with open(dataset, errors='ignore') as f:
114
+ data_dict = yaml.safe_load(f) # model dict
115
+ from utils.dataloaders import LoadImagesAndLabels
116
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
117
+
118
+ # Get label wh
119
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
120
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
121
+
122
+ # Filter
123
+ i = (wh0 < 3.0).any(1).sum()
124
+ if i:
125
+ LOGGER.info(f'{PREFIX}WARNING ⚠️ Extremely small objects found: {i} of {len(wh0)} labels are <3 pixels in size')
126
+ wh = wh0[(wh0 >= 2.0).any(1)].astype(np.float32) # filter > 2 pixels
127
+ # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
128
+
129
+ # Kmeans init
130
+ try:
131
+ LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')
132
+ assert n <= len(wh) # apply overdetermined constraint
133
+ s = wh.std(0) # sigmas for whitening
134
+ k = kmeans(wh / s, n, iter=30)[0] * s # points
135
+ assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar
136
+ except Exception:
137
+ LOGGER.warning(f'{PREFIX}WARNING ⚠️ switching strategies from kmeans to random init')
138
+ k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init
139
+ wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))
140
+ k = print_results(k, verbose=False)
141
+
142
+ # Plot
143
+ # k, d = [None] * 20, [None] * 20
144
+ # for i in tqdm(range(1, 21)):
145
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
146
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
147
+ # ax = ax.ravel()
148
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
149
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
150
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
151
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
152
+ # fig.savefig('wh.png', dpi=200)
153
+
154
+ # Evolve
155
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
156
+ pbar = tqdm(range(gen), bar_format=TQDM_BAR_FORMAT) # progress bar
157
+ for _ in pbar:
158
+ v = np.ones(sh)
159
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
160
+ v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
161
+ kg = (k.copy() * v).clip(min=2.0)
162
+ fg = anchor_fitness(kg)
163
+ if fg > f:
164
+ f, k = fg, kg.copy()
165
+ pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
166
+ if verbose:
167
+ print_results(k, verbose)
168
+
169
+ return print_results(k).astype(np.float32)
utils/autobatch.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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.8, batch_size=16):
22
+ # Automatically estimate best YOLOv5 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
+ if torch.backends.cudnn.benchmark:
37
+ LOGGER.info(f'{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}')
38
+ return batch_size
39
+
40
+ # Inspect CUDA memory
41
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
42
+ d = str(device).upper() # 'CUDA:0'
43
+ properties = torch.cuda.get_device_properties(device) # device properties
44
+ t = properties.total_memory / gb # GiB total
45
+ r = torch.cuda.memory_reserved(device) / gb # GiB reserved
46
+ a = torch.cuda.memory_allocated(device) / gb # GiB allocated
47
+ f = t - (r + a) # GiB free
48
+ LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
49
+
50
+ # Profile batch sizes
51
+ batch_sizes = [1, 2, 4, 8, 16]
52
+ try:
53
+ img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
54
+ results = profile(img, model, n=3, device=device)
55
+ except Exception as e:
56
+ LOGGER.warning(f'{prefix}{e}')
57
+
58
+ # Fit a solution
59
+ y = [x[2] for x in results if x] # memory [2]
60
+ p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit
61
+ b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
62
+ if None in results: # some sizes failed
63
+ i = results.index(None) # first fail index
64
+ if b >= batch_sizes[i]: # y intercept above failure point
65
+ b = batch_sizes[max(i - 1, 0)] # select prior safe point
66
+ if b < 1 or b > 1024: # b outside of safe range
67
+ b = batch_size
68
+ LOGGER.warning(f'{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command.')
69
+
70
+ fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
71
+ LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')
72
+ return b
utils/callbacks.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Callback utils
4
+ """
5
+
6
+ import threading
7
+
8
+
9
+ class Callbacks:
10
+ """"
11
+ Handles all registered callbacks for YOLOv5 Hooks
12
+ """
13
+
14
+ def __init__(self):
15
+ # Define the available callbacks
16
+ self._callbacks = {
17
+ 'on_pretrain_routine_start': [],
18
+ 'on_pretrain_routine_end': [],
19
+ 'on_train_start': [],
20
+ 'on_train_epoch_start': [],
21
+ 'on_train_batch_start': [],
22
+ 'optimizer_step': [],
23
+ 'on_before_zero_grad': [],
24
+ 'on_train_batch_end': [],
25
+ 'on_train_epoch_end': [],
26
+ 'on_val_start': [],
27
+ 'on_val_batch_start': [],
28
+ 'on_val_image_end': [],
29
+ 'on_val_batch_end': [],
30
+ 'on_val_end': [],
31
+ 'on_fit_epoch_end': [], # fit = train + val
32
+ 'on_model_save': [],
33
+ 'on_train_end': [],
34
+ 'on_params_update': [],
35
+ 'teardown': [],}
36
+ self.stop_training = False # set True to interrupt training
37
+
38
+ def register_action(self, hook, name='', callback=None):
39
+ """
40
+ Register a new action to a callback hook
41
+
42
+ Args:
43
+ hook: The callback hook name to register the action to
44
+ name: The name of the action for later reference
45
+ callback: The callback to fire
46
+ """
47
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
48
+ assert callable(callback), f"callback '{callback}' is not callable"
49
+ self._callbacks[hook].append({'name': name, 'callback': callback})
50
+
51
+ def get_registered_actions(self, hook=None):
52
+ """"
53
+ Returns all the registered actions by callback hook
54
+
55
+ Args:
56
+ hook: The name of the hook to check, defaults to all
57
+ """
58
+ return self._callbacks[hook] if hook else self._callbacks
59
+
60
+ def run(self, hook, *args, thread=False, **kwargs):
61
+ """
62
+ Loop through the registered actions and fire all callbacks on main thread
63
+
64
+ Args:
65
+ hook: The name of the hook to check, defaults to all
66
+ args: Arguments to receive from YOLOv5
67
+ thread: (boolean) Run callbacks in daemon thread
68
+ kwargs: Keyword Arguments to receive from YOLOv5
69
+ """
70
+
71
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
72
+ for logger in self._callbacks[hook]:
73
+ if thread:
74
+ threading.Thread(target=logger['callback'], args=args, kwargs=kwargs, daemon=True).start()
75
+ else:
76
+ logger['callback'](*args, **kwargs)
utils/dataloaders.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Dataloaders and dataset utils
4
+ """
5
+
6
+ import contextlib
7
+ import glob
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import os
12
+ import random
13
+ import shutil
14
+ import time
15
+ from itertools import repeat
16
+ from multiprocessing.pool import Pool, ThreadPool
17
+ from pathlib import Path
18
+ from threading import Thread
19
+ from urllib.parse import urlparse
20
+
21
+ import numpy as np
22
+ import psutil
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torchvision
26
+ import yaml
27
+ from PIL import ExifTags, Image, ImageOps
28
+ from torch.utils.data import DataLoader, Dataset, dataloader, distributed
29
+ from tqdm import tqdm
30
+
31
+ from utils.augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,
32
+ letterbox, mixup, random_perspective)
33
+ from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, check_dataset, check_requirements,
34
+ check_yaml, clean_str, cv2, is_colab, is_kaggle, segments2boxes, unzip_file, xyn2xy,
35
+ xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
36
+ from utils.torch_utils import torch_distributed_zero_first
37
+
38
+ # Parameters
39
+ HELP_URL = 'See https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
40
+ IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm' # include image suffixes
41
+ VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes
42
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
43
+ RANK = int(os.getenv('RANK', -1))
44
+ PIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true' # global pin_memory for dataloaders
45
+
46
+ # Get orientation exif tag
47
+ for orientation in ExifTags.TAGS.keys():
48
+ if ExifTags.TAGS[orientation] == 'Orientation':
49
+ break
50
+
51
+
52
+ def get_hash(paths):
53
+ # Returns a single hash value of a list of paths (files or dirs)
54
+ size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
55
+ h = hashlib.md5(str(size).encode()) # hash sizes
56
+ h.update(''.join(paths).encode()) # hash paths
57
+ return h.hexdigest() # return hash
58
+
59
+
60
+ def exif_size(img):
61
+ # Returns exif-corrected PIL size
62
+ s = img.size # (width, height)
63
+ with contextlib.suppress(Exception):
64
+ rotation = dict(img._getexif().items())[orientation]
65
+ if rotation in [6, 8]: # rotation 270 or 90
66
+ s = (s[1], s[0])
67
+ return s
68
+
69
+
70
+ def exif_transpose(image):
71
+ """
72
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
73
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
74
+
75
+ :param image: The image to transpose.
76
+ :return: An image.
77
+ """
78
+ exif = image.getexif()
79
+ orientation = exif.get(0x0112, 1) # default 1
80
+ if orientation > 1:
81
+ method = {
82
+ 2: Image.FLIP_LEFT_RIGHT,
83
+ 3: Image.ROTATE_180,
84
+ 4: Image.FLIP_TOP_BOTTOM,
85
+ 5: Image.TRANSPOSE,
86
+ 6: Image.ROTATE_270,
87
+ 7: Image.TRANSVERSE,
88
+ 8: Image.ROTATE_90}.get(orientation)
89
+ if method is not None:
90
+ image = image.transpose(method)
91
+ del exif[0x0112]
92
+ image.info["exif"] = exif.tobytes()
93
+ return image
94
+
95
+
96
+ def seed_worker(worker_id):
97
+ # Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader
98
+ worker_seed = torch.initial_seed() % 2 ** 32
99
+ np.random.seed(worker_seed)
100
+ random.seed(worker_seed)
101
+
102
+
103
+
104
+ class LoadImages:
105
+ # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
106
+ def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
107
+ if isinstance(path, str) and Path(path).suffix == ".txt": # *.txt file with img/vid/dir on each line
108
+ path = Path(path).read_text().rsplit()
109
+ files = []
110
+ for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
111
+ p = str(Path(p).resolve())
112
+ if '*' in p:
113
+ files.extend(sorted(glob.glob(p, recursive=True))) # glob
114
+ elif os.path.isdir(p):
115
+ files.extend(sorted(glob.glob(os.path.join(p, '*.*')))) # dir
116
+ elif os.path.isfile(p):
117
+ files.append(p) # files
118
+ else:
119
+ raise FileNotFoundError(f'{p} does not exist')
120
+
121
+ images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
122
+ videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
123
+ ni, nv = len(images), len(videos)
124
+
125
+ self.img_size = img_size
126
+ self.stride = stride
127
+ self.files = images + videos
128
+ self.nf = ni + nv # number of files
129
+ self.video_flag = [False] * ni + [True] * nv
130
+ self.mode = 'image'
131
+ self.auto = auto
132
+ self.transforms = transforms # optional
133
+ self.vid_stride = vid_stride # video frame-rate stride
134
+ if any(videos):
135
+ self._new_video(videos[0]) # new video
136
+ else:
137
+ self.cap = None
138
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
139
+ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
140
+
141
+ def __iter__(self):
142
+ self.count = 0
143
+ return self
144
+
145
+ def __next__(self):
146
+ if self.count == self.nf:
147
+ raise StopIteration
148
+ path = self.files[self.count]
149
+
150
+ if self.video_flag[self.count]:
151
+ # Read video
152
+ self.mode = 'video'
153
+ for _ in range(self.vid_stride):
154
+ self.cap.grab()
155
+ ret_val, im0 = self.cap.retrieve()
156
+ while not ret_val:
157
+ self.count += 1
158
+ self.cap.release()
159
+ if self.count == self.nf: # last video
160
+ raise StopIteration
161
+ path = self.files[self.count]
162
+ self._new_video(path)
163
+ ret_val, im0 = self.cap.read()
164
+
165
+ self.frame += 1
166
+ # im0 = self._cv2_rotate(im0) # for use if cv2 autorotation is False
167
+ s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
168
+
169
+ else:
170
+ # Read image
171
+ self.count += 1
172
+ im0 = cv2.imread(path) # BGR
173
+ assert im0 is not None, f'Image Not Found {path}'
174
+ s = f'image {self.count}/{self.nf} {path}: '
175
+
176
+ if self.transforms:
177
+ im = self.transforms(im0) # transforms
178
+ else:
179
+ im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize
180
+ im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
181
+ im = np.ascontiguousarray(im) # contiguous
182
+
183
+ return path, im, im0, self.cap, s
184
+
185
+ def _new_video(self, path):
186
+ # Create a new video capture object
187
+ self.frame = 0
188
+ self.cap = cv2.VideoCapture(path)
189
+ self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)
190
+ self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META)) # rotation degrees
191
+ # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0) # disable https://github.com/ultralytics/yolov5/issues/8493
192
+
193
+ def _cv2_rotate(self, im):
194
+ # Rotate a cv2 video manually
195
+ if self.orientation == 0:
196
+ return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)
197
+ elif self.orientation == 180:
198
+ return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)
199
+ elif self.orientation == 90:
200
+ return cv2.rotate(im, cv2.ROTATE_180)
201
+ return im
202
+
203
+ def __len__(self):
204
+ return self.nf # number of files
205
+
206
+ def img2label_paths(img_paths):
207
+ # Define label paths as a function of image paths
208
+ sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings
209
+ return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
210
+
211
+ # Ancillary functions --------------------------------------------------------------------------------------------------
212
+ def flatten_recursive(path=DATASETS_DIR / 'coco128'):
213
+ # Flatten a recursive directory by bringing all files to top level
214
+ new_path = Path(f'{str(path)}_flat')
215
+ if os.path.exists(new_path):
216
+ shutil.rmtree(new_path) # delete output folder
217
+ os.makedirs(new_path) # make new output folder
218
+ for file in tqdm(glob.glob(f'{str(Path(path))}/**/*.*', recursive=True)):
219
+ shutil.copyfile(file, new_path / Path(file).name)
220
+
221
+
222
+ def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.dataloaders import *; extract_boxes()
223
+ # Convert detection dataset into classification dataset, with one directory per class
224
+ path = Path(path) # images dir
225
+ shutil.rmtree(path / 'classification') if (path / 'classification').is_dir() else None # remove existing
226
+ files = list(path.rglob('*.*'))
227
+ n = len(files) # number of files
228
+ for im_file in tqdm(files, total=n):
229
+ if im_file.suffix[1:] in IMG_FORMATS:
230
+ # image
231
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
232
+ h, w = im.shape[:2]
233
+
234
+ # labels
235
+ lb_file = Path(img2label_paths([str(im_file)])[0])
236
+ if Path(lb_file).exists():
237
+ with open(lb_file) as f:
238
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
239
+
240
+ for j, x in enumerate(lb):
241
+ c = int(x[0]) # class
242
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
243
+ if not f.parent.is_dir():
244
+ f.parent.mkdir(parents=True)
245
+
246
+ b = x[1:] * [w, h, w, h] # box
247
+ # b[2:] = b[2:].max() # rectangle to square
248
+ b[2:] = b[2:] * 1.2 + 3 # pad
249
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(int)
250
+
251
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
252
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
253
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
254
+
255
+
256
+ def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
257
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
258
+ Usage: from utils.dataloaders import *; autosplit()
259
+ Arguments
260
+ path: Path to images directory
261
+ weights: Train, val, test weights (list, tuple)
262
+ annotated_only: Only use images with an annotated txt file
263
+ """
264
+ path = Path(path) # images dir
265
+ files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only
266
+ n = len(files) # number of files
267
+ random.seed(0) # for reproducibility
268
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
269
+
270
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
271
+ for x in txt:
272
+ if (path.parent / x).exists():
273
+ (path.parent / x).unlink() # remove existing
274
+
275
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
276
+ for i, img in tqdm(zip(indices, files), total=n):
277
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
278
+ with open(path.parent / txt[i], 'a') as f:
279
+ f.write(f'./{img.relative_to(path.parent).as_posix()}' + '\n') # add image to txt file
280
+
281
+
282
+ def verify_image_label(args):
283
+ # Verify one image-label pair
284
+ im_file, lb_file, prefix = args
285
+ nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
286
+ try:
287
+ # verify images
288
+ im = Image.open(im_file)
289
+ im.verify() # PIL verify
290
+ shape = exif_size(im) # image size
291
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
292
+ assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
293
+ if im.format.lower() in ('jpg', 'jpeg'):
294
+ with open(im_file, 'rb') as f:
295
+ f.seek(-2, 2)
296
+ if f.read() != b'\xff\xd9': # corrupt JPEG
297
+ ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
298
+ msg = f'{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved'
299
+
300
+ # verify labels
301
+ if os.path.isfile(lb_file):
302
+ nf = 1 # label found
303
+ with open(lb_file) as f:
304
+ lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
305
+ if any(len(x) > 6 for x in lb): # is segment
306
+ classes = np.array([x[0] for x in lb], dtype=np.float32)
307
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
308
+ lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
309
+ lb = np.array(lb, dtype=np.float32)
310
+ nl = len(lb)
311
+ if nl:
312
+ assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'
313
+ assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'
314
+ assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'
315
+ _, i = np.unique(lb, axis=0, return_index=True)
316
+ if len(i) < nl: # duplicate row check
317
+ lb = lb[i] # remove duplicates
318
+ if segments:
319
+ segments = [segments[x] for x in i]
320
+ msg = f'{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed'
321
+ else:
322
+ ne = 1 # label empty
323
+ lb = np.zeros((0, 5), dtype=np.float32)
324
+ else:
325
+ nm = 1 # label missing
326
+ lb = np.zeros((0, 5), dtype=np.float32)
327
+ return im_file, lb, shape, segments, nm, nf, ne, nc, msg
328
+ except Exception as e:
329
+ nc = 1
330
+ msg = f'{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}'
331
+ return [None, None, None, None, nm, nf, ne, nc, msg]
utils/general.py ADDED
@@ -0,0 +1,1083 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging.config
11
+ import math
12
+ import os
13
+ import platform
14
+ import random
15
+ import re
16
+ import signal
17
+ import sys
18
+ import time
19
+ import urllib
20
+ from copy import deepcopy
21
+ from datetime import datetime
22
+ from itertools import repeat
23
+ from multiprocessing.pool import ThreadPool
24
+ from pathlib import Path
25
+ from subprocess import check_output
26
+ from tarfile import is_tarfile
27
+ from typing import Optional
28
+ from zipfile import ZipFile, is_zipfile
29
+
30
+ import cv2
31
+ import IPython
32
+ import numpy as np
33
+ import pandas as pd
34
+ import pkg_resources as pkg
35
+ import torch
36
+ import torchvision
37
+ import yaml
38
+
39
+ from utils import TryExcept, emojis
40
+ #from utils.downloads import gsutil_getsize
41
+ from utils.metrics import box_iou, fitness
42
+
43
+ FILE = Path(__file__).resolve()
44
+ ROOT = FILE.parents[1] # YOLOv5 root directory
45
+ RANK = int(os.getenv('RANK', -1))
46
+
47
+ # Settings
48
+ NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads
49
+ DATASETS_DIR = Path(os.getenv('YOLOv5_DATASETS_DIR', ROOT.parent / 'datasets')) # global datasets directory
50
+ AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode
51
+ VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode
52
+ TQDM_BAR_FORMAT = '{l_bar}{bar:10}{r_bar}' # tqdm bar format
53
+ FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf
54
+
55
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
56
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
57
+ pd.options.display.max_columns = 10
58
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
59
+ os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads
60
+ os.environ['OMP_NUM_THREADS'] = '1' if platform.system() == 'darwin' else str(NUM_THREADS) # OpenMP (PyTorch and SciPy)
61
+
62
+
63
+ def is_ascii(s=''):
64
+ # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7)
65
+ s = str(s) # convert list, tuple, None, etc. to str
66
+ return len(s.encode().decode('ascii', 'ignore')) == len(s)
67
+
68
+
69
+ def is_chinese(s='人工智能'):
70
+ # Is string composed of any Chinese characters?
71
+ return bool(re.search('[\u4e00-\u9fff]', str(s)))
72
+
73
+
74
+ def is_colab():
75
+ # Is environment a Google Colab instance?
76
+ return 'google.colab' in sys.modules
77
+
78
+
79
+ def is_notebook():
80
+ # Is environment a Jupyter notebook? Verified on Colab, Jupyterlab, Kaggle, Paperspace
81
+ ipython_type = str(type(IPython.get_ipython()))
82
+ return 'colab' in ipython_type or 'zmqshell' in ipython_type
83
+
84
+
85
+ def is_kaggle():
86
+ # Is environment a Kaggle Notebook?
87
+ return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'
88
+
89
+
90
+ def is_docker() -> bool:
91
+ """Check if the process runs inside a docker container."""
92
+ if Path("/.dockerenv").exists():
93
+ return True
94
+ try: # check if docker is in control groups
95
+ with open("/proc/self/cgroup") as file:
96
+ return any("docker" in line for line in file)
97
+ except OSError:
98
+ return False
99
+
100
+
101
+ def is_writeable(dir, test=False):
102
+ # Return True if directory has write permissions, test opening a file with write permissions if test=True
103
+ if not test:
104
+ return os.access(dir, os.W_OK) # possible issues on Windows
105
+ file = Path(dir) / 'tmp.txt'
106
+ try:
107
+ with open(file, 'w'): # open file with write permissions
108
+ pass
109
+ file.unlink() # remove file
110
+ return True
111
+ except OSError:
112
+ return False
113
+
114
+
115
+ LOGGING_NAME = "yolov5"
116
+
117
+
118
+ def set_logging(name=LOGGING_NAME, verbose=True):
119
+ # sets up logging for the given name
120
+ rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
121
+ level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
122
+ logging.config.dictConfig({
123
+ "version": 1,
124
+ "disable_existing_loggers": False,
125
+ "formatters": {
126
+ name: {
127
+ "format": "%(message)s"}},
128
+ "handlers": {
129
+ name: {
130
+ "class": "logging.StreamHandler",
131
+ "formatter": name,
132
+ "level": level,}},
133
+ "loggers": {
134
+ name: {
135
+ "level": level,
136
+ "handlers": [name],
137
+ "propagate": False,}}})
138
+
139
+
140
+ set_logging(LOGGING_NAME) # run before defining LOGGER
141
+ LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)
142
+ if platform.system() == 'Windows':
143
+ for fn in LOGGER.info, LOGGER.warning:
144
+ setattr(LOGGER, fn.__name__, lambda x: fn(emojis(x))) # emoji safe logging
145
+
146
+
147
+ def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):
148
+ # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.
149
+ env = os.getenv(env_var)
150
+ if env:
151
+ path = Path(env) # use environment variable
152
+ else:
153
+ cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs
154
+ path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir
155
+ path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable
156
+ path.mkdir(exist_ok=True) # make if required
157
+ return path
158
+
159
+
160
+ CONFIG_DIR = user_config_dir() # Ultralytics settings dir
161
+
162
+
163
+ class Profile(contextlib.ContextDecorator):
164
+ # YOLOv5 Profile class. Usage: @Profile() decorator or 'with Profile():' context manager
165
+ def __init__(self, t=0.0):
166
+ self.t = t
167
+ self.cuda = torch.cuda.is_available()
168
+
169
+ def __enter__(self):
170
+ self.start = self.time()
171
+ return self
172
+
173
+ def __exit__(self, type, value, traceback):
174
+ self.dt = self.time() - self.start # delta-time
175
+ self.t += self.dt # accumulate dt
176
+
177
+ def time(self):
178
+ if self.cuda:
179
+ torch.cuda.synchronize()
180
+ return time.time()
181
+
182
+
183
+ class Timeout(contextlib.ContextDecorator):
184
+ # YOLOv5 Timeout class. Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
185
+ def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):
186
+ self.seconds = int(seconds)
187
+ self.timeout_message = timeout_msg
188
+ self.suppress = bool(suppress_timeout_errors)
189
+
190
+ def _timeout_handler(self, signum, frame):
191
+ raise TimeoutError(self.timeout_message)
192
+
193
+ def __enter__(self):
194
+ if platform.system() != 'Windows': # not supported on Windows
195
+ signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM
196
+ signal.alarm(self.seconds) # start countdown for SIGALRM to be raised
197
+
198
+ def __exit__(self, exc_type, exc_val, exc_tb):
199
+ if platform.system() != 'Windows':
200
+ signal.alarm(0) # Cancel SIGALRM if it's scheduled
201
+ if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError
202
+ return True
203
+
204
+
205
+ class WorkingDirectory(contextlib.ContextDecorator):
206
+ # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager
207
+ def __init__(self, new_dir):
208
+ self.dir = new_dir # new dir
209
+ self.cwd = Path.cwd().resolve() # current dir
210
+
211
+ def __enter__(self):
212
+ os.chdir(self.dir)
213
+
214
+ def __exit__(self, exc_type, exc_val, exc_tb):
215
+ os.chdir(self.cwd)
216
+
217
+
218
+ def methods(instance):
219
+ # Get class/instance methods
220
+ return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]
221
+
222
+
223
+ def print_args(args: Optional[dict] = None, show_file=True, show_func=False):
224
+ # Print function arguments (optional args dict)
225
+ x = inspect.currentframe().f_back # previous frame
226
+ file, _, func, _, _ = inspect.getframeinfo(x)
227
+ if args is None: # get args automatically
228
+ args, _, _, frm = inspect.getargvalues(x)
229
+ args = {k: v for k, v in frm.items() if k in args}
230
+ try:
231
+ file = Path(file).resolve().relative_to(ROOT).with_suffix('')
232
+ except ValueError:
233
+ file = Path(file).stem
234
+ s = (f'{file}: ' if show_file else '') + (f'{func}: ' if show_func else '')
235
+ LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items()))
236
+
237
+
238
+ def init_seeds(seed=0, deterministic=False):
239
+ # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html
240
+ random.seed(seed)
241
+ np.random.seed(seed)
242
+ torch.manual_seed(seed)
243
+ torch.cuda.manual_seed(seed)
244
+ torch.cuda.manual_seed_all(seed) # for Multi-GPU, exception safe
245
+ # torch.backends.cudnn.benchmark = True # AutoBatch problem https://github.com/ultralytics/yolov5/issues/9287
246
+ if deterministic and check_version(torch.__version__, '1.12.0'): # https://github.com/ultralytics/yolov5/pull/8213
247
+ torch.use_deterministic_algorithms(True)
248
+ torch.backends.cudnn.deterministic = True
249
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
250
+ os.environ['PYTHONHASHSEED'] = str(seed)
251
+
252
+
253
+ def intersect_dicts(da, db, exclude=()):
254
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
255
+ return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape}
256
+
257
+
258
+ def get_default_args(func):
259
+ # Get func() default arguments
260
+ signature = inspect.signature(func)
261
+ return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
262
+
263
+
264
+ def get_latest_run(search_dir='.'):
265
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
266
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
267
+ return max(last_list, key=os.path.getctime) if last_list else ''
268
+
269
+
270
+ def file_age(path=__file__):
271
+ # Return days since last file update
272
+ dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)) # delta
273
+ return dt.days # + dt.seconds / 86400 # fractional days
274
+
275
+
276
+ def file_date(path=__file__):
277
+ # Return human-readable file modification date, i.e. '2021-3-26'
278
+ t = datetime.fromtimestamp(Path(path).stat().st_mtime)
279
+ return f'{t.year}-{t.month}-{t.day}'
280
+
281
+
282
+ def file_size(path):
283
+ # Return file/dir size (MB)
284
+ mb = 1 << 20 # bytes to MiB (1024 ** 2)
285
+ path = Path(path)
286
+ if path.is_file():
287
+ return path.stat().st_size / mb
288
+ elif path.is_dir():
289
+ return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb
290
+ else:
291
+ return 0.0
292
+
293
+
294
+ def check_online():
295
+ # Check internet connectivity
296
+ import socket
297
+
298
+ def run_once():
299
+ # Check once
300
+ try:
301
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility
302
+ return True
303
+ except OSError:
304
+ return False
305
+
306
+ return run_once() or run_once() # check twice to increase robustness to intermittent connectivity issues
307
+
308
+
309
+ def git_describe(path=ROOT): # path must be a directory
310
+ # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
311
+ try:
312
+ assert (Path(path) / '.git').is_dir()
313
+ return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]
314
+ except Exception:
315
+ return ''
316
+
317
+
318
+ def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):
319
+ # Check version vs. required version
320
+ current, minimum = (pkg.parse_version(x) for x in (current, minimum))
321
+ result = (current == minimum) if pinned else (current >= minimum) # bool
322
+ s = f'WARNING ⚠️ {name}{minimum} is required by YOLOv5, but {name}{current} is currently installed' # string
323
+ if hard:
324
+ assert result, emojis(s) # assert min requirements met
325
+ if verbose and not result:
326
+ LOGGER.warning(s)
327
+ return result
328
+
329
+
330
+ @TryExcept()
331
+ def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=''):
332
+ # Check installed dependencies meet YOLOv5 requirements (pass *.txt file or list of packages or single package str)
333
+ prefix = colorstr('red', 'bold', 'requirements:')
334
+ if isinstance(requirements, Path): # requirements.txt file
335
+ file = requirements.resolve()
336
+ assert file.exists(), f"{prefix} {file} not found, check failed."
337
+ with file.open() as f:
338
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]
339
+ elif isinstance(requirements, str):
340
+ requirements = [requirements]
341
+
342
+ s = ''
343
+ n = 0
344
+ for r in requirements:
345
+ try:
346
+ pkg.require(r)
347
+ except (pkg.VersionConflict, pkg.DistributionNotFound): # exception if requirements not met
348
+ s += f'"{r}" '
349
+ n += 1
350
+
351
+ if s and install and AUTOINSTALL: # check environment variable
352
+ LOGGER.info(f"{prefix} YOLOv5 requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...")
353
+ try:
354
+ # assert check_online(), "AutoUpdate skipped (offline)"
355
+ LOGGER.info(check_output(f'pip install {s} {cmds}', shell=True).decode())
356
+ source = file if 'file' in locals() else requirements
357
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
358
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
359
+ LOGGER.info(s)
360
+ except Exception as e:
361
+ LOGGER.warning(f'{prefix} ❌ {e}')
362
+
363
+
364
+ def check_img_size(imgsz, s=32, floor=0):
365
+ # Verify image size is a multiple of stride s in each dimension
366
+ if isinstance(imgsz, int): # integer i.e. img_size=640
367
+ new_size = max(make_divisible(imgsz, int(s)), floor)
368
+ else: # list i.e. img_size=[640, 480]
369
+ imgsz = list(imgsz) # convert to list if tuple
370
+ new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]
371
+ if new_size != imgsz:
372
+ LOGGER.warning(f'WARNING ⚠️ --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')
373
+ return new_size
374
+
375
+
376
+ def check_imshow(warn=False):
377
+ # Check if environment supports image displays
378
+ try:
379
+ assert not is_notebook()
380
+ assert not is_docker()
381
+ cv2.imshow('test', np.zeros((1, 1, 3)))
382
+ cv2.waitKey(1)
383
+ cv2.destroyAllWindows()
384
+ cv2.waitKey(1)
385
+ return True
386
+ except Exception as e:
387
+ if warn:
388
+ LOGGER.warning(f'WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()\n{e}')
389
+ return False
390
+
391
+
392
+ def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''):
393
+ # Check file(s) for acceptable suffix
394
+ if file and suffix:
395
+ if isinstance(suffix, str):
396
+ suffix = [suffix]
397
+ for f in file if isinstance(file, (list, tuple)) else [file]:
398
+ s = Path(f).suffix.lower() # file suffix
399
+ if len(s):
400
+ assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}"
401
+
402
+
403
+ def check_yaml(file, suffix=('.yaml', '.yml')):
404
+ # Search/download YAML file (if necessary) and return path, checking suffix
405
+ return check_file(file, suffix)
406
+
407
+
408
+ def check_file(file, suffix=''):
409
+ # Search/download file (if necessary) and return path
410
+ check_suffix(file, suffix) # optional
411
+ file = str(file) # convert to str()
412
+ if os.path.isfile(file) or not file: # exists
413
+ return file
414
+ elif file.startswith(('http:/', 'https:/')): # download
415
+ url = file # warning: Pathlib turns :// -> :/
416
+ file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth
417
+ if os.path.isfile(file):
418
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
419
+ else:
420
+ LOGGER.info(f'Downloading {url} to {file}...')
421
+ torch.hub.download_url_to_file(url, file)
422
+ assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check
423
+ return file
424
+ elif file.startswith('clearml://'): # ClearML Dataset ID
425
+ assert 'clearml' in sys.modules, "ClearML is not installed, so cannot use ClearML dataset. Try running 'pip install clearml'."
426
+ return file
427
+ else: # search
428
+ files = []
429
+ for d in 'data', 'models', 'utils': # search directories
430
+ files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file
431
+ assert len(files), f'File not found: {file}' # assert file was found
432
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
433
+ return files[0] # return file
434
+
435
+
436
+ def check_font(font=FONT, progress=False):
437
+ # Download font to CONFIG_DIR if necessary
438
+ font = Path(font)
439
+ file = CONFIG_DIR / font.name
440
+ if not font.exists() and not file.exists():
441
+ url = f'https://ultralytics.com/assets/{font.name}'
442
+ LOGGER.info(f'Downloading {url} to {file}...')
443
+ torch.hub.download_url_to_file(url, str(file), progress=progress)
444
+
445
+
446
+ def check_dataset(data, autodownload=True):
447
+ # Download, check and/or unzip dataset if not found locally
448
+
449
+ # Download (optional)
450
+ extract_dir = ''
451
+ if isinstance(data, (str, Path)) and (is_zipfile(data) or is_tarfile(data)):
452
+ download(data, dir=f'{DATASETS_DIR}/{Path(data).stem}', unzip=True, delete=False, curl=False, threads=1)
453
+ data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml'))
454
+ extract_dir, autodownload = data.parent, False
455
+
456
+ # Read yaml (optional)
457
+ if isinstance(data, (str, Path)):
458
+ data = yaml_load(data) # dictionary
459
+
460
+ # Checks
461
+ for k in 'train', 'val', 'names':
462
+ assert k in data, emojis(f"data.yaml '{k}:' field missing ❌")
463
+ if isinstance(data['names'], (list, tuple)): # old array format
464
+ data['names'] = dict(enumerate(data['names'])) # convert to dict
465
+ assert all(isinstance(k, int) for k in data['names'].keys()), 'data.yaml names keys must be integers, i.e. 2: car'
466
+ data['nc'] = len(data['names'])
467
+
468
+ # Resolve paths
469
+ path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.'
470
+ if not path.is_absolute():
471
+ path = (ROOT / path).resolve()
472
+ data['path'] = path # download scripts
473
+ for k in 'train', 'val', 'test':
474
+ if data.get(k): # prepend path
475
+ if isinstance(data[k], str):
476
+ x = (path / data[k]).resolve()
477
+ if not x.exists() and data[k].startswith('../'):
478
+ x = (path / data[k][3:]).resolve()
479
+ data[k] = str(x)
480
+ else:
481
+ data[k] = [str((path / x).resolve()) for x in data[k]]
482
+
483
+ # Parse yaml
484
+ train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))
485
+ if val:
486
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
487
+ if not all(x.exists() for x in val):
488
+ LOGGER.info('\nDataset not found ⚠️, missing paths %s' % [str(x) for x in val if not x.exists()])
489
+ if not s or not autodownload:
490
+ raise Exception('Dataset not found ❌')
491
+ t = time.time()
492
+ if s.startswith('http') and s.endswith('.zip'): # URL
493
+ f = Path(s).name # filename
494
+ LOGGER.info(f'Downloading {s} to {f}...')
495
+ torch.hub.download_url_to_file(s, f)
496
+ Path(DATASETS_DIR).mkdir(parents=True, exist_ok=True) # create root
497
+ unzip_file(f, path=DATASETS_DIR) # unzip
498
+ Path(f).unlink() # remove zip
499
+ r = None # success
500
+ elif s.startswith('bash '): # bash script
501
+ LOGGER.info(f'Running {s} ...')
502
+ r = os.system(s)
503
+ else: # python script
504
+ r = exec(s, {'yaml': data}) # return None
505
+ dt = f'({round(time.time() - t, 1)}s)'
506
+ s = f"success ✅ {dt}, saved to {colorstr('bold', DATASETS_DIR)}" if r in (0, None) else f"failure {dt} ❌"
507
+ LOGGER.info(f"Dataset download {s}")
508
+ check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts
509
+ return data # dictionary
510
+
511
+
512
+ def check_amp(model):
513
+ # Check PyTorch Automatic Mixed Precision (AMP) functionality. Return True on correct operation
514
+ from models.common import AutoShape, DetectMultiBackend
515
+
516
+ def amp_allclose(model, im):
517
+ # All close FP32 vs AMP results
518
+ m = AutoShape(model, verbose=False) # model
519
+ a = m(im).xywhn[0] # FP32 inference
520
+ m.amp = True
521
+ b = m(im).xywhn[0] # AMP inference
522
+ return a.shape == b.shape and torch.allclose(a, b, atol=0.1) # close to 10% absolute tolerance
523
+
524
+ prefix = colorstr('AMP: ')
525
+ device = next(model.parameters()).device # get model device
526
+ if device.type in ('cpu', 'mps'):
527
+ return False # AMP only used on CUDA devices
528
+ f = ROOT / 'data' / 'images' / 'bus.jpg' # image to check
529
+ im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if check_online() else np.ones((640, 640, 3))
530
+ try:
531
+ assert amp_allclose(deepcopy(model), im) or amp_allclose(DetectMultiBackend('yolov5n.pt', device), im)
532
+ LOGGER.info(f'{prefix}checks passed ✅')
533
+ return True
534
+ except Exception:
535
+ help_url = 'https://github.com/ultralytics/yolov5/issues/7908'
536
+ LOGGER.warning(f'{prefix}checks failed ❌, disabling Automatic Mixed Precision. See {help_url}')
537
+ return False
538
+
539
+
540
+ def yaml_load(file='data.yaml'):
541
+ # Single-line safe yaml loading
542
+ with open(file, errors='ignore') as f:
543
+ return yaml.safe_load(f)
544
+
545
+
546
+ def yaml_save(file='data.yaml', data={}):
547
+ # Single-line safe yaml saving
548
+ with open(file, 'w') as f:
549
+ yaml.safe_dump({k: str(v) if isinstance(v, Path) else v for k, v in data.items()}, f, sort_keys=False)
550
+
551
+
552
+ def unzip_file(file, path=None, exclude=('.DS_Store', '__MACOSX')):
553
+ # Unzip a *.zip file to path/, excluding files containing strings in exclude list
554
+ if path is None:
555
+ path = Path(file).parent # default path
556
+ with ZipFile(file) as zipObj:
557
+ for f in zipObj.namelist(): # list all archived filenames in the zip
558
+ if all(x not in f for x in exclude):
559
+ zipObj.extract(f, path=path)
560
+
561
+
562
+ def url2file(url):
563
+ # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt
564
+ url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/
565
+ return Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth
566
+
567
+
568
+ def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3):
569
+ # Multithreaded file download and unzip function, used in data.yaml for autodownload
570
+ def download_one(url, dir):
571
+ # Download 1 file
572
+ success = True
573
+ if os.path.isfile(url):
574
+ f = Path(url) # filename
575
+ else: # does not exist
576
+ f = dir / Path(url).name
577
+ LOGGER.info(f'Downloading {url} to {f}...')
578
+ for i in range(retry + 1):
579
+ if curl:
580
+ s = 'sS' if threads > 1 else '' # silent
581
+ r = os.system(
582
+ f'curl -# -{s}L "{url}" -o "{f}" --retry 9 -C -') # curl download with retry, continue
583
+ success = r == 0
584
+ else:
585
+ torch.hub.download_url_to_file(url, f, progress=threads == 1) # torch download
586
+ success = f.is_file()
587
+ if success:
588
+ break
589
+ elif i < retry:
590
+ LOGGER.warning(f'⚠️ Download failure, retrying {i + 1}/{retry} {url}...')
591
+ else:
592
+ LOGGER.warning(f'❌ Failed to download {url}...')
593
+
594
+ if unzip and success and (f.suffix == '.gz' or is_zipfile(f) or is_tarfile(f)):
595
+ LOGGER.info(f'Unzipping {f}...')
596
+ if is_zipfile(f):
597
+ unzip_file(f, dir) # unzip
598
+ elif is_tarfile(f):
599
+ os.system(f'tar xf {f} --directory {f.parent}') # unzip
600
+ elif f.suffix == '.gz':
601
+ os.system(f'tar xfz {f} --directory {f.parent}') # unzip
602
+ if delete:
603
+ f.unlink() # remove zip
604
+
605
+ dir = Path(dir)
606
+ dir.mkdir(parents=True, exist_ok=True) # make directory
607
+ if threads > 1:
608
+ pool = ThreadPool(threads)
609
+ pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multithreaded
610
+ pool.close()
611
+ pool.join()
612
+ else:
613
+ for u in [url] if isinstance(url, (str, Path)) else url:
614
+ download_one(u, dir)
615
+
616
+
617
+ def make_divisible(x, divisor):
618
+ # Returns nearest x divisible by divisor
619
+ if isinstance(divisor, torch.Tensor):
620
+ divisor = int(divisor.max()) # to int
621
+ return math.ceil(x / divisor) * divisor
622
+
623
+
624
+ def clean_str(s):
625
+ # Cleans a string by replacing special characters with underscore _
626
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
627
+
628
+
629
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
630
+ # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf
631
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
632
+
633
+
634
+ def colorstr(*input):
635
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
636
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
637
+ colors = {
638
+ 'black': '\033[30m', # basic colors
639
+ 'red': '\033[31m',
640
+ 'green': '\033[32m',
641
+ 'yellow': '\033[33m',
642
+ 'blue': '\033[34m',
643
+ 'magenta': '\033[35m',
644
+ 'cyan': '\033[36m',
645
+ 'white': '\033[37m',
646
+ 'bright_black': '\033[90m', # bright colors
647
+ 'bright_red': '\033[91m',
648
+ 'bright_green': '\033[92m',
649
+ 'bright_yellow': '\033[93m',
650
+ 'bright_blue': '\033[94m',
651
+ 'bright_magenta': '\033[95m',
652
+ 'bright_cyan': '\033[96m',
653
+ 'bright_white': '\033[97m',
654
+ 'end': '\033[0m', # misc
655
+ 'bold': '\033[1m',
656
+ 'underline': '\033[4m'}
657
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
658
+
659
+
660
+ def labels_to_class_weights(labels, nc=80):
661
+ # Get class weights (inverse frequency) from training labels
662
+ if labels[0] is None: # no labels loaded
663
+ return torch.Tensor()
664
+
665
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
666
+ classes = labels[:, 0].astype(int) # labels = [class xywh]
667
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
668
+
669
+ # Prepend gridpoint count (for uCE training)
670
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
671
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
672
+
673
+ weights[weights == 0] = 1 # replace empty bins with 1
674
+ weights = 1 / weights # number of targets per class
675
+ weights /= weights.sum() # normalize
676
+ return torch.from_numpy(weights).float()
677
+
678
+
679
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
680
+ # Produces image weights based on class_weights and image contents
681
+ # Usage: index = random.choices(range(n), weights=image_weights, k=1) # weighted image sample
682
+ class_counts = np.array([np.bincount(x[:, 0].astype(int), minlength=nc) for x in labels])
683
+ return (class_weights.reshape(1, nc) * class_counts).sum(1)
684
+
685
+
686
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
687
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
688
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
689
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
690
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
691
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
692
+ return [
693
+ 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,
694
+ 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,
695
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
696
+
697
+
698
+ def xyxy2xywh(x):
699
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
700
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
701
+ y[..., 0] = (x[..., 0] + x[..., 2]) / 2 # x center
702
+ y[..., 1] = (x[..., 1] + x[..., 3]) / 2 # y center
703
+ y[..., 2] = x[..., 2] - x[..., 0] # width
704
+ y[..., 3] = x[..., 3] - x[..., 1] # height
705
+ return y
706
+
707
+
708
+ def xywh2xyxy(x):
709
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
710
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
711
+ y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
712
+ y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
713
+ y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x
714
+ y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y
715
+ return y
716
+
717
+
718
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
719
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
720
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
721
+ y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw # top left x
722
+ y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh # top left y
723
+ y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw # bottom right x
724
+ y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh # bottom right y
725
+ return y
726
+
727
+
728
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
729
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
730
+ if clip:
731
+ clip_boxes(x, (h - eps, w - eps)) # warning: inplace clip
732
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
733
+ y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w # x center
734
+ y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h # y center
735
+ y[..., 2] = (x[..., 2] - x[..., 0]) / w # width
736
+ y[..., 3] = (x[..., 3] - x[..., 1]) / h # height
737
+ return y
738
+
739
+
740
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
741
+ # Convert normalized segments into pixel segments, shape (n,2)
742
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
743
+ y[..., 0] = w * x[..., 0] + padw # top left x
744
+ y[..., 1] = h * x[..., 1] + padh # top left y
745
+ return y
746
+
747
+
748
+ def segment2box(segment, width=640, height=640):
749
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
750
+ x, y = segment.T # segment xy
751
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
752
+ x, y, = x[inside], y[inside]
753
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
754
+
755
+
756
+ def segments2boxes(segments):
757
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
758
+ boxes = []
759
+ for s in segments:
760
+ x, y = s.T # segment xy
761
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
762
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
763
+
764
+
765
+ def resample_segments(segments, n=1000):
766
+ # Up-sample an (n,2) segment
767
+ for i, s in enumerate(segments):
768
+ s = np.concatenate((s, s[0:1, :]), axis=0)
769
+ x = np.linspace(0, len(s) - 1, n)
770
+ xp = np.arange(len(s))
771
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
772
+ return segments
773
+
774
+
775
+ def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):
776
+ # Rescale boxes (xyxy) from img1_shape to img0_shape
777
+ if ratio_pad is None: # calculate from img0_shape
778
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
779
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
780
+ else:
781
+ gain = ratio_pad[0][0]
782
+ pad = ratio_pad[1]
783
+
784
+ boxes[..., [0, 2]] -= pad[0] # x padding
785
+ boxes[..., [1, 3]] -= pad[1] # y padding
786
+ boxes[..., :4] /= gain
787
+ clip_boxes(boxes, img0_shape)
788
+ return boxes
789
+
790
+
791
+ def scale_segments(img1_shape, segments, img0_shape, ratio_pad=None, normalize=False):
792
+ # Rescale coords (xyxy) from img1_shape to img0_shape
793
+ if ratio_pad is None: # calculate from img0_shape
794
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
795
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
796
+ else:
797
+ gain = ratio_pad[0][0]
798
+ pad = ratio_pad[1]
799
+
800
+ segments[:, 0] -= pad[0] # x padding
801
+ segments[:, 1] -= pad[1] # y padding
802
+ segments /= gain
803
+ clip_segments(segments, img0_shape)
804
+ if normalize:
805
+ segments[:, 0] /= img0_shape[1] # width
806
+ segments[:, 1] /= img0_shape[0] # height
807
+ return segments
808
+
809
+
810
+ def clip_boxes(boxes, shape):
811
+ # Clip boxes (xyxy) to image shape (height, width)
812
+ if isinstance(boxes, torch.Tensor): # faster individually
813
+ boxes[..., 0].clamp_(0, shape[1]) # x1
814
+ boxes[..., 1].clamp_(0, shape[0]) # y1
815
+ boxes[..., 2].clamp_(0, shape[1]) # x2
816
+ boxes[..., 3].clamp_(0, shape[0]) # y2
817
+ else: # np.array (faster grouped)
818
+ boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1]) # x1, x2
819
+ boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0]) # y1, y2
820
+
821
+
822
+ def clip_segments(segments, shape):
823
+ # Clip segments (xy1,xy2,...) to image shape (height, width)
824
+ if isinstance(segments, torch.Tensor): # faster individually
825
+ segments[:, 0].clamp_(0, shape[1]) # x
826
+ segments[:, 1].clamp_(0, shape[0]) # y
827
+ else: # np.array (faster grouped)
828
+ segments[:, 0] = segments[:, 0].clip(0, shape[1]) # x
829
+ segments[:, 1] = segments[:, 1].clip(0, shape[0]) # y
830
+
831
+
832
+ def non_max_suppression(
833
+ prediction,
834
+ conf_thres=0.25,
835
+ iou_thres=0.45,
836
+ classes=None,
837
+ agnostic=False,
838
+ multi_label=False,
839
+ labels=(),
840
+ max_det=300,
841
+ nm=0, # number of masks
842
+ ):
843
+ """Non-Maximum Suppression (NMS) on inference results to reject overlapping detections
844
+
845
+ Returns:
846
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
847
+ """
848
+
849
+ # Checks
850
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
851
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
852
+ if isinstance(prediction, (list, tuple)): # YOLOv5 model in validation model, output = (inference_out, loss_out)
853
+ prediction = prediction[0] # select only inference output
854
+
855
+ device = prediction.device
856
+ mps = 'mps' in device.type # Apple MPS
857
+ if mps: # MPS not fully supported yet, convert tensors to CPU before NMS
858
+ prediction = prediction.cpu()
859
+ bs = prediction.shape[0] # batch size
860
+ nc = prediction.shape[2] - nm - 5 # number of classes
861
+ xc = prediction[..., 4] > conf_thres # candidates
862
+
863
+ # Settings
864
+ # min_wh = 2 # (pixels) minimum box width and height
865
+ max_wh = 7680 # (pixels) maximum box width and height
866
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
867
+ time_limit = 0.5 + 0.05 * bs # seconds to quit after
868
+ redundant = True # require redundant detections
869
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
870
+ merge = False # use merge-NMS
871
+
872
+ t = time.time()
873
+ mi = 5 + nc # mask start index
874
+ output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs
875
+ for xi, x in enumerate(prediction): # image index, image inference
876
+ # Apply constraints
877
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
878
+ x = x[xc[xi]] # confidence
879
+
880
+ # Cat apriori labels if autolabelling
881
+ if labels and len(labels[xi]):
882
+ lb = labels[xi]
883
+ v = torch.zeros((len(lb), nc + nm + 5), device=x.device)
884
+ v[:, :4] = lb[:, 1:5] # box
885
+ v[:, 4] = 1.0 # conf
886
+ v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls
887
+ x = torch.cat((x, v), 0)
888
+
889
+ # If none remain process next image
890
+ if not x.shape[0]:
891
+ continue
892
+
893
+ # Compute conf
894
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
895
+
896
+ # Box/Mask
897
+ box = xywh2xyxy(x[:, :4]) # center_x, center_y, width, height) to (x1, y1, x2, y2)
898
+ mask = x[:, mi:] # zero columns if no masks
899
+
900
+ # Detections matrix nx6 (xyxy, conf, cls)
901
+ if multi_label:
902
+ i, j = (x[:, 5:mi] > conf_thres).nonzero(as_tuple=False).T
903
+ x = torch.cat((box[i], x[i, 5 + j, None], j[:, None].float(), mask[i]), 1)
904
+ else: # best class only
905
+ conf, j = x[:, 5:mi].max(1, keepdim=True)
906
+ x = torch.cat((box, conf, j.float(), mask), 1)[conf.view(-1) > conf_thres]
907
+
908
+ # Filter by class
909
+ if classes is not None:
910
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
911
+
912
+ # Apply finite constraint
913
+ # if not torch.isfinite(x).all():
914
+ # x = x[torch.isfinite(x).all(1)]
915
+
916
+ # Check shape
917
+ n = x.shape[0] # number of boxes
918
+ if not n: # no boxes
919
+ continue
920
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence and remove excess boxes
921
+
922
+ # Batched NMS
923
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
924
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
925
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
926
+ i = i[:max_det] # limit detections
927
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
928
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
929
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
930
+ weights = iou * scores[None] # box weights
931
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
932
+ if redundant:
933
+ i = i[iou.sum(1) > 1] # require redundancy
934
+
935
+ output[xi] = x[i]
936
+ if mps:
937
+ output[xi] = output[xi].to(device)
938
+ if (time.time() - t) > time_limit:
939
+ LOGGER.warning(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')
940
+ break # time limit exceeded
941
+
942
+ return output
943
+
944
+
945
+ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
946
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
947
+ x = torch.load(f, map_location=torch.device('cpu'))
948
+ if x.get('ema'):
949
+ x['model'] = x['ema'] # replace model with ema
950
+ for k in 'optimizer', 'best_fitness', 'ema', 'updates': # keys
951
+ x[k] = None
952
+ x['epoch'] = -1
953
+ x['model'].half() # to FP16
954
+ for p in x['model'].parameters():
955
+ p.requires_grad = False
956
+ torch.save(x, s or f)
957
+ mb = os.path.getsize(s or f) / 1E6 # filesize
958
+ LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB")
959
+
960
+
961
+ def print_mutation(keys, results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')):
962
+ evolve_csv = save_dir / 'evolve.csv'
963
+ evolve_yaml = save_dir / 'hyp_evolve.yaml'
964
+ keys = tuple(keys) + tuple(hyp.keys()) # [results + hyps]
965
+ keys = tuple(x.strip() for x in keys)
966
+ vals = results + tuple(hyp.values())
967
+ n = len(keys)
968
+
969
+ # Download (optional)
970
+ # if bucket:
971
+ # url = f'gs://{bucket}/evolve.csv'
972
+ # if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0):
973
+ # os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local
974
+
975
+ # Log to evolve.csv
976
+ s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header
977
+ with open(evolve_csv, 'a') as f:
978
+ f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n')
979
+
980
+ # Save yaml
981
+ with open(evolve_yaml, 'w') as f:
982
+ data = pd.read_csv(evolve_csv, skipinitialspace=True)
983
+ data = data.rename(columns=lambda x: x.strip()) # strip keys
984
+ i = np.argmax(fitness(data.values[:, :4])) #
985
+ generations = len(data)
986
+ f.write('# YOLOv5 Hyperparameter Evolution Results\n' + f'# Best generation: {i}\n' +
987
+ f'# Last generation: {generations - 1}\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) +
988
+ '\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n')
989
+ yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False)
990
+
991
+ # Print to screen
992
+ LOGGER.info(prefix + f'{generations} generations finished, current result:\n' + prefix +
993
+ ', '.join(f'{x.strip():>20s}' for x in keys) + '\n' + prefix + ', '.join(f'{x:20.5g}'
994
+ for x in vals) + '\n\n')
995
+
996
+ if bucket:
997
+ os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload
998
+
999
+
1000
+ def apply_classifier(x, model, img, im0):
1001
+ # Apply a second stage classifier to YOLO outputs
1002
+ # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval()
1003
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
1004
+ for i, d in enumerate(x): # per image
1005
+ if d is not None and len(d):
1006
+ d = d.clone()
1007
+
1008
+ # Reshape and pad cutouts
1009
+ b = xyxy2xywh(d[:, :4]) # boxes
1010
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
1011
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
1012
+ d[:, :4] = xywh2xyxy(b).long()
1013
+
1014
+ # Rescale boxes from img_size to im0 size
1015
+ scale_boxes(img.shape[2:], d[:, :4], im0[i].shape)
1016
+
1017
+ # Classes
1018
+ pred_cls1 = d[:, 5].long()
1019
+ ims = []
1020
+ for a in d:
1021
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
1022
+ im = cv2.resize(cutout, (224, 224)) # BGR
1023
+
1024
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
1025
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
1026
+ im /= 255 # 0 - 255 to 0.0 - 1.0
1027
+ ims.append(im)
1028
+
1029
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
1030
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
1031
+
1032
+ return x
1033
+
1034
+
1035
+ def increment_path(path, exist_ok=False, sep='', mkdir=False):
1036
+ # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
1037
+ path = Path(path) # os-agnostic
1038
+ if path.exists() and not exist_ok:
1039
+ path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
1040
+
1041
+ # Method 1
1042
+ for n in range(2, 9999):
1043
+ p = f'{path}{sep}{n}{suffix}' # increment path
1044
+ if not os.path.exists(p): #
1045
+ break
1046
+ path = Path(p)
1047
+
1048
+ # Method 2 (deprecated)
1049
+ # dirs = glob.glob(f"{path}{sep}*") # similar paths
1050
+ # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs]
1051
+ # i = [int(m.groups()[0]) for m in matches if m] # indices
1052
+ # n = max(i) + 1 if i else 2 # increment number
1053
+ # path = Path(f"{path}{sep}{n}{suffix}") # increment path
1054
+
1055
+ if mkdir:
1056
+ path.mkdir(parents=True, exist_ok=True) # make directory
1057
+
1058
+ return path
1059
+
1060
+
1061
+ # OpenCV Multilanguage-friendly functions ------------------------------------------------------------------------------------
1062
+ imshow_ = cv2.imshow # copy to avoid recursion errors
1063
+
1064
+
1065
+ def imread(path, flags=cv2.IMREAD_COLOR):
1066
+ return cv2.imdecode(np.fromfile(path, np.uint8), flags)
1067
+
1068
+
1069
+ def imwrite(path, im):
1070
+ try:
1071
+ cv2.imencode(Path(path).suffix, im)[1].tofile(path)
1072
+ return True
1073
+ except Exception:
1074
+ return False
1075
+
1076
+
1077
+ def imshow(path, im):
1078
+ imshow_(path.encode('unicode_escape').decode(), im)
1079
+
1080
+
1081
+ cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow # redefine
1082
+
1083
+ # Variables ------------------------------------------------------------------------------------------------------------
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,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from utils import TryExcept, threaded
15
+
16
+
17
+ def fitness(x):
18
+ # Model fitness as a weighted combination of metrics
19
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
20
+ return (x[:, :4] * w).sum(1)
21
+
22
+
23
+ def smooth(y, f=0.05):
24
+ # Box filter of fraction f
25
+ nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
26
+ p = np.ones(nf // 2) # ones padding
27
+ yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
28
+ return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
29
+
30
+
31
+ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16, prefix=""):
32
+ """ Compute the average precision, given the recall and precision curves.
33
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
34
+ # Arguments
35
+ tp: True positives (nparray, nx1 or nx10).
36
+ conf: Objectness value from 0-1 (nparray).
37
+ pred_cls: Predicted object classes (nparray).
38
+ target_cls: True object classes (nparray).
39
+ plot: Plot precision-recall curve at mAP@0.5
40
+ save_dir: Plot save directory
41
+ # Returns
42
+ The average precision as computed in py-faster-rcnn.
43
+ """
44
+
45
+ # Sort by objectness
46
+ i = np.argsort(-conf)
47
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
48
+
49
+ # Find unique classes
50
+ unique_classes, nt = np.unique(target_cls, return_counts=True)
51
+ nc = unique_classes.shape[0] # number of classes, number of detections
52
+
53
+ # Create Precision-Recall curve and compute AP for each class
54
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
55
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
56
+ for ci, c in enumerate(unique_classes):
57
+ i = pred_cls == c
58
+ n_l = nt[ci] # number of labels
59
+ n_p = i.sum() # number of predictions
60
+ if n_p == 0 or n_l == 0:
61
+ continue
62
+
63
+ # Accumulate FPs and TPs
64
+ fpc = (1 - tp[i]).cumsum(0)
65
+ tpc = tp[i].cumsum(0)
66
+
67
+ # Recall
68
+ recall = tpc / (n_l + eps) # recall curve
69
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
70
+
71
+ # Precision
72
+ precision = tpc / (tpc + fpc) # precision curve
73
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
74
+
75
+ # AP from recall-precision curve
76
+ for j in range(tp.shape[1]):
77
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
78
+ if plot and j == 0:
79
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
80
+
81
+ # Compute F1 (harmonic mean of precision and recall)
82
+ f1 = 2 * p * r / (p + r + eps)
83
+ names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
84
+ names = dict(enumerate(names)) # to dict
85
+ if plot:
86
+ plot_pr_curve(px, py, ap, Path(save_dir) / f'{prefix}PR_curve.png', names)
87
+ plot_mc_curve(px, f1, Path(save_dir) / f'{prefix}F1_curve.png', names, ylabel='F1')
88
+ plot_mc_curve(px, p, Path(save_dir) / f'{prefix}P_curve.png', names, ylabel='Precision')
89
+ plot_mc_curve(px, r, Path(save_dir) / f'{prefix}R_curve.png', names, ylabel='Recall')
90
+
91
+ i = smooth(f1.mean(0), 0.1).argmax() # max F1 index
92
+ p, r, f1 = p[:, i], r[:, i], f1[:, i]
93
+ tp = (r * nt).round() # true positives
94
+ fp = (tp / (p + eps) - tp).round() # false positives
95
+ return tp, fp, p, r, f1, ap, unique_classes.astype(int)
96
+
97
+
98
+ def compute_ap(recall, precision):
99
+ """ Compute the average precision, given the recall and precision curves
100
+ # Arguments
101
+ recall: The recall curve (list)
102
+ precision: The precision curve (list)
103
+ # Returns
104
+ Average precision, precision curve, recall curve
105
+ """
106
+
107
+ # Append sentinel values to beginning and end
108
+ mrec = np.concatenate(([0.0], recall, [1.0]))
109
+ mpre = np.concatenate(([1.0], precision, [0.0]))
110
+
111
+ # Compute the precision envelope
112
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
113
+
114
+ # Integrate area under curve
115
+ method = 'interp' # methods: 'continuous', 'interp'
116
+ if method == 'interp':
117
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
118
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
119
+ else: # 'continuous'
120
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
121
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
122
+
123
+ return ap, mpre, mrec
124
+
125
+
126
+ class ConfusionMatrix:
127
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
128
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
129
+ self.matrix = np.zeros((nc + 1, nc + 1))
130
+ self.nc = nc # number of classes
131
+ self.conf = conf
132
+ self.iou_thres = iou_thres
133
+
134
+ def process_batch(self, detections, labels):
135
+ """
136
+ Return intersection-over-union (Jaccard index) of boxes.
137
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
138
+ Arguments:
139
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
140
+ labels (Array[M, 5]), class, x1, y1, x2, y2
141
+ Returns:
142
+ None, updates confusion matrix accordingly
143
+ """
144
+ if detections is None:
145
+ gt_classes = labels.int()
146
+ for gc in gt_classes:
147
+ self.matrix[self.nc, gc] += 1 # background FN
148
+ return
149
+
150
+ detections = detections[detections[:, 4] > self.conf]
151
+ gt_classes = labels[:, 0].int()
152
+ detection_classes = detections[:, 5].int()
153
+ iou = box_iou(labels[:, 1:], detections[:, :4])
154
+
155
+ x = torch.where(iou > self.iou_thres)
156
+ if x[0].shape[0]:
157
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
158
+ if x[0].shape[0] > 1:
159
+ matches = matches[matches[:, 2].argsort()[::-1]]
160
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
161
+ matches = matches[matches[:, 2].argsort()[::-1]]
162
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
163
+ else:
164
+ matches = np.zeros((0, 3))
165
+
166
+ n = matches.shape[0] > 0
167
+ m0, m1, _ = matches.transpose().astype(int)
168
+ for i, gc in enumerate(gt_classes):
169
+ j = m0 == i
170
+ if n and sum(j) == 1:
171
+ self.matrix[detection_classes[m1[j]], gc] += 1 # correct
172
+ else:
173
+ self.matrix[self.nc, gc] += 1 # true background
174
+
175
+ if n:
176
+ for i, dc in enumerate(detection_classes):
177
+ if not any(m1 == i):
178
+ self.matrix[dc, self.nc] += 1 # predicted background
179
+
180
+ def tp_fp(self):
181
+ tp = self.matrix.diagonal() # true positives
182
+ fp = self.matrix.sum(1) - tp # false positives
183
+ # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
184
+ return tp[:-1], fp[:-1] # remove background class
185
+
186
+ @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')
187
+ def plot(self, normalize=True, save_dir='', names=()):
188
+ import seaborn as sn
189
+
190
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns
191
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
192
+
193
+ fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
194
+ nc, nn = self.nc, len(names) # number of classes, names
195
+ sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
196
+ labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
197
+ ticklabels = (names + ['background']) if labels else "auto"
198
+ with warnings.catch_warnings():
199
+ warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
200
+ sn.heatmap(array,
201
+ ax=ax,
202
+ annot=nc < 30,
203
+ annot_kws={
204
+ "size": 8},
205
+ cmap='Blues',
206
+ fmt='.2f',
207
+ square=True,
208
+ vmin=0.0,
209
+ xticklabels=ticklabels,
210
+ yticklabels=ticklabels).set_facecolor((1, 1, 1))
211
+ ax.set_xlabel('True')
212
+ ax.set_ylabel('Predicted')
213
+ ax.set_title('Confusion Matrix')
214
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
215
+ plt.close(fig)
216
+
217
+ def print(self):
218
+ for i in range(self.nc + 1):
219
+ print(' '.join(map(str, self.matrix[i])))
220
+
221
+
222
+ def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
223
+ # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
224
+
225
+ # Get the coordinates of bounding boxes
226
+ if xywh: # transform from xywh to xyxy
227
+ (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
228
+ w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
229
+ b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
230
+ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
231
+ else: # x1, y1, x2, y2 = box1
232
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
233
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
234
+ w1, h1 = b1_x2 - b1_x1, (b1_y2 - b1_y1).clamp(eps)
235
+ w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(eps)
236
+
237
+ # Intersection area
238
+ inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \
239
+ (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)
240
+
241
+ # Union Area
242
+ union = w1 * h1 + w2 * h2 - inter + eps
243
+
244
+ # IoU
245
+ iou = inter / union
246
+ if CIoU or DIoU or GIoU:
247
+ cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
248
+ ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
249
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
250
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
251
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
252
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
253
+ v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
254
+ with torch.no_grad():
255
+ alpha = v / (v - iou + (1 + eps))
256
+ return iou - (rho2 / c2 + v * alpha) # CIoU
257
+ return iou - rho2 / c2 # DIoU
258
+ c_area = cw * ch + eps # convex area
259
+ return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
260
+ return iou # IoU
261
+
262
+
263
+ def box_iou(box1, box2, eps=1e-7):
264
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
265
+ """
266
+ Return intersection-over-union (Jaccard index) of boxes.
267
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
268
+ Arguments:
269
+ box1 (Tensor[N, 4])
270
+ box2 (Tensor[M, 4])
271
+ Returns:
272
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
273
+ IoU values for every element in boxes1 and boxes2
274
+ """
275
+
276
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
277
+ (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)
278
+ inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)
279
+
280
+ # IoU = inter / (area1 + area2 - inter)
281
+ return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
282
+
283
+
284
+ def bbox_ioa(box1, box2, eps=1e-7):
285
+ """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
286
+ box1: np.array of shape(4)
287
+ box2: np.array of shape(nx4)
288
+ returns: np.array of shape(n)
289
+ """
290
+
291
+ # Get the coordinates of bounding boxes
292
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1
293
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
294
+
295
+ # Intersection area
296
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
297
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
298
+
299
+ # box2 area
300
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
301
+
302
+ # Intersection over box2 area
303
+ return inter_area / box2_area
304
+
305
+
306
+ def wh_iou(wh1, wh2, eps=1e-7):
307
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
308
+ wh1 = wh1[:, None] # [N,1,2]
309
+ wh2 = wh2[None] # [1,M,2]
310
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
311
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter + eps) # iou = inter / (area1 + area2 - inter)
312
+
313
+
314
+ # Plots ----------------------------------------------------------------------------------------------------------------
315
+
316
+
317
+ @threaded
318
+ def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
319
+ # Precision-recall curve
320
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
321
+ py = np.stack(py, axis=1)
322
+
323
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
324
+ for i, y in enumerate(py.T):
325
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
326
+ else:
327
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
328
+
329
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
330
+ ax.set_xlabel('Recall')
331
+ ax.set_ylabel('Precision')
332
+ ax.set_xlim(0, 1)
333
+ ax.set_ylim(0, 1)
334
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
335
+ ax.set_title('Precision-Recall Curve')
336
+ fig.savefig(save_dir, dpi=250)
337
+ plt.close(fig)
338
+
339
+
340
+ @threaded
341
+ def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'):
342
+ # Metric-confidence curve
343
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
344
+
345
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
346
+ for i, y in enumerate(py):
347
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
348
+ else:
349
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
350
+
351
+ y = smooth(py.mean(0), 0.05)
352
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
353
+ ax.set_xlabel(xlabel)
354
+ ax.set_ylabel(ylabel)
355
+ ax.set_xlim(0, 1)
356
+ ax.set_ylim(0, 1)
357
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
358
+ ax.set_title(f'{ylabel}-Confidence Curve')
359
+ fig.savefig(save_dir, dpi=250)
360
+ plt.close(fig)
utils/plots.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Plotting utils
4
+ """
5
+
6
+ import contextlib
7
+ import math
8
+ import os
9
+ from copy import copy
10
+ from pathlib import Path
11
+ from urllib.error import URLError
12
+
13
+ import cv2
14
+ import matplotlib
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+ import pandas as pd
18
+ import seaborn as sn
19
+ import torch
20
+ from PIL import Image, ImageDraw, ImageFont
21
+
22
+ from utils import TryExcept, threaded
23
+ from utils.general import (CONFIG_DIR, FONT, LOGGER, check_font, check_requirements, clip_boxes, increment_path,
24
+ is_ascii, xywh2xyxy, xyxy2xywh)
25
+ from utils.metrics import fitness
26
+ #from utils.segment.general import scale_image
27
+
28
+ # Settings
29
+ RANK = int(os.getenv('RANK', -1))
30
+ matplotlib.rc('font', **{'size': 11})
31
+ matplotlib.use('Agg') # for writing to files only
32
+
33
+
34
+ class Colors:
35
+ # Ultralytics color palette https://ultralytics.com/
36
+ def __init__(self):
37
+ # hex = matplotlib.colors.TABLEAU_COLORS.values()
38
+ hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
39
+ '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
40
+ self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
41
+ self.n = len(self.palette)
42
+
43
+ def __call__(self, i, bgr=False):
44
+ c = self.palette[int(i) % self.n]
45
+ return (c[2], c[1], c[0]) if bgr else c
46
+
47
+ @staticmethod
48
+ def hex2rgb(h): # rgb order (PIL)
49
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
50
+
51
+
52
+ colors = Colors() # create instance for 'from utils.plots import colors'
53
+
54
+
55
+ def check_pil_font(font=FONT, size=10):
56
+ # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary
57
+ font = Path(font)
58
+ font = font if font.exists() else (CONFIG_DIR / font.name)
59
+ try:
60
+ return ImageFont.truetype(str(font) if font.exists() else font.name, size)
61
+ except Exception: # download if missing
62
+ try:
63
+ check_font(font)
64
+ return ImageFont.truetype(str(font), size)
65
+ except TypeError:
66
+ check_requirements('Pillow>=8.4.0') # known issue https://github.com/ultralytics/yolov5/issues/5374
67
+ except URLError: # not online
68
+ return ImageFont.load_default()
69
+
70
+
71
+ class Annotator:
72
+ # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations
73
+ def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'):
74
+ assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'
75
+ non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic
76
+ self.pil = pil or non_ascii
77
+ if self.pil: # use PIL
78
+ self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
79
+ self.draw = ImageDraw.Draw(self.im)
80
+ self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font,
81
+ size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))
82
+ else: # use cv2
83
+ self.im = im
84
+ self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width
85
+
86
+ def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
87
+ # Add one xyxy box to image with label
88
+ if self.pil or not is_ascii(label):
89
+ self.draw.rectangle(box, width=self.lw, outline=color) # box
90
+ if label:
91
+ w, h = self.font.getsize(label) # text width, height (WARNING: deprecated) in 9.2.0
92
+ # _, _, w, h = self.font.getbbox(label) # text width, height (New)
93
+ outside = box[1] - h >= 0 # label fits outside box
94
+ self.draw.rectangle(
95
+ (box[0], box[1] - h if outside else box[1], box[0] + w + 1,
96
+ box[1] + 1 if outside else box[1] + h + 1),
97
+ fill=color,
98
+ )
99
+ # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0
100
+ self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)
101
+ else: # cv2
102
+ p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
103
+ cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)
104
+ if label:
105
+ tf = max(self.lw - 1, 1) # font thickness
106
+ w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height
107
+ outside = p1[1] - h >= 3
108
+ p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
109
+ cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled
110
+ cv2.putText(self.im,
111
+ label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
112
+ 0,
113
+ self.lw / 3,
114
+ txt_color,
115
+ thickness=tf,
116
+ lineType=cv2.LINE_AA)
117
+
118
+ # def masks(self, masks, colors, im_gpu, alpha=0.5, retina_masks=False):
119
+ # """Plot masks at once.
120
+ # Args:
121
+ # masks (tensor): predicted masks on cuda, shape: [n, h, w]
122
+ # colors (List[List[Int]]): colors for predicted masks, [[r, g, b] * n]
123
+ # im_gpu (tensor): img is in cuda, shape: [3, h, w], range: [0, 1]
124
+ # alpha (float): mask transparency: 0.0 fully transparent, 1.0 opaque
125
+ # """
126
+ # if self.pil:
127
+ # # convert to numpy first
128
+ # self.im = np.asarray(self.im).copy()
129
+ # if len(masks) == 0:
130
+ # self.im[:] = im_gpu.permute(1, 2, 0).contiguous().cpu().numpy() * 255
131
+ # colors = torch.tensor(colors, device=im_gpu.device, dtype=torch.float32) / 255.0
132
+ # colors = colors[:, None, None] # shape(n,1,1,3)
133
+ # masks = masks.unsqueeze(3) # shape(n,h,w,1)
134
+ # masks_color = masks * (colors * alpha) # shape(n,h,w,3)
135
+
136
+ # inv_alph_masks = (1 - masks * alpha).cumprod(0) # shape(n,h,w,1)
137
+ # mcs = (masks_color * inv_alph_masks).sum(0) * 2 # mask color summand shape(n,h,w,3)
138
+
139
+ # im_gpu = im_gpu.flip(dims=[0]) # flip channel
140
+ # im_gpu = im_gpu.permute(1, 2, 0).contiguous() # shape(h,w,3)
141
+ # im_gpu = im_gpu * inv_alph_masks[-1] + mcs
142
+ # im_mask = (im_gpu * 255).byte().cpu().numpy()
143
+ # self.im[:] = im_mask if retina_masks else scale_image(im_gpu.shape, im_mask, self.im.shape)
144
+ # if self.pil:
145
+ # # convert im back to PIL and update draw
146
+ # self.fromarray(self.im)
147
+
148
+ def rectangle(self, xy, fill=None, outline=None, width=1):
149
+ # Add rectangle to image (PIL-only)
150
+ self.draw.rectangle(xy, fill, outline, width)
151
+
152
+ def text(self, xy, text, txt_color=(255, 255, 255), anchor='top'):
153
+ # Add text to image (PIL-only)
154
+ if anchor == 'bottom': # start y from font bottom
155
+ w, h = self.font.getsize(text) # text width, height
156
+ xy[1] += 1 - h
157
+ self.draw.text(xy, text, fill=txt_color, font=self.font)
158
+
159
+ def fromarray(self, im):
160
+ # Update self.im from a numpy array
161
+ self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
162
+ self.draw = ImageDraw.Draw(self.im)
163
+
164
+ def result(self):
165
+ # Return annotated image as array
166
+ return np.asarray(self.im)
167
+
168
+
169
+ def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
170
+ """
171
+ x: Features to be visualized
172
+ module_type: Module type
173
+ stage: Module stage within model
174
+ n: Maximum number of feature maps to plot
175
+ save_dir: Directory to save results
176
+ """
177
+ if 'Detect' not in module_type:
178
+ batch, channels, height, width = x.shape # batch, channels, height, width
179
+ if height > 1 and width > 1:
180
+ f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
181
+
182
+ blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
183
+ n = min(n, channels) # number of plots
184
+ fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
185
+ ax = ax.ravel()
186
+ plt.subplots_adjust(wspace=0.05, hspace=0.05)
187
+ for i in range(n):
188
+ ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
189
+ ax[i].axis('off')
190
+
191
+ LOGGER.info(f'Saving {f}... ({n}/{channels})')
192
+ plt.savefig(f, dpi=300, bbox_inches='tight')
193
+ plt.close()
194
+ np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save
195
+
196
+
197
+ def hist2d(x, y, n=100):
198
+ # 2d histogram used in labels.png and evolve.png
199
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
200
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
201
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
202
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
203
+ return np.log(hist[xidx, yidx])
204
+
205
+
206
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
207
+ from scipy.signal import butter, filtfilt
208
+
209
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
210
+ def butter_lowpass(cutoff, fs, order):
211
+ nyq = 0.5 * fs
212
+ normal_cutoff = cutoff / nyq
213
+ return butter(order, normal_cutoff, btype='low', analog=False)
214
+
215
+ b, a = butter_lowpass(cutoff, fs, order=order)
216
+ return filtfilt(b, a, data) # forward-backward filter
217
+
218
+
219
+ def output_to_target(output, max_det=300):
220
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting
221
+ targets = []
222
+ for i, o in enumerate(output):
223
+ box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)
224
+ j = torch.full((conf.shape[0], 1), i)
225
+ targets.append(torch.cat((j, cls, xyxy2xywh(box), conf), 1))
226
+ return torch.cat(targets, 0).numpy()
227
+
228
+
229
+ @threaded
230
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None):
231
+ # Plot image grid with labels
232
+ if isinstance(images, torch.Tensor):
233
+ images = images.cpu().float().numpy()
234
+ if isinstance(targets, torch.Tensor):
235
+ targets = targets.cpu().numpy()
236
+
237
+ max_size = 1920 # max image size
238
+ max_subplots = 16 # max image subplots, i.e. 4x4
239
+ bs, _, h, w = images.shape # batch size, _, height, width
240
+ bs = min(bs, max_subplots) # limit plot images
241
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
242
+ if np.max(images[0]) <= 1:
243
+ images *= 255 # de-normalise (optional)
244
+
245
+ # Build Image
246
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
247
+ for i, im in enumerate(images):
248
+ if i == max_subplots: # if last batch has fewer images than we expect
249
+ break
250
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
251
+ im = im.transpose(1, 2, 0)
252
+ mosaic[y:y + h, x:x + w, :] = im
253
+
254
+ # Resize (optional)
255
+ scale = max_size / ns / max(h, w)
256
+ if scale < 1:
257
+ h = math.ceil(scale * h)
258
+ w = math.ceil(scale * w)
259
+ mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
260
+
261
+ # Annotate
262
+ fs = int((h + w) * ns * 0.01) # font size
263
+ annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)
264
+ for i in range(i + 1):
265
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
266
+ annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
267
+ if paths:
268
+ annotator.text((x + 5, y + 5), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
269
+ if len(targets) > 0:
270
+ ti = targets[targets[:, 0] == i] # image targets
271
+ boxes = xywh2xyxy(ti[:, 2:6]).T
272
+ classes = ti[:, 1].astype('int')
273
+ labels = ti.shape[1] == 6 # labels if no conf column
274
+ conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
275
+
276
+ if boxes.shape[1]:
277
+ if boxes.max() <= 1.01: # if normalized with tolerance 0.01
278
+ boxes[[0, 2]] *= w # scale to pixels
279
+ boxes[[1, 3]] *= h
280
+ elif scale < 1: # absolute coords need scale if image scales
281
+ boxes *= scale
282
+ boxes[[0, 2]] += x
283
+ boxes[[1, 3]] += y
284
+ for j, box in enumerate(boxes.T.tolist()):
285
+ cls = classes[j]
286
+ color = colors(cls)
287
+ cls = names[cls] if names else cls
288
+ if labels or conf[j] > 0.25: # 0.25 conf thresh
289
+ label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'
290
+ annotator.box_label(box, label, color=color)
291
+ annotator.im.save(fname) # save
292
+
293
+
294
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
295
+ # Plot LR simulating training for full epochs
296
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
297
+ y = []
298
+ for _ in range(epochs):
299
+ scheduler.step()
300
+ y.append(optimizer.param_groups[0]['lr'])
301
+ plt.plot(y, '.-', label='LR')
302
+ plt.xlabel('epoch')
303
+ plt.ylabel('LR')
304
+ plt.grid()
305
+ plt.xlim(0, epochs)
306
+ plt.ylim(0)
307
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
308
+ plt.close()
309
+
310
+
311
+ def plot_val_txt(): # from utils.plots import *; plot_val()
312
+ # Plot val.txt histograms
313
+ x = np.loadtxt('val.txt', dtype=np.float32)
314
+ box = xyxy2xywh(x[:, :4])
315
+ cx, cy = box[:, 0], box[:, 1]
316
+
317
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
318
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
319
+ ax.set_aspect('equal')
320
+ plt.savefig('hist2d.png', dpi=300)
321
+
322
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
323
+ ax[0].hist(cx, bins=600)
324
+ ax[1].hist(cy, bins=600)
325
+ plt.savefig('hist1d.png', dpi=200)
326
+
327
+
328
+ def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
329
+ # Plot targets.txt histograms
330
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
331
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
332
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
333
+ ax = ax.ravel()
334
+ for i in range(4):
335
+ ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}')
336
+ ax[i].legend()
337
+ ax[i].set_title(s[i])
338
+ plt.savefig('targets.jpg', dpi=200)
339
+
340
+
341
+ def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()
342
+ # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)
343
+ save_dir = Path(file).parent if file else Path(dir)
344
+ plot2 = False # plot additional results
345
+ if plot2:
346
+ ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
347
+
348
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
349
+ # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
350
+ for f in sorted(save_dir.glob('study*.txt')):
351
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
352
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
353
+ if plot2:
354
+ s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
355
+ for i in range(7):
356
+ ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
357
+ ax[i].set_title(s[i])
358
+
359
+ j = y[3].argmax() + 1
360
+ ax2.plot(y[5, 1:j],
361
+ y[3, 1:j] * 1E2,
362
+ '.-',
363
+ linewidth=2,
364
+ markersize=8,
365
+ label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
366
+
367
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
368
+ 'k.-',
369
+ linewidth=2,
370
+ markersize=8,
371
+ alpha=.25,
372
+ label='EfficientDet')
373
+
374
+ ax2.grid(alpha=0.2)
375
+ ax2.set_yticks(np.arange(20, 60, 5))
376
+ ax2.set_xlim(0, 57)
377
+ ax2.set_ylim(25, 55)
378
+ ax2.set_xlabel('GPU Speed (ms/img)')
379
+ ax2.set_ylabel('COCO AP val')
380
+ ax2.legend(loc='lower right')
381
+ f = save_dir / 'study.png'
382
+ print(f'Saving {f}...')
383
+ plt.savefig(f, dpi=300)
384
+
385
+
386
+ @TryExcept() # known issue https://github.com/ultralytics/yolov5/issues/5395
387
+ def plot_labels(labels, names=(), save_dir=Path('')):
388
+ # plot dataset labels
389
+ LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
390
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
391
+ nc = int(c.max() + 1) # number of classes
392
+ x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
393
+
394
+ # seaborn correlogram
395
+ sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
396
+ plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
397
+ plt.close()
398
+
399
+ # matplotlib labels
400
+ matplotlib.use('svg') # faster
401
+ ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
402
+ y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
403
+ with contextlib.suppress(Exception): # color histogram bars by class
404
+ [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195
405
+ ax[0].set_ylabel('instances')
406
+ if 0 < len(names) < 30:
407
+ ax[0].set_xticks(range(len(names)))
408
+ ax[0].set_xticklabels(list(names.values()), rotation=90, fontsize=10)
409
+ else:
410
+ ax[0].set_xlabel('classes')
411
+ sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
412
+ sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
413
+
414
+ # rectangles
415
+ labels[:, 1:3] = 0.5 # center
416
+ labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
417
+ img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
418
+ for cls, *box in labels[:1000]:
419
+ ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
420
+ ax[1].imshow(img)
421
+ ax[1].axis('off')
422
+
423
+ for a in [0, 1, 2, 3]:
424
+ for s in ['top', 'right', 'left', 'bottom']:
425
+ ax[a].spines[s].set_visible(False)
426
+
427
+ plt.savefig(save_dir / 'labels.jpg', dpi=200)
428
+ matplotlib.use('Agg')
429
+ plt.close()
430
+
431
+
432
+ def imshow_cls(im, labels=None, pred=None, names=None, nmax=25, verbose=False, f=Path('images.jpg')):
433
+ # Show classification image grid with labels (optional) and predictions (optional)
434
+ from utils.augmentations import denormalize
435
+
436
+ names = names or [f'class{i}' for i in range(1000)]
437
+ blocks = torch.chunk(denormalize(im.clone()).cpu().float(), len(im),
438
+ dim=0) # select batch index 0, block by channels
439
+ n = min(len(blocks), nmax) # number of plots
440
+ m = min(8, round(n ** 0.5)) # 8 x 8 default
441
+ fig, ax = plt.subplots(math.ceil(n / m), m) # 8 rows x n/8 cols
442
+ ax = ax.ravel() if m > 1 else [ax]
443
+ # plt.subplots_adjust(wspace=0.05, hspace=0.05)
444
+ for i in range(n):
445
+ ax[i].imshow(blocks[i].squeeze().permute((1, 2, 0)).numpy().clip(0.0, 1.0))
446
+ ax[i].axis('off')
447
+ if labels is not None:
448
+ s = names[labels[i]] + (f'—{names[pred[i]]}' if pred is not None else '')
449
+ ax[i].set_title(s, fontsize=8, verticalalignment='top')
450
+ plt.savefig(f, dpi=300, bbox_inches='tight')
451
+ plt.close()
452
+ if verbose:
453
+ LOGGER.info(f"Saving {f}")
454
+ if labels is not None:
455
+ LOGGER.info('True: ' + ' '.join(f'{names[i]:3s}' for i in labels[:nmax]))
456
+ if pred is not None:
457
+ LOGGER.info('Predicted:' + ' '.join(f'{names[i]:3s}' for i in pred[:nmax]))
458
+ return f
459
+
460
+
461
+ def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve()
462
+ # Plot evolve.csv hyp evolution results
463
+ evolve_csv = Path(evolve_csv)
464
+ data = pd.read_csv(evolve_csv)
465
+ keys = [x.strip() for x in data.columns]
466
+ x = data.values
467
+ f = fitness(x)
468
+ j = np.argmax(f) # max fitness index
469
+ plt.figure(figsize=(10, 12), tight_layout=True)
470
+ matplotlib.rc('font', **{'size': 8})
471
+ print(f'Best results from row {j} of {evolve_csv}:')
472
+ for i, k in enumerate(keys[7:]):
473
+ v = x[:, 7 + i]
474
+ mu = v[j] # best single result
475
+ plt.subplot(6, 5, i + 1)
476
+ plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
477
+ plt.plot(mu, f.max(), 'k+', markersize=15)
478
+ plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9}) # limit to 40 characters
479
+ if i % 5 != 0:
480
+ plt.yticks([])
481
+ print(f'{k:>15}: {mu:.3g}')
482
+ f = evolve_csv.with_suffix('.png') # filename
483
+ plt.savefig(f, dpi=200)
484
+ plt.close()
485
+ print(f'Saved {f}')
486
+
487
+
488
+ def plot_results(file='path/to/results.csv', dir=''):
489
+ # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
490
+ save_dir = Path(file).parent if file else Path(dir)
491
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
492
+ ax = ax.ravel()
493
+ files = list(save_dir.glob('results*.csv'))
494
+ assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
495
+ for f in files:
496
+ try:
497
+ data = pd.read_csv(f)
498
+ s = [x.strip() for x in data.columns]
499
+ x = data.values[:, 0]
500
+ for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
501
+ y = data.values[:, j].astype('float')
502
+ # y[y == 0] = np.nan # don't show zero values
503
+ ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)
504
+ ax[i].set_title(s[j], fontsize=12)
505
+ # if j in [8, 9, 10]: # share train and val loss y axes
506
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
507
+ except Exception as e:
508
+ LOGGER.info(f'Warning: Plotting error for {f}: {e}')
509
+ ax[1].legend()
510
+ fig.savefig(save_dir / 'results.png', dpi=200)
511
+ plt.close()
512
+
513
+
514
+ def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
515
+ # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
516
+ ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
517
+ s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
518
+ files = list(Path(save_dir).glob('frames*.txt'))
519
+ for fi, f in enumerate(files):
520
+ try:
521
+ results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
522
+ n = results.shape[1] # number of rows
523
+ x = np.arange(start, min(stop, n) if stop else n)
524
+ results = results[:, x]
525
+ t = (results[0] - results[0].min()) # set t0=0s
526
+ results[0] = x
527
+ for i, a in enumerate(ax):
528
+ if i < len(results):
529
+ label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
530
+ a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
531
+ a.set_title(s[i])
532
+ a.set_xlabel('time (s)')
533
+ # if fi == len(files) - 1:
534
+ # a.set_ylim(bottom=0)
535
+ for side in ['top', 'right']:
536
+ a.spines[side].set_visible(False)
537
+ else:
538
+ a.remove()
539
+ except Exception as e:
540
+ print(f'Warning: Plotting error for {f}; {e}')
541
+ ax[1].legend()
542
+ plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
543
+
544
+
545
+ def save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True):
546
+ # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop
547
+ xyxy = torch.tensor(xyxy).view(-1, 4)
548
+ b = xyxy2xywh(xyxy) # boxes
549
+ if square:
550
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
551
+ b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
552
+ xyxy = xywh2xyxy(b).long()
553
+ clip_boxes(xyxy, im.shape)
554
+ crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]
555
+ if save:
556
+ file.parent.mkdir(parents=True, exist_ok=True) # make directory
557
+ f = str(increment_path(file).with_suffix('.jpg'))
558
+ # cv2.imwrite(f, crop) # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue
559
+ Image.fromarray(crop[..., ::-1]).save(f, quality=95, subsampling=0) # save RGB
560
+ return crop
utils/torch_utils.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from torch.nn.parallel import DistributedDataParallel as DDP
21
+
22
+ from utils.general import LOGGER, check_version, colorstr, file_date, git_describe
23
+
24
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
25
+ RANK = int(os.getenv('RANK', -1))
26
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
27
+
28
+ try:
29
+ import thop # for FLOPs computation
30
+ except ImportError:
31
+ thop = None
32
+
33
+ # Suppress PyTorch warnings
34
+ warnings.filterwarnings('ignore', message='User provided device_type of \'cuda\', but CUDA is not available. Disabling')
35
+ warnings.filterwarnings('ignore', category=UserWarning)
36
+
37
+
38
+ def smart_inference_mode(torch_1_9=check_version(torch.__version__, '1.9.0')):
39
+ # Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator
40
+ def decorate(fn):
41
+ return (torch.inference_mode if torch_1_9 else torch.no_grad)()(fn)
42
+
43
+ return decorate
44
+
45
+
46
+ def smartCrossEntropyLoss(label_smoothing=0.0):
47
+ # Returns nn.CrossEntropyLoss with label smoothing enabled for torch>=1.10.0
48
+ if check_version(torch.__version__, '1.10.0'):
49
+ return nn.CrossEntropyLoss(label_smoothing=label_smoothing)
50
+ if label_smoothing > 0:
51
+ LOGGER.warning(f'WARNING ⚠️ label smoothing {label_smoothing} requires torch>=1.10.0')
52
+ return nn.CrossEntropyLoss()
53
+
54
+
55
+ def smart_DDP(model):
56
+ # Model DDP creation with checks
57
+ assert not check_version(torch.__version__, '1.12.0', pinned=True), \
58
+ 'torch==1.12.0 torchvision==0.13.0 DDP training is not supported due to a known issue. ' \
59
+ 'Please upgrade or downgrade torch to use DDP. See https://github.com/ultralytics/yolov5/issues/8395'
60
+ if check_version(torch.__version__, '1.11.0'):
61
+ return DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK, static_graph=True)
62
+ else:
63
+ return DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK)
64
+
65
+
66
+ def reshape_classifier_output(model, n=1000):
67
+ # Update a TorchVision classification model to class count 'n' if required
68
+ from models.common import Classify
69
+ name, m = list((model.model if hasattr(model, 'model') else model).named_children())[-1] # last module
70
+ if isinstance(m, Classify): # YOLOv5 Classify() head
71
+ if m.linear.out_features != n:
72
+ m.linear = nn.Linear(m.linear.in_features, n)
73
+ elif isinstance(m, nn.Linear): # ResNet, EfficientNet
74
+ if m.out_features != n:
75
+ setattr(model, name, nn.Linear(m.in_features, n))
76
+ elif isinstance(m, nn.Sequential):
77
+ types = [type(x) for x in m]
78
+ if nn.Linear in types:
79
+ i = types.index(nn.Linear) # nn.Linear index
80
+ if m[i].out_features != n:
81
+ m[i] = nn.Linear(m[i].in_features, n)
82
+ elif nn.Conv2d in types:
83
+ i = types.index(nn.Conv2d) # nn.Conv2d index
84
+ if m[i].out_channels != n:
85
+ m[i] = nn.Conv2d(m[i].in_channels, n, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)
86
+
87
+
88
+ @contextmanager
89
+ def torch_distributed_zero_first(local_rank: int):
90
+ # Decorator to make all processes in distributed training wait for each local_master to do something
91
+ if local_rank not in [-1, 0]:
92
+ dist.barrier(device_ids=[local_rank])
93
+ yield
94
+ if local_rank == 0:
95
+ dist.barrier(device_ids=[0])
96
+
97
+
98
+ def device_count():
99
+ # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Supports Linux and Windows
100
+ assert platform.system() in ('Linux', 'Windows'), 'device_count() only supported on Linux or Windows'
101
+ try:
102
+ cmd = 'nvidia-smi -L | wc -l' if platform.system() == 'Linux' else 'nvidia-smi -L | find /c /v ""' # Windows
103
+ return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1])
104
+ except Exception:
105
+ return 0
106
+
107
+
108
+ def select_device(device='', batch_size=0, newline=True):
109
+ # device = None or 'cpu' or 0 or '0' or '0,1,2,3'
110
+ s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} '
111
+ device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0'
112
+ cpu = device == 'cpu'
113
+ mps = device == 'mps' # Apple Metal Performance Shaders (MPS)
114
+ if cpu or mps:
115
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
116
+ elif device: # non-cpu device requested
117
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available()
118
+ assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \
119
+ f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)"
120
+
121
+ if not cpu and not mps and torch.cuda.is_available(): # prefer GPU if available
122
+ devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7
123
+ n = len(devices) # device count
124
+ if n > 1 and batch_size > 0: # check batch_size is divisible by device_count
125
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
126
+ space = ' ' * (len(s) + 1)
127
+ for i, d in enumerate(devices):
128
+ p = torch.cuda.get_device_properties(i)
129
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB
130
+ arg = 'cuda:0'
131
+ elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available(): # prefer MPS if available
132
+ s += 'MPS\n'
133
+ arg = 'mps'
134
+ else: # revert to CPU
135
+ s += 'CPU\n'
136
+ arg = 'cpu'
137
+
138
+ if not newline:
139
+ s = s.rstrip()
140
+ LOGGER.info(s)
141
+ return torch.device(arg)
142
+
143
+
144
+ def time_sync():
145
+ # PyTorch-accurate time
146
+ if torch.cuda.is_available():
147
+ torch.cuda.synchronize()
148
+ return time.time()
149
+
150
+
151
+ def profile(input, ops, n=10, device=None):
152
+ """ YOLOv5 speed/memory/FLOPs profiler
153
+ Usage:
154
+ input = torch.randn(16, 3, 640, 640)
155
+ m1 = lambda x: x * torch.sigmoid(x)
156
+ m2 = nn.SiLU()
157
+ profile(input, [m1, m2], n=100) # profile over 100 iterations
158
+ """
159
+ results = []
160
+ if not isinstance(device, torch.device):
161
+ device = select_device(device)
162
+ print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}"
163
+ f"{'input':>24s}{'output':>24s}")
164
+
165
+ for x in input if isinstance(input, list) else [input]:
166
+ x = x.to(device)
167
+ x.requires_grad = True
168
+ for m in ops if isinstance(ops, list) else [ops]:
169
+ m = m.to(device) if hasattr(m, 'to') else m # device
170
+ m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m
171
+ tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward
172
+ try:
173
+ flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs
174
+ except Exception:
175
+ flops = 0
176
+
177
+ try:
178
+ for _ in range(n):
179
+ t[0] = time_sync()
180
+ y = m(x)
181
+ t[1] = time_sync()
182
+ try:
183
+ _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()
184
+ t[2] = time_sync()
185
+ except Exception: # no backward method
186
+ # print(e) # for debug
187
+ t[2] = float('nan')
188
+ tf += (t[1] - t[0]) * 1000 / n # ms per op forward
189
+ tb += (t[2] - t[1]) * 1000 / n # ms per op backward
190
+ mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB)
191
+ s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y)) # shapes
192
+ p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters
193
+ print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')
194
+ results.append([p, flops, mem, tf, tb, s_in, s_out])
195
+ except Exception as e:
196
+ print(e)
197
+ results.append(None)
198
+ torch.cuda.empty_cache()
199
+ return results
200
+
201
+
202
+ def is_parallel(model):
203
+ # Returns True if model is of type DP or DDP
204
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
205
+
206
+
207
+ def de_parallel(model):
208
+ # De-parallelize a model: returns single-GPU model if model is of type DP or DDP
209
+ return model.module if is_parallel(model) else model
210
+
211
+
212
+ def initialize_weights(model):
213
+ for m in model.modules():
214
+ t = type(m)
215
+ if t is nn.Conv2d:
216
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
217
+ elif t is nn.BatchNorm2d:
218
+ m.eps = 1e-3
219
+ m.momentum = 0.03
220
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
221
+ m.inplace = True
222
+
223
+
224
+ def find_modules(model, mclass=nn.Conv2d):
225
+ # Finds layer indices matching module class 'mclass'
226
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
227
+
228
+
229
+ def sparsity(model):
230
+ # Return global model sparsity
231
+ a, b = 0, 0
232
+ for p in model.parameters():
233
+ a += p.numel()
234
+ b += (p == 0).sum()
235
+ return b / a
236
+
237
+
238
+ def prune(model, amount=0.3):
239
+ # Prune model to requested global sparsity
240
+ import torch.nn.utils.prune as prune
241
+ for name, m in model.named_modules():
242
+ if isinstance(m, nn.Conv2d):
243
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
244
+ prune.remove(m, 'weight') # make permanent
245
+ LOGGER.info(f'Model pruned to {sparsity(model):.3g} global sparsity')
246
+
247
+
248
+ def fuse_conv_and_bn(conv, bn):
249
+ # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
250
+ fusedconv = nn.Conv2d(conv.in_channels,
251
+ conv.out_channels,
252
+ kernel_size=conv.kernel_size,
253
+ stride=conv.stride,
254
+ padding=conv.padding,
255
+ dilation=conv.dilation,
256
+ groups=conv.groups,
257
+ bias=True).requires_grad_(False).to(conv.weight.device)
258
+
259
+ # Prepare filters
260
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
261
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
262
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
263
+
264
+ # Prepare spatial bias
265
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
266
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
267
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
268
+
269
+ return fusedconv
270
+
271
+
272
+ def model_info(model, verbose=False, imgsz=640):
273
+ # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
274
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
275
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
276
+ if verbose:
277
+ print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}")
278
+ for i, (name, p) in enumerate(model.named_parameters()):
279
+ name = name.replace('module_list.', '')
280
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
281
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
282
+
283
+ try: # FLOPs
284
+ p = next(model.parameters())
285
+ stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 # max stride
286
+ im = torch.empty((1, p.shape[1], stride, stride), device=p.device) # input image in BCHW format
287
+ flops = thop.profile(deepcopy(model), inputs=(im,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs
288
+ imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz] # expand if int/float
289
+ fs = f', {flops * imgsz[0] / stride * imgsz[1] / stride:.1f} GFLOPs' # 640x640 GFLOPs
290
+ except Exception:
291
+ fs = ''
292
+
293
+ name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model'
294
+ LOGGER.info(f"{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
295
+
296
+
297
+ def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
298
+ # Scales img(bs,3,y,x) by ratio constrained to gs-multiple
299
+ if ratio == 1.0:
300
+ return img
301
+ h, w = img.shape[2:]
302
+ s = (int(h * ratio), int(w * ratio)) # new size
303
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
304
+ if not same_shape: # pad/crop img
305
+ h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
306
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
307
+
308
+
309
+ def copy_attr(a, b, include=(), exclude=()):
310
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
311
+ for k, v in b.__dict__.items():
312
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
313
+ continue
314
+ else:
315
+ setattr(a, k, v)
316
+
317
+
318
+ def smart_optimizer(model, name='Adam', lr=0.001, momentum=0.9, decay=1e-5):
319
+ # YOLOv5 3-param group optimizer: 0) weights with decay, 1) weights no decay, 2) biases no decay
320
+ g = [], [], [] # optimizer parameter groups
321
+ bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k) # normalization layers, i.e. BatchNorm2d()
322
+ for v in model.modules():
323
+ for p_name, p in v.named_parameters(recurse=0):
324
+ if p_name == 'bias': # bias (no decay)
325
+ g[2].append(p)
326
+ elif p_name == 'weight' and isinstance(v, bn): # weight (no decay)
327
+ g[1].append(p)
328
+ else:
329
+ g[0].append(p) # weight (with decay)
330
+
331
+ if name == 'Adam':
332
+ optimizer = torch.optim.Adam(g[2], lr=lr, betas=(momentum, 0.999)) # adjust beta1 to momentum
333
+ elif name == 'AdamW':
334
+ optimizer = torch.optim.AdamW(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)
335
+ elif name == 'RMSProp':
336
+ optimizer = torch.optim.RMSprop(g[2], lr=lr, momentum=momentum)
337
+ elif name == 'SGD':
338
+ optimizer = torch.optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)
339
+ else:
340
+ raise NotImplementedError(f'Optimizer {name} not implemented.')
341
+
342
+ optimizer.add_param_group({'params': g[0], 'weight_decay': decay}) # add g0 with weight_decay
343
+ optimizer.add_param_group({'params': g[1], 'weight_decay': 0.0}) # add g1 (BatchNorm2d weights)
344
+ LOGGER.info(f"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}) with parameter groups "
345
+ f"{len(g[1])} weight(decay=0.0), {len(g[0])} weight(decay={decay}), {len(g[2])} bias")
346
+ return optimizer
347
+
348
+
349
+ def smart_hub_load(repo='ultralytics/yolov5', model='yolov5s', **kwargs):
350
+ # YOLOv5 torch.hub.load() wrapper with smart error/issue handling
351
+ if check_version(torch.__version__, '1.9.1'):
352
+ kwargs['skip_validation'] = True # validation causes GitHub API rate limit errors
353
+ if check_version(torch.__version__, '1.12.0'):
354
+ kwargs['trust_repo'] = True # argument required starting in torch 0.12
355
+ try:
356
+ return torch.hub.load(repo, model, **kwargs)
357
+ except Exception:
358
+ return torch.hub.load(repo, model, force_reload=True, **kwargs)
359
+
360
+
361
+ def smart_resume(ckpt, optimizer, ema=None, weights='yolov5s.pt', epochs=300, resume=True):
362
+ # Resume training from a partially trained checkpoint
363
+ best_fitness = 0.0
364
+ start_epoch = ckpt['epoch'] + 1
365
+ if ckpt['optimizer'] is not None:
366
+ optimizer.load_state_dict(ckpt['optimizer']) # optimizer
367
+ best_fitness = ckpt['best_fitness']
368
+ if ema and ckpt.get('ema'):
369
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict()) # EMA
370
+ ema.updates = ckpt['updates']
371
+ if resume:
372
+ assert start_epoch > 0, f'{weights} training to {epochs} epochs is finished, nothing to resume.\n' \
373
+ f"Start a new training without --resume, i.e. 'python train.py --weights {weights}'"
374
+ LOGGER.info(f'Resuming training from {weights} from epoch {start_epoch} to {epochs} total epochs')
375
+ if epochs < start_epoch:
376
+ LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.")
377
+ epochs += ckpt['epoch'] # finetune additional epochs
378
+ return best_fitness, start_epoch, epochs
379
+
380
+
381
+ class EarlyStopping:
382
+ # YOLOv5 simple early stopper
383
+ def __init__(self, patience=30):
384
+ self.best_fitness = 0.0 # i.e. mAP
385
+ self.best_epoch = 0
386
+ self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop
387
+ self.possible_stop = False # possible stop may occur next epoch
388
+
389
+ def __call__(self, epoch, fitness):
390
+ if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training
391
+ self.best_epoch = epoch
392
+ self.best_fitness = fitness
393
+ delta = epoch - self.best_epoch # epochs without improvement
394
+ self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch
395
+ stop = delta >= self.patience # stop training if patience exceeded
396
+ if stop:
397
+ LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. '
398
+ f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n'
399
+ f'To update EarlyStopping(patience={self.patience}) pass a new patience value, '
400
+ f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.')
401
+ return stop
402
+
403
+
404
+ class ModelEMA:
405
+ """ Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models
406
+ Keeps a moving average of everything in the model state_dict (parameters and buffers)
407
+ For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
408
+ """
409
+
410
+ def __init__(self, model, decay=0.9999, tau=2000, updates=0):
411
+ # Create EMA
412
+ self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA
413
+ self.updates = updates # number of EMA updates
414
+ self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
415
+ for p in self.ema.parameters():
416
+ p.requires_grad_(False)
417
+
418
+ def update(self, model):
419
+ # Update EMA parameters
420
+ self.updates += 1
421
+ d = self.decay(self.updates)
422
+
423
+ msd = de_parallel(model).state_dict() # model state_dict
424
+ for k, v in self.ema.state_dict().items():
425
+ if v.dtype.is_floating_point: # true for FP16 and FP32
426
+ v *= d
427
+ v += (1 - d) * msd[k].detach()
428
+ # assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype} and model {msd[k].dtype} must be FP32'
429
+
430
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
431
+ # Update EMA attributes
432
+ copy_attr(self.ema, model, include, exclude)