Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

428 linhas
18KB

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