2018-08-26 08:51:39 +00:00
|
|
|
import random
|
|
|
|
|
|
|
|
import cv2
|
|
|
|
import numpy as np
|
|
|
|
import torch
|
|
|
|
import torch.nn.functional as F
|
|
|
|
|
2018-12-05 10:55:27 +00:00
|
|
|
from utils import torch_utils
|
|
|
|
|
2018-09-02 09:15:39 +00:00
|
|
|
# Set printoptions
|
2018-08-26 08:51:39 +00:00
|
|
|
torch.set_printoptions(linewidth=1320, precision=5, profile='long')
|
2018-10-03 11:55:56 +00:00
|
|
|
np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
2018-12-05 10:55:27 +00:00
|
|
|
def init_seeds(seed=0):
|
|
|
|
random.seed(seed)
|
|
|
|
np.random.seed(seed)
|
|
|
|
torch_utils.init_seeds(seed=seed)
|
|
|
|
|
|
|
|
|
2018-08-26 08:51:39 +00:00
|
|
|
def load_classes(path):
|
|
|
|
"""
|
|
|
|
Loads class labels at 'path'
|
|
|
|
"""
|
2019-01-06 20:54:04 +00:00
|
|
|
fp = open(path, 'r')
|
2018-12-28 20:12:31 +00:00
|
|
|
names = fp.read().split('\n')
|
|
|
|
return list(filter(None, names)) # filter removes empty strings (such as last line)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
2018-10-10 14:16:17 +00:00
|
|
|
def model_info(model): # Plots a line-by-line description of a PyTorch model
|
2018-11-22 12:52:22 +00:00
|
|
|
n_p = sum(x.numel() for x in model.parameters()) # number parameters
|
|
|
|
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
|
2018-11-23 14:32:41 +00:00
|
|
|
print('\n%5s %50s %9s %12s %20s %12s %12s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
|
2018-08-26 08:51:39 +00:00
|
|
|
for i, (name, p) in enumerate(model.named_parameters()):
|
|
|
|
name = name.replace('module_list.', '')
|
2018-12-11 20:49:56 +00:00
|
|
|
print('%5g %50s %9s %12g %20s %12.3g %12.3g' % (
|
2018-08-26 08:51:39 +00:00
|
|
|
i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
|
2018-11-23 14:32:41 +00:00
|
|
|
print('Model Summary: %g layers, %g parameters, %g gradients\n' % (i + 1, n_p, n_g))
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
2018-10-10 14:16:17 +00:00
|
|
|
def class_weights(): # frequency of each class in coco train2014
|
2018-08-26 08:51:39 +00:00
|
|
|
weights = 1 / torch.FloatTensor(
|
2018-10-10 14:16:17 +00:00
|
|
|
[187437, 4955, 30920, 6033, 3838, 4332, 3160, 7051, 7677, 9167, 1316, 1372, 833, 6757, 7355, 3302, 3776, 4671,
|
|
|
|
6769, 5706, 3908, 903, 3686, 3596, 6200, 7920, 8779, 4505, 4272, 1862, 4698, 1962, 4403, 6659, 2402, 2689,
|
|
|
|
4012, 4175, 3411, 17048, 5637, 14553, 3923, 5539, 4289, 10084, 7018, 4314, 3099, 4638, 4939, 5543, 2038, 4004,
|
|
|
|
5053, 4578, 27292, 4113, 5931, 2905, 11174, 2873, 4036, 3415, 1517, 4122, 1980, 4464, 1190, 2302, 156, 3933,
|
|
|
|
1877, 17630, 4337, 4624, 1075, 3468, 135, 1380])
|
2018-08-26 08:51:39 +00:00
|
|
|
weights /= weights.sum()
|
2018-10-10 14:16:17 +00:00
|
|
|
return weights
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
2018-09-02 09:15:39 +00:00
|
|
|
def plot_one_box(x, img, color=None, label=None, line_thickness=None): # Plots one bounding box on image img
|
2018-09-08 12:46:22 +00:00
|
|
|
tl = line_thickness or round(0.002 * max(img.shape[0:2])) + 1 # line thickness
|
2018-08-26 08:51:39 +00:00
|
|
|
color = color or [random.randint(0, 255) for _ in range(3)]
|
|
|
|
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
|
2018-09-02 09:15:39 +00:00
|
|
|
cv2.rectangle(img, c1, c2, color, thickness=tl)
|
2018-08-26 08:51:39 +00:00
|
|
|
if label:
|
|
|
|
tf = max(tl - 1, 1) # font thickness
|
|
|
|
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
|
|
|
|
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
|
2018-09-02 09:15:39 +00:00
|
|
|
cv2.rectangle(img, c1, c2, color, -1) # filled
|
|
|
|
cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
def weights_init_normal(m):
|
|
|
|
classname = m.__class__.__name__
|
|
|
|
if classname.find('Conv') != -1:
|
|
|
|
torch.nn.init.normal_(m.weight.data, 0.0, 0.03)
|
|
|
|
elif classname.find('BatchNorm2d') != -1:
|
|
|
|
torch.nn.init.normal_(m.weight.data, 1.0, 0.03)
|
|
|
|
torch.nn.init.constant_(m.bias.data, 0.0)
|
|
|
|
|
|
|
|
|
2019-02-10 20:01:49 +00:00
|
|
|
def xyxy2xywh(x):
|
|
|
|
# Convert bounding box format from [x1, y1, x2, y2] to [x, y, w, h]
|
2018-09-02 09:26:56 +00:00
|
|
|
y = torch.zeros(x.shape) if x.dtype is torch.float32 else np.zeros(x.shape)
|
2018-09-02 09:15:39 +00:00
|
|
|
y[:, 0] = (x[:, 0] + x[:, 2]) / 2
|
|
|
|
y[:, 1] = (x[:, 1] + x[:, 3]) / 2
|
|
|
|
y[:, 2] = x[:, 2] - x[:, 0]
|
|
|
|
y[:, 3] = x[:, 3] - x[:, 1]
|
|
|
|
return y
|
|
|
|
|
|
|
|
|
2019-02-10 20:01:49 +00:00
|
|
|
def xywh2xyxy(x):
|
|
|
|
# Convert bounding box format from [x, y, w, h] to [x1, y1, x2, y2]
|
2018-09-02 09:26:56 +00:00
|
|
|
y = torch.zeros(x.shape) if x.dtype is torch.float32 else np.zeros(x.shape)
|
|
|
|
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)
|
2018-09-02 09:15:39 +00:00
|
|
|
return y
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
2019-02-10 20:01:49 +00:00
|
|
|
def scale_coords(img_size, coords, img0_shape):
|
|
|
|
# Rescale x1, y1, x2, y2 from 416 to image size
|
|
|
|
gain = float(img_size) / max(img0_shape) # gain = old / new
|
|
|
|
pad_x = (img_size - img0_shape[1] * gain) / 2 # width padding
|
|
|
|
pad_y = (img_size - img0_shape[0] * gain) / 2 # height padding
|
|
|
|
coords[:, [0, 2]] -= pad_x
|
|
|
|
coords[:, [1, 3]] -= pad_y
|
|
|
|
coords[:, :4] /= gain
|
|
|
|
coords[:, :4] = torch.round(torch.clamp(coords[:, :4], min=0))
|
|
|
|
return coords
|
|
|
|
|
|
|
|
|
2018-09-10 13:12:13 +00:00
|
|
|
def ap_per_class(tp, conf, pred_cls, target_cls):
|
|
|
|
""" Compute the average precision, given the recall and precision curves.
|
|
|
|
Method originally from https://github.com/rafaelpadilla/Object-Detection-Metrics.
|
|
|
|
# Arguments
|
|
|
|
tp: True positives (list).
|
|
|
|
conf: Objectness value from 0-1 (list).
|
|
|
|
pred_cls: Predicted object classes (list).
|
|
|
|
target_cls: True object classes (list).
|
|
|
|
# Returns
|
|
|
|
The average precision as computed in py-faster-rcnn.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# lists/pytorch to numpy
|
|
|
|
tp, conf, pred_cls, target_cls = np.array(tp), np.array(conf), np.array(pred_cls), np.array(target_cls)
|
|
|
|
|
|
|
|
# Sort by objectness
|
|
|
|
i = np.argsort(-conf)
|
|
|
|
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
|
|
|
|
|
|
|
|
# Find unique classes
|
2018-09-10 14:41:02 +00:00
|
|
|
unique_classes = np.unique(np.concatenate((pred_cls, target_cls), 0))
|
2018-09-10 13:12:13 +00:00
|
|
|
|
|
|
|
# Create Precision-Recall curve and compute AP for each class
|
2018-11-22 12:52:22 +00:00
|
|
|
ap, p, r = [], [], []
|
2018-09-10 13:12:13 +00:00
|
|
|
for c in unique_classes:
|
|
|
|
i = pred_cls == c
|
2018-09-10 13:50:37 +00:00
|
|
|
n_gt = sum(target_cls == c) # Number of ground truth objects
|
2018-09-10 14:31:56 +00:00
|
|
|
n_p = sum(i) # Number of predicted objects
|
2018-09-10 13:12:13 +00:00
|
|
|
|
2018-09-10 14:31:56 +00:00
|
|
|
if (n_p == 0) and (n_gt == 0):
|
|
|
|
continue
|
2018-11-22 12:52:22 +00:00
|
|
|
elif (n_p == 0) or (n_gt == 0):
|
2018-09-10 13:12:13 +00:00
|
|
|
ap.append(0)
|
2018-11-22 12:52:22 +00:00
|
|
|
r.append(0)
|
|
|
|
p.append(0)
|
2018-09-10 13:12:13 +00:00
|
|
|
else:
|
|
|
|
# Accumulate FPs and TPs
|
2018-11-22 12:52:22 +00:00
|
|
|
fpc = np.cumsum(1 - tp[i])
|
|
|
|
tpc = np.cumsum(tp[i])
|
2018-09-10 13:12:13 +00:00
|
|
|
|
|
|
|
# Recall
|
2018-11-22 12:52:22 +00:00
|
|
|
recall_curve = tpc / (n_gt + 1e-16)
|
|
|
|
r.append(tpc[-1] / (n_gt + 1e-16))
|
2018-09-10 13:12:13 +00:00
|
|
|
|
|
|
|
# Precision
|
2018-11-22 12:52:22 +00:00
|
|
|
precision_curve = tpc / (tpc + fpc)
|
|
|
|
p.append(tpc[-1] / (tpc[-1] + fpc[-1]))
|
2018-09-10 13:12:13 +00:00
|
|
|
|
|
|
|
# AP from recall-precision curve
|
2018-11-22 12:52:22 +00:00
|
|
|
ap.append(compute_ap(recall_curve, precision_curve))
|
2018-09-10 13:12:13 +00:00
|
|
|
|
2018-11-22 12:52:22 +00:00
|
|
|
return np.array(ap), unique_classes.astype('int32'), np.array(r), np.array(p)
|
2018-09-10 13:12:13 +00:00
|
|
|
|
|
|
|
|
2018-08-26 08:51:39 +00:00
|
|
|
def compute_ap(recall, precision):
|
|
|
|
""" Compute the average precision, given the recall and precision curves.
|
|
|
|
Code originally from https://github.com/rbgirshick/py-faster-rcnn.
|
|
|
|
# Arguments
|
|
|
|
recall: The recall curve (list).
|
|
|
|
precision: The precision curve (list).
|
|
|
|
# Returns
|
|
|
|
The average precision as computed in py-faster-rcnn.
|
|
|
|
"""
|
|
|
|
# correct AP calculation
|
|
|
|
# first append sentinel values at the end
|
2018-09-10 13:12:13 +00:00
|
|
|
|
2018-08-26 08:51:39 +00:00
|
|
|
mrec = np.concatenate(([0.], recall, [1.]))
|
|
|
|
mpre = np.concatenate(([0.], precision, [0.]))
|
|
|
|
|
|
|
|
# compute the precision envelope
|
|
|
|
for i in range(mpre.size - 1, 0, -1):
|
|
|
|
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
|
|
|
|
|
|
|
|
# to calculate area under PR curve, look for points
|
|
|
|
# where X axis (recall) changes value
|
|
|
|
i = np.where(mrec[1:] != mrec[:-1])[0]
|
|
|
|
|
|
|
|
# and sum (\Delta recall) * prec
|
|
|
|
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
|
|
|
|
return ap
|
|
|
|
|
|
|
|
|
|
|
|
def bbox_iou(box1, box2, x1y1x2y2=True):
|
|
|
|
"""
|
|
|
|
Returns the IoU of two bounding boxes
|
|
|
|
"""
|
|
|
|
if x1y1x2y2:
|
|
|
|
# Get the coordinates of bounding boxes
|
|
|
|
b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]
|
|
|
|
b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]
|
|
|
|
else:
|
|
|
|
# Transform from center and width to exact coordinates
|
|
|
|
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
|
|
|
|
b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
|
|
|
|
b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
|
|
|
|
b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
|
|
|
|
|
2018-10-10 14:16:17 +00:00
|
|
|
# get the coordinates of the intersection rectangle
|
2018-08-26 08:51:39 +00:00
|
|
|
inter_rect_x1 = torch.max(b1_x1, b2_x1)
|
|
|
|
inter_rect_y1 = torch.max(b1_y1, b2_y1)
|
|
|
|
inter_rect_x2 = torch.min(b1_x2, b2_x2)
|
|
|
|
inter_rect_y2 = torch.min(b1_y2, b2_y2)
|
|
|
|
# Intersection area
|
|
|
|
inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1, 0) * torch.clamp(inter_rect_y2 - inter_rect_y1, 0)
|
|
|
|
# Union Area
|
|
|
|
b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
|
|
|
|
b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
|
|
|
|
|
|
|
|
return inter_area / (b1_area + b2_area - inter_area + 1e-16)
|
|
|
|
|
|
|
|
|
2019-02-10 21:01:53 +00:00
|
|
|
def build_targets(target, anchor_wh, nA, nC, nG):
|
2018-08-26 08:51:39 +00:00
|
|
|
"""
|
2018-09-19 02:32:16 +00:00
|
|
|
returns nT, nCorrect, tx, ty, tw, th, tconf, tcls
|
2018-08-26 08:51:39 +00:00
|
|
|
"""
|
2018-10-10 14:16:17 +00:00
|
|
|
nB = len(target) # number of images in batch
|
2018-08-26 08:51:39 +00:00
|
|
|
nT = [len(x) for x in target] # torch.argmin(target[:, :, 4], 1) # targets per image
|
|
|
|
tx = torch.zeros(nB, nA, nG, nG) # batch size (4), number of anchors (3), number of grid points (13)
|
|
|
|
ty = torch.zeros(nB, nA, nG, nG)
|
|
|
|
tw = torch.zeros(nB, nA, nG, nG)
|
|
|
|
th = torch.zeros(nB, nA, nG, nG)
|
|
|
|
tconf = torch.ByteTensor(nB, nA, nG, nG).fill_(0)
|
|
|
|
tcls = torch.ByteTensor(nB, nA, nG, nG, nC).fill_(0) # nC = number of classes
|
|
|
|
|
|
|
|
for b in range(nB):
|
|
|
|
nTb = nT[b] # number of targets
|
|
|
|
if nTb == 0:
|
|
|
|
continue
|
|
|
|
t = target[b]
|
|
|
|
|
|
|
|
# Convert to position relative to box
|
2019-02-10 22:27:31 +00:00
|
|
|
gx, gy, gw, gh = t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG
|
|
|
|
|
2018-08-26 08:51:39 +00:00
|
|
|
# Get grid box indices and prevent overflows (i.e. 13.01 on 13 anchors)
|
|
|
|
gi = torch.clamp(gx.long(), min=0, max=nG - 1)
|
|
|
|
gj = torch.clamp(gy.long(), min=0, max=nG - 1)
|
|
|
|
|
|
|
|
# iou of targets-anchors (using wh only)
|
|
|
|
box1 = t[:, 3:5] * nG
|
2019-01-01 16:52:45 +00:00
|
|
|
box2 = anchor_wh.unsqueeze(1)
|
2018-08-26 08:51:39 +00:00
|
|
|
inter_area = torch.min(box1, box2).prod(2)
|
2019-01-01 16:52:45 +00:00
|
|
|
iou = inter_area / (gw * gh + box2.prod(2) - inter_area + 1e-16)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
# Select best iou_pred and anchor
|
2019-01-01 16:52:45 +00:00
|
|
|
iou_best, a = iou.max(0) # best anchor [0-2] for each target
|
2018-08-26 08:51:39 +00:00
|
|
|
|
2018-09-10 13:12:13 +00:00
|
|
|
# Select best unique target-anchor combinations
|
2018-08-26 08:51:39 +00:00
|
|
|
if nTb > 1:
|
2019-01-01 16:52:45 +00:00
|
|
|
iou_order = torch.argsort(-iou_best) # best to worst
|
2018-09-09 14:14:24 +00:00
|
|
|
|
2019-01-01 16:52:45 +00:00
|
|
|
# Unique anchor selection
|
2019-02-11 17:15:51 +00:00
|
|
|
u = torch.cat((gi, gj, a), 0).view((3, -1))
|
2018-09-09 14:14:24 +00:00
|
|
|
_, first_unique = np.unique(u[:, iou_order], axis=1, return_index=True) # first unique indices
|
2019-01-01 16:52:45 +00:00
|
|
|
# _, first_unique = torch.unique(u[:, iou_order], dim=1, return_inverse=True) # different than numpy?
|
2018-09-09 14:14:24 +00:00
|
|
|
|
2018-08-26 08:51:39 +00:00
|
|
|
i = iou_order[first_unique]
|
|
|
|
# best anchor must share significant commonality (iou) with target
|
2019-01-01 16:52:45 +00:00
|
|
|
i = i[iou_best[i] > 0.10]
|
2018-08-26 08:51:39 +00:00
|
|
|
if len(i) == 0:
|
|
|
|
continue
|
|
|
|
|
|
|
|
a, gj, gi, t = a[i], gj[i], gi[i], t[i]
|
|
|
|
if len(t.shape) == 1:
|
|
|
|
t = t.view(1, 5)
|
|
|
|
else:
|
2019-01-01 16:52:45 +00:00
|
|
|
if iou_best < 0.10:
|
2018-08-26 08:51:39 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
tc, gx, gy, gw, gh = t[:, 0].long(), t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG
|
|
|
|
|
|
|
|
# Coordinates
|
|
|
|
tx[b, a, gj, gi] = gx - gi.float()
|
|
|
|
ty[b, a, gj, gi] = gy - gj.float()
|
2018-09-20 16:03:19 +00:00
|
|
|
|
2018-09-23 20:41:36 +00:00
|
|
|
# Width and height (yolo method)
|
2018-11-17 11:54:44 +00:00
|
|
|
tw[b, a, gj, gi] = torch.log(gw / anchor_wh[a, 0])
|
|
|
|
th[b, a, gj, gi] = torch.log(gh / anchor_wh[a, 1])
|
2018-09-20 16:03:19 +00:00
|
|
|
|
2018-09-23 20:41:36 +00:00
|
|
|
# Width and height (power method)
|
2018-11-17 11:54:44 +00:00
|
|
|
# tw[b, a, gj, gi] = torch.sqrt(gw / anchor_wh[a, 0]) / 2
|
|
|
|
# th[b, a, gj, gi] = torch.sqrt(gh / anchor_wh[a, 1]) / 2
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
# One-hot encoding of label
|
|
|
|
tcls[b, a, gj, gi, tc] = 1
|
|
|
|
tconf[b, a, gj, gi] = 1
|
|
|
|
|
2019-02-10 21:01:53 +00:00
|
|
|
return tx, ty, tw, th, tconf, tcls
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
def non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.4):
|
|
|
|
"""
|
|
|
|
Removes detections with lower object confidence score than 'conf_thres' and performs
|
|
|
|
Non-Maximum Suppression to further filter detections.
|
|
|
|
Returns detections with shape:
|
|
|
|
(x1, y1, x2, y2, object_conf, class_score, class_pred)
|
|
|
|
"""
|
|
|
|
|
|
|
|
output = [None for _ in range(len(prediction))]
|
|
|
|
for image_i, pred in enumerate(prediction):
|
|
|
|
# Filter out confidence scores below threshold
|
|
|
|
# Get score and class with highest confidence
|
|
|
|
|
2018-11-22 15:42:58 +00:00
|
|
|
# cross-class NMS (experimental)
|
2018-08-26 08:51:39 +00:00
|
|
|
cross_class_nms = False
|
|
|
|
if cross_class_nms:
|
|
|
|
a = pred.clone()
|
2018-11-23 14:34:49 +00:00
|
|
|
_, indices = torch.sort(-a[:, 4], 0) # sort best to worst
|
2018-11-22 13:36:14 +00:00
|
|
|
a = a[indices]
|
2018-08-26 08:51:39 +00:00
|
|
|
radius = 30 # area to search for cross-class ious
|
|
|
|
for i in range(len(a)):
|
|
|
|
if i >= len(a) - 1:
|
|
|
|
break
|
|
|
|
|
2018-11-22 13:36:14 +00:00
|
|
|
close = (torch.abs(a[i, 0] - a[i + 1:, 0]) < radius) & (torch.abs(a[i, 1] - a[i + 1:, 1]) < radius)
|
2018-08-26 08:51:39 +00:00
|
|
|
close = close.nonzero()
|
|
|
|
|
|
|
|
if len(close) > 0:
|
|
|
|
close = close + i + 1
|
|
|
|
iou = bbox_iou(a[i:i + 1, :4], a[close.squeeze(), :4].reshape(-1, 4), x1y1x2y2=False)
|
2019-01-02 15:32:38 +00:00
|
|
|
bad = close[iou > nms_thres]
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
if len(bad) > 0:
|
|
|
|
mask = torch.ones(len(a)).type(torch.ByteTensor)
|
|
|
|
mask[bad] = 0
|
|
|
|
a = a[mask]
|
|
|
|
pred = a
|
|
|
|
|
2019-01-02 15:32:38 +00:00
|
|
|
# Experiment: Prior class size rejection
|
|
|
|
# x, y, w, h = pred[:, 0], pred[:, 1], pred[:, 2], pred[:, 3]
|
|
|
|
# a = w * h # area
|
|
|
|
# ar = w / (h + 1e-16) # aspect ratio
|
2018-08-26 08:51:39 +00:00
|
|
|
# n = len(w)
|
2019-01-02 15:32:38 +00:00
|
|
|
# log_w, log_h, log_a, log_ar = torch.log(w), torch.log(h), torch.log(a), torch.log(ar)
|
2018-08-26 08:51:39 +00:00
|
|
|
# shape_likelihood = np.zeros((n, 60), dtype=np.float32)
|
|
|
|
# x = np.concatenate((log_w.reshape(-1, 1), log_h.reshape(-1, 1)), 1)
|
|
|
|
# from scipy.stats import multivariate_normal
|
|
|
|
# for c in range(60):
|
2019-02-11 17:15:51 +00:00
|
|
|
# shape_likelihood[:, c] =
|
|
|
|
# multivariate_normal.pdf(x, mean=mat['class_mu'][c, :2], cov=mat['class_cov'][c, :2, :2])
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
class_prob, class_pred = torch.max(F.softmax(pred[:, 5:], 1), 1)
|
|
|
|
|
2019-01-02 15:32:38 +00:00
|
|
|
v = ((pred[:, 4] > conf_thres) & (class_prob > .3)) # TODO examine arbitrary 0.3 thres here
|
2018-11-22 13:36:14 +00:00
|
|
|
v = v.nonzero().squeeze()
|
|
|
|
if len(v.shape) == 0:
|
|
|
|
v = v.unsqueeze(0)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
pred = pred[v]
|
|
|
|
class_prob = class_prob[v]
|
|
|
|
class_pred = class_pred[v]
|
|
|
|
|
|
|
|
# If none are remaining => process next image
|
|
|
|
nP = pred.shape[0]
|
|
|
|
if not nP:
|
|
|
|
continue
|
|
|
|
|
|
|
|
# From (center x, center y, width, height) to (x1, y1, x2, y2)
|
2018-12-19 22:48:52 +00:00
|
|
|
pred[:, :4] = xywh2xyxy(pred[:, :4])
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
# Detections ordered as (x1, y1, x2, y2, obj_conf, class_prob, class_pred)
|
|
|
|
detections = torch.cat((pred[:, :5], class_prob.float().unsqueeze(1), class_pred.float().unsqueeze(1)), 1)
|
|
|
|
# Iterate through all predicted classes
|
|
|
|
unique_labels = detections[:, -1].cpu().unique()
|
|
|
|
if prediction.is_cuda:
|
2018-11-22 13:36:14 +00:00
|
|
|
unique_labels = unique_labels.cuda(prediction.device)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
nms_style = 'OR' # 'AND' or 'OR' (classical)
|
|
|
|
for c in unique_labels:
|
|
|
|
# Get the detections with the particular class
|
2019-01-02 15:32:38 +00:00
|
|
|
det_class = detections[detections[:, -1] == c]
|
2018-08-26 08:51:39 +00:00
|
|
|
# Sort the detections by maximum objectness confidence
|
2019-01-02 15:32:38 +00:00
|
|
|
_, conf_sort_index = torch.sort(det_class[:, 4], descending=True)
|
|
|
|
det_class = det_class[conf_sort_index]
|
2018-08-26 08:51:39 +00:00
|
|
|
# Perform non-maximum suppression
|
2019-01-02 15:32:38 +00:00
|
|
|
det_max = []
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
if nms_style == 'OR': # Classical NMS
|
2019-01-02 15:32:38 +00:00
|
|
|
while det_class.shape[0]:
|
2018-08-26 08:51:39 +00:00
|
|
|
# Get detection with highest confidence and save as max detection
|
2019-01-02 15:32:38 +00:00
|
|
|
det_max.append(det_class[0].unsqueeze(0))
|
2018-08-26 08:51:39 +00:00
|
|
|
# Stop if we're at the last detection
|
2019-01-02 15:32:38 +00:00
|
|
|
if len(det_class) == 1:
|
2018-08-26 08:51:39 +00:00
|
|
|
break
|
|
|
|
# Get the IOUs for all boxes with lower confidence
|
2019-01-02 15:32:38 +00:00
|
|
|
ious = bbox_iou(det_max[-1], det_class[1:])
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
# Remove detections with IoU >= NMS threshold
|
2019-01-02 15:32:38 +00:00
|
|
|
det_class = det_class[1:][ious < nms_thres]
|
2018-08-26 08:51:39 +00:00
|
|
|
|
2019-01-02 15:32:38 +00:00
|
|
|
elif nms_style == 'AND': # 'AND'-style NMS: >=2 boxes must share commonality to pass, single boxes erased
|
|
|
|
while det_class.shape[0]:
|
|
|
|
if len(det_class) == 1:
|
2018-08-26 08:51:39 +00:00
|
|
|
break
|
|
|
|
|
2019-01-02 15:32:38 +00:00
|
|
|
ious = bbox_iou(det_class[:1], det_class[1:])
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
if ious.max() > 0.5:
|
2019-01-02 15:32:38 +00:00
|
|
|
det_max.append(det_class[0].unsqueeze(0))
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
# Remove detections with IoU >= NMS threshold
|
2019-01-02 15:32:38 +00:00
|
|
|
det_class = det_class[1:][ious < nms_thres]
|
2018-08-26 08:51:39 +00:00
|
|
|
|
2019-01-02 15:32:38 +00:00
|
|
|
if len(det_max) > 0:
|
|
|
|
det_max = torch.cat(det_max).data
|
2018-08-26 08:51:39 +00:00
|
|
|
# Add max detections to outputs
|
2019-01-02 15:32:38 +00:00
|
|
|
output[image_i] = det_max if output[image_i] is None else torch.cat((output[image_i], det_max))
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
return output
|
|
|
|
|
|
|
|
|
2018-10-26 22:42:34 +00:00
|
|
|
def strip_optimizer_from_checkpoint(filename='weights/best.pt'):
|
2018-08-26 08:51:39 +00:00
|
|
|
# Strip optimizer from *.pt files for lighter files (reduced by 2/3 size)
|
|
|
|
import torch
|
|
|
|
a = torch.load(filename, map_location='cpu')
|
|
|
|
a['optimizer'] = []
|
|
|
|
torch.save(a, filename.replace('.pt', '_lite.pt'))
|
|
|
|
|
|
|
|
|
2018-12-03 20:08:45 +00:00
|
|
|
def coco_class_count(path='../coco/labels/train2014/'):
|
2019-01-02 15:32:38 +00:00
|
|
|
# histogram of occurrences per class
|
2018-10-10 14:16:17 +00:00
|
|
|
import glob
|
|
|
|
|
|
|
|
nC = 80 # number classes
|
|
|
|
x = np.zeros(nC, dtype='int32')
|
|
|
|
files = sorted(glob.glob('%s/*.*' % path))
|
|
|
|
for i, file in enumerate(files):
|
|
|
|
labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
|
|
|
|
x += np.bincount(labels[:, 0].astype('int32'), minlength=nC)
|
|
|
|
print(i, len(files))
|
|
|
|
|
|
|
|
|
|
|
|
def plot_results():
|
2018-11-22 12:52:22 +00:00
|
|
|
# Plot YOLO training results file 'results.txt'
|
2018-12-03 14:42:10 +00:00
|
|
|
import glob
|
2018-08-26 08:51:39 +00:00
|
|
|
import matplotlib.pyplot as plt
|
2018-12-23 12:46:47 +00:00
|
|
|
# import os; os.system('rm -rf results.txt && wget https://storage.googleapis.com/ultralytics/results_v1_0.txt')
|
2019-01-02 15:32:38 +00:00
|
|
|
|
2018-09-01 11:17:21 +00:00
|
|
|
plt.figure(figsize=(16, 8))
|
2018-11-14 15:14:41 +00:00
|
|
|
s = ['X', 'Y', 'Width', 'Height', 'Objectness', 'Classification', 'Total Loss', 'Precision', 'Recall', 'mAP']
|
2018-12-03 14:42:10 +00:00
|
|
|
files = sorted(glob.glob('results*.txt'))
|
|
|
|
for f in files:
|
2018-11-30 10:56:38 +00:00
|
|
|
results = np.loadtxt(f, usecols=[2, 3, 4, 5, 6, 7, 8, 17, 18, 16]).T # column 16 is mAP
|
2018-12-03 13:12:46 +00:00
|
|
|
n = results.shape[1]
|
2018-11-30 10:56:38 +00:00
|
|
|
for i in range(10):
|
2018-08-26 08:51:39 +00:00
|
|
|
plt.subplot(2, 5, i + 1)
|
2018-12-03 14:42:10 +00:00
|
|
|
plt.plot(range(1, n), results[i, 1:], marker='.', label=f)
|
2018-08-26 08:51:39 +00:00
|
|
|
plt.title(s[i])
|
2018-11-11 17:58:41 +00:00
|
|
|
if i == 0:
|
|
|
|
plt.legend()
|