2021-03-26 20:23:11 +08:00
|
|
|
# YOLOv5 common modules
|
2020-05-30 08:04:54 +08:00
|
|
|
|
2021-07-19 16:43:01 +08:00
|
|
|
import logging
|
2021-04-07 22:28:07 +08:00
|
|
|
from copy import copy
|
2021-07-18 21:25:37 +08:00
|
|
|
from pathlib import Path, PosixPath
|
2021-01-11 12:06:11 +08:00
|
|
|
|
2021-07-02 19:25:54 +08:00
|
|
|
import math
|
2020-10-16 02:10:08 +08:00
|
|
|
import numpy as np
|
2021-04-07 22:28:07 +08:00
|
|
|
import pandas as pd
|
2020-12-27 11:58:26 +08:00
|
|
|
import requests
|
2020-08-03 06:47:36 +08:00
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
2021-02-20 07:39:09 +08:00
|
|
|
from PIL import Image
|
2021-04-10 00:19:49 +08:00
|
|
|
from torch.cuda import amp
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2021-07-02 19:25:54 +08:00
|
|
|
from utils.datasets import exif_transpose, letterbox
|
2021-04-21 05:51:08 +08:00
|
|
|
from utils.general import non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh, save_one_box
|
2021-04-28 22:05:14 +08:00
|
|
|
from utils.plots import colors, plot_one_box
|
2021-07-19 16:43:01 +08:00
|
|
|
from utils.torch_utils import time_sync
|
|
|
|
|
|
|
|
LOGGER = logging.getLogger(__name__)
|
2020-05-30 08:04:54 +08:00
|
|
|
|
|
|
|
|
2020-07-02 10:15:59 +08:00
|
|
|
def autopad(k, p=None): # kernel, padding
|
2020-07-02 02:44:49 +08:00
|
|
|
# Pad to 'same'
|
2020-07-02 10:15:59 +08:00
|
|
|
if p is None:
|
|
|
|
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
|
|
|
return p
|
2020-07-02 02:44:49 +08:00
|
|
|
|
|
|
|
|
2020-06-09 13:13:01 +08:00
|
|
|
def DWConv(c1, c2, k=1, s=1, act=True):
|
|
|
|
# Depthwise convolution
|
2020-05-30 08:04:54 +08:00
|
|
|
return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
|
|
|
|
|
|
|
|
|
2020-06-09 13:13:01 +08:00
|
|
|
class Conv(nn.Module):
|
|
|
|
# Standard convolution
|
2020-07-02 02:44:49 +08:00
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-07-02 10:15:59 +08:00
|
|
|
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
|
2020-05-30 08:04:54 +08:00
|
|
|
self.bn = nn.BatchNorm2d(c2)
|
2021-01-05 11:54:09 +08:00
|
|
|
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
|
2020-05-30 08:04:54 +08:00
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return self.act(self.bn(self.conv(x)))
|
|
|
|
|
2020-06-08 04:42:33 +08:00
|
|
|
def fuseforward(self, x):
|
|
|
|
return self.act(self.conv(x))
|
|
|
|
|
2020-05-30 08:04:54 +08:00
|
|
|
|
2021-04-01 23:26:53 +08:00
|
|
|
class TransformerLayer(nn.Module):
|
|
|
|
# Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
|
|
|
|
def __init__(self, c, num_heads):
|
|
|
|
super().__init__()
|
|
|
|
self.q = nn.Linear(c, c, bias=False)
|
|
|
|
self.k = nn.Linear(c, c, bias=False)
|
|
|
|
self.v = nn.Linear(c, c, bias=False)
|
|
|
|
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
|
|
|
|
self.fc1 = nn.Linear(c, c, bias=False)
|
|
|
|
self.fc2 = nn.Linear(c, c, bias=False)
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
|
|
|
|
x = self.fc2(self.fc1(x)) + x
|
|
|
|
return x
|
|
|
|
|
|
|
|
|
|
|
|
class TransformerBlock(nn.Module):
|
|
|
|
# Vision Transformer https://arxiv.org/abs/2010.11929
|
|
|
|
def __init__(self, c1, c2, num_heads, num_layers):
|
|
|
|
super().__init__()
|
|
|
|
self.conv = None
|
|
|
|
if c1 != c2:
|
|
|
|
self.conv = Conv(c1, c2)
|
|
|
|
self.linear = nn.Linear(c2, c2) # learnable position embedding
|
|
|
|
self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
|
|
|
|
self.c2 = c2
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
if self.conv is not None:
|
|
|
|
x = self.conv(x)
|
|
|
|
b, _, w, h = x.shape
|
2021-06-29 22:03:10 +08:00
|
|
|
p = x.flatten(2).unsqueeze(0).transpose(0, 3).squeeze(3)
|
|
|
|
return self.tr(p + self.linear(p)).unsqueeze(3).transpose(0, 3).reshape(b, self.c2, w, h)
|
2021-04-01 23:26:53 +08:00
|
|
|
|
|
|
|
|
2020-05-30 08:04:54 +08:00
|
|
|
class Bottleneck(nn.Module):
|
2020-06-09 13:13:01 +08:00
|
|
|
# Standard bottleneck
|
2020-05-30 08:04:54 +08:00
|
|
|
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-05-30 08:04:54 +08:00
|
|
|
c_ = int(c2 * e) # hidden channels
|
|
|
|
self.cv1 = Conv(c1, c_, 1, 1)
|
|
|
|
self.cv2 = Conv(c_, c2, 3, 1, g=g)
|
|
|
|
self.add = shortcut and c1 == c2
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
|
|
|
|
|
|
|
|
|
|
|
class BottleneckCSP(nn.Module):
|
2020-06-09 13:13:01 +08:00
|
|
|
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
2020-05-30 08:04:54 +08:00
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-05-30 08:04:54 +08:00
|
|
|
c_ = int(c2 * e) # hidden channels
|
|
|
|
self.cv1 = Conv(c1, c_, 1, 1)
|
|
|
|
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
|
|
|
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
2020-07-02 02:44:49 +08:00
|
|
|
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
2020-05-30 08:04:54 +08:00
|
|
|
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
|
|
|
self.act = nn.LeakyReLU(0.1, inplace=True)
|
|
|
|
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
y1 = self.cv3(self.m(self.cv1(x)))
|
|
|
|
y2 = self.cv2(x)
|
|
|
|
return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
|
|
|
|
|
|
|
|
|
2020-12-16 14:13:08 +08:00
|
|
|
class C3(nn.Module):
|
|
|
|
# CSP Bottleneck with 3 convolutions
|
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-12-16 14:13:08 +08:00
|
|
|
c_ = int(c2 * e) # hidden channels
|
|
|
|
self.cv1 = Conv(c1, c_, 1, 1)
|
|
|
|
self.cv2 = Conv(c1, c_, 1, 1)
|
|
|
|
self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
|
|
|
|
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
|
|
|
|
# self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
|
|
|
|
|
|
|
|
|
2021-04-01 23:26:53 +08:00
|
|
|
class C3TR(C3):
|
|
|
|
# C3 module with TransformerBlock()
|
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
|
|
|
super().__init__(c1, c2, n, shortcut, g, e)
|
|
|
|
c_ = int(c2 * e)
|
|
|
|
self.m = TransformerBlock(c_, c_, 4, n)
|
|
|
|
|
|
|
|
|
2021-07-19 18:41:15 +08:00
|
|
|
class C3SPP(C3):
|
|
|
|
# C3 module with SPP()
|
|
|
|
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
|
|
|
|
super().__init__(c1, c2, n, shortcut, g, e)
|
|
|
|
c_ = int(c2 * e)
|
|
|
|
self.m = SPP(c_, c_, k)
|
|
|
|
|
|
|
|
|
2020-06-09 13:13:01 +08:00
|
|
|
class SPP(nn.Module):
|
|
|
|
# Spatial pyramid pooling layer used in YOLOv3-SPP
|
2020-05-30 08:04:54 +08:00
|
|
|
def __init__(self, c1, c2, k=(5, 9, 13)):
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-05-30 08:04:54 +08:00
|
|
|
c_ = c1 // 2 # hidden channels
|
|
|
|
self.cv1 = Conv(c1, c_, 1, 1)
|
|
|
|
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
|
|
|
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
x = self.cv1(x)
|
|
|
|
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
|
|
|
|
|
|
|
|
|
|
|
class Focus(nn.Module):
|
|
|
|
# Focus wh information into c-space
|
2020-07-02 02:44:49 +08:00
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-07-02 02:44:49 +08:00
|
|
|
self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
|
2021-01-05 11:54:09 +08:00
|
|
|
# self.contract = Contract(gain=2)
|
2020-05-30 08:04:54 +08:00
|
|
|
|
|
|
|
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
|
|
|
|
return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
|
2021-01-05 11:54:09 +08:00
|
|
|
# return self.conv(self.contract(x))
|
|
|
|
|
|
|
|
|
|
|
|
class Contract(nn.Module):
|
|
|
|
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
|
|
|
|
def __init__(self, gain=2):
|
|
|
|
super().__init__()
|
|
|
|
self.gain = gain
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
|
|
|
|
s = self.gain
|
|
|
|
x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2)
|
|
|
|
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
|
|
|
|
return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40)
|
|
|
|
|
|
|
|
|
|
|
|
class Expand(nn.Module):
|
|
|
|
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
|
|
|
|
def __init__(self, gain=2):
|
|
|
|
super().__init__()
|
|
|
|
self.gain = gain
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
|
|
|
|
s = self.gain
|
|
|
|
x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80)
|
|
|
|
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
|
|
|
|
return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160)
|
2020-05-30 08:04:54 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Concat(nn.Module):
|
|
|
|
# Concatenate a list of tensors along dimension
|
|
|
|
def __init__(self, dimension=1):
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-05-30 08:04:54 +08:00
|
|
|
self.d = dimension
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return torch.cat(x, self.d)
|
2020-07-17 08:18:41 +08:00
|
|
|
|
|
|
|
|
2021-05-16 21:46:45 +08:00
|
|
|
class AutoShape(nn.Module):
|
2021-07-12 21:54:43 +08:00
|
|
|
# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
|
2020-10-16 02:10:08 +08:00
|
|
|
conf = 0.25 # NMS confidence threshold
|
|
|
|
iou = 0.45 # NMS IoU threshold
|
|
|
|
classes = None # (optional list) filter by class
|
2021-05-18 04:47:44 +08:00
|
|
|
max_det = 1000 # maximum number of detections per image
|
2020-10-16 02:10:08 +08:00
|
|
|
|
|
|
|
def __init__(self, model):
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-11-17 06:09:55 +08:00
|
|
|
self.model = model.eval()
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2020-12-27 11:58:26 +08:00
|
|
|
def autoshape(self):
|
2021-07-19 16:43:01 +08:00
|
|
|
LOGGER.info('AutoShape already enabled, skipping... ') # model already converted to model.autoshape()
|
2020-12-27 11:58:26 +08:00
|
|
|
return self
|
|
|
|
|
2021-04-07 22:28:07 +08:00
|
|
|
@torch.no_grad()
|
2020-11-17 06:09:55 +08:00
|
|
|
def forward(self, imgs, size=640, augment=False, profile=False):
|
2021-04-07 22:28:07 +08:00
|
|
|
# Inference from various sources. For height=640, width=1280, RGB images example inputs are:
|
2021-07-18 21:25:37 +08:00
|
|
|
# filename: imgs = 'data/images/zidane.jpg' # str or PosixPath
|
|
|
|
# URI: = 'https://ultralytics.com/images/zidane.jpg'
|
2021-04-07 22:28:07 +08:00
|
|
|
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
|
|
|
|
# PIL: = Image.open('image.jpg') # HWC x(640,1280,3)
|
|
|
|
# numpy: = np.zeros((640,1280,3)) # HWC
|
|
|
|
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
|
2020-12-27 11:58:26 +08:00
|
|
|
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2021-07-19 16:43:01 +08:00
|
|
|
t = [time_sync()]
|
2020-10-16 02:10:08 +08:00
|
|
|
p = next(self.model.parameters()) # for device and type
|
2020-11-17 06:09:55 +08:00
|
|
|
if isinstance(imgs, torch.Tensor): # torch
|
2021-04-10 00:19:49 +08:00
|
|
|
with amp.autocast(enabled=p.device.type != 'cpu'):
|
|
|
|
return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
|
2020-10-16 02:10:08 +08:00
|
|
|
|
|
|
|
# Pre-process
|
2020-12-27 11:58:26 +08:00
|
|
|
n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
|
2021-02-13 07:37:51 +08:00
|
|
|
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
|
2020-12-27 11:58:26 +08:00
|
|
|
for i, im in enumerate(imgs):
|
2021-04-06 04:20:09 +08:00
|
|
|
f = f'image{i}' # filename
|
2021-07-18 21:25:37 +08:00
|
|
|
if isinstance(im, (str, PosixPath)): # filename or uri
|
|
|
|
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
|
2021-07-02 19:25:54 +08:00
|
|
|
im = np.asarray(exif_transpose(im))
|
2021-04-06 04:20:09 +08:00
|
|
|
elif isinstance(im, Image.Image): # PIL Image
|
2021-07-07 22:13:12 +08:00
|
|
|
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
|
2021-04-06 04:20:09 +08:00
|
|
|
files.append(Path(f).with_suffix('.jpg').name)
|
2020-12-27 11:58:26 +08:00
|
|
|
if im.shape[0] < 5: # image in CHW
|
|
|
|
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
|
2021-07-05 02:12:32 +08:00
|
|
|
im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
|
2020-12-27 11:58:26 +08:00
|
|
|
s = im.shape[:2] # HWC
|
2020-10-16 02:10:08 +08:00
|
|
|
shape0.append(s) # image shape
|
|
|
|
g = (size / max(s)) # gain
|
|
|
|
shape1.append([y * g for y in s])
|
2021-04-18 19:47:40 +08:00
|
|
|
imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
|
2020-10-16 02:10:08 +08:00
|
|
|
shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
|
2020-12-27 11:58:26 +08:00
|
|
|
x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
|
|
|
|
x = np.stack(x, 0) if n > 1 else x[0][None] # stack
|
2020-10-16 02:10:08 +08:00
|
|
|
x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
|
|
|
|
x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
|
2021-07-19 16:43:01 +08:00
|
|
|
t.append(time_sync())
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2021-04-10 00:19:49 +08:00
|
|
|
with amp.autocast(enabled=p.device.type != 'cpu'):
|
|
|
|
# Inference
|
|
|
|
y = self.model(x, augment, profile)[0] # forward
|
2021-07-19 16:43:01 +08:00
|
|
|
t.append(time_sync())
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2021-04-10 00:19:49 +08:00
|
|
|
# Post-process
|
2021-05-18 04:47:44 +08:00
|
|
|
y = non_max_suppression(y, self.conf, iou_thres=self.iou, classes=self.classes, max_det=self.max_det) # NMS
|
2021-04-10 00:19:49 +08:00
|
|
|
for i in range(n):
|
|
|
|
scale_coords(shape1, y[i][:, :4], shape0[i])
|
2020-11-17 06:09:55 +08:00
|
|
|
|
2021-07-19 16:43:01 +08:00
|
|
|
t.append(time_sync())
|
2021-04-10 00:19:49 +08:00
|
|
|
return Detections(imgs, y, files, t, self.names, x.shape)
|
2020-11-17 06:09:55 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Detections:
|
2021-07-12 21:54:43 +08:00
|
|
|
# YOLOv5 detections class for inference results
|
2021-03-23 21:10:47 +08:00
|
|
|
def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-12-09 23:44:06 +08:00
|
|
|
d = pred[0].device # device
|
|
|
|
gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
|
2020-11-17 06:09:55 +08:00
|
|
|
self.imgs = imgs # list of images as numpy arrays
|
|
|
|
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
|
|
|
|
self.names = names # class names
|
2021-02-13 07:37:51 +08:00
|
|
|
self.files = files # image filenames
|
2020-11-17 06:09:55 +08:00
|
|
|
self.xyxy = pred # xyxy pixels
|
|
|
|
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
|
|
|
|
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
|
|
|
|
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
|
2021-03-27 04:19:15 +08:00
|
|
|
self.n = len(self.pred) # number of images (batch size)
|
2021-03-26 20:23:11 +08:00
|
|
|
self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
|
2021-03-14 11:50:34 +08:00
|
|
|
self.s = shape # inference BCHW shape
|
2020-11-17 06:09:55 +08:00
|
|
|
|
2021-04-21 05:51:08 +08:00
|
|
|
def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
|
|
|
|
for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
|
|
|
|
str = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '
|
2021-07-13 01:48:47 +08:00
|
|
|
if pred.shape[0]:
|
2020-11-17 06:09:55 +08:00
|
|
|
for c in pred[:, -1].unique():
|
|
|
|
n = (pred[:, -1] == c).sum() # detections per class
|
2021-01-23 07:39:08 +08:00
|
|
|
str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
|
2021-04-21 05:51:08 +08:00
|
|
|
if show or save or render or crop:
|
2021-06-30 21:10:40 +08:00
|
|
|
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
|
2021-02-20 04:38:05 +08:00
|
|
|
label = f'{self.names[int(cls)]} {conf:.2f}'
|
2021-04-21 05:51:08 +08:00
|
|
|
if crop:
|
|
|
|
save_one_box(box, im, file=save_dir / 'crops' / self.names[int(cls)] / self.files[i])
|
|
|
|
else: # all others
|
2021-04-28 22:05:14 +08:00
|
|
|
plot_one_box(box, im, label=label, color=colors(cls))
|
2021-07-13 01:48:47 +08:00
|
|
|
else:
|
|
|
|
str += '(no detections)'
|
2021-04-21 05:51:08 +08:00
|
|
|
|
|
|
|
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
|
2021-01-11 12:06:11 +08:00
|
|
|
if pprint:
|
2021-07-19 16:43:01 +08:00
|
|
|
LOGGER.info(str.rstrip(', '))
|
2021-01-11 12:06:11 +08:00
|
|
|
if show:
|
2021-04-21 05:51:08 +08:00
|
|
|
im.show(self.files[i]) # show
|
2020-11-17 06:09:55 +08:00
|
|
|
if save:
|
2021-04-02 17:55:10 +08:00
|
|
|
f = self.files[i]
|
2021-04-21 05:51:08 +08:00
|
|
|
im.save(save_dir / f) # save
|
2021-07-19 16:43:01 +08:00
|
|
|
if i == self.n - 1:
|
|
|
|
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to '{save_dir}'")
|
2021-01-11 12:06:11 +08:00
|
|
|
if render:
|
2021-04-21 05:51:08 +08:00
|
|
|
self.imgs[i] = np.asarray(im)
|
2020-11-17 06:09:55 +08:00
|
|
|
|
|
|
|
def print(self):
|
|
|
|
self.display(pprint=True) # print results
|
2021-07-19 16:43:01 +08:00
|
|
|
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
|
|
|
|
self.t)
|
2020-11-17 06:09:55 +08:00
|
|
|
|
|
|
|
def show(self):
|
|
|
|
self.display(show=True) # show results
|
|
|
|
|
2021-07-19 16:43:01 +08:00
|
|
|
def save(self, save_dir='runs/detect/exp'):
|
|
|
|
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
|
2021-02-11 08:10:43 +08:00
|
|
|
self.display(save=True, save_dir=save_dir) # save results
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2021-07-19 16:43:01 +08:00
|
|
|
def crop(self, save_dir='runs/detect/exp'):
|
|
|
|
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
|
2021-04-21 05:51:08 +08:00
|
|
|
self.display(crop=True, save_dir=save_dir) # crop results
|
2021-07-19 16:43:01 +08:00
|
|
|
LOGGER.info(f'Saved results to {save_dir}\n')
|
2021-04-21 05:51:08 +08:00
|
|
|
|
2021-01-11 12:06:11 +08:00
|
|
|
def render(self):
|
|
|
|
self.display(render=True) # render results
|
|
|
|
return self.imgs
|
|
|
|
|
2021-04-07 22:28:07 +08:00
|
|
|
def pandas(self):
|
|
|
|
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
|
|
|
|
new = copy(self) # return copy
|
|
|
|
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
|
|
|
|
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
|
|
|
|
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
|
|
|
|
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
|
|
|
|
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
|
|
|
|
return new
|
2020-11-19 05:50:21 +08:00
|
|
|
|
|
|
|
def tolist(self):
|
|
|
|
# return a list of Detections objects, i.e. 'for result in results.tolist():'
|
2021-04-07 22:28:07 +08:00
|
|
|
x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
|
2020-11-19 05:50:21 +08:00
|
|
|
for d in x:
|
|
|
|
for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
|
|
|
|
setattr(d, k, getattr(d, k)[0]) # pop out of list
|
|
|
|
return x
|
|
|
|
|
2021-04-07 22:28:07 +08:00
|
|
|
def __len__(self):
|
|
|
|
return self.n
|
|
|
|
|
2020-10-16 02:10:08 +08:00
|
|
|
|
2020-07-17 08:18:41 +08:00
|
|
|
class Classify(nn.Module):
|
|
|
|
# Classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-07-17 08:18:41 +08:00
|
|
|
self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
|
2020-12-04 22:06:33 +08:00
|
|
|
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
|
2021-01-05 11:54:09 +08:00
|
|
|
self.flat = nn.Flatten()
|
2020-07-17 08:18:41 +08:00
|
|
|
|
|
|
|
def forward(self, x):
|
2020-07-17 14:59:51 +08:00
|
|
|
z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
|
|
|
|
return self.flat(self.conv(z)) # flatten to x(b,c2)
|