common.py 17 KB

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