|
import math
|
|
import torch
|
|
import torch.nn as nn
|
|
import torch.nn.functional as F
|
|
import cv2
|
|
import numpy as np
|
|
import time
|
|
import torchvision
|
|
|
|
def scale_img(img, ratio=1.0, same_shape=False, gs=32):
|
|
|
|
if ratio == 1.0:
|
|
return img
|
|
else:
|
|
h, w = img.shape[2:]
|
|
s = (int(h * ratio), int(w * ratio))
|
|
img = F.interpolate(img, size=s, mode='bilinear', align_corners=False)
|
|
if not same_shape:
|
|
h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
|
|
return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447)
|
|
|
|
def fuse_conv_and_bn(conv, bn):
|
|
|
|
fusedconv = nn.Conv2d(conv.in_channels,
|
|
conv.out_channels,
|
|
kernel_size=conv.kernel_size,
|
|
stride=conv.stride,
|
|
padding=conv.padding,
|
|
groups=conv.groups,
|
|
bias=True).requires_grad_(False).to(conv.weight.device)
|
|
|
|
|
|
w_conv = conv.weight.clone().view(conv.out_channels, -1)
|
|
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
|
|
fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
|
|
|
|
|
|
b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
|
|
b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
|
|
fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
|
|
|
|
return fusedconv
|
|
|
|
def check_anchor_order(m):
|
|
|
|
a = m.anchors.prod(-1).view(-1)
|
|
da = a[-1] - a[0]
|
|
ds = m.stride[-1] - m.stride[0]
|
|
if da.sign() != ds.sign():
|
|
m.anchors[:] = m.anchors.flip(0)
|
|
|
|
def initialize_weights(model):
|
|
for m in model.modules():
|
|
t = type(m)
|
|
if t is nn.Conv2d:
|
|
pass
|
|
elif t is nn.BatchNorm2d:
|
|
m.eps = 1e-3
|
|
m.momentum = 0.03
|
|
elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
|
|
m.inplace = True
|
|
|
|
def make_divisible(x, divisor):
|
|
|
|
if isinstance(divisor, torch.Tensor):
|
|
divisor = int(divisor.max())
|
|
return math.ceil(x / divisor) * divisor
|
|
|
|
def intersect_dicts(da, db, exclude=()):
|
|
|
|
return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
|
|
|
|
def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False):
|
|
|
|
from packaging import version
|
|
current, minimum = (version.parse(x) for x in (current, minimum))
|
|
result = (current == minimum) if pinned else (current >= minimum)
|
|
if hard:
|
|
assert result, f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed'
|
|
else:
|
|
return result
|
|
|
|
class Colors:
|
|
|
|
def __init__(self):
|
|
|
|
hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
|
|
'2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
|
|
self.palette = [self.hex2rgb('#' + c) for c in hex]
|
|
self.n = len(self.palette)
|
|
|
|
def __call__(self, i, bgr=False):
|
|
c = self.palette[int(i) % self.n]
|
|
return (c[2], c[1], c[0]) if bgr else c
|
|
|
|
@staticmethod
|
|
def hex2rgb(h):
|
|
return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
|
|
|
|
def box_iou(box1, box2):
|
|
|
|
"""
|
|
Return intersection-over-union (Jaccard index) of boxes.
|
|
Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
|
|
Arguments:
|
|
box1 (Tensor[N, 4])
|
|
box2 (Tensor[M, 4])
|
|
Returns:
|
|
iou (Tensor[N, M]): the NxM matrix containing the pairwise
|
|
IoU values for every element in boxes1 and boxes2
|
|
"""
|
|
|
|
def box_area(box):
|
|
|
|
return (box[2] - box[0]) * (box[3] - box[1])
|
|
|
|
area1 = box_area(box1.T)
|
|
area2 = box_area(box2.T)
|
|
|
|
|
|
inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
|
|
return inter / (area1[:, None] + area2 - inter)
|
|
|
|
def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
|
|
labels=(), max_det=300):
|
|
"""Runs Non-Maximum Suppression (NMS) on inference results
|
|
|
|
Returns:
|
|
list of detections, on (n,6) tensor per image [xyxy, conf, cls]
|
|
"""
|
|
|
|
if isinstance(prediction, np.ndarray):
|
|
prediction = torch.from_numpy(prediction)
|
|
|
|
nc = prediction.shape[2] - 5
|
|
xc = prediction[..., 4] > conf_thres
|
|
|
|
|
|
assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
|
|
assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
|
|
|
|
|
|
min_wh, max_wh = 2, 4096
|
|
max_nms = 30000
|
|
time_limit = 10.0
|
|
redundant = True
|
|
multi_label &= nc > 1
|
|
merge = False
|
|
|
|
t = time.time()
|
|
output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
|
|
for xi, x in enumerate(prediction):
|
|
|
|
|
|
x = x[xc[xi]]
|
|
|
|
|
|
if labels and len(labels[xi]):
|
|
l = labels[xi]
|
|
v = torch.zeros((len(l), nc + 5), device=x.device)
|
|
v[:, :4] = l[:, 1:5]
|
|
v[:, 4] = 1.0
|
|
v[range(len(l)), l[:, 0].long() + 5] = 1.0
|
|
x = torch.cat((x, v), 0)
|
|
|
|
|
|
if not x.shape[0]:
|
|
continue
|
|
|
|
|
|
x[:, 5:] *= x[:, 4:5]
|
|
|
|
|
|
box = xywh2xyxy(x[:, :4])
|
|
|
|
|
|
if multi_label:
|
|
i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
|
|
x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
|
|
else:
|
|
conf, j = x[:, 5:].max(1, keepdim=True)
|
|
x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
|
|
|
|
|
|
if classes is not None:
|
|
x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
n = x.shape[0]
|
|
if not n:
|
|
continue
|
|
elif n > max_nms:
|
|
x = x[x[:, 4].argsort(descending=True)[:max_nms]]
|
|
|
|
|
|
c = x[:, 5:6] * (0 if agnostic else max_wh)
|
|
boxes, scores = x[:, :4] + c, x[:, 4]
|
|
i = torchvision.ops.nms(boxes, scores, iou_thres)
|
|
if i.shape[0] > max_det:
|
|
i = i[:max_det]
|
|
if merge and (1 < n < 3E3):
|
|
|
|
iou = box_iou(boxes[i], boxes) > iou_thres
|
|
weights = iou * scores[None]
|
|
x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)
|
|
if redundant:
|
|
i = i[iou.sum(1) > 1]
|
|
|
|
output[xi] = x[i]
|
|
if (time.time() - t) > time_limit:
|
|
print(f'WARNING: NMS time limit {time_limit}s exceeded')
|
|
break
|
|
|
|
return output
|
|
|
|
def xywh2xyxy(x):
|
|
|
|
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
|
|
y[:, 0] = x[:, 0] - x[:, 2] / 2
|
|
y[:, 1] = x[:, 1] - x[:, 3] / 2
|
|
y[:, 2] = x[:, 0] + x[:, 2] / 2
|
|
y[:, 3] = x[:, 1] + x[:, 3] / 2
|
|
return y
|
|
|
|
DEFAULT_LANG_LIST = ['eng', 'ja']
|
|
def draw_bbox(pred, img, lang_list=None):
|
|
if lang_list is None:
|
|
lang_list = DEFAULT_LANG_LIST
|
|
lw = max(round(sum(img.shape) / 2 * 0.003), 2)
|
|
pred = pred.astype(np.int32)
|
|
colors = Colors()
|
|
img = np.copy(img)
|
|
for ii, obj in enumerate(pred):
|
|
p1, p2 = (obj[0], obj[1]), (obj[2], obj[3])
|
|
label = lang_list[obj[-1]] + str(ii+1)
|
|
cv2.rectangle(img, p1, p2, colors(obj[-1], bgr=True), lw, lineType=cv2.LINE_AA)
|
|
t_w, t_h = cv2.getTextSize(label, 0, fontScale=lw / 3, thickness=lw)[0]
|
|
cv2.putText(img, label, (p1[0], p1[1] + t_h + 2), 0, lw / 3, colors(obj[-1], bgr=True), max(lw-1, 1), cv2.LINE_AA)
|
|
return img |