Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

386 Zeilen
16KB

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