Carzit commited on
Commit
4bec64b
1 Parent(s): aa1369c

Upload 21 files

Browse files
FaceCropper.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from PIL import Image
5
+ import torch
6
+ import torch.backends.cudnn as cudnn
7
+ from numpy import random
8
+
9
+ from models.experimental import attempt_load
10
+ from utils.datasets import LoadStreams, LoadImages
11
+ from utils.general import (
12
+ check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer)
13
+ from utils.torch_utils import select_device, load_classifier, time_synchronized
14
+
15
+ import gradio as gr
16
+ import huggingface_hub
17
+
18
+ from crop import crop
19
+
20
+ class FaceCrop:
21
+ def __init__(self):
22
+ self.device = select_device()
23
+ self.half = self.device.type != 'cpu'
24
+ self.results = {}
25
+
26
+ def load_dataset(self, source):
27
+ self.source = source
28
+ self.dataset = LoadImages(source)
29
+ print(f'Successfully load {source}')
30
+
31
+ def load_model(self, model):
32
+ self.model = attempt_load(model, map_location=self.device)
33
+ if self.half:
34
+ self.model.half()
35
+ print(f'Successfully load model weights from {model}')
36
+
37
+ def set_crop_config(self, target_size, mode=0, face_ratio=3, threshold=1.5):
38
+ self.target_size = target_size
39
+ self.mode = mode
40
+ self.face_ratio = face_ratio
41
+ self.threshold = threshold
42
+
43
+ def info(self):
44
+ attributes = dir(self)
45
+ for attribute in attributes:
46
+ if not attribute.startswith('__') and not callable(getattr(self, attribute)):
47
+ value = getattr(self, attribute)
48
+ print(attribute, " = ", value)
49
+
50
+ def process(self):
51
+ for path, img, im0s, vid_cap in self.dataset:
52
+ img = torch.from_numpy(img).to(self.device)
53
+ img = img.half() if self.half else img.float() # uint8 to fp16/32
54
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
55
+ if img.ndimension() == 3:
56
+ img = img.unsqueeze(0)
57
+
58
+ # Inference
59
+ pred = self.model(img, augment=False)[0]
60
+
61
+ # Apply NMS
62
+ pred = non_max_suppression(pred)
63
+
64
+ # Process detections
65
+ for i, det in enumerate(pred): # detections per image
66
+
67
+ p, s, im0 = path, '', im0s
68
+
69
+ in_path = str(Path(self.source) / Path(p).name)
70
+
71
+ #txt_path = str(Path(out) / Path(p).stem)
72
+ s += '%gx%g ' % img.shape[2:] # print string
73
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
74
+
75
+ if det is not None and len(det):
76
+ # Rescale boxes from img_size to im0 size
77
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
78
+
79
+ # Write results
80
+ ind = 0
81
+ for *xyxy, conf, cls in det:
82
+ if conf > 0.6: # Write to file
83
+ out_path = os.path.join(str(Path(self.out_folder)), Path(p).name.replace('.', '_'+str(ind)+'.'))
84
+
85
+ x, y, w, h = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
86
+ self.results[ind] = crop(in_path, (x, y), out_path, mode=self.mode, size=self.target_size, box=(w, h), face_ratio=self.face_ratio, shreshold=self.threshold)
87
+
88
+ ind += 1
89
+
90
+ def run(img, mode, width, height):
91
+ face_crop_pipeline.set_crop_config(mode=mode, target_size=(width,height))
92
+ face_crop_pipeline.process
93
+ return face_crop_pipeline.results[0]
94
+
95
+ if __name__ == '__main__':
96
+ model_path = huggingface_hub.hf_hub_download("Carzit/yolo5x_anime", "yolo5x_anime.pt")
97
+ face_crop_pipeline = FaceCrop()
98
+ face_crop_pipeline.load_model(model_path)
99
+
100
+
101
+ app = gr.Blocks()
102
+ with app:
103
+ gr.Markdown("# Anime Face Crop\n\n"
104
+ "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=skytnt.animeseg)\n\n"
105
+ "demo for [https://github.com/SkyTNT/anime-segmentation/](https://github.com/SkyTNT/anime-segmentation/)")
106
+ with gr.Row():
107
+ input_img = gr.Image(label="input image")
108
+ output_img = gr.Image(label="result", image_mode="RGB")
109
+ crop_mode = gr.Dropdown([0, 1, 2, 3], label="Crop Mode", info="0:Auto; 1:No Scale; 2:Full Screen; 3:Fixed Face Ratio")
110
+ tgt_width = gr.Slider(10, 2048, value=512, label="Width")
111
+ tgt_height = gr.Slider(10, 2048, value=512, label="Height")
112
+
113
+ run_btn = gr.Button(variant="primary")
114
+
115
+ run_btn.click(run, [input_img, crop_mode, tgt_width, tgt_height], [output_img])
116
+ app.launch()
117
+
118
+
119
+
crop.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+ def crop(img, point, mode=0, size=(512, 512), box=None, face_ratio=3, shreshold=1.5):
7
+ img_width, img_height = img.size
8
+ tgt_width, tgt_height = size
9
+ point = (point[0]*img_width, point[1]*img_height)
10
+
11
+ # mode 0 : automatic
12
+ if mode == 0:
13
+ if box is None:
14
+ raise RuntimeError('face bax parameter expected: missing box=(width, height)')
15
+ if img_width < tgt_width or img_height < tgt_height:
16
+ mode = 1
17
+ elif face_ratio ** 2 * shreshold ** 2 * box[0] * box[1] * img_width * img_height < tgt_width * tgt_height:
18
+ mode = 2
19
+ else:
20
+ mode = 3
21
+
22
+ # mode 1 : no scale
23
+ if mode == 1:
24
+ pass
25
+
26
+ # mode 2 : full screen - crop as largr as possible
27
+ if mode == 2:
28
+ if tgt_width/img_width > tgt_height/img_height:
29
+ r = tgt_height / tgt_width
30
+ tgt_width = img_width
31
+ tgt_height = round(tgt_width * r)
32
+ else:
33
+ r = tgt_width / tgt_height
34
+ tgt_height = img_height
35
+ tgt_width = round(tgt_height * r)
36
+
37
+ # mode 3 : fixed face ratio
38
+ if mode == 3:
39
+ if box is None:
40
+ raise RuntimeError('face bax parameter expected: missing box=(width, height)')
41
+ box_width = box[0] * img_height
42
+ box_height = box[1] * img_height
43
+ if box_width/tgt_width > box_height/tgt_width:
44
+ r = tgt_height / tgt_width
45
+ tgt_width = round(box_width * face_ratio)
46
+ tgt_height = round(tgt_width * r)
47
+ else:
48
+ r = tgt_width / tgt_height
49
+ tgt_height = round(box_height * face_ratio)
50
+ tgt_width = round(tgt_height * r)
51
+
52
+
53
+ # upscale raw image if target size is over raw image size
54
+ if img_width < tgt_width or img_height < tgt_height:
55
+ if img_width < img_height:
56
+ img_height = round(tgt_width * img_height / img_width)
57
+ img_width = tgt_width
58
+ img = img.resize((img_width, img_height))
59
+ else:
60
+ img_width = round(tgt_height * img_width / img_height)
61
+ img_height = tgt_height
62
+ img = img.resize((img_width, img_height))
63
+
64
+ left = point[0] - tgt_width // 2
65
+ top = point[1] - tgt_height // 2
66
+ right = point[0] + tgt_width // 2
67
+ bottom = point[1] + tgt_height // 2
68
+
69
+ if left < 0:
70
+ right -= left
71
+ left = 0
72
+ if right > img_width:
73
+ left -= (right-img_width)
74
+ right = img_width
75
+ if top < 0:
76
+ bottom -= top
77
+ top = 0
78
+ if bottom > img_height:
79
+ top -= (bottom-img_height)
80
+ bottom = img_height
81
+
82
+ cropped_img = img.crop((left, top, right, bottom))
83
+ cropped_img = cropped_img.resize(size)
84
+ return np.ndarray(cropped_img)
models/__init__.py ADDED
File without changes
models/common.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains modules common to various models
2
+ import math
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+
8
+ def autopad(k, p=None): # kernel, padding
9
+ # Pad to 'same'
10
+ if p is None:
11
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
12
+ return p
13
+
14
+
15
+ def DWConv(c1, c2, k=1, s=1, act=True):
16
+ # Depthwise convolution
17
+ return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
18
+
19
+
20
+ class Conv(nn.Module):
21
+ # Standard convolution
22
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
23
+ super(Conv, self).__init__()
24
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
25
+ self.bn = nn.BatchNorm2d(c2)
26
+ self.act = nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity()
27
+
28
+ def forward(self, x):
29
+ return self.act(self.bn(self.conv(x)))
30
+
31
+ def fuseforward(self, x):
32
+ return self.act(self.conv(x))
33
+
34
+
35
+ class Bottleneck(nn.Module):
36
+ # Standard bottleneck
37
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
38
+ super(Bottleneck, self).__init__()
39
+ c_ = int(c2 * e) # hidden channels
40
+ self.cv1 = Conv(c1, c_, 1, 1)
41
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
42
+ self.add = shortcut and c1 == c2
43
+
44
+ def forward(self, x):
45
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
46
+
47
+
48
+ class BottleneckCSP(nn.Module):
49
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
50
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
51
+ super(BottleneckCSP, self).__init__()
52
+ c_ = int(c2 * e) # hidden channels
53
+ self.cv1 = Conv(c1, c_, 1, 1)
54
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
55
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
56
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
57
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
58
+ self.act = nn.LeakyReLU(0.1, inplace=True)
59
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
60
+
61
+ def forward(self, x):
62
+ y1 = self.cv3(self.m(self.cv1(x)))
63
+ y2 = self.cv2(x)
64
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
65
+
66
+
67
+ class SPP(nn.Module):
68
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
69
+ def __init__(self, c1, c2, k=(5, 9, 13)):
70
+ super(SPP, self).__init__()
71
+ c_ = c1 // 2 # hidden channels
72
+ self.cv1 = Conv(c1, c_, 1, 1)
73
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
74
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
75
+
76
+ def forward(self, x):
77
+ x = self.cv1(x)
78
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
79
+
80
+
81
+ class Focus(nn.Module):
82
+ # Focus wh information into c-space
83
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
84
+ super(Focus, self).__init__()
85
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
86
+
87
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
88
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
89
+
90
+
91
+ class Concat(nn.Module):
92
+ # Concatenate a list of tensors along dimension
93
+ def __init__(self, dimension=1):
94
+ super(Concat, self).__init__()
95
+ self.d = dimension
96
+
97
+ def forward(self, x):
98
+ return torch.cat(x, self.d)
99
+
100
+
101
+ class Flatten(nn.Module):
102
+ # Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions
103
+ @staticmethod
104
+ def forward(x):
105
+ return x.view(x.size(0), -1)
106
+
107
+
108
+ class Classify(nn.Module):
109
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
110
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
111
+ super(Classify, self).__init__()
112
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
113
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) # to x(b,c2,1,1)
114
+ self.flat = Flatten()
115
+
116
+ def forward(self, x):
117
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
118
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
models/experimental.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains experimental modules
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from models.common import Conv, DWConv
8
+ from utils.google_utils import attempt_download
9
+
10
+
11
+ class CrossConv(nn.Module):
12
+ # Cross Convolution Downsample
13
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
14
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
15
+ super(CrossConv, self).__init__()
16
+ c_ = int(c2 * e) # hidden channels
17
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
18
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
19
+ self.add = shortcut and c1 == c2
20
+
21
+ def forward(self, x):
22
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
23
+
24
+
25
+ class C3(nn.Module):
26
+ # Cross Convolution CSP
27
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
28
+ super(C3, self).__init__()
29
+ c_ = int(c2 * e) # hidden channels
30
+ self.cv1 = Conv(c1, c_, 1, 1)
31
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
32
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
33
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
34
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
35
+ self.act = nn.LeakyReLU(0.1, inplace=True)
36
+ self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
37
+
38
+ def forward(self, x):
39
+ y1 = self.cv3(self.m(self.cv1(x)))
40
+ y2 = self.cv2(x)
41
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
42
+
43
+
44
+ class Sum(nn.Module):
45
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
46
+ def __init__(self, n, weight=False): # n: number of inputs
47
+ super(Sum, self).__init__()
48
+ self.weight = weight # apply weights boolean
49
+ self.iter = range(n - 1) # iter object
50
+ if weight:
51
+ self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
52
+
53
+ def forward(self, x):
54
+ y = x[0] # no weight
55
+ if self.weight:
56
+ w = torch.sigmoid(self.w) * 2
57
+ for i in self.iter:
58
+ y = y + x[i + 1] * w[i]
59
+ else:
60
+ for i in self.iter:
61
+ y = y + x[i + 1]
62
+ return y
63
+
64
+
65
+ class GhostConv(nn.Module):
66
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
67
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
68
+ super(GhostConv, self).__init__()
69
+ c_ = c2 // 2 # hidden channels
70
+ self.cv1 = Conv(c1, c_, k, s, g, act)
71
+ self.cv2 = Conv(c_, c_, 5, 1, c_, act)
72
+
73
+ def forward(self, x):
74
+ y = self.cv1(x)
75
+ return torch.cat([y, self.cv2(y)], 1)
76
+
77
+
78
+ class GhostBottleneck(nn.Module):
79
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
80
+ def __init__(self, c1, c2, k, s):
81
+ super(GhostBottleneck, self).__init__()
82
+ c_ = c2 // 2
83
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
84
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
85
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
86
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
87
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
88
+
89
+ def forward(self, x):
90
+ return self.conv(x) + self.shortcut(x)
91
+
92
+
93
+ class MixConv2d(nn.Module):
94
+ # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
95
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
96
+ super(MixConv2d, self).__init__()
97
+ groups = len(k)
98
+ if equal_ch: # equal c_ per group
99
+ i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
100
+ c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
101
+ else: # equal weight.numel() per group
102
+ b = [c2] + [0] * groups
103
+ a = np.eye(groups + 1, groups, k=-1)
104
+ a -= np.roll(a, 1, axis=1)
105
+ a *= np.array(k) ** 2
106
+ a[0] = 1
107
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
108
+
109
+ self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
110
+ self.bn = nn.BatchNorm2d(c2)
111
+ self.act = nn.LeakyReLU(0.1, inplace=True)
112
+
113
+ def forward(self, x):
114
+ return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
115
+
116
+
117
+ class Ensemble(nn.ModuleList):
118
+ # Ensemble of models
119
+ def __init__(self):
120
+ super(Ensemble, self).__init__()
121
+
122
+ def forward(self, x, augment=False):
123
+ y = []
124
+ for module in self:
125
+ y.append(module(x, augment)[0])
126
+ # y = torch.stack(y).max(0)[0] # max ensemble
127
+ # y = torch.cat(y, 1) # nms ensemble
128
+ y = torch.stack(y).mean(0) # mean ensemble
129
+ return y, None # inference, train output
130
+
131
+
132
+ def attempt_load(weights, map_location=None):
133
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
134
+ model = Ensemble()
135
+ for w in weights if isinstance(weights, list) else [weights]:
136
+ attempt_download(w)
137
+ model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval()) # load FP32 model
138
+
139
+ if len(model) == 1:
140
+ return model[-1] # return model
141
+ else:
142
+ print('Ensemble created with %s\n' % weights)
143
+ for k in ['names', 'stride']:
144
+ setattr(model, k, getattr(model[-1], k))
145
+ return model # return ensemble
models/export.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
2
+
3
+ Usage:
4
+ $ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
5
+ """
6
+
7
+ import argparse
8
+
9
+ import torch
10
+
11
+ from utils.google_utils import attempt_download
12
+
13
+ if __name__ == '__main__':
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
16
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size')
17
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
18
+ opt = parser.parse_args()
19
+ opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
20
+ print(opt)
21
+
22
+ # Input
23
+ img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size(1,3,320,192) iDetection
24
+
25
+ # Load PyTorch model
26
+ attempt_download(opt.weights)
27
+ model = torch.load(opt.weights, map_location=torch.device('cpu'))['model'].float()
28
+ model.eval()
29
+ model.model[-1].export = True # set Detect() layer export=True
30
+ y = model(img) # dry run
31
+
32
+ # TorchScript export
33
+ try:
34
+ print('\nStarting TorchScript export with torch %s...' % torch.__version__)
35
+ f = opt.weights.replace('.pt', '.torchscript.pt') # filename
36
+ ts = torch.jit.trace(model, img)
37
+ ts.save(f)
38
+ print('TorchScript export success, saved as %s' % f)
39
+ except Exception as e:
40
+ print('TorchScript export failure: %s' % e)
41
+
42
+ # ONNX export
43
+ try:
44
+ import onnx
45
+
46
+ print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
47
+ f = opt.weights.replace('.pt', '.onnx') # filename
48
+ model.fuse() # only for ONNX
49
+ torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
50
+ output_names=['classes', 'boxes'] if y is None else ['output'])
51
+
52
+ # Checks
53
+ onnx_model = onnx.load(f) # load onnx model
54
+ onnx.checker.check_model(onnx_model) # check onnx model
55
+ print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
56
+ print('ONNX export success, saved as %s' % f)
57
+ except Exception as e:
58
+ print('ONNX export failure: %s' % e)
59
+
60
+ # CoreML export
61
+ try:
62
+ import coremltools as ct
63
+
64
+ print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
65
+ # convert model from torchscript and apply pixel scaling as per detect.py
66
+ model = ct.convert(ts, inputs=[ct.ImageType(name='images', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
67
+ f = opt.weights.replace('.pt', '.mlmodel') # filename
68
+ model.save(f)
69
+ print('CoreML export success, saved as %s' % f)
70
+ except Exception as e:
71
+ print('CoreML export failure: %s' % e)
72
+
73
+ # Finish
74
+ print('\nExport complete. Visualize with https://github.com/lutzroeder/netron.')
models/hub/yolov3-spp.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # darknet53 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Conv, [32, 3, 1]], # 0
16
+ [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17
+ [-1, 1, Bottleneck, [64]],
18
+ [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19
+ [-1, 2, Bottleneck, [128]],
20
+ [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21
+ [-1, 8, Bottleneck, [256]],
22
+ [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23
+ [-1, 8, Bottleneck, [512]],
24
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25
+ [-1, 4, Bottleneck, [1024]], # 10
26
+ ]
27
+
28
+ # YOLOv3-SPP head
29
+ head:
30
+ [[-1, 1, Bottleneck, [1024, False]],
31
+ [-1, 1, SPP, [512, [5, 9, 13]]],
32
+ [-1, 1, Conv, [1024, 3, 1]],
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35
+
36
+ [-2, 1, Conv, [256, 1, 1]],
37
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38
+ [[-1, 8], 1, Concat, [1]], # cat backbone P4
39
+ [-1, 1, Bottleneck, [512, False]],
40
+ [-1, 1, Bottleneck, [512, False]],
41
+ [-1, 1, Conv, [256, 1, 1]],
42
+ [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43
+
44
+ [-2, 1, Conv, [128, 1, 1]],
45
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46
+ [[-1, 6], 1, Concat, [1]], # cat backbone P3
47
+ [-1, 1, Bottleneck, [256, False]],
48
+ [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49
+
50
+ [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51
+ ]
models/hub/yolov5-fpn.yaml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, Bottleneck, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 6, BottleneckCSP, [1024]], # 9
25
+ ]
26
+
27
+ # YOLOv5 FPN head
28
+ head:
29
+ [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
30
+
31
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
33
+ [-1, 1, Conv, [512, 1, 1]],
34
+ [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
35
+
36
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
38
+ [-1, 1, Conv, [256, 1, 1]],
39
+ [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
40
+
41
+ [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42
+ ]
models/hub/yolov5-panet.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [116,90, 156,198, 373,326] # P5/32
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [10,13, 16,30, 33,23] # P3/8
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 PANet head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, BottleneckCSP, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3)
48
+ ]
models/yolo.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ from copy import deepcopy
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ from models.common import Conv, Bottleneck, SPP, DWConv, Focus, BottleneckCSP, Concat
10
+ from models.experimental import MixConv2d, CrossConv, C3
11
+ from utils.general import check_anchor_order, make_divisible, check_file
12
+ from utils.torch_utils import (
13
+ time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, select_device)
14
+
15
+
16
+ class Detect(nn.Module):
17
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
18
+ super(Detect, self).__init__()
19
+ self.stride = None # strides computed during build
20
+ self.nc = nc # number of classes
21
+ self.no = nc + 5 # number of outputs per anchor
22
+ self.nl = len(anchors) # number of detection layers
23
+ self.na = len(anchors[0]) // 2 # number of anchors
24
+ self.grid = [torch.zeros(1)] * self.nl # init grid
25
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
26
+ self.register_buffer('anchors', a) # shape(nl,na,2)
27
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
28
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
29
+ self.export = False # onnx export
30
+
31
+ def forward(self, x):
32
+ # x = x.copy() # for profiling
33
+ z = [] # inference output
34
+ self.training |= self.export
35
+ for i in range(self.nl):
36
+ x[i] = self.m[i](x[i]) # conv
37
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
38
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
39
+
40
+ if not self.training: # inference
41
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
42
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
43
+
44
+ y = x[i].sigmoid()
45
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
46
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
47
+ z.append(y.view(bs, -1, self.no))
48
+
49
+ return x if self.training else (torch.cat(z, 1), x)
50
+
51
+ @staticmethod
52
+ def _make_grid(nx=20, ny=20):
53
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
54
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
55
+
56
+
57
+ class Model(nn.Module):
58
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes
59
+ super(Model, self).__init__()
60
+ if isinstance(cfg, dict):
61
+ self.yaml = cfg # model dict
62
+ else: # is *.yaml
63
+ import yaml # for torch hub
64
+ self.yaml_file = Path(cfg).name
65
+ with open(cfg) as f:
66
+ self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
67
+
68
+ # Define model
69
+ if nc and nc != self.yaml['nc']:
70
+ print('Overriding %s nc=%g with nc=%g' % (cfg, self.yaml['nc'], nc))
71
+ self.yaml['nc'] = nc # override yaml value
72
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist, ch_out
73
+ # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
74
+
75
+ # Build strides, anchors
76
+ m = self.model[-1] # Detect()
77
+ if isinstance(m, Detect):
78
+ s = 128 # 2x min stride
79
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
80
+ m.anchors /= m.stride.view(-1, 1, 1)
81
+ check_anchor_order(m)
82
+ self.stride = m.stride
83
+ self._initialize_biases() # only run once
84
+ # print('Strides: %s' % m.stride.tolist())
85
+
86
+ # Init weights, biases
87
+ initialize_weights(self)
88
+ self.info()
89
+ print('')
90
+
91
+ def forward(self, x, augment=False, profile=False):
92
+ if augment:
93
+ img_size = x.shape[-2:] # height, width
94
+ s = [1, 0.83, 0.67] # scales
95
+ f = [None, 3, None] # flips (2-ud, 3-lr)
96
+ y = [] # outputs
97
+ for si, fi in zip(s, f):
98
+ xi = scale_img(x.flip(fi) if fi else x, si)
99
+ yi = self.forward_once(xi)[0] # forward
100
+ # cv2.imwrite('img%g.jpg' % s, 255 * xi[0].numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
101
+ yi[..., :4] /= si # de-scale
102
+ if fi == 2:
103
+ yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
104
+ elif fi == 3:
105
+ yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
106
+ y.append(yi)
107
+ return torch.cat(y, 1), None # augmented inference, train
108
+ else:
109
+ return self.forward_once(x, profile) # single-scale inference, train
110
+
111
+ def forward_once(self, x, profile=False):
112
+ y, dt = [], [] # outputs
113
+ for m in self.model:
114
+ if m.f != -1: # if not from previous layer
115
+ 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
116
+
117
+ if profile:
118
+ try:
119
+ import thop
120
+ o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS
121
+ except:
122
+ o = 0
123
+ t = time_synchronized()
124
+ for _ in range(10):
125
+ _ = m(x)
126
+ dt.append((time_synchronized() - t) * 100)
127
+ print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
128
+
129
+ x = m(x) # run
130
+ y.append(x if m.i in self.save else None) # save output
131
+
132
+ if profile:
133
+ print('%.1fms total' % sum(dt))
134
+ return x
135
+
136
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
137
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
138
+ m = self.model[-1] # Detect() module
139
+ for mi, s in zip(m.m, m.stride): # from
140
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
141
+ b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
142
+ b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
143
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
144
+
145
+ def _print_biases(self):
146
+ m = self.model[-1] # Detect() module
147
+ for mi in m.m: # from
148
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
149
+ print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
150
+
151
+ # def _print_weights(self):
152
+ # for m in self.model.modules():
153
+ # if type(m) is Bottleneck:
154
+ # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
155
+
156
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
157
+ print('Fusing layers... ', end='')
158
+ for m in self.model.modules():
159
+ if type(m) is Conv:
160
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatability
161
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
162
+ m.bn = None # remove batchnorm
163
+ m.forward = m.fuseforward # update forward
164
+ self.info()
165
+ return self
166
+
167
+ def info(self): # print model information
168
+ model_info(self)
169
+
170
+
171
+ def parse_model(d, ch): # model_dict, input_channels(3)
172
+ print('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
173
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
174
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
175
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
176
+
177
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
178
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
179
+ m = eval(m) if isinstance(m, str) else m # eval strings
180
+ for j, a in enumerate(args):
181
+ try:
182
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
183
+ except:
184
+ pass
185
+
186
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
187
+ if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:
188
+ c1, c2 = ch[f], args[0]
189
+
190
+ # Normal
191
+ # if i > 0 and args[0] != no: # channel expansion factor
192
+ # ex = 1.75 # exponential (default 2.0)
193
+ # e = math.log(c2 / ch[1]) / math.log(2)
194
+ # c2 = int(ch[1] * ex ** e)
195
+ # if m != Focus:
196
+
197
+ c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
198
+
199
+ # Experimental
200
+ # if i > 0 and args[0] != no: # channel expansion factor
201
+ # ex = 1 + gw # exponential (default 2.0)
202
+ # ch1 = 32 # ch[1]
203
+ # e = math.log(c2 / ch1) / math.log(2) # level 1-n
204
+ # c2 = int(ch1 * ex ** e)
205
+ # if m != Focus:
206
+ # c2 = make_divisible(c2, 8) if c2 != no else c2
207
+
208
+ args = [c1, c2, *args[1:]]
209
+ if m in [BottleneckCSP, C3]:
210
+ args.insert(2, n)
211
+ n = 1
212
+ elif m is nn.BatchNorm2d:
213
+ args = [ch[f]]
214
+ elif m is Concat:
215
+ c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])
216
+ elif m is Detect:
217
+ args.append([ch[x + 1] for x in f])
218
+ if isinstance(args[1], int): # number of anchors
219
+ args[1] = [list(range(args[1] * 2))] * len(f)
220
+ else:
221
+ c2 = ch[f]
222
+
223
+ m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
224
+ t = str(m)[8:-2].replace('__main__.', '') # module type
225
+ np = sum([x.numel() for x in m_.parameters()]) # number params
226
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
227
+ print('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
228
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
229
+ layers.append(m_)
230
+ ch.append(c2)
231
+ return nn.Sequential(*layers), sorted(save)
232
+
233
+
234
+ if __name__ == '__main__':
235
+ parser = argparse.ArgumentParser()
236
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
237
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
238
+ opt = parser.parse_args()
239
+ opt.cfg = check_file(opt.cfg) # check file
240
+ device = select_device(opt.device)
241
+
242
+ # Create model
243
+ model = Model(opt.cfg).to(device)
244
+ model.train()
245
+
246
+ # Profile
247
+ # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
248
+ # y = model(img, profile=True)
249
+
250
+ # ONNX export
251
+ # model.model[-1].export = True
252
+ # torch.onnx.export(model, img, opt.cfg.replace('.yaml', '.onnx'), verbose=True, opset_version=11)
253
+
254
+ # Tensorboard
255
+ # from torch.utils.tensorboard import SummaryWriter
256
+ # tb_writer = SummaryWriter()
257
+ # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
258
+ # tb_writer.add_graph(model.model, img) # add model to tensorboard
259
+ # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
models/yolov5l.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, BottleneckCSP, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5m.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.67 # model depth multiple
4
+ width_multiple: 0.75 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, BottleneckCSP, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5s.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 80 # number of classes
3
+ depth_multiple: 0.33 # model depth multiple
4
+ width_multiple: 0.50 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, BottleneckCSP, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
models/yolov5x.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 1 # number of classes
3
+ depth_multiple: 1.33 # model depth multiple
4
+ width_multiple: 1.25 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [10,13, 16,30, 33,23] # P3/8
9
+ - [30,61, 62,45, 59,119] # P4/16
10
+ - [116,90, 156,198, 373,326] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
16
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17
+ [-1, 3, BottleneckCSP, [128]],
18
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19
+ [-1, 9, BottleneckCSP, [256]],
20
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21
+ [-1, 9, BottleneckCSP, [512]],
22
+ [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23
+ [-1, 1, SPP, [1024, [5, 9, 13]]],
24
+ [-1, 3, BottleneckCSP, [1024, False]], # 9
25
+ ]
26
+
27
+ # YOLOv5 head
28
+ head:
29
+ [[-1, 1, Conv, [512, 1, 1]],
30
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
32
+ [-1, 3, BottleneckCSP, [512, False]], # 13
33
+
34
+ [-1, 1, Conv, [256, 1, 1]],
35
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
37
+ [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38
+
39
+ [-1, 1, Conv, [256, 3, 2]],
40
+ [[-1, 14], 1, Concat, [1]], # cat head P4
41
+ [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42
+
43
+ [-1, 1, Conv, [512, 3, 2]],
44
+ [[-1, 10], 1, Concat, [1]], # cat head P5
45
+ [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46
+
47
+ [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ matplotlib>=3.2.2
2
+ numpy>=1.18.5
3
+ opencv-python>=4.1.2
4
+ opencv-python-headless==4.9.0.80
5
+ pillow
6
+ PyYAML>=5.3
7
+ scipy>=1.4.1
8
+ torch>=1.6.0
9
+ torchvision>=0.7.0
10
+ tqdm>=4.41.0
utils/__init__.py ADDED
File without changes
utils/activations.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ # Swish https://arxiv.org/pdf/1905.02244.pdf ---------------------------------------------------------------------------
7
+ class Swish(nn.Module): #
8
+ @staticmethod
9
+ def forward(x):
10
+ return x * torch.sigmoid(x)
11
+
12
+
13
+ class HardSwish(nn.Module):
14
+ @staticmethod
15
+ def forward(x):
16
+ return x * F.hardtanh(x + 3, 0., 6., True) / 6.
17
+
18
+
19
+ class MemoryEfficientSwish(nn.Module):
20
+ class F(torch.autograd.Function):
21
+ @staticmethod
22
+ def forward(ctx, x):
23
+ ctx.save_for_backward(x)
24
+ return x * torch.sigmoid(x)
25
+
26
+ @staticmethod
27
+ def backward(ctx, grad_output):
28
+ x = ctx.saved_tensors[0]
29
+ sx = torch.sigmoid(x)
30
+ return grad_output * (sx * (1 + x * (1 - sx)))
31
+
32
+ def forward(self, x):
33
+ return self.F.apply(x)
34
+
35
+
36
+ # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
37
+ class Mish(nn.Module):
38
+ @staticmethod
39
+ def forward(x):
40
+ return x * F.softplus(x).tanh()
41
+
42
+
43
+ class MemoryEfficientMish(nn.Module):
44
+ class F(torch.autograd.Function):
45
+ @staticmethod
46
+ def forward(ctx, x):
47
+ ctx.save_for_backward(x)
48
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
49
+
50
+ @staticmethod
51
+ def backward(ctx, grad_output):
52
+ x = ctx.saved_tensors[0]
53
+ sx = torch.sigmoid(x)
54
+ fx = F.softplus(x).tanh()
55
+ return grad_output * (fx + x * sx * (1 - fx * fx))
56
+
57
+ def forward(self, x):
58
+ return self.F.apply(x)
59
+
60
+
61
+ # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
62
+ class FReLU(nn.Module):
63
+ def __init__(self, c1, k=3): # ch_in, kernel
64
+ super().__init__()
65
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1)
66
+ self.bn = nn.BatchNorm2d(c1)
67
+
68
+ def forward(self, x):
69
+ return torch.max(x, self.bn(self.conv(x)))
utils/datasets.py ADDED
@@ -0,0 +1,907 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import math
3
+ import os
4
+ import random
5
+ import shutil
6
+ import time
7
+ from pathlib import Path
8
+ from threading import Thread
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import torch
13
+ from PIL import Image, ExifTags
14
+ from torch.utils.data import Dataset
15
+ from tqdm import tqdm
16
+
17
+ from utils.general import xyxy2xywh, xywh2xyxy, torch_distributed_zero_first
18
+
19
+ help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
20
+ img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
21
+ vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv']
22
+
23
+ # Get orientation exif tag
24
+ for orientation in ExifTags.TAGS.keys():
25
+ if ExifTags.TAGS[orientation] == 'Orientation':
26
+ break
27
+
28
+
29
+ def get_hash(files):
30
+ # Returns a single hash value of a list of files
31
+ return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
32
+
33
+
34
+ def exif_size(img):
35
+ # Returns exif-corrected PIL size
36
+ s = img.size # (width, height)
37
+ try:
38
+ rotation = dict(img._getexif().items())[orientation]
39
+ if rotation == 6: # rotation 270
40
+ s = (s[1], s[0])
41
+ elif rotation == 8: # rotation 90
42
+ s = (s[1], s[0])
43
+ except:
44
+ pass
45
+
46
+ return s
47
+
48
+
49
+ def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
50
+ local_rank=-1, world_size=1):
51
+ # Make sure only the first process in DDP process the dataset first, and the following others can use the cache.
52
+ with torch_distributed_zero_first(local_rank):
53
+ dataset = LoadImagesAndLabels(path, imgsz, batch_size,
54
+ augment=augment, # augment images
55
+ hyp=hyp, # augmentation hyperparameters
56
+ rect=rect, # rectangular training
57
+ cache_images=cache,
58
+ single_cls=opt.single_cls,
59
+ stride=int(stride),
60
+ pad=pad)
61
+
62
+ batch_size = min(batch_size, len(dataset))
63
+ nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, 8]) # number of workers
64
+ train_sampler = torch.utils.data.distributed.DistributedSampler(dataset) if local_rank != -1 else None
65
+ dataloader = torch.utils.data.DataLoader(dataset,
66
+ batch_size=batch_size,
67
+ num_workers=nw,
68
+ sampler=train_sampler,
69
+ pin_memory=True,
70
+ collate_fn=LoadImagesAndLabels.collate_fn)
71
+ return dataloader, dataset
72
+
73
+
74
+ class LoadImages: # for inference
75
+ def __init__(self, path, img_size=640):
76
+ p = str(Path(path)) # os-agnostic
77
+ p = os.path.abspath(p) # absolute path
78
+ if '*' in p:
79
+ files = sorted(glob.glob(p)) # glob
80
+ elif os.path.isdir(p):
81
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
82
+ elif os.path.isfile(p):
83
+ files = [p] # files
84
+ else:
85
+ raise Exception('ERROR: %s does not exist' % p)
86
+
87
+ images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
88
+ videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats]
89
+ ni, nv = len(images), len(videos)
90
+
91
+ self.img_size = img_size
92
+ self.files = images + videos
93
+ self.nf = ni + nv # number of files
94
+ self.video_flag = [False] * ni + [True] * nv
95
+ self.mode = 'images'
96
+ if any(videos):
97
+ self.new_video(videos[0]) # new video
98
+ else:
99
+ self.cap = None
100
+ assert self.nf > 0, 'No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s' % \
101
+ (p, img_formats, vid_formats)
102
+
103
+ def __iter__(self):
104
+ self.count = 0
105
+ return self
106
+
107
+ def __next__(self):
108
+ if self.count == self.nf:
109
+ raise StopIteration
110
+ path = self.files[self.count]
111
+
112
+ if self.video_flag[self.count]:
113
+ # Read video
114
+ self.mode = 'video'
115
+ ret_val, img0 = self.cap.read()
116
+ if not ret_val:
117
+ self.count += 1
118
+ self.cap.release()
119
+ if self.count == self.nf: # last video
120
+ raise StopIteration
121
+ else:
122
+ path = self.files[self.count]
123
+ self.new_video(path)
124
+ ret_val, img0 = self.cap.read()
125
+
126
+ self.frame += 1
127
+ print('video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nf, self.frame, self.nframes, path), end='')
128
+
129
+ else:
130
+ # Read image
131
+ self.count += 1
132
+ img0 = cv2.imread(path) # BGR
133
+ assert img0 is not None, 'Image Not Found ' + path
134
+ print('image %g/%g %s: ' % (self.count, self.nf, path), end='')
135
+
136
+ # Padded resize
137
+ img = letterbox(img0, new_shape=self.img_size)[0]
138
+
139
+ # Convert
140
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
141
+ img = np.ascontiguousarray(img)
142
+
143
+ # cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image
144
+ return path, img, img0, self.cap
145
+
146
+ def new_video(self, path):
147
+ self.frame = 0
148
+ self.cap = cv2.VideoCapture(path)
149
+ self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
150
+
151
+ def __len__(self):
152
+ return self.nf # number of files
153
+
154
+
155
+ class LoadWebcam: # for inference
156
+ def __init__(self, pipe=0, img_size=640):
157
+ self.img_size = img_size
158
+
159
+ if pipe == '0':
160
+ pipe = 0 # local camera
161
+ # pipe = 'rtsp://192.168.1.64/1' # IP camera
162
+ # pipe = 'rtsp://username:[email protected]/1' # IP camera with login
163
+ # pipe = 'rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa' # IP traffic camera
164
+ # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
165
+
166
+ # https://answers.opencv.org/question/215996/changing-gstreamer-pipeline-to-opencv-in-pythonsolved/
167
+ # pipe = '"rtspsrc location="rtsp://username:[email protected]/1" latency=10 ! appsink' # GStreamer
168
+
169
+ # https://answers.opencv.org/question/200787/video-acceleration-gstremer-pipeline-in-videocapture/
170
+ # https://stackoverflow.com/questions/54095699/install-gstreamer-support-for-opencv-python-package # install help
171
+ # pipe = "rtspsrc location=rtsp://root:[email protected]:554/axis-media/media.amp?videocodec=h264&resolution=3840x2160 protocols=GST_RTSP_LOWER_TRANS_TCP ! rtph264depay ! queue ! vaapih264dec ! videoconvert ! appsink" # GStreamer
172
+
173
+ self.pipe = pipe
174
+ self.cap = cv2.VideoCapture(pipe) # video capture object
175
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
176
+
177
+ def __iter__(self):
178
+ self.count = -1
179
+ return self
180
+
181
+ def __next__(self):
182
+ self.count += 1
183
+ if cv2.waitKey(1) == ord('q'): # q to quit
184
+ self.cap.release()
185
+ cv2.destroyAllWindows()
186
+ raise StopIteration
187
+
188
+ # Read frame
189
+ if self.pipe == 0: # local camera
190
+ ret_val, img0 = self.cap.read()
191
+ img0 = cv2.flip(img0, 1) # flip left-right
192
+ else: # IP camera
193
+ n = 0
194
+ while True:
195
+ n += 1
196
+ self.cap.grab()
197
+ if n % 30 == 0: # skip frames
198
+ ret_val, img0 = self.cap.retrieve()
199
+ if ret_val:
200
+ break
201
+
202
+ # Print
203
+ assert ret_val, 'Camera Error %s' % self.pipe
204
+ img_path = 'webcam.jpg'
205
+ print('webcam %g: ' % self.count, end='')
206
+
207
+ # Padded resize
208
+ img = letterbox(img0, new_shape=self.img_size)[0]
209
+
210
+ # Convert
211
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
212
+ img = np.ascontiguousarray(img)
213
+
214
+ return img_path, img, img0, None
215
+
216
+ def __len__(self):
217
+ return 0
218
+
219
+
220
+ class LoadStreams: # multiple IP or RTSP cameras
221
+ def __init__(self, sources='streams.txt', img_size=640):
222
+ self.mode = 'images'
223
+ self.img_size = img_size
224
+
225
+ if os.path.isfile(sources):
226
+ with open(sources, 'r') as f:
227
+ sources = [x.strip() for x in f.read().splitlines() if len(x.strip())]
228
+ else:
229
+ sources = [sources]
230
+
231
+ n = len(sources)
232
+ self.imgs = [None] * n
233
+ self.sources = sources
234
+ for i, s in enumerate(sources):
235
+ # Start the thread to read frames from the video stream
236
+ print('%g/%g: %s... ' % (i + 1, n, s), end='')
237
+ cap = cv2.VideoCapture(0 if s == '0' else s)
238
+ assert cap.isOpened(), 'Failed to open %s' % s
239
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
240
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
241
+ fps = cap.get(cv2.CAP_PROP_FPS) % 100
242
+ _, self.imgs[i] = cap.read() # guarantee first frame
243
+ thread = Thread(target=self.update, args=([i, cap]), daemon=True)
244
+ print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
245
+ thread.start()
246
+ print('') # newline
247
+
248
+ # check for common shapes
249
+ s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0) # inference shapes
250
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
251
+ if not self.rect:
252
+ print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
253
+
254
+ def update(self, index, cap):
255
+ # Read next stream frame in a daemon thread
256
+ n = 0
257
+ while cap.isOpened():
258
+ n += 1
259
+ # _, self.imgs[index] = cap.read()
260
+ cap.grab()
261
+ if n == 4: # read every 4th frame
262
+ _, self.imgs[index] = cap.retrieve()
263
+ n = 0
264
+ time.sleep(0.01) # wait time
265
+
266
+ def __iter__(self):
267
+ self.count = -1
268
+ return self
269
+
270
+ def __next__(self):
271
+ self.count += 1
272
+ img0 = self.imgs.copy()
273
+ if cv2.waitKey(1) == ord('q'): # q to quit
274
+ cv2.destroyAllWindows()
275
+ raise StopIteration
276
+
277
+ # Letterbox
278
+ img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]
279
+
280
+ # Stack
281
+ img = np.stack(img, 0)
282
+
283
+ # Convert
284
+ img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
285
+ img = np.ascontiguousarray(img)
286
+
287
+ return self.sources, img, img0, None
288
+
289
+ def __len__(self):
290
+ return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
291
+
292
+
293
+ class LoadImagesAndLabels(Dataset): # for training/testing
294
+ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
295
+ cache_images=False, single_cls=False, stride=32, pad=0.0):
296
+ try:
297
+ f = [] # image files
298
+ for p in path if isinstance(path, list) else [path]:
299
+ p = str(Path(p)) # os-agnostic
300
+ parent = str(Path(p).parent) + os.sep
301
+ if os.path.isfile(p): # file
302
+ with open(p, 'r') as t:
303
+ t = t.read().splitlines()
304
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
305
+ elif os.path.isdir(p): # folder
306
+ f += glob.iglob(p + os.sep + '*.*')
307
+ else:
308
+ raise Exception('%s does not exist' % p)
309
+ self.img_files = sorted(
310
+ [x.replace('/', os.sep) for x in f if os.path.splitext(x)[-1].lower() in img_formats])
311
+ except Exception as e:
312
+ raise Exception('Error loading data from %s: %s\nSee %s' % (path, e, help_url))
313
+
314
+ n = len(self.img_files)
315
+ assert n > 0, 'No images found in %s. See %s' % (path, help_url)
316
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
317
+ nb = bi[-1] + 1 # number of batches
318
+
319
+ self.n = n # number of images
320
+ self.batch = bi # batch index of image
321
+ self.img_size = img_size
322
+ self.augment = augment
323
+ self.hyp = hyp
324
+ self.image_weights = image_weights
325
+ self.rect = False if image_weights else rect
326
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
327
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
328
+ self.stride = stride
329
+
330
+ # Define labels
331
+ self.label_files = [x.replace('images', 'labels').replace(os.path.splitext(x)[-1], '.txt') for x in
332
+ self.img_files]
333
+
334
+ # Check cache
335
+ cache_path = str(Path(self.label_files[0]).parent) + '.cache' # cached labels
336
+ if os.path.isfile(cache_path):
337
+ cache = torch.load(cache_path) # load
338
+ if cache['hash'] != get_hash(self.label_files + self.img_files): # dataset changed
339
+ cache = self.cache_labels(cache_path) # re-cache
340
+ else:
341
+ cache = self.cache_labels(cache_path) # cache
342
+
343
+ # Get labels
344
+ labels, shapes = zip(*[cache[x] for x in self.img_files])
345
+ self.shapes = np.array(shapes, dtype=np.float64)
346
+ self.labels = list(labels)
347
+
348
+ # Rectangular Training https://github.com/ultralytics/yolov3/issues/232
349
+ if self.rect:
350
+ # Sort by aspect ratio
351
+ s = self.shapes # wh
352
+ ar = s[:, 1] / s[:, 0] # aspect ratio
353
+ irect = ar.argsort()
354
+ self.img_files = [self.img_files[i] for i in irect]
355
+ self.label_files = [self.label_files[i] for i in irect]
356
+ self.labels = [self.labels[i] for i in irect]
357
+ self.shapes = s[irect] # wh
358
+ ar = ar[irect]
359
+
360
+ # Set training image shapes
361
+ shapes = [[1, 1]] * nb
362
+ for i in range(nb):
363
+ ari = ar[bi == i]
364
+ mini, maxi = ari.min(), ari.max()
365
+ if maxi < 1:
366
+ shapes[i] = [maxi, 1]
367
+ elif mini > 1:
368
+ shapes[i] = [1, 1 / mini]
369
+
370
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
371
+
372
+ # Cache labels
373
+ create_datasubset, extract_bounding_boxes, labels_loaded = False, False, False
374
+ nm, nf, ne, ns, nd = 0, 0, 0, 0, 0 # number missing, found, empty, datasubset, duplicate
375
+ pbar = tqdm(self.label_files)
376
+ for i, file in enumerate(pbar):
377
+ l = self.labels[i] # label
378
+ if l.shape[0]:
379
+ assert l.shape[1] == 5, '> 5 label columns: %s' % file
380
+ assert (l >= 0).all(), 'negative labels: %s' % file
381
+ assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file
382
+ if np.unique(l, axis=0).shape[0] < l.shape[0]: # duplicate rows
383
+ nd += 1 # print('WARNING: duplicate rows in %s' % self.label_files[i]) # duplicate rows
384
+ if single_cls:
385
+ l[:, 0] = 0 # force dataset into single-class mode
386
+ self.labels[i] = l
387
+ nf += 1 # file found
388
+
389
+ # Create subdataset (a smaller dataset)
390
+ if create_datasubset and ns < 1E4:
391
+ if ns == 0:
392
+ create_folder(path='./datasubset')
393
+ os.makedirs('./datasubset/images')
394
+ exclude_classes = 43
395
+ if exclude_classes not in l[:, 0]:
396
+ ns += 1
397
+ # shutil.copy(src=self.img_files[i], dst='./datasubset/images/') # copy image
398
+ with open('./datasubset/images.txt', 'a') as f:
399
+ f.write(self.img_files[i] + '\n')
400
+
401
+ # Extract object detection boxes for a second stage classifier
402
+ if extract_bounding_boxes:
403
+ p = Path(self.img_files[i])
404
+ img = cv2.imread(str(p))
405
+ h, w = img.shape[:2]
406
+ for j, x in enumerate(l):
407
+ f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name)
408
+ if not os.path.exists(Path(f).parent):
409
+ os.makedirs(Path(f).parent) # make new output folder
410
+
411
+ b = x[1:] * [w, h, w, h] # box
412
+ b[2:] = b[2:].max() # rectangle to square
413
+ b[2:] = b[2:] * 1.3 + 30 # pad
414
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
415
+
416
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
417
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
418
+ assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes'
419
+ else:
420
+ ne += 1 # print('empty labels for image %s' % self.img_files[i]) # file empty
421
+ # os.system("rm '%s' '%s'" % (self.img_files[i], self.label_files[i])) # remove
422
+
423
+ pbar.desc = 'Scanning labels %s (%g found, %g missing, %g empty, %g duplicate, for %g images)' % (
424
+ cache_path, nf, nm, ne, nd, n)
425
+ if nf == 0:
426
+ s = 'WARNING: No labels found in %s. See %s' % (os.path.dirname(file) + os.sep, help_url)
427
+ print(s)
428
+ assert not augment, '%s. Can not train without labels.' % s
429
+
430
+ # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
431
+ self.imgs = [None] * n
432
+ if cache_images:
433
+ gb = 0 # Gigabytes of cached images
434
+ pbar = tqdm(range(len(self.img_files)), desc='Caching images')
435
+ self.img_hw0, self.img_hw = [None] * n, [None] * n
436
+ for i in pbar: # max 10k images
437
+ self.imgs[i], self.img_hw0[i], self.img_hw[i] = load_image(self, i) # img, hw_original, hw_resized
438
+ gb += self.imgs[i].nbytes
439
+ pbar.desc = 'Caching images (%.1fGB)' % (gb / 1E9)
440
+
441
+ def cache_labels(self, path='labels.cache'):
442
+ # Cache dataset labels, check images and read shapes
443
+ x = {} # dict
444
+ pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
445
+ for (img, label) in pbar:
446
+ try:
447
+ l = []
448
+ image = Image.open(img)
449
+ image.verify() # PIL verify
450
+ # _ = io.imread(img) # skimage verify (from skimage import io)
451
+ shape = exif_size(image) # image size
452
+ assert (shape[0] > 9) & (shape[1] > 9), 'image size <10 pixels'
453
+ if os.path.isfile(label):
454
+ with open(label, 'r') as f:
455
+ l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32) # labels
456
+ if len(l) == 0:
457
+ l = np.zeros((0, 5), dtype=np.float32)
458
+ x[img] = [l, shape]
459
+ except Exception as e:
460
+ x[img] = [None, None]
461
+ print('WARNING: %s: %s' % (img, e))
462
+
463
+ x['hash'] = get_hash(self.label_files + self.img_files)
464
+ torch.save(x, path) # save for next time
465
+ return x
466
+
467
+ def __len__(self):
468
+ return len(self.img_files)
469
+
470
+ # def __iter__(self):
471
+ # self.count = -1
472
+ # print('ran dataset iter')
473
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
474
+ # return self
475
+
476
+ def __getitem__(self, index):
477
+ if self.image_weights:
478
+ index = self.indices[index]
479
+
480
+ hyp = self.hyp
481
+ if self.mosaic:
482
+ # Load mosaic
483
+ img, labels = load_mosaic(self, index)
484
+ shapes = None
485
+
486
+ # MixUp https://arxiv.org/pdf/1710.09412.pdf
487
+ if random.random() < hyp['mixup']:
488
+ img2, labels2 = load_mosaic(self, random.randint(0, len(self.labels) - 1))
489
+ r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
490
+ img = (img * r + img2 * (1 - r)).astype(np.uint8)
491
+ labels = np.concatenate((labels, labels2), 0)
492
+
493
+ else:
494
+ # Load image
495
+ img, (h0, w0), (h, w) = load_image(self, index)
496
+
497
+ # Letterbox
498
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
499
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
500
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
501
+
502
+ # Load labels
503
+ labels = []
504
+ x = self.labels[index]
505
+ if x.size > 0:
506
+ # Normalized xywh to pixel xyxy format
507
+ labels = x.copy()
508
+ labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0] # pad width
509
+ labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1] # pad height
510
+ labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0]
511
+ labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1]
512
+
513
+ if self.augment:
514
+ # Augment imagespace
515
+ if not self.mosaic:
516
+ img, labels = random_perspective(img, labels,
517
+ degrees=hyp['degrees'],
518
+ translate=hyp['translate'],
519
+ scale=hyp['scale'],
520
+ shear=hyp['shear'],
521
+ perspective=hyp['perspective'])
522
+
523
+ # Augment colorspace
524
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
525
+
526
+ # Apply cutouts
527
+ # if random.random() < 0.9:
528
+ # labels = cutout(img, labels)
529
+
530
+ nL = len(labels) # number of labels
531
+ if nL:
532
+ labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
533
+ labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
534
+ labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
535
+
536
+ if self.augment:
537
+ # flip up-down
538
+ if random.random() < hyp['flipud']:
539
+ img = np.flipud(img)
540
+ if nL:
541
+ labels[:, 2] = 1 - labels[:, 2]
542
+
543
+ # flip left-right
544
+ if random.random() < hyp['fliplr']:
545
+ img = np.fliplr(img)
546
+ if nL:
547
+ labels[:, 1] = 1 - labels[:, 1]
548
+
549
+ labels_out = torch.zeros((nL, 6))
550
+ if nL:
551
+ labels_out[:, 1:] = torch.from_numpy(labels)
552
+
553
+ # Convert
554
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
555
+ img = np.ascontiguousarray(img)
556
+
557
+ return torch.from_numpy(img), labels_out, self.img_files[index], shapes
558
+
559
+ @staticmethod
560
+ def collate_fn(batch):
561
+ img, label, path, shapes = zip(*batch) # transposed
562
+ for i, l in enumerate(label):
563
+ l[:, 0] = i # add target image index for build_targets()
564
+ return torch.stack(img, 0), torch.cat(label, 0), path, shapes
565
+
566
+
567
+ # Ancillary functions --------------------------------------------------------------------------------------------------
568
+ def load_image(self, index):
569
+ # loads 1 image from dataset, returns img, original hw, resized hw
570
+ img = self.imgs[index]
571
+ if img is None: # not cached
572
+ path = self.img_files[index]
573
+ img = cv2.imread(path) # BGR
574
+ assert img is not None, 'Image Not Found ' + path
575
+ h0, w0 = img.shape[:2] # orig hw
576
+ r = self.img_size / max(h0, w0) # resize image to img_size
577
+ if r != 1: # always resize down, only resize up if training with augmentation
578
+ interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
579
+ img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
580
+ return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
581
+ else:
582
+ return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
583
+
584
+
585
+ def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
586
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
587
+ hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
588
+ dtype = img.dtype # uint8
589
+
590
+ x = np.arange(0, 256, dtype=np.int16)
591
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
592
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
593
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
594
+
595
+ img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
596
+ cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
597
+
598
+ # Histogram equalization
599
+ # if random.random() < 0.2:
600
+ # for i in range(3):
601
+ # img[:, :, i] = cv2.equalizeHist(img[:, :, i])
602
+
603
+
604
+ def load_mosaic(self, index):
605
+ # loads images in a mosaic
606
+
607
+ labels4 = []
608
+ s = self.img_size
609
+ yc, xc = s, s # mosaic center x, y
610
+ indices = [index] + [random.randint(0, len(self.labels) - 1) for _ in range(3)] # 3 additional image indices
611
+ for i, index in enumerate(indices):
612
+ # Load image
613
+ img, _, (h, w) = load_image(self, index)
614
+
615
+ # place img in img4
616
+ if i == 0: # top left
617
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
618
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
619
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
620
+ elif i == 1: # top right
621
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
622
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
623
+ elif i == 2: # bottom left
624
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
625
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, max(xc, w), min(y2a - y1a, h)
626
+ elif i == 3: # bottom right
627
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
628
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
629
+
630
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
631
+ padw = x1a - x1b
632
+ padh = y1a - y1b
633
+
634
+ # Labels
635
+ x = self.labels[index]
636
+ labels = x.copy()
637
+ if x.size > 0: # Normalized xywh to pixel xyxy format
638
+ labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw
639
+ labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh
640
+ labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw
641
+ labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh
642
+ labels4.append(labels)
643
+
644
+ # Concat/clip labels
645
+ if len(labels4):
646
+ labels4 = np.concatenate(labels4, 0)
647
+ # np.clip(labels4[:, 1:] - s / 2, 0, s, out=labels4[:, 1:]) # use with center crop
648
+ np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:]) # use with random_affine
649
+
650
+ # Replicate
651
+ # img4, labels4 = replicate(img4, labels4)
652
+
653
+ # Augment
654
+ # img4 = img4[s // 2: int(s * 1.5), s // 2:int(s * 1.5)] # center crop (WARNING, requires box pruning)
655
+ img4, labels4 = random_perspective(img4, labels4,
656
+ degrees=self.hyp['degrees'],
657
+ translate=self.hyp['translate'],
658
+ scale=self.hyp['scale'],
659
+ shear=self.hyp['shear'],
660
+ perspective=self.hyp['perspective'],
661
+ border=self.mosaic_border) # border to remove
662
+
663
+ return img4, labels4
664
+
665
+
666
+ def replicate(img, labels):
667
+ # Replicate labels
668
+ h, w = img.shape[:2]
669
+ boxes = labels[:, 1:].astype(int)
670
+ x1, y1, x2, y2 = boxes.T
671
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
672
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
673
+ x1b, y1b, x2b, y2b = boxes[i]
674
+ bh, bw = y2b - y1b, x2b - x1b
675
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
676
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
677
+ img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
678
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
679
+
680
+ return img, labels
681
+
682
+
683
+ def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
684
+ # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
685
+ shape = img.shape[:2] # current shape [height, width]
686
+ if isinstance(new_shape, int):
687
+ new_shape = (new_shape, new_shape)
688
+
689
+ # Scale ratio (new / old)
690
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
691
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
692
+ r = min(r, 1.0)
693
+
694
+ # Compute padding
695
+ ratio = r, r # width, height ratios
696
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
697
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
698
+ if auto: # minimum rectangle
699
+ dw, dh = np.mod(dw, 64), np.mod(dh, 64) # wh padding
700
+ elif scaleFill: # stretch
701
+ dw, dh = 0.0, 0.0
702
+ new_unpad = (new_shape[1], new_shape[0])
703
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
704
+
705
+ dw /= 2 # divide padding into 2 sides
706
+ dh /= 2
707
+
708
+ if shape[::-1] != new_unpad: # resize
709
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
710
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
711
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
712
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
713
+ return img, ratio, (dw, dh)
714
+
715
+
716
+ def random_perspective(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)):
717
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
718
+ # targets = [cls, xyxy]
719
+
720
+ height = img.shape[0] + border[0] * 2 # shape(h,w,c)
721
+ width = img.shape[1] + border[1] * 2
722
+
723
+ # Center
724
+ C = np.eye(3)
725
+ C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
726
+ C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
727
+
728
+ # Perspective
729
+ P = np.eye(3)
730
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
731
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
732
+
733
+ # Rotation and Scale
734
+ R = np.eye(3)
735
+ a = random.uniform(-degrees, degrees)
736
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
737
+ s = random.uniform(1 - scale, 1 + scale)
738
+ # s = 2 ** random.uniform(-scale, scale)
739
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
740
+
741
+ # Shear
742
+ S = np.eye(3)
743
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
744
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
745
+
746
+ # Translation
747
+ T = np.eye(3)
748
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
749
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
750
+
751
+ # Combined rotation matrix
752
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
753
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
754
+ if perspective:
755
+ img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
756
+ else: # affine
757
+ img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
758
+
759
+ # Visualize
760
+ # import matplotlib.pyplot as plt
761
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
762
+ # ax[0].imshow(img[:, :, ::-1]) # base
763
+ # ax[1].imshow(img2[:, :, ::-1]) # warped
764
+
765
+ # Transform label coordinates
766
+ n = len(targets)
767
+ if n:
768
+ # warp points
769
+ xy = np.ones((n * 4, 3))
770
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
771
+ xy = xy @ M.T # transform
772
+ if perspective:
773
+ xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8) # rescale
774
+ else: # affine
775
+ xy = xy[:, :2].reshape(n, 8)
776
+
777
+ # create new boxes
778
+ x = xy[:, [0, 2, 4, 6]]
779
+ y = xy[:, [1, 3, 5, 7]]
780
+ xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
781
+
782
+ # # apply angle-based reduction of bounding boxes
783
+ # radians = a * math.pi / 180
784
+ # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5
785
+ # x = (xy[:, 2] + xy[:, 0]) / 2
786
+ # y = (xy[:, 3] + xy[:, 1]) / 2
787
+ # w = (xy[:, 2] - xy[:, 0]) * reduction
788
+ # h = (xy[:, 3] - xy[:, 1]) * reduction
789
+ # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T
790
+
791
+ # clip boxes
792
+ xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)
793
+ xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)
794
+
795
+ # filter candidates
796
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=xy.T)
797
+ targets = targets[i]
798
+ targets[:, 1:5] = xy[i]
799
+
800
+ return img, targets
801
+
802
+
803
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.2): # box1(4,n), box2(4,n)
804
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
805
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
806
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
807
+ ar = np.maximum(w2 / (h2 + 1e-16), h2 / (w2 + 1e-16)) # aspect ratio
808
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + 1e-16) > area_thr) & (ar < ar_thr) # candidates
809
+
810
+
811
+ def cutout(image, labels):
812
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
813
+ h, w = image.shape[:2]
814
+
815
+ def bbox_ioa(box1, box2):
816
+ # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
817
+ box2 = box2.transpose()
818
+
819
+ # Get the coordinates of bounding boxes
820
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
821
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
822
+
823
+ # Intersection area
824
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
825
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
826
+
827
+ # box2 area
828
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
829
+
830
+ # Intersection over box2 area
831
+ return inter_area / box2_area
832
+
833
+ # create random masks
834
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
835
+ for s in scales:
836
+ mask_h = random.randint(1, int(h * s))
837
+ mask_w = random.randint(1, int(w * s))
838
+
839
+ # box
840
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
841
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
842
+ xmax = min(w, xmin + mask_w)
843
+ ymax = min(h, ymin + mask_h)
844
+
845
+ # apply random color mask
846
+ image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
847
+
848
+ # return unobscured labels
849
+ if len(labels) and s > 0.03:
850
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
851
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
852
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
853
+
854
+ return labels
855
+
856
+
857
+ def reduce_img_size(path='path/images', img_size=1024): # from utils.datasets import *; reduce_img_size()
858
+ # creates a new ./images_reduced folder with reduced size images of maximum size img_size
859
+ path_new = path + '_reduced' # reduced images path
860
+ create_folder(path_new)
861
+ for f in tqdm(glob.glob('%s/*.*' % path)):
862
+ try:
863
+ img = cv2.imread(f)
864
+ h, w = img.shape[:2]
865
+ r = img_size / max(h, w) # size ratio
866
+ if r < 1.0:
867
+ img = cv2.resize(img, (int(w * r), int(h * r)), interpolation=cv2.INTER_AREA) # _LINEAR fastest
868
+ fnew = f.replace(path, path_new) # .replace(Path(f).suffix, '.jpg')
869
+ cv2.imwrite(fnew, img)
870
+ except:
871
+ print('WARNING: image failure %s' % f)
872
+
873
+
874
+ def recursive_dataset2bmp(dataset='path/dataset_bmp'): # from utils.datasets import *; recursive_dataset2bmp()
875
+ # Converts dataset to bmp (for faster training)
876
+ formats = [x.lower() for x in img_formats] + [x.upper() for x in img_formats]
877
+ for a, b, files in os.walk(dataset):
878
+ for file in tqdm(files, desc=a):
879
+ p = a + '/' + file
880
+ s = Path(file).suffix
881
+ if s == '.txt': # replace text
882
+ with open(p, 'r') as f:
883
+ lines = f.read()
884
+ for f in formats:
885
+ lines = lines.replace(f, '.bmp')
886
+ with open(p, 'w') as f:
887
+ f.write(lines)
888
+ elif s in formats: # replace image
889
+ cv2.imwrite(p.replace(s, '.bmp'), cv2.imread(p))
890
+ if s != '.bmp':
891
+ os.system("rm '%s'" % p)
892
+
893
+
894
+ def imagelist2folder(path='path/images.txt'): # from utils.datasets import *; imagelist2folder()
895
+ # Copies all the images in a text file (list of images) into a folder
896
+ create_folder(path[:-4])
897
+ with open(path, 'r') as f:
898
+ for line in f.read().splitlines():
899
+ os.system('cp "%s" %s' % (line, path[:-4]))
900
+ print(line)
901
+
902
+
903
+ def create_folder(path='./new'):
904
+ # Create folder
905
+ if os.path.exists(path):
906
+ shutil.rmtree(path) # delete output folder
907
+ os.makedirs(path) # make new output folder
utils/general.py ADDED
@@ -0,0 +1,1263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import math
3
+ import os
4
+ import random
5
+ import shutil
6
+ import subprocess
7
+ import time
8
+ from contextlib import contextmanager
9
+ from copy import copy
10
+ from pathlib import Path
11
+ from sys import platform
12
+
13
+ import cv2
14
+ import matplotlib
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn as nn
19
+ import torchvision
20
+ import yaml
21
+ from scipy.cluster.vq import kmeans
22
+ from scipy.signal import butter, filtfilt
23
+ from tqdm import tqdm
24
+
25
+ from utils.torch_utils import init_seeds, is_parallel
26
+
27
+ # Set printoptions
28
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
29
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
30
+ matplotlib.rc('font', **{'size': 11})
31
+
32
+ # Prevent OpenCV from multithreading (to use PyTorch DataLoader)
33
+ cv2.setNumThreads(0)
34
+
35
+
36
+ @contextmanager
37
+ def torch_distributed_zero_first(local_rank: int):
38
+ """
39
+ Decorator to make all processes in distributed training wait for each local_master to do something.
40
+ """
41
+ if local_rank not in [-1, 0]:
42
+ torch.distributed.barrier()
43
+ yield
44
+ if local_rank == 0:
45
+ torch.distributed.barrier()
46
+
47
+
48
+ def init_seeds(seed=0):
49
+ random.seed(seed)
50
+ np.random.seed(seed)
51
+ init_seeds(seed=seed)
52
+
53
+
54
+ def get_latest_run(search_dir='./runs'):
55
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
56
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
57
+ return max(last_list, key=os.path.getctime)
58
+
59
+
60
+ def check_git_status():
61
+ # Suggest 'git pull' if repo is out of date
62
+ if platform in ['linux', 'darwin'] and not os.path.isfile('/.dockerenv'):
63
+ s = subprocess.check_output('if [ -d .git ]; then git fetch && git status -uno; fi', shell=True).decode('utf-8')
64
+ if 'Your branch is behind' in s:
65
+ print(s[s.find('Your branch is behind'):s.find('\n\n')] + '\n')
66
+
67
+
68
+ def check_img_size(img_size, s=32):
69
+ # Verify img_size is a multiple of stride s
70
+ new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
71
+ if new_size != img_size:
72
+ print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))
73
+ return new_size
74
+
75
+
76
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
77
+ # Check anchor fit to data, recompute if necessary
78
+ print('\nAnalyzing anchors... ', end='')
79
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
80
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
81
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
82
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
83
+
84
+ def metric(k): # compute metric
85
+ r = wh[:, None] / k[None]
86
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
87
+ best = x.max(1)[0] # best_x
88
+ aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
89
+ bpr = (best > 1. / thr).float().mean() # best possible recall
90
+ return bpr, aat
91
+
92
+ bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))
93
+ print('anchors/target = %.2f, Best Possible Recall (BPR) = %.4f' % (aat, bpr), end='')
94
+ if bpr < 0.98: # threshold to recompute
95
+ print('. Attempting to generate improved anchors, please wait...' % bpr)
96
+ na = m.anchor_grid.numel() // 2 # number of anchors
97
+ new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
98
+ new_bpr = metric(new_anchors.reshape(-1, 2))[0]
99
+ if new_bpr > bpr: # replace anchors
100
+ new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors)
101
+ m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference
102
+ m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
103
+ check_anchor_order(m)
104
+ print('New anchors saved to model. Update model *.yaml to use these anchors in the future.')
105
+ else:
106
+ print('Original anchors better than new anchors. Proceeding with original anchors.')
107
+ print('') # newline
108
+
109
+
110
+ def check_anchor_order(m):
111
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
112
+ a = m.anchor_grid.prod(-1).view(-1) # anchor area
113
+ da = a[-1] - a[0] # delta a
114
+ ds = m.stride[-1] - m.stride[0] # delta s
115
+ if da.sign() != ds.sign(): # same order
116
+ print('Reversing anchor order')
117
+ m.anchors[:] = m.anchors.flip(0)
118
+ m.anchor_grid[:] = m.anchor_grid.flip(0)
119
+
120
+
121
+ def check_file(file):
122
+ # Searches for file if not found locally
123
+ if os.path.isfile(file) or file == '':
124
+ return file
125
+ else:
126
+ files = glob.glob('./**/' + file, recursive=True) # find file
127
+ assert len(files), 'File Not Found: %s' % file # assert file was found
128
+ return files[0] # return first file if multiple found
129
+
130
+
131
+ def check_dataset(dict):
132
+ # Download dataset if not found
133
+ train, val = os.path.abspath(dict['train']), os.path.abspath(dict['val']) # data paths
134
+ if not (os.path.exists(train) and os.path.exists(val)):
135
+ print('\nWARNING: Dataset not found, nonexistant paths: %s' % [train, val])
136
+ if 'download' in dict:
137
+ s = dict['download']
138
+ print('Attempting autodownload from: %s' % s)
139
+ if s.startswith('http') and s.endswith('.zip'): # URL
140
+ f = Path(s).name # filename
141
+ torch.hub.download_url_to_file(s, f)
142
+ r = os.system('unzip -q %s -d ../ && rm %s' % (f, f))
143
+ else: # bash script
144
+ r = os.system(s)
145
+ print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value
146
+ else:
147
+ Exception('Dataset autodownload unavailable.')
148
+
149
+
150
+ def make_divisible(x, divisor):
151
+ # Returns x evenly divisble by divisor
152
+ return math.ceil(x / divisor) * divisor
153
+
154
+
155
+ def labels_to_class_weights(labels, nc=80):
156
+ # Get class weights (inverse frequency) from training labels
157
+ if labels[0] is None: # no labels loaded
158
+ return torch.Tensor()
159
+
160
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
161
+ classes = labels[:, 0].astype(np.int) # labels = [class xywh]
162
+ weights = np.bincount(classes, minlength=nc) # occurences per class
163
+
164
+ # Prepend gridpoint count (for uCE trianing)
165
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
166
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
167
+
168
+ weights[weights == 0] = 1 # replace empty bins with 1
169
+ weights = 1 / weights # number of targets per class
170
+ weights /= weights.sum() # normalize
171
+ return torch.from_numpy(weights)
172
+
173
+
174
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
175
+ # Produces image weights based on class mAPs
176
+ n = len(labels)
177
+ class_counts = np.array([np.bincount(labels[i][:, 0].astype(np.int), minlength=nc) for i in range(n)])
178
+ image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
179
+ # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
180
+ return image_weights
181
+
182
+
183
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
184
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
185
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
186
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
187
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
188
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
189
+ x = [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,
190
+ 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,
191
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
192
+ return x
193
+
194
+
195
+ def xyxy2xywh(x):
196
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
197
+ y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
198
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
199
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
200
+ y[:, 2] = x[:, 2] - x[:, 0] # width
201
+ y[:, 3] = x[:, 3] - x[:, 1] # height
202
+ return y
203
+
204
+
205
+ def xywh2xyxy(x):
206
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
207
+ y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
208
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
209
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
210
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
211
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
212
+ return y
213
+
214
+
215
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
216
+ # Rescale coords (xyxy) from img1_shape to img0_shape
217
+ if ratio_pad is None: # calculate from img0_shape
218
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
219
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
220
+ else:
221
+ gain = ratio_pad[0][0]
222
+ pad = ratio_pad[1]
223
+
224
+ coords[:, [0, 2]] -= pad[0] # x padding
225
+ coords[:, [1, 3]] -= pad[1] # y padding
226
+ coords[:, :4] /= gain
227
+ clip_coords(coords, img0_shape)
228
+ return coords
229
+
230
+
231
+ def clip_coords(boxes, img_shape):
232
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
233
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
234
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
235
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
236
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
237
+
238
+
239
+ def ap_per_class(tp, conf, pred_cls, target_cls):
240
+ """ Compute the average precision, given the recall and precision curves.
241
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
242
+ # Arguments
243
+ tp: True positives (nparray, nx1 or nx10).
244
+ conf: Objectness value from 0-1 (nparray).
245
+ pred_cls: Predicted object classes (nparray).
246
+ target_cls: True object classes (nparray).
247
+ # Returns
248
+ The average precision as computed in py-faster-rcnn.
249
+ """
250
+
251
+ # Sort by objectness
252
+ i = np.argsort(-conf)
253
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
254
+
255
+ # Find unique classes
256
+ unique_classes = np.unique(target_cls)
257
+
258
+ # Create Precision-Recall curve and compute AP for each class
259
+ pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898
260
+ s = [unique_classes.shape[0], tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)
261
+ ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)
262
+ for ci, c in enumerate(unique_classes):
263
+ i = pred_cls == c
264
+ n_gt = (target_cls == c).sum() # Number of ground truth objects
265
+ n_p = i.sum() # Number of predicted objects
266
+
267
+ if n_p == 0 or n_gt == 0:
268
+ continue
269
+ else:
270
+ # Accumulate FPs and TPs
271
+ fpc = (1 - tp[i]).cumsum(0)
272
+ tpc = tp[i].cumsum(0)
273
+
274
+ # Recall
275
+ recall = tpc / (n_gt + 1e-16) # recall curve
276
+ r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases
277
+
278
+ # Precision
279
+ precision = tpc / (tpc + fpc) # precision curve
280
+ p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score
281
+
282
+ # AP from recall-precision curve
283
+ for j in range(tp.shape[1]):
284
+ ap[ci, j] = compute_ap(recall[:, j], precision[:, j])
285
+
286
+ # Plot
287
+ # fig, ax = plt.subplots(1, 1, figsize=(5, 5))
288
+ # ax.plot(recall, precision)
289
+ # ax.set_xlabel('Recall')
290
+ # ax.set_ylabel('Precision')
291
+ # ax.set_xlim(0, 1.01)
292
+ # ax.set_ylim(0, 1.01)
293
+ # fig.tight_layout()
294
+ # fig.savefig('PR_curve.png', dpi=300)
295
+
296
+ # Compute F1 score (harmonic mean of precision and recall)
297
+ f1 = 2 * p * r / (p + r + 1e-16)
298
+
299
+ return p, r, ap, f1, unique_classes.astype('int32')
300
+
301
+
302
+ def compute_ap(recall, precision):
303
+ """ Compute the average precision, given the recall and precision curves.
304
+ Source: https://github.com/rbgirshick/py-faster-rcnn.
305
+ # Arguments
306
+ recall: The recall curve (list).
307
+ precision: The precision curve (list).
308
+ # Returns
309
+ The average precision as computed in py-faster-rcnn.
310
+ """
311
+
312
+ # Append sentinel values to beginning and end
313
+ mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)]))
314
+ mpre = np.concatenate(([0.], precision, [0.]))
315
+
316
+ # Compute the precision envelope
317
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
318
+
319
+ # Integrate area under curve
320
+ method = 'interp' # methods: 'continuous', 'interp'
321
+ if method == 'interp':
322
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
323
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
324
+ else: # 'continuous'
325
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
326
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
327
+
328
+ return ap
329
+
330
+
331
+ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False):
332
+ # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
333
+ box2 = box2.T
334
+
335
+ # Get the coordinates of bounding boxes
336
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
337
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
338
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
339
+ else: # transform from xywh to xyxy
340
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
341
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
342
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
343
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
344
+
345
+ # Intersection area
346
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
347
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
348
+
349
+ # Union Area
350
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
351
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
352
+ union = (w1 * h1 + 1e-16) + w2 * h2 - inter
353
+
354
+ iou = inter / union # iou
355
+ if GIoU or DIoU or CIoU:
356
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
357
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
358
+ if GIoU: # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
359
+ c_area = cw * ch + 1e-16 # convex area
360
+ return iou - (c_area - union) / c_area # GIoU
361
+ if DIoU or CIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
362
+ # convex diagonal squared
363
+ c2 = cw ** 2 + ch ** 2 + 1e-16
364
+ # centerpoint distance squared
365
+ rho2 = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2)) ** 2 / 4 + ((b2_y1 + b2_y2) - (b1_y1 + b1_y2)) ** 2 / 4
366
+ if DIoU:
367
+ return iou - rho2 / c2 # DIoU
368
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
369
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
370
+ with torch.no_grad():
371
+ alpha = v / (1 - iou + v + 1e-16)
372
+ return iou - (rho2 / c2 + v * alpha) # CIoU
373
+
374
+ return iou
375
+
376
+
377
+ def box_iou(box1, box2):
378
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
379
+ """
380
+ Return intersection-over-union (Jaccard index) of boxes.
381
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
382
+ Arguments:
383
+ box1 (Tensor[N, 4])
384
+ box2 (Tensor[M, 4])
385
+ Returns:
386
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
387
+ IoU values for every element in boxes1 and boxes2
388
+ """
389
+
390
+ def box_area(box):
391
+ # box = 4xn
392
+ return (box[2] - box[0]) * (box[3] - box[1])
393
+
394
+ area1 = box_area(box1.T)
395
+ area2 = box_area(box2.T)
396
+
397
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
398
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
399
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
400
+
401
+
402
+ def wh_iou(wh1, wh2):
403
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
404
+ wh1 = wh1[:, None] # [N,1,2]
405
+ wh2 = wh2[None] # [1,M,2]
406
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
407
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
408
+
409
+
410
+ class FocalLoss(nn.Module):
411
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
412
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
413
+ super(FocalLoss, self).__init__()
414
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
415
+ self.gamma = gamma
416
+ self.alpha = alpha
417
+ self.reduction = loss_fcn.reduction
418
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
419
+
420
+ def forward(self, pred, true):
421
+ loss = self.loss_fcn(pred, true)
422
+ # p_t = torch.exp(-loss)
423
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
424
+
425
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
426
+ pred_prob = torch.sigmoid(pred) # prob from logits
427
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
428
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
429
+ modulating_factor = (1.0 - p_t) ** self.gamma
430
+ loss *= alpha_factor * modulating_factor
431
+
432
+ if self.reduction == 'mean':
433
+ return loss.mean()
434
+ elif self.reduction == 'sum':
435
+ return loss.sum()
436
+ else: # 'none'
437
+ return loss
438
+
439
+
440
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
441
+ # return positive, negative label smoothing BCE targets
442
+ return 1.0 - 0.5 * eps, 0.5 * eps
443
+
444
+
445
+ class BCEBlurWithLogitsLoss(nn.Module):
446
+ # BCEwithLogitLoss() with reduced missing label effects.
447
+ def __init__(self, alpha=0.05):
448
+ super(BCEBlurWithLogitsLoss, self).__init__()
449
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
450
+ self.alpha = alpha
451
+
452
+ def forward(self, pred, true):
453
+ loss = self.loss_fcn(pred, true)
454
+ pred = torch.sigmoid(pred) # prob from logits
455
+ dx = pred - true # reduce only missing label effects
456
+ # dx = (pred - true).abs() # reduce missing label and false label effects
457
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
458
+ loss *= alpha_factor
459
+ return loss.mean()
460
+
461
+
462
+ def compute_loss(p, targets, model): # predictions, targets, model
463
+ device = targets.device
464
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
465
+ tcls, tbox, indices, anchors = build_targets(p, targets, model) # targets
466
+ h = model.hyp # hyperparameters
467
+
468
+ # Define criteria
469
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['cls_pw']])).to(device)
470
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['obj_pw']])).to(device)
471
+
472
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
473
+ cp, cn = smooth_BCE(eps=0.0)
474
+
475
+ # Focal loss
476
+ g = h['fl_gamma'] # focal loss gamma
477
+ if g > 0:
478
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
479
+
480
+ # Losses
481
+ nt = 0 # number of targets
482
+ np = len(p) # number of outputs
483
+ balance = [4.0, 1.0, 0.4] if np == 3 else [4.0, 1.0, 0.4, 0.1] # P3-5 or P3-6
484
+ for i, pi in enumerate(p): # layer index, layer predictions
485
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
486
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
487
+
488
+ n = b.shape[0] # number of targets
489
+ if n:
490
+ nt += n # cumulative targets
491
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
492
+
493
+ # Regression
494
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
495
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
496
+ pbox = torch.cat((pxy, pwh), 1).to(device) # predicted box
497
+ giou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # giou(prediction, target)
498
+ lbox += (1.0 - giou).mean() # giou loss
499
+
500
+ # Objectness
501
+ tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * giou.detach().clamp(0).type(tobj.dtype) # giou ratio
502
+
503
+ # Classification
504
+ if model.nc > 1: # cls loss (only if multiple classes)
505
+ t = torch.full_like(ps[:, 5:], cn, device=device) # targets
506
+ t[range(n), tcls[i]] = cp
507
+ lcls += BCEcls(ps[:, 5:], t) # BCE
508
+
509
+ # Append targets to text file
510
+ # with open('targets.txt', 'a') as file:
511
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
512
+
513
+ lobj += BCEobj(pi[..., 4], tobj) * balance[i] # obj loss
514
+
515
+ s = 3 / np # output count scaling
516
+ lbox *= h['giou'] * s
517
+ lobj *= h['obj'] * s * (1.4 if np == 4 else 1.)
518
+ lcls *= h['cls'] * s
519
+ bs = tobj.shape[0] # batch size
520
+
521
+ loss = lbox + lobj + lcls
522
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
523
+
524
+
525
+ def build_targets(p, targets, model):
526
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
527
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
528
+ na, nt = det.na, targets.shape[0] # number of anchors, targets
529
+ tcls, tbox, indices, anch = [], [], [], []
530
+ gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
531
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
532
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
533
+
534
+ g = 0.5 # bias
535
+ off = torch.tensor([[0, 0],
536
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
537
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
538
+ ], device=targets.device).float() * g # offsets
539
+
540
+ for i in range(det.nl):
541
+ anchors = det.anchors[i]
542
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
543
+
544
+ # Match targets to anchors
545
+ t = targets * gain
546
+ if nt:
547
+ # Matches
548
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
549
+ j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare
550
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
551
+ t = t[j] # filter
552
+
553
+ # Offsets
554
+ gxy = t[:, 2:4] # grid xy
555
+ gxi = gain[[2, 3]] - gxy # inverse
556
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
557
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
558
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
559
+ t = t.repeat((5, 1, 1))[j]
560
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
561
+ else:
562
+ t = targets[0]
563
+ offsets = 0
564
+
565
+ # Define
566
+ b, c = t[:, :2].long().T # image, class
567
+ gxy = t[:, 2:4] # grid xy
568
+ gwh = t[:, 4:6] # grid wh
569
+ gij = (gxy - offsets).long()
570
+ gi, gj = gij.T # grid xy indices
571
+
572
+ # Append
573
+ a = t[:, 6].long() # anchor indices
574
+ indices.append((b, a, gj, gi)) # image, anchor, grid indices
575
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
576
+ anch.append(anchors[a]) # anchors
577
+ tcls.append(c) # class
578
+
579
+ return tcls, tbox, indices, anch
580
+
581
+
582
+ def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, merge=False, classes=None, agnostic=False):
583
+ """Performs Non-Maximum Suppression (NMS) on inference results
584
+
585
+ Returns:
586
+ detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
587
+ """
588
+ if prediction.dtype is torch.float16:
589
+ prediction = prediction.float() # to FP32
590
+
591
+ nc = prediction[0].shape[1] - 5 # number of classes
592
+ xc = prediction[..., 4] > conf_thres # candidates
593
+
594
+ # Settings
595
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
596
+ max_det = 300 # maximum number of detections per image
597
+ time_limit = 10.0 # seconds to quit after
598
+ redundant = True # require redundant detections
599
+ multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)
600
+
601
+ t = time.time()
602
+ output = [None] * prediction.shape[0]
603
+ for xi, x in enumerate(prediction): # image index, image inference
604
+ # Apply constraints
605
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
606
+ x = x[xc[xi]] # confidence
607
+
608
+ # If none remain process next image
609
+ if not x.shape[0]:
610
+ continue
611
+
612
+ # Compute conf
613
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
614
+
615
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
616
+ box = xywh2xyxy(x[:, :4])
617
+
618
+ # Detections matrix nx6 (xyxy, conf, cls)
619
+ if multi_label:
620
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
621
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
622
+ else: # best class only
623
+ conf, j = x[:, 5:].max(1, keepdim=True)
624
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
625
+
626
+ # Filter by class
627
+ if classes:
628
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
629
+
630
+ # Apply finite constraint
631
+ # if not torch.isfinite(x).all():
632
+ # x = x[torch.isfinite(x).all(1)]
633
+
634
+ # If none remain process next image
635
+ n = x.shape[0] # number of boxes
636
+ if not n:
637
+ continue
638
+
639
+ # Sort by confidence
640
+ # x = x[x[:, 4].argsort(descending=True)]
641
+
642
+ # Batched NMS
643
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
644
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
645
+ i = torchvision.ops.boxes.nms(boxes, scores, iou_thres)
646
+ if i.shape[0] > max_det: # limit detections
647
+ i = i[:max_det]
648
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
649
+ try: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
650
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
651
+ weights = iou * scores[None] # box weights
652
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
653
+ if redundant:
654
+ i = i[iou.sum(1) > 1] # require redundancy
655
+ except: # possible CUDA error https://github.com/ultralytics/yolov3/issues/1139
656
+ print(x, i, x.shape, i.shape)
657
+ pass
658
+
659
+ output[xi] = x[i]
660
+ if (time.time() - t) > time_limit:
661
+ break # time limit exceeded
662
+
663
+ return output
664
+
665
+
666
+ def strip_optimizer(f='weights/best.pt', s=''): # from utils.utils import *; strip_optimizer()
667
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
668
+ x = torch.load(f, map_location=torch.device('cpu'))
669
+ x['optimizer'] = None
670
+ x['training_results'] = None
671
+ x['epoch'] = -1
672
+ x['model'].half() # to FP16
673
+ for p in x['model'].parameters():
674
+ p.requires_grad = False
675
+ torch.save(x, s or f)
676
+ mb = os.path.getsize(s or f) / 1E6 # filesize
677
+ print('Optimizer stripped from %s,%s %.1fMB' % (f, (' saved as %s,' % s) if s else '', mb))
678
+
679
+
680
+ def coco_class_count(path='../coco/labels/train2014/'):
681
+ # Histogram of occurrences per class
682
+ nc = 80 # number classes
683
+ x = np.zeros(nc, dtype='int32')
684
+ files = sorted(glob.glob('%s/*.*' % path))
685
+ for i, file in enumerate(files):
686
+ labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
687
+ x += np.bincount(labels[:, 0].astype('int32'), minlength=nc)
688
+ print(i, len(files))
689
+
690
+
691
+ def coco_only_people(path='../coco/labels/train2017/'): # from utils.utils import *; coco_only_people()
692
+ # Find images with only people
693
+ files = sorted(glob.glob('%s/*.*' % path))
694
+ for i, file in enumerate(files):
695
+ labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
696
+ if all(labels[:, 0] == 0):
697
+ print(labels.shape[0], file)
698
+
699
+
700
+ def crop_images_random(path='../images/', scale=0.50): # from utils.utils import *; crop_images_random()
701
+ # crops images into random squares up to scale fraction
702
+ # WARNING: overwrites images!
703
+ for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
704
+ img = cv2.imread(file) # BGR
705
+ if img is not None:
706
+ h, w = img.shape[:2]
707
+
708
+ # create random mask
709
+ a = 30 # minimum size (pixels)
710
+ mask_h = random.randint(a, int(max(a, h * scale))) # mask height
711
+ mask_w = mask_h # mask width
712
+
713
+ # box
714
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
715
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
716
+ xmax = min(w, xmin + mask_w)
717
+ ymax = min(h, ymin + mask_h)
718
+
719
+ # apply random color mask
720
+ cv2.imwrite(file, img[ymin:ymax, xmin:xmax])
721
+
722
+
723
+ def coco_single_class_labels(path='../coco/labels/train2014/', label_class=43):
724
+ # Makes single-class coco datasets. from utils.utils import *; coco_single_class_labels()
725
+ if os.path.exists('new/'):
726
+ shutil.rmtree('new/') # delete output folder
727
+ os.makedirs('new/') # make new output folder
728
+ os.makedirs('new/labels/')
729
+ os.makedirs('new/images/')
730
+ for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
731
+ with open(file, 'r') as f:
732
+ labels = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
733
+ i = labels[:, 0] == label_class
734
+ if any(i):
735
+ img_file = file.replace('labels', 'images').replace('txt', 'jpg')
736
+ labels[:, 0] = 0 # reset class to 0
737
+ with open('new/images.txt', 'a') as f: # add image to dataset list
738
+ f.write(img_file + '\n')
739
+ with open('new/labels/' + Path(file).name, 'a') as f: # write label
740
+ for l in labels[i]:
741
+ f.write('%g %.6f %.6f %.6f %.6f\n' % tuple(l))
742
+ shutil.copyfile(src=img_file, dst='new/images/' + Path(file).name.replace('txt', 'jpg')) # copy images
743
+
744
+
745
+ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
746
+ """ Creates kmeans-evolved anchors from training dataset
747
+
748
+ Arguments:
749
+ path: path to dataset *.yaml, or a loaded dataset
750
+ n: number of anchors
751
+ img_size: image size used for training
752
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
753
+ gen: generations to evolve anchors using genetic algorithm
754
+
755
+ Return:
756
+ k: kmeans evolved anchors
757
+
758
+ Usage:
759
+ from utils.utils import *; _ = kmean_anchors()
760
+ """
761
+ thr = 1. / thr
762
+
763
+ def metric(k, wh): # compute metrics
764
+ r = wh[:, None] / k[None]
765
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
766
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
767
+ return x, x.max(1)[0] # x, best_x
768
+
769
+ def fitness(k): # mutation fitness
770
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
771
+ return (best * (best > thr).float()).mean() # fitness
772
+
773
+ def print_results(k):
774
+ k = k[np.argsort(k.prod(1))] # sort small to large
775
+ x, best = metric(k, wh0)
776
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
777
+ print('thr=%.2f: %.4f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
778
+ print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
779
+ (n, img_size, x.mean(), best.mean(), x[x > thr].mean()), end='')
780
+ for i, x in enumerate(k):
781
+ print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
782
+ return k
783
+
784
+ if isinstance(path, str): # *.yaml file
785
+ with open(path) as f:
786
+ data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
787
+ from utils.datasets import LoadImagesAndLabels
788
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
789
+ else:
790
+ dataset = path # dataset
791
+
792
+ # Get label wh
793
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
794
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
795
+
796
+ # Filter
797
+ i = (wh0 < 3.0).any(1).sum()
798
+ if i:
799
+ print('WARNING: Extremely small objects found. '
800
+ '%g of %g labels are < 3 pixels in width or height.' % (i, len(wh0)))
801
+ wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
802
+
803
+ # Kmeans calculation
804
+ print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
805
+ s = wh.std(0) # sigmas for whitening
806
+ k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
807
+ k *= s
808
+ wh = torch.tensor(wh, dtype=torch.float32) # filtered
809
+ wh0 = torch.tensor(wh0, dtype=torch.float32) # unflitered
810
+ k = print_results(k)
811
+
812
+ # Plot
813
+ # k, d = [None] * 20, [None] * 20
814
+ # for i in tqdm(range(1, 21)):
815
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
816
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7))
817
+ # ax = ax.ravel()
818
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
819
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
820
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
821
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
822
+ # fig.tight_layout()
823
+ # fig.savefig('wh.png', dpi=200)
824
+
825
+ # Evolve
826
+ npr = np.random
827
+ f, sh, mp, s = fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
828
+ pbar = tqdm(range(gen), desc='Evolving anchors with Genetic Algorithm') # progress bar
829
+ for _ in pbar:
830
+ v = np.ones(sh)
831
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
832
+ v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
833
+ kg = (k.copy() * v).clip(min=2.0)
834
+ fg = fitness(kg)
835
+ if fg > f:
836
+ f, k = fg, kg.copy()
837
+ pbar.desc = 'Evolving anchors with Genetic Algorithm: fitness = %.4f' % f
838
+ if verbose:
839
+ print_results(k)
840
+
841
+ return print_results(k)
842
+
843
+
844
+ def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
845
+ # Print mutation results to evolve.txt (for use with train.py --evolve)
846
+ a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
847
+ b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
848
+ c = '%10.4g' * len(results) % results # results (P, R, [email protected], [email protected]:0.95, val_losses x 3)
849
+ print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
850
+
851
+ if bucket:
852
+ os.system('gsutil cp gs://%s/evolve.txt .' % bucket) # download evolve.txt
853
+
854
+ with open('evolve.txt', 'a') as f: # append result
855
+ f.write(c + b + '\n')
856
+ x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
857
+ x = x[np.argsort(-fitness(x))] # sort
858
+ np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
859
+
860
+ if bucket:
861
+ os.system('gsutil cp evolve.txt gs://%s' % bucket) # upload evolve.txt
862
+
863
+ # Save yaml
864
+ for i, k in enumerate(hyp.keys()):
865
+ hyp[k] = float(x[0, i + 7])
866
+ with open(yaml_file, 'w') as f:
867
+ results = tuple(x[0, :7])
868
+ c = '%10.4g' * len(results) % results # results (P, R, [email protected], [email protected]:0.95, val_losses x 3)
869
+ f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
870
+ yaml.dump(hyp, f, sort_keys=False)
871
+
872
+
873
+ def apply_classifier(x, model, img, im0):
874
+ # applies a second stage classifier to yolo outputs
875
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
876
+ for i, d in enumerate(x): # per image
877
+ if d is not None and len(d):
878
+ d = d.clone()
879
+
880
+ # Reshape and pad cutouts
881
+ b = xyxy2xywh(d[:, :4]) # boxes
882
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
883
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
884
+ d[:, :4] = xywh2xyxy(b).long()
885
+
886
+ # Rescale boxes from img_size to im0 size
887
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
888
+
889
+ # Classes
890
+ pred_cls1 = d[:, 5].long()
891
+ ims = []
892
+ for j, a in enumerate(d): # per item
893
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
894
+ im = cv2.resize(cutout, (224, 224)) # BGR
895
+ # cv2.imwrite('test%i.jpg' % j, cutout)
896
+
897
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
898
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
899
+ im /= 255.0 # 0 - 255 to 0.0 - 1.0
900
+ ims.append(im)
901
+
902
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
903
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
904
+
905
+ return x
906
+
907
+
908
+ def fitness(x):
909
+ # Returns fitness (for use with results.txt or evolve.txt)
910
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, [email protected], [email protected]:0.95]
911
+ return (x[:, :4] * w).sum(1)
912
+
913
+
914
+ def output_to_target(output, width, height):
915
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
916
+ if isinstance(output, torch.Tensor):
917
+ output = output.cpu().numpy()
918
+
919
+ targets = []
920
+ for i, o in enumerate(output):
921
+ if o is not None:
922
+ for pred in o:
923
+ box = pred[:4]
924
+ w = (box[2] - box[0]) / width
925
+ h = (box[3] - box[1]) / height
926
+ x = box[0] / width + w / 2
927
+ y = box[1] / height + h / 2
928
+ conf = pred[4]
929
+ cls = int(pred[5])
930
+
931
+ targets.append([i, cls, x, y, w, h, conf])
932
+
933
+ return np.array(targets)
934
+
935
+
936
+ def increment_dir(dir, comment=''):
937
+ # Increments a directory runs/exp1 --> runs/exp2_comment
938
+ n = 0 # number
939
+ dir = str(Path(dir)) # os-agnostic
940
+ d = sorted(glob.glob(dir + '*')) # directories
941
+ if len(d):
942
+ n = max([int(x[len(dir):x.find('_') if '_' in x else None]) for x in d]) + 1 # increment
943
+ return dir + str(n) + ('_' + comment if comment else '')
944
+
945
+
946
+ # Plotting functions ---------------------------------------------------------------------------------------------------
947
+ def hist2d(x, y, n=100):
948
+ # 2d histogram used in labels.png and evolve.png
949
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
950
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
951
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
952
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
953
+ return np.log(hist[xidx, yidx])
954
+
955
+
956
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
957
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
958
+ def butter_lowpass(cutoff, fs, order):
959
+ nyq = 0.5 * fs
960
+ normal_cutoff = cutoff / nyq
961
+ b, a = butter(order, normal_cutoff, btype='low', analog=False)
962
+ return b, a
963
+
964
+ b, a = butter_lowpass(cutoff, fs, order=order)
965
+ return filtfilt(b, a, data) # forward-backward filter
966
+
967
+
968
+ def plot_one_box(x, img, color=None, label=None, line_thickness=None):
969
+ # Plots one bounding box on image img
970
+ tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
971
+ color = color or [random.randint(0, 255) for _ in range(3)]
972
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
973
+ cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
974
+ if label:
975
+ tf = max(tl - 1, 1) # font thickness
976
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
977
+ c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
978
+ cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
979
+ cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
980
+
981
+
982
+ def plot_wh_methods(): # from utils.utils import *; plot_wh_methods()
983
+ # Compares the two methods for width-height anchor multiplication
984
+ # https://github.com/ultralytics/yolov3/issues/168
985
+ x = np.arange(-4.0, 4.0, .1)
986
+ ya = np.exp(x)
987
+ yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
988
+
989
+ fig = plt.figure(figsize=(6, 3), dpi=150)
990
+ plt.plot(x, ya, '.-', label='YOLOv3')
991
+ plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
992
+ plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
993
+ plt.xlim(left=-4, right=4)
994
+ plt.ylim(bottom=0, top=6)
995
+ plt.xlabel('input')
996
+ plt.ylabel('output')
997
+ plt.grid()
998
+ plt.legend()
999
+ fig.tight_layout()
1000
+ fig.savefig('comparison.png', dpi=200)
1001
+
1002
+
1003
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
1004
+ tl = 3 # line thickness
1005
+ tf = max(tl - 1, 1) # font thickness
1006
+ if os.path.isfile(fname): # do not overwrite
1007
+ return None
1008
+
1009
+ if isinstance(images, torch.Tensor):
1010
+ images = images.cpu().float().numpy()
1011
+
1012
+ if isinstance(targets, torch.Tensor):
1013
+ targets = targets.cpu().numpy()
1014
+
1015
+ # un-normalise
1016
+ if np.max(images[0]) <= 1:
1017
+ images *= 255
1018
+
1019
+ bs, _, h, w = images.shape # batch size, _, height, width
1020
+ bs = min(bs, max_subplots) # limit plot images
1021
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
1022
+
1023
+ # Check if we should resize
1024
+ scale_factor = max_size / max(h, w)
1025
+ if scale_factor < 1:
1026
+ h = math.ceil(scale_factor * h)
1027
+ w = math.ceil(scale_factor * w)
1028
+
1029
+ # Empty array for output
1030
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)
1031
+
1032
+ # Fix class - colour map
1033
+ prop_cycle = plt.rcParams['axes.prop_cycle']
1034
+ # https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
1035
+ hex2rgb = lambda h: tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
1036
+ color_lut = [hex2rgb(h) for h in prop_cycle.by_key()['color']]
1037
+
1038
+ for i, img in enumerate(images):
1039
+ if i == max_subplots: # if last batch has fewer images than we expect
1040
+ break
1041
+
1042
+ block_x = int(w * (i // ns))
1043
+ block_y = int(h * (i % ns))
1044
+
1045
+ img = img.transpose(1, 2, 0)
1046
+ if scale_factor < 1:
1047
+ img = cv2.resize(img, (w, h))
1048
+
1049
+ mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
1050
+ if len(targets) > 0:
1051
+ image_targets = targets[targets[:, 0] == i]
1052
+ boxes = xywh2xyxy(image_targets[:, 2:6]).T
1053
+ classes = image_targets[:, 1].astype('int')
1054
+ gt = image_targets.shape[1] == 6 # ground truth if no conf column
1055
+ conf = None if gt else image_targets[:, 6] # check for confidence presence (gt vs pred)
1056
+
1057
+ boxes[[0, 2]] *= w
1058
+ boxes[[0, 2]] += block_x
1059
+ boxes[[1, 3]] *= h
1060
+ boxes[[1, 3]] += block_y
1061
+ for j, box in enumerate(boxes.T):
1062
+ cls = int(classes[j])
1063
+ color = color_lut[cls % len(color_lut)]
1064
+ cls = names[cls] if names else cls
1065
+ if gt or conf[j] > 0.3: # 0.3 conf thresh
1066
+ label = '%s' % cls if gt else '%s %.1f' % (cls, conf[j])
1067
+ plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
1068
+
1069
+ # Draw image filename labels
1070
+ if paths is not None:
1071
+ label = os.path.basename(paths[i])[:40] # trim to 40 char
1072
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
1073
+ cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
1074
+ lineType=cv2.LINE_AA)
1075
+
1076
+ # Image border
1077
+ cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
1078
+
1079
+ if fname is not None:
1080
+ mosaic = cv2.resize(mosaic, (int(ns * w * 0.5), int(ns * h * 0.5)), interpolation=cv2.INTER_AREA)
1081
+ cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB))
1082
+
1083
+ return mosaic
1084
+
1085
+
1086
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
1087
+ # Plot LR simulating training for full epochs
1088
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
1089
+ y = []
1090
+ for _ in range(epochs):
1091
+ scheduler.step()
1092
+ y.append(optimizer.param_groups[0]['lr'])
1093
+ plt.plot(y, '.-', label='LR')
1094
+ plt.xlabel('epoch')
1095
+ plt.ylabel('LR')
1096
+ plt.grid()
1097
+ plt.xlim(0, epochs)
1098
+ plt.ylim(0)
1099
+ plt.tight_layout()
1100
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
1101
+
1102
+
1103
+ def plot_test_txt(): # from utils.utils import *; plot_test()
1104
+ # Plot test.txt histograms
1105
+ x = np.loadtxt('test.txt', dtype=np.float32)
1106
+ box = xyxy2xywh(x[:, :4])
1107
+ cx, cy = box[:, 0], box[:, 1]
1108
+
1109
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
1110
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
1111
+ ax.set_aspect('equal')
1112
+ plt.savefig('hist2d.png', dpi=300)
1113
+
1114
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
1115
+ ax[0].hist(cx, bins=600)
1116
+ ax[1].hist(cy, bins=600)
1117
+ plt.savefig('hist1d.png', dpi=200)
1118
+
1119
+
1120
+ def plot_targets_txt(): # from utils.utils import *; plot_targets_txt()
1121
+ # Plot targets.txt histograms
1122
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
1123
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
1124
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
1125
+ ax = ax.ravel()
1126
+ for i in range(4):
1127
+ ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
1128
+ ax[i].legend()
1129
+ ax[i].set_title(s[i])
1130
+ plt.savefig('targets.jpg', dpi=200)
1131
+
1132
+
1133
+ def plot_study_txt(f='study.txt', x=None): # from utils.utils import *; plot_study_txt()
1134
+ # Plot study.txt generated by test.py
1135
+ fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
1136
+ ax = ax.ravel()
1137
+
1138
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
1139
+ for f in ['coco_study/study_coco_yolov5%s.txt' % x for x in ['s', 'm', 'l', 'x']]:
1140
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
1141
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
1142
+ s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
1143
+ for i in range(7):
1144
+ ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
1145
+ ax[i].set_title(s[i])
1146
+
1147
+ j = y[3].argmax() + 1
1148
+ ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8,
1149
+ label=Path(f).stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
1150
+
1151
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [33.8, 39.6, 43.0, 47.5, 49.4, 50.7],
1152
+ 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
1153
+
1154
+ ax2.grid()
1155
+ ax2.set_xlim(0, 30)
1156
+ ax2.set_ylim(28, 50)
1157
+ ax2.set_yticks(np.arange(30, 55, 5))
1158
+ ax2.set_xlabel('GPU Speed (ms/img)')
1159
+ ax2.set_ylabel('COCO AP val')
1160
+ ax2.legend(loc='lower right')
1161
+ plt.savefig('study_mAP_latency.png', dpi=300)
1162
+ plt.savefig(f.replace('.txt', '.png'), dpi=200)
1163
+
1164
+
1165
+ def plot_labels(labels, save_dir=''):
1166
+ # plot dataset labels
1167
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
1168
+ nc = int(c.max() + 1) # number of classes
1169
+
1170
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
1171
+ ax = ax.ravel()
1172
+ ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
1173
+ ax[0].set_xlabel('classes')
1174
+ ax[1].scatter(b[0], b[1], c=hist2d(b[0], b[1], 90), cmap='jet')
1175
+ ax[1].set_xlabel('x')
1176
+ ax[1].set_ylabel('y')
1177
+ ax[2].scatter(b[2], b[3], c=hist2d(b[2], b[3], 90), cmap='jet')
1178
+ ax[2].set_xlabel('width')
1179
+ ax[2].set_ylabel('height')
1180
+ plt.savefig(Path(save_dir) / 'labels.png', dpi=200)
1181
+ plt.close()
1182
+
1183
+
1184
+ def plot_evolution(yaml_file='runs/evolve/hyp_evolved.yaml'): # from utils.utils import *; plot_evolution()
1185
+ # Plot hyperparameter evolution results in evolve.txt
1186
+ with open(yaml_file) as f:
1187
+ hyp = yaml.load(f, Loader=yaml.FullLoader)
1188
+ x = np.loadtxt('evolve.txt', ndmin=2)
1189
+ f = fitness(x)
1190
+ # weights = (f - f.min()) ** 2 # for weighted results
1191
+ plt.figure(figsize=(10, 10), tight_layout=True)
1192
+ matplotlib.rc('font', **{'size': 8})
1193
+ for i, (k, v) in enumerate(hyp.items()):
1194
+ y = x[:, i + 7]
1195
+ # mu = (y * weights).sum() / weights.sum() # best weighted result
1196
+ mu = y[f.argmax()] # best single result
1197
+ plt.subplot(5, 5, i + 1)
1198
+ plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
1199
+ plt.plot(mu, f.max(), 'k+', markersize=15)
1200
+ plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
1201
+ if i % 5 != 0:
1202
+ plt.yticks([])
1203
+ print('%15s: %.3g' % (k, mu))
1204
+ plt.savefig('evolve.png', dpi=200)
1205
+ print('\nPlot saved as evolve.png')
1206
+
1207
+
1208
+ def plot_results_overlay(start=0, stop=0): # from utils.utils import *; plot_results_overlay()
1209
+ # Plot training 'results*.txt', overlaying train and val losses
1210
+ s = ['train', 'train', 'train', 'Precision', '[email protected]', 'val', 'val', 'val', 'Recall', '[email protected]:0.95'] # legends
1211
+ t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
1212
+ for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
1213
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
1214
+ n = results.shape[1] # number of rows
1215
+ x = range(start, min(stop, n) if stop else n)
1216
+ fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
1217
+ ax = ax.ravel()
1218
+ for i in range(5):
1219
+ for j in [i, i + 5]:
1220
+ y = results[j, x]
1221
+ ax[i].plot(x, y, marker='.', label=s[j])
1222
+ # y_smooth = butter_lowpass_filtfilt(y)
1223
+ # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
1224
+
1225
+ ax[i].set_title(t[i])
1226
+ ax[i].legend()
1227
+ ax[i].set_ylabel(f) if i == 0 else None # add filename
1228
+ fig.savefig(f.replace('.txt', '.png'), dpi=200)
1229
+
1230
+
1231
+ def plot_results(start=0, stop=0, bucket='', id=(), labels=(),
1232
+ save_dir=''): # from utils.utils import *; plot_results()
1233
+ # Plot training 'results*.txt' as seen in https://github.com/ultralytics/yolov5#reproduce-our-training
1234
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6))
1235
+ ax = ax.ravel()
1236
+ s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
1237
+ 'val GIoU', 'val Objectness', 'val Classification', '[email protected]', '[email protected]:0.95']
1238
+ if bucket:
1239
+ os.system('rm -rf storage.googleapis.com')
1240
+ files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
1241
+ else:
1242
+ files = glob.glob(str(Path(save_dir) / 'results*.txt')) + glob.glob('../../Downloads/results*.txt')
1243
+ for fi, f in enumerate(files):
1244
+ try:
1245
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
1246
+ n = results.shape[1] # number of rows
1247
+ x = range(start, min(stop, n) if stop else n)
1248
+ for i in range(10):
1249
+ y = results[i, x]
1250
+ if i in [0, 1, 2, 5, 6, 7]:
1251
+ y[y == 0] = np.nan # dont show zero loss values
1252
+ # y /= y[0] # normalize
1253
+ label = labels[fi] if len(labels) else Path(f).stem
1254
+ ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
1255
+ ax[i].set_title(s[i])
1256
+ # if i in [5, 6, 7]: # share train and val loss y axes
1257
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
1258
+ except:
1259
+ print('Warning: Plotting error for %s, skipping file' % f)
1260
+
1261
+ fig.tight_layout()
1262
+ ax[1].legend()
1263
+ fig.savefig(Path(save_dir) / 'results.png', dpi=200)
utils/google_utils.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains google utils: https://cloud.google.com/storage/docs/reference/libraries
2
+ # pip install --upgrade google-cloud-storage
3
+ # from google.cloud import storage
4
+
5
+ import os
6
+ import platform
7
+ import time
8
+ from pathlib import Path
9
+
10
+
11
+ def attempt_download(weights):
12
+ # Attempt to download pretrained weights if not found locally
13
+ weights = weights.strip().replace("'", '')
14
+ msg = weights + ' missing, try downloading from https://drive.google.com/drive/folders/1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J'
15
+
16
+ r = 1 # return
17
+ if len(weights) > 0 and not os.path.isfile(weights):
18
+ d = {'yolov3-spp.pt': '1mM67oNw4fZoIOL1c8M3hHmj66d8e-ni_', # yolov3-spp.yaml
19
+ 'yolov5s.pt': '1R5T6rIyy3lLwgFXNms8whc-387H0tMQO', # yolov5s.yaml
20
+ 'yolov5m.pt': '1vobuEExpWQVpXExsJ2w-Mbf3HJjWkQJr', # yolov5m.yaml
21
+ 'yolov5l.pt': '1hrlqD1Wdei7UT4OgT785BEk1JwnSvNEV', # yolov5l.yaml
22
+ 'yolov5x.pt': '1mM8aZJlWTxOg7BZJvNUMrTnA2AbeCVzS', # yolov5x.yaml
23
+ }
24
+
25
+ file = Path(weights).name
26
+ if file in d:
27
+ r = gdrive_download(id=d[file], name=weights)
28
+
29
+ if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB
30
+ os.remove(weights) if os.path.exists(weights) else None # remove partial downloads
31
+ s = 'curl -L -o %s "storage.googleapis.com/ultralytics/yolov5/ckpt/%s"' % (weights, file)
32
+ r = os.system(s) # execute, capture return values
33
+
34
+ # Error check
35
+ if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB
36
+ os.remove(weights) if os.path.exists(weights) else None # remove partial downloads
37
+ raise Exception(msg)
38
+
39
+
40
+ def gdrive_download(id='1n_oKgR81BJtqk75b00eAjdv03qVCQn2f', name='coco128.zip'):
41
+ # Downloads a file from Google Drive, accepting presented query
42
+ # from utils.google_utils import *; gdrive_download()
43
+ t = time.time()
44
+
45
+ print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='')
46
+ os.remove(name) if os.path.exists(name) else None # remove existing
47
+ os.remove('cookie') if os.path.exists('cookie') else None
48
+
49
+ # Attempt file download
50
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
51
+ os.system('curl -c ./cookie -s -L "drive.google.com/uc?export=download&id=%s" > %s ' % (id, out))
52
+ if os.path.exists('cookie'): # large file
53
+ s = 'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm=%s&id=%s" -o %s' % (get_token(), id, name)
54
+ else: # small file
55
+ s = 'curl -s -L -o %s "drive.google.com/uc?export=download&id=%s"' % (name, id)
56
+ r = os.system(s) # execute, capture return values
57
+ os.remove('cookie') if os.path.exists('cookie') else None
58
+
59
+ # Error check
60
+ if r != 0:
61
+ os.remove(name) if os.path.exists(name) else None # remove partial
62
+ print('Download error ') # raise Exception('Download error')
63
+ return r
64
+
65
+ # Unzip if archive
66
+ if name.endswith('.zip'):
67
+ print('unzipping... ', end='')
68
+ os.system('unzip -q %s' % name) # unzip
69
+ os.remove(name) # remove zip to free space
70
+
71
+ print('Done (%.1fs)' % (time.time() - t))
72
+ return r
73
+
74
+
75
+ def get_token(cookie="./cookie"):
76
+ with open(cookie) as f:
77
+ for line in f:
78
+ if "download" in line:
79
+ return line.split()[-1]
80
+ return ""
81
+
82
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
83
+ # # Uploads a file to a bucket
84
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
85
+ #
86
+ # storage_client = storage.Client()
87
+ # bucket = storage_client.get_bucket(bucket_name)
88
+ # blob = bucket.blob(destination_blob_name)
89
+ #
90
+ # blob.upload_from_filename(source_file_name)
91
+ #
92
+ # print('File {} uploaded to {}.'.format(
93
+ # source_file_name,
94
+ # destination_blob_name))
95
+ #
96
+ #
97
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
98
+ # # Uploads a blob from a bucket
99
+ # storage_client = storage.Client()
100
+ # bucket = storage_client.get_bucket(bucket_name)
101
+ # blob = bucket.blob(source_blob_name)
102
+ #
103
+ # blob.download_to_filename(destination_file_name)
104
+ #
105
+ # print('Blob {} downloaded to {}.'.format(
106
+ # source_blob_name,
107
+ # destination_file_name))
utils/torch_utils.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import time
4
+ from copy import deepcopy
5
+
6
+ import torch
7
+ import torch.backends.cudnn as cudnn
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ import torchvision.models as models
11
+
12
+
13
+ def init_seeds(seed=0):
14
+ torch.manual_seed(seed)
15
+
16
+ # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
17
+ if seed == 0: # slower, more reproducible
18
+ cudnn.deterministic = True
19
+ cudnn.benchmark = False
20
+ else: # faster, less reproducible
21
+ cudnn.deterministic = False
22
+ cudnn.benchmark = True
23
+
24
+
25
+ def select_device(device='', batch_size=None):
26
+ # device = 'cpu' or '0' or '0,1,2,3'
27
+ cpu_request = device.lower() == 'cpu'
28
+ if device and not cpu_request: # if device requested other than 'cpu'
29
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
30
+ assert torch.cuda.is_available(), 'CUDA unavailable, invalid device %s requested' % device # check availablity
31
+
32
+ cuda = False if cpu_request else torch.cuda.is_available()
33
+ if cuda:
34
+ c = 1024 ** 2 # bytes to MB
35
+ ng = torch.cuda.device_count()
36
+ if ng > 1 and batch_size: # check that batch_size is compatible with device_count
37
+ assert batch_size % ng == 0, 'batch-size %g not multiple of GPU count %g' % (batch_size, ng)
38
+ x = [torch.cuda.get_device_properties(i) for i in range(ng)]
39
+ s = 'Using CUDA '
40
+ for i in range(0, ng):
41
+ if i == 1:
42
+ s = ' ' * len(s)
43
+ print("%sdevice%g _CudaDeviceProperties(name='%s', total_memory=%dMB)" %
44
+ (s, i, x[i].name, x[i].total_memory / c))
45
+ else:
46
+ print('Using CPU')
47
+
48
+ print('') # skip a line
49
+ return torch.device('cuda:0' if cuda else 'cpu')
50
+
51
+
52
+ def time_synchronized():
53
+ torch.cuda.synchronize() if torch.cuda.is_available() else None
54
+ return time.time()
55
+
56
+
57
+ def is_parallel(model):
58
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
59
+
60
+
61
+ def intersect_dicts(da, db, exclude=()):
62
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
63
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
64
+
65
+
66
+ def initialize_weights(model):
67
+ for m in model.modules():
68
+ t = type(m)
69
+ if t is nn.Conv2d:
70
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
71
+ elif t is nn.BatchNorm2d:
72
+ m.eps = 1e-3
73
+ m.momentum = 0.03
74
+ elif t in [nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
75
+ m.inplace = True
76
+
77
+
78
+ def find_modules(model, mclass=nn.Conv2d):
79
+ # Finds layer indices matching module class 'mclass'
80
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
81
+
82
+
83
+ def sparsity(model):
84
+ # Return global model sparsity
85
+ a, b = 0., 0.
86
+ for p in model.parameters():
87
+ a += p.numel()
88
+ b += (p == 0).sum()
89
+ return b / a
90
+
91
+
92
+ def prune(model, amount=0.3):
93
+ # Prune model to requested global sparsity
94
+ import torch.nn.utils.prune as prune
95
+ print('Pruning model... ', end='')
96
+ for name, m in model.named_modules():
97
+ if isinstance(m, nn.Conv2d):
98
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
99
+ prune.remove(m, 'weight') # make permanent
100
+ print(' %.3g global sparsity' % sparsity(model))
101
+
102
+
103
+ def fuse_conv_and_bn(conv, bn):
104
+ # https://tehnokv.com/posts/fusing-batchnorm-and-conv/
105
+ with torch.no_grad():
106
+ # init
107
+ fusedconv = nn.Conv2d(conv.in_channels,
108
+ conv.out_channels,
109
+ kernel_size=conv.kernel_size,
110
+ stride=conv.stride,
111
+ padding=conv.padding,
112
+ bias=True).to(conv.weight.device)
113
+
114
+ # prepare filters
115
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
116
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
117
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
118
+
119
+ # prepare spatial bias
120
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
121
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
122
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
123
+
124
+ return fusedconv
125
+
126
+
127
+ def model_info(model, verbose=False):
128
+ # Plots a line-by-line description of a PyTorch model
129
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
130
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
131
+ if verbose:
132
+ print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
133
+ for i, (name, p) in enumerate(model.named_parameters()):
134
+ name = name.replace('module_list.', '')
135
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
136
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
137
+
138
+ try: # FLOPS
139
+ from thop import profile
140
+ flops = profile(deepcopy(model), inputs=(torch.zeros(1, 3, 64, 64),), verbose=False)[0] / 1E9 * 2
141
+ fs = ', %.1f GFLOPS' % (flops * 100) # 640x640 FLOPS
142
+ except:
143
+ fs = ''
144
+
145
+ print('Model Summary: %g layers, %g parameters, %g gradients%s' % (len(list(model.parameters())), n_p, n_g, fs))
146
+
147
+
148
+ def load_classifier(name='resnet101', n=2):
149
+ # Loads a pretrained model reshaped to n-class output
150
+ model = models.__dict__[name](pretrained=True)
151
+
152
+ # Display model properties
153
+ input_size = [3, 224, 224]
154
+ input_space = 'RGB'
155
+ input_range = [0, 1]
156
+ mean = [0.485, 0.456, 0.406]
157
+ std = [0.229, 0.224, 0.225]
158
+ for x in [input_size, input_space, input_range, mean, std]:
159
+ print(x + ' =', eval(x))
160
+
161
+ # Reshape output to n classes
162
+ filters = model.fc.weight.shape[1]
163
+ model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
164
+ model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
165
+ model.fc.out_features = n
166
+ return model
167
+
168
+
169
+ def scale_img(img, ratio=1.0, same_shape=False): # img(16,3,256,416), r=ratio
170
+ # scales img(bs,3,y,x) by ratio
171
+ if ratio == 1.0:
172
+ return img
173
+ else:
174
+ h, w = img.shape[2:]
175
+ s = (int(h * ratio), int(w * ratio)) # new size
176
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
177
+ if not same_shape: # pad/crop img
178
+ gs = 32 # (pixels) grid size
179
+ h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
180
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
181
+
182
+
183
+ def copy_attr(a, b, include=(), exclude=()):
184
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
185
+ for k, v in b.__dict__.items():
186
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
187
+ continue
188
+ else:
189
+ setattr(a, k, v)
190
+
191
+
192
+ class ModelEMA:
193
+ """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
194
+ Keep a moving average of everything in the model state_dict (parameters and buffers).
195
+ This is intended to allow functionality like
196
+ https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
197
+ A smoothed version of the weights is necessary for some training schemes to perform well.
198
+ This class is sensitive where it is initialized in the sequence of model init,
199
+ GPU assignment and distributed training wrappers.
200
+ """
201
+
202
+ def __init__(self, model, decay=0.9999, updates=0):
203
+ # Create EMA
204
+ self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
205
+ # if next(model.parameters()).device.type != 'cpu':
206
+ # self.ema.half() # FP16 EMA
207
+ self.updates = updates # number of EMA updates
208
+ self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
209
+ for p in self.ema.parameters():
210
+ p.requires_grad_(False)
211
+
212
+ def update(self, model):
213
+ # Update EMA parameters
214
+ with torch.no_grad():
215
+ self.updates += 1
216
+ d = self.decay(self.updates)
217
+
218
+ msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
219
+ for k, v in self.ema.state_dict().items():
220
+ if v.dtype.is_floating_point:
221
+ v *= d
222
+ v += (1. - d) * msd[k].detach()
223
+
224
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
225
+ # Update EMA attributes
226
+ copy_attr(self.ema, model, include, exclude)