Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

common.py 12 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  1. # This file contains modules common to various models
  2. import math
  3. import numpy as np
  4. import requests
  5. import torch
  6. import torch.nn as nn
  7. from PIL import Image, ImageDraw
  8. from utils.datasets import letterbox
  9. from utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh
  10. from utils.plots import color_list
  11. def autopad(k, p=None): # kernel, padding
  12. # Pad to 'same'
  13. if p is None:
  14. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  15. return p
  16. def DWConv(c1, c2, k=1, s=1, act=True):
  17. # Depthwise convolution
  18. return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
  19. class Conv(nn.Module):
  20. # Standard convolution
  21. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
  22. super(Conv, self).__init__()
  23. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
  24. self.bn = nn.BatchNorm2d(c2)
  25. self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
  26. def forward(self, x):
  27. return self.act(self.bn(self.conv(x)))
  28. def fuseforward(self, x):
  29. return self.act(self.conv(x))
  30. class Bottleneck(nn.Module):
  31. # Standard bottleneck
  32. def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
  33. super(Bottleneck, self).__init__()
  34. c_ = int(c2 * e) # hidden channels
  35. self.cv1 = Conv(c1, c_, 1, 1)
  36. self.cv2 = Conv(c_, c2, 3, 1, g=g)
  37. self.add = shortcut and c1 == c2
  38. def forward(self, x):
  39. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  40. class BottleneckCSP(nn.Module):
  41. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  42. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  43. super(BottleneckCSP, self).__init__()
  44. c_ = int(c2 * e) # hidden channels
  45. self.cv1 = Conv(c1, c_, 1, 1)
  46. self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
  47. self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
  48. self.cv4 = Conv(2 * c_, c2, 1, 1)
  49. self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
  50. self.act = nn.LeakyReLU(0.1, inplace=True)
  51. self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  52. def forward(self, x):
  53. y1 = self.cv3(self.m(self.cv1(x)))
  54. y2 = self.cv2(x)
  55. return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
  56. class C3(nn.Module):
  57. # CSP Bottleneck with 3 convolutions
  58. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  59. super(C3, self).__init__()
  60. c_ = int(c2 * e) # hidden channels
  61. self.cv1 = Conv(c1, c_, 1, 1)
  62. self.cv2 = Conv(c1, c_, 1, 1)
  63. self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
  64. self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  65. # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
  66. def forward(self, x):
  67. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
  68. class SPP(nn.Module):
  69. # Spatial pyramid pooling layer used in YOLOv3-SPP
  70. def __init__(self, c1, c2, k=(5, 9, 13)):
  71. super(SPP, self).__init__()
  72. c_ = c1 // 2 # hidden channels
  73. self.cv1 = Conv(c1, c_, 1, 1)
  74. self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
  75. self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
  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. class Focus(nn.Module):
  80. # Focus wh information into c-space
  81. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
  82. super(Focus, self).__init__()
  83. self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
  84. # self.contract = Contract(gain=2)
  85. def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
  86. return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
  87. # return self.conv(self.contract(x))
  88. class Contract(nn.Module):
  89. # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
  90. def __init__(self, gain=2):
  91. super().__init__()
  92. self.gain = gain
  93. def forward(self, x):
  94. N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
  95. s = self.gain
  96. x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2)
  97. x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
  98. return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40)
  99. class Expand(nn.Module):
  100. # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
  101. def __init__(self, gain=2):
  102. super().__init__()
  103. self.gain = gain
  104. def forward(self, x):
  105. N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
  106. s = self.gain
  107. x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80)
  108. x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
  109. return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160)
  110. class Concat(nn.Module):
  111. # Concatenate a list of tensors along dimension
  112. def __init__(self, dimension=1):
  113. super(Concat, self).__init__()
  114. self.d = dimension
  115. def forward(self, x):
  116. return torch.cat(x, self.d)
  117. class NMS(nn.Module):
  118. # Non-Maximum Suppression (NMS) module
  119. conf = 0.25 # confidence threshold
  120. iou = 0.45 # IoU threshold
  121. classes = None # (optional list) filter by class
  122. def __init__(self):
  123. super(NMS, self).__init__()
  124. def forward(self, x):
  125. return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
  126. class autoShape(nn.Module):
  127. # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
  128. img_size = 640 # inference size (pixels)
  129. conf = 0.25 # NMS confidence threshold
  130. iou = 0.45 # NMS IoU threshold
  131. classes = None # (optional list) filter by class
  132. def __init__(self, model):
  133. super(autoShape, self).__init__()
  134. self.model = model.eval()
  135. def autoshape(self):
  136. print('autoShape already enabled, skipping... ') # model already converted to model.autoshape()
  137. return self
  138. def forward(self, imgs, size=640, augment=False, profile=False):
  139. # Inference from various sources. For height=720, width=1280, RGB images example inputs are:
  140. # filename: imgs = 'data/samples/zidane.jpg'
  141. # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg'
  142. # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(720,1280,3)
  143. # PIL: = Image.open('image.jpg') # HWC x(720,1280,3)
  144. # numpy: = np.zeros((720,1280,3)) # HWC
  145. # torch: = torch.zeros(16,3,720,1280) # BCHW
  146. # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
  147. p = next(self.model.parameters()) # for device and type
  148. if isinstance(imgs, torch.Tensor): # torch
  149. return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
  150. # Pre-process
  151. n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
  152. shape0, shape1 = [], [] # image and inference shapes
  153. for i, im in enumerate(imgs):
  154. if isinstance(im, str): # filename or uri
  155. im = Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im) # open
  156. im = np.array(im) # to numpy
  157. if im.shape[0] < 5: # image in CHW
  158. im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
  159. im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input
  160. s = im.shape[:2] # HWC
  161. shape0.append(s) # image shape
  162. g = (size / max(s)) # gain
  163. shape1.append([y * g for y in s])
  164. imgs[i] = im # update
  165. shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
  166. x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
  167. x = np.stack(x, 0) if n > 1 else x[0][None] # stack
  168. x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
  169. x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
  170. # Inference
  171. with torch.no_grad():
  172. y = self.model(x, augment, profile)[0] # forward
  173. y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS
  174. # Post-process
  175. for i in range(n):
  176. scale_coords(shape1, y[i][:, :4], shape0[i])
  177. return Detections(imgs, y, self.names)
  178. class Detections:
  179. # detections class for YOLOv5 inference results
  180. def __init__(self, imgs, pred, names=None):
  181. super(Detections, self).__init__()
  182. d = pred[0].device # device
  183. gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
  184. self.imgs = imgs # list of images as numpy arrays
  185. self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
  186. self.names = names # class names
  187. self.xyxy = pred # xyxy pixels
  188. self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
  189. self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
  190. self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
  191. self.n = len(self.pred)
  192. def display(self, pprint=False, show=False, save=False):
  193. colors = color_list()
  194. for i, (img, pred) in enumerate(zip(self.imgs, self.pred)):
  195. str = f'Image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} '
  196. if pred is not None:
  197. for c in pred[:, -1].unique():
  198. n = (pred[:, -1] == c).sum() # detections per class
  199. str += f'{n} {self.names[int(c)]}s, ' # add to string
  200. if show or save:
  201. img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np
  202. for *box, conf, cls in pred: # xyxy, confidence, class
  203. # str += '%s %.2f, ' % (names[int(cls)], conf) # label
  204. ImageDraw.Draw(img).rectangle(box, width=4, outline=colors[int(cls) % 10]) # plot
  205. if save:
  206. f = f'results{i}.jpg'
  207. str += f"saved to '{f}'"
  208. img.save(f) # save
  209. if show:
  210. img.show(f'Image {i}') # show
  211. if pprint:
  212. print(str)
  213. def print(self):
  214. self.display(pprint=True) # print results
  215. def show(self):
  216. self.display(show=True) # show results
  217. def save(self):
  218. self.display(save=True) # save results
  219. def __len__(self):
  220. return self.n
  221. def tolist(self):
  222. # return a list of Detections objects, i.e. 'for result in results.tolist():'
  223. x = [Detections([self.imgs[i]], [self.pred[i]], self.names) for i in range(self.n)]
  224. for d in x:
  225. for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
  226. setattr(d, k, getattr(d, k)[0]) # pop out of list
  227. return x
  228. class Classify(nn.Module):
  229. # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
  230. def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
  231. super(Classify, self).__init__()
  232. self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
  233. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
  234. self.flat = nn.Flatten()
  235. def forward(self, x):
  236. z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
  237. return self.flat(self.conv(z)) # flatten to x(b,c2)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...