car-detection-bayes/test.py

303 lines
13 KiB
Python
Raw Normal View History

2018-08-26 08:51:39 +00:00
import argparse
2019-02-26 01:53:11 +00:00
import json
2018-10-10 15:07:21 +00:00
2019-03-21 20:41:12 +00:00
from torch.utils.data import DataLoader
2018-08-26 08:51:39 +00:00
from models import *
from utils.datasets import *
from utils.utils import *
2019-07-15 15:00:04 +00:00
def test(cfg,
2019-07-20 13:10:31 +00:00
data,
2019-07-15 15:00:04 +00:00
weights=None,
batch_size=16,
img_size=416,
conf_thres=0.001,
2020-02-27 19:29:38 +00:00
iou_thres=0.6, # for nms
2019-07-15 15:00:04 +00:00
save_json=False,
2020-01-18 01:58:37 +00:00
single_cls=False,
2020-03-26 18:28:46 +00:00
augment=False,
2019-12-05 07:02:32 +00:00
model=None,
2020-01-18 01:58:37 +00:00
dataloader=None):
2019-07-15 15:00:04 +00:00
# Initialize/load model and set device
if model is None:
2019-11-25 04:29:29 +00:00
device = torch_utils.select_device(opt.device, batch_size=batch_size)
2019-12-24 22:11:31 +00:00
verbose = opt.task == 'test'
2019-12-13 19:05:05 +00:00
# Remove previous
2020-02-26 21:40:17 +00:00
for f in glob.glob('test_batch*.png'):
2019-12-13 19:05:05 +00:00
os.remove(f)
# Initialize model
model = Darknet(cfg, img_size)
2018-11-14 15:14:41 +00:00
# Load weights
2019-09-19 16:05:04 +00:00
attempt_download(weights)
if weights.endswith('.pt'): # pytorch format
model.load_state_dict(torch.load(weights, map_location=device)['model'])
else: # darknet format
2020-01-17 18:55:30 +00:00
load_darknet_weights(model, weights)
2018-11-14 15:14:41 +00:00
# Fuse
model.fuse()
model.to(device)
2020-03-09 20:33:23 +00:00
if device.type != 'cpu' and torch.cuda.device_count() > 1:
model = nn.DataParallel(model)
2019-12-13 19:05:05 +00:00
else: # called by train.py
2019-04-02 11:43:18 +00:00
device = next(model.parameters()).device # get model device
2019-07-21 19:28:38 +00:00
verbose = False
# Configure run
2019-07-20 13:10:31 +00:00
data = parse_data_cfg(data)
2020-01-18 01:52:28 +00:00
nc = 1 if single_cls else int(data['classes']) # number of classes
2019-12-20 16:41:28 +00:00
path = data['valid'] # path to test images
2019-07-20 13:10:31 +00:00
names = load_classes(data['names']) # class names
2019-12-27 18:31:12 +00:00
iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
2020-01-11 07:31:25 +00:00
iouv = iouv[0].view(1) # comment for mAP@0.5:0.95
2019-12-27 18:31:12 +00:00
niou = iouv.numel()
2018-11-14 15:14:41 +00:00
2019-03-21 20:41:12 +00:00
# Dataloader
2019-12-05 07:02:32 +00:00
if dataloader is None:
2020-03-02 22:30:01 +00:00
dataset = LoadImagesAndLabels(path, img_size, batch_size, rect=True, single_cls=opt.single_cls)
2019-12-05 07:02:32 +00:00
batch_size = min(batch_size, len(dataset))
dataloader = DataLoader(dataset,
batch_size=batch_size,
num_workers=min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]),
pin_memory=True,
collate_fn=dataset.collate_fn)
2018-11-14 15:14:41 +00:00
seen = 0
2019-04-05 13:34:42 +00:00
model.eval()
2019-02-26 13:57:28 +00:00
coco91class = coco80_to_coco91_class()
2019-11-08 04:01:47 +00:00
s = ('%20s' + '%10s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@0.5', 'F1')
2020-03-04 17:00:48 +00:00
p, r, f1, mp, mr, map, mf1, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
2020-03-04 20:17:37 +00:00
loss = torch.zeros(3, device=device)
2019-04-05 13:34:42 +00:00
jdict, stats, ap, ap_class = [], [], [], []
2019-07-12 12:28:46 +00:00
for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
2019-12-09 01:52:44 +00:00
imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0
targets = targets.to(device)
2020-03-16 01:39:54 +00:00
nb, _, height, width = imgs.shape # batch size, channels, height, width
2020-03-04 09:47:31 +00:00
whwh = torch.Tensor([width, height, width, height]).to(device)
2019-04-09 10:24:01 +00:00
# Plot images with bounding boxes
2020-02-26 21:40:17 +00:00
f = 'test_batch%g.png' % batch_i # filename
if batch_i < 1 and not os.path.exists(f):
plot_images(imgs=imgs, targets=targets, paths=paths, fname=f)
2019-04-09 10:24:01 +00:00
2019-12-20 17:07:25 +00:00
# Disable gradients
with torch.no_grad():
2020-03-26 18:34:32 +00:00
# Augment images
if augment: # https://github.com/ultralytics/yolov3/issues/931
2020-03-16 01:39:54 +00:00
imgs = torch.cat((imgs,
2020-03-26 23:20:06 +00:00
torch_utils.scale_img(imgs.flip(3), 0.9), # flip-lr and scale
2020-03-16 01:39:54 +00:00
torch_utils.scale_img(imgs, 0.7), # scale
), 0)
2019-12-20 17:07:25 +00:00
# Run model
2020-03-04 18:26:35 +00:00
t = torch_utils.time_synchronized()
2019-12-20 17:07:25 +00:00
inf_out, train_out = model(imgs) # inference and training outputs
2020-03-04 18:26:35 +00:00
t0 += torch_utils.time_synchronized() - t
2019-12-20 17:07:25 +00:00
2020-03-26 18:34:32 +00:00
# De-augment results
2020-03-26 18:28:46 +00:00
if augment:
2020-03-16 01:39:54 +00:00
x = torch.split(inf_out, nb, dim=0)
2020-03-26 23:20:06 +00:00
x[1][..., :4] /= 0.9 # scale
2020-03-16 01:39:54 +00:00
x[1][..., 0] = width - x[1][..., 0] # flip lr
x[2][..., :4] /= 0.7 # scale
inf_out = torch.cat(x, 1)
2019-12-20 17:07:25 +00:00
# Compute loss
if hasattr(model, 'hyp'): # if model has loss hyperparameters
2020-03-04 20:17:37 +00:00
loss += compute_loss(train_out, targets, model)[1][:3] # GIoU, obj, cls
2018-11-14 15:14:41 +00:00
2019-12-22 21:03:45 +00:00
# Run NMS
2020-03-04 18:26:35 +00:00
t = torch_utils.time_synchronized()
output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres) # nms
t1 += torch_utils.time_synchronized() - t
2019-04-05 13:34:42 +00:00
# Statistics per image
for si, pred in enumerate(output):
labels = targets[targets[:, 0] == si, 1:]
2019-04-10 14:17:08 +00:00
nl = len(labels)
tcls = labels[:, 0].tolist() if nl else [] # target class
2019-02-23 22:50:23 +00:00
seen += 1
2018-11-14 15:14:41 +00:00
if pred is None:
2019-04-10 14:17:08 +00:00
if nl:
2020-01-09 02:48:41 +00:00
stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
2018-11-14 15:14:41 +00:00
continue
2019-06-01 16:29:14 +00:00
# Append to text file
# with open('test.txt', 'a') as file:
# [file.write('%11.5g' * 7 % tuple(x) + '\n') for x in pred]
2019-12-24 20:42:22 +00:00
# Clip boxes to image bounds
clip_coords(pred, (height, width))
2019-04-05 13:34:42 +00:00
# Append to pycocotools JSON dictionary
if save_json:
2019-02-26 13:57:28 +00:00
# [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
2019-04-02 11:43:18 +00:00
image_id = int(Path(paths[si]).stem.split('_')[-1])
box = pred[:, :4].clone() # xyxy
2019-12-01 02:45:43 +00:00
scale_coords(imgs[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
2019-02-26 13:57:28 +00:00
box = xyxy2xywh(box) # xywh
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
for p, b in zip(pred.tolist(), box.tolist()):
2019-07-15 15:00:04 +00:00
jdict.append({'image_id': image_id,
'category_id': coco91class[int(p[5])],
'bbox': [round(x, 3) for x in b],
'score': round(p[4], 5)})
2019-02-26 01:53:11 +00:00
2019-04-10 14:17:08 +00:00
# Assign all predictions as incorrect
2020-03-04 20:17:37 +00:00
correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
2019-04-10 14:17:08 +00:00
if nl:
2019-12-23 00:05:43 +00:00
detected = [] # target indices
2019-04-26 12:14:28 +00:00
tcls_tensor = labels[:, 0]
# target boxes
2020-03-04 09:47:31 +00:00
tbox = xywh2xyxy(labels[:, 1:5]) * whwh
2018-11-14 15:14:41 +00:00
2019-12-23 00:05:43 +00:00
# Per target class
for cls in torch.unique(tcls_tensor):
ti = (cls == tcls_tensor).nonzero().view(-1) # prediction indices
pi = (cls == pred[:, 5]).nonzero().view(-1) # target indices
# Search for detections
2020-03-04 09:47:31 +00:00
if pi.shape[0]:
2019-12-23 00:05:43 +00:00
# Prediction to target ious
ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices
# Append detections
2019-12-27 18:31:12 +00:00
for j in (ious > iouv[0]).nonzero():
2019-12-23 00:05:43 +00:00
d = ti[i[j]] # detected target
if d not in detected:
detected.append(d)
2020-03-04 09:47:31 +00:00
correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
2019-12-23 00:05:43 +00:00
if len(detected) == nl: # all targets already located in image
break
2018-11-14 15:14:41 +00:00
2019-04-10 14:17:08 +00:00
# Append statistics (correct, conf, pcls, tcls)
2020-03-04 09:47:31 +00:00
stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
2018-11-14 15:14:41 +00:00
2019-04-05 13:34:42 +00:00
# Compute statistics
2020-01-11 21:12:58 +00:00
stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
2019-04-18 19:18:54 +00:00
if len(stats):
p, r, ap, f1, ap_class = ap_per_class(*stats)
2020-01-09 00:36:35 +00:00
if niou > 1:
p, r, ap, f1 = p[:, 0], r[:, 0], ap.mean(1), ap[:, 0] # [P, R, AP@0.5:0.95, AP@0.5]
2019-04-05 13:34:42 +00:00
mp, mr, map, mf1 = p.mean(), r.mean(), ap.mean(), f1.mean()
2019-07-16 21:14:10 +00:00
nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
else:
nt = torch.zeros(1)
2018-11-14 15:14:41 +00:00
2019-04-05 13:34:42 +00:00
# Print results
2019-08-24 14:43:43 +00:00
pf = '%20s' + '%10.3g' * 6 # print format
2019-05-21 15:37:34 +00:00
print(pf % ('all', seen, nt.sum(), mp, mr, map, mf1))
2018-11-14 15:14:41 +00:00
2019-04-05 13:34:42 +00:00
# Print results per class
2019-07-20 15:31:21 +00:00
if verbose and nc > 1 and len(stats):
2019-04-05 13:34:42 +00:00
for i, c in enumerate(ap_class):
2019-04-05 13:51:06 +00:00
print(pf % (names[c], seen, nt[c], p[i], r[i], ap[i], f1[i]))
2018-11-14 15:14:41 +00:00
2020-03-08 19:05:42 +00:00
# Print speeds
if verbose:
t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (img_size, img_size, batch_size) # tuple
print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
2019-02-26 01:53:11 +00:00
# Save JSON
2019-04-05 13:34:42 +00:00
if save_json and map and len(jdict):
2020-03-08 19:35:04 +00:00
print('\nCOCO mAP with pycocotools...')
2019-12-05 07:02:32 +00:00
imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataloader.dataset.img_files]
2019-12-01 01:47:33 +00:00
with open('results.json', 'w') as file:
json.dump(jdict, file)
2019-08-28 14:15:10 +00:00
2019-12-01 01:47:33 +00:00
try:
2019-08-28 14:15:10 +00:00
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
2019-12-01 01:47:33 +00:00
except:
print('WARNING: missing pycocotools package, can not compute official COCO mAP. See requirements.txt.')
2019-08-28 14:15:10 +00:00
2019-12-01 01:47:33 +00:00
# https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
2019-12-14 03:31:50 +00:00
cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api
2019-12-01 01:47:33 +00:00
cocoDt = cocoGt.loadRes('results.json') # initialize COCO pred api
2019-08-28 14:15:10 +00:00
2019-12-01 01:47:33 +00:00
cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
cocoEval.params.imgIds = imgIds # [:32] # only evaluate these images
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()
2019-12-17 00:29:40 +00:00
mf1, map = cocoEval.stats[:2] # update to pycocotools results (mAP@0.5:0.95, mAP@0.5)
2019-02-26 01:53:11 +00:00
2019-04-05 13:34:42 +00:00
# Return results
2019-05-13 12:41:17 +00:00
maps = np.zeros(nc) + map
2019-05-10 12:15:09 +00:00
for i, c in enumerate(ap_class):
maps[c] = ap[i]
2020-03-04 20:17:37 +00:00
return (mp, mr, map, mf1, *(loss.cpu() / len(dataloader)).tolist()), maps
2018-11-14 15:14:41 +00:00
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='test.py')
2019-12-15 20:47:53 +00:00
parser.add_argument('--cfg', type=str, default='cfg/yolov3-spp.cfg', help='*.cfg path')
2019-12-20 02:09:13 +00:00
parser.add_argument('--data', type=str, default='data/coco2014.data', help='*.data path')
2020-02-17 07:12:07 +00:00
parser.add_argument('--weights', type=str, default='weights/yolov3-spp-ultralytics.pt', help='weights path')
2020-03-26 21:22:59 +00:00
parser.add_argument('--batch-size', type=int, default=16, help='size of each image batch')
2019-12-01 01:47:49 +00:00
parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
2020-01-18 03:42:04 +00:00
parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')
2019-02-26 12:52:03 +00:00
parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
2019-12-24 21:58:45 +00:00
parser.add_argument('--task', default='test', help="'test', 'study', 'benchmark'")
2019-09-16 12:31:07 +00:00
parser.add_argument('--device', default='', help='device id (i.e. 0 or 0,1) or cpu')
2020-01-18 01:52:28 +00:00
parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
2020-03-26 18:25:44 +00:00
parser.add_argument('--augment', action='store_true', help='augmented testing')
opt = parser.parse_args()
2019-12-20 17:23:33 +00:00
opt.save_json = opt.save_json or any([x in opt.data for x in ['coco.data', 'coco2014.data', 'coco2017.data']])
2019-05-03 16:14:16 +00:00
print(opt)
2020-03-02 22:07:09 +00:00
# task = 'test', 'study', 'benchmark'
if opt.task == 'test': # (default) test normally
2019-12-20 17:08:57 +00:00
test(opt.cfg,
opt.data,
opt.weights,
opt.batch_size,
opt.img_size,
opt.conf_thres,
2019-12-26 20:30:51 +00:00
opt.iou_thres,
2020-01-18 01:52:28 +00:00
opt.save_json,
2020-03-26 18:28:46 +00:00
opt.single_cls,
opt.augment)
2019-12-24 21:57:12 +00:00
2020-03-02 22:07:09 +00:00
elif opt.task == 'benchmark': # mAPs at 320-608 at conf 0.5 and 0.7
2019-12-24 21:57:12 +00:00
y = []
2020-03-02 22:07:09 +00:00
for i in [320, 416, 512, 608]: # img-size
for j in [0.5, 0.7]: # iou-thres
2019-12-24 21:57:12 +00:00
t = time.time()
r = test(opt.cfg, opt.data, opt.weights, opt.batch_size, i, opt.conf_thres, j, opt.save_json)[0]
y.append(r + (time.time() - t,))
np.savetxt('benchmark.txt', y, fmt='%10.4g') # y = np.loadtxt('study.txt')
2020-03-02 22:07:09 +00:00
elif opt.task == 'study': # Parameter study
2019-12-20 17:08:57 +00:00
y = []
2020-03-02 22:07:09 +00:00
x = np.arange(0.4, 0.9, 0.05) # iou-thres
2019-12-27 17:28:10 +00:00
for i in x:
2019-12-20 17:23:33 +00:00
t = time.time()
2019-12-27 17:28:10 +00:00
r = test(opt.cfg, opt.data, opt.weights, opt.batch_size, opt.img_size, opt.conf_thres, i, opt.save_json)[0]
2019-12-20 17:44:21 +00:00
y.append(r + (time.time() - t,))
2019-12-20 19:24:21 +00:00
np.savetxt('study.txt', y, fmt='%10.4g') # y = np.loadtxt('study.txt')
2019-12-20 17:08:57 +00:00
# Plot
2019-12-20 19:18:55 +00:00
fig, ax = plt.subplots(3, 1, figsize=(6, 6))
2019-12-24 21:57:12 +00:00
y = np.stack(y, 0)
2019-12-20 17:59:25 +00:00
ax[0].plot(x, y[:, 2], marker='.', label='mAP@0.5')
ax[0].set_ylabel('mAP')
2019-12-20 19:18:55 +00:00
ax[1].plot(x, y[:, 3], marker='.', label='mAP@0.5:0.95')
ax[1].set_ylabel('mAP')
ax[2].plot(x, y[:, -1], marker='.', label='time')
ax[2].set_ylabel('time (s)')
for i in range(3):
ax[i].legend()
2019-12-26 20:30:51 +00:00
ax[i].set_xlabel('iou_thr')
2019-12-20 17:08:57 +00:00
fig.tight_layout()
2019-12-20 17:59:25 +00:00
plt.savefig('study.jpg', dpi=200)