car-detection-bayes/test.py

215 lines
8.8 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
2019-02-27 11:32:25 +00:00
import time
2019-02-26 01:53:11 +00:00
from pathlib import Path
2018-10-10 15:07:21 +00:00
2018-08-26 08:51:39 +00:00
from models import *
from utils.datasets import *
from utils.utils import *
2019-02-10 20:07:26 +00:00
def test(
cfg,
data_cfg,
weights,
batch_size=16,
img_size=416,
iou_thres=0.5,
conf_thres=0.3,
2019-02-26 01:53:11 +00:00
nms_thres=0.45,
save_json=False
2019-02-10 20:07:26 +00:00
):
device = torch_utils.select_device()
2018-11-14 15:14:41 +00:00
# Configure run
2019-02-11 21:44:25 +00:00
data_cfg_dict = parse_data_cfg(data_cfg)
nC = int(data_cfg_dict['classes']) # number of classes (80 for COCO)
test_path = data_cfg_dict['valid']
2018-11-14 15:14:41 +00:00
2019-02-11 11:32:54 +00:00
# Initialize model
2019-02-08 21:43:05 +00:00
model = Darknet(cfg, img_size)
2018-11-14 15:14:41 +00:00
# Load weights
2019-02-08 21:43:05 +00:00
if weights.endswith('.pt'): # pytorch format
2019-02-08 22:20:41 +00:00
model.load_state_dict(torch.load(weights, map_location='cpu')['model'])
2018-12-04 18:17:03 +00:00
else: # darknet format
2019-02-08 21:43:05 +00:00
load_darknet_weights(model, weights)
2018-11-14 15:14:41 +00:00
model.to(device).eval()
# Get dataloader
2019-02-26 13:57:28 +00:00
# dataloader = torch.utils.data.DataLoader(LoadImagesAndLabels(test_path), batch_size=batch_size)
2019-02-11 11:44:12 +00:00
dataloader = LoadImagesAndLabels(test_path, batch_size=batch_size, img_size=img_size)
2018-11-14 15:14:41 +00:00
2019-02-23 22:50:23 +00:00
mean_mAP, mean_R, mean_P, seen = 0.0, 0.0, 0.0, 0
2018-11-22 12:52:22 +00:00
print('%11s' * 5 % ('Image', 'Total', 'P', 'R', 'mAP'))
2019-02-26 13:57:28 +00:00
outputs, mAPs, mR, mP, TP, confidence, pred_class, target_class, jdict = \
[], [], [], [], [], [], [], [], []
2018-11-14 15:14:41 +00:00
AP_accum, AP_accum_count = np.zeros(nC), np.zeros(nC)
2019-02-26 13:57:28 +00:00
coco91class = coco80_to_coco91_class()
2019-02-26 01:53:11 +00:00
for batch_i, (imgs, targets, paths, shapes) in enumerate(dataloader):
2019-02-27 11:32:25 +00:00
t = time.time()
2019-02-10 20:10:50 +00:00
output = model(imgs.to(device))
output = non_max_suppression(output, conf_thres=conf_thres, nms_thres=nms_thres)
2018-11-14 15:14:41 +00:00
# Compute average precision for each sample
2019-02-26 01:53:11 +00:00
for si, (labels, detections) in enumerate(zip(targets, output)):
2019-02-23 22:50:23 +00:00
seen += 1
2018-11-14 15:14:41 +00:00
if detections is None:
2019-02-23 22:50:23 +00:00
# If there are labels but no detections mark as zero AP
2018-11-23 17:09:47 +00:00
if labels.size(0) != 0:
mAPs.append(0), mR.append(0), mP.append(0)
2018-11-14 15:14:41 +00:00
continue
# Get detections sorted by decreasing confidence scores
2018-11-23 17:09:47 +00:00
detections = detections.cpu().numpy()
2018-11-14 15:14:41 +00:00
detections = detections[np.argsort(-detections[:, 4])]
2019-02-26 01:53:11 +00:00
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}, ...
box = torch.from_numpy(detections[:, :4]).clone() # xyxy
scale_coords(img_size, box, shapes[si]) # to original shape
box = xyxy2xywh(box) # xywh
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
2019-02-26 01:53:11 +00:00
2019-02-26 13:57:28 +00:00
# add to json dictionary
2019-02-26 01:53:11 +00:00
for di, d in enumerate(detections):
2019-02-26 13:57:28 +00:00
jdict.append({
2019-02-26 01:53:11 +00:00
'image_id': int(Path(paths[si]).stem.split('_')[-1]),
2019-02-26 14:00:27 +00:00
'category_id': coco91class[int(d[6])],
2019-02-26 12:52:03 +00:00
'bbox': [float3(x) for x in box[di]],
2019-02-26 01:53:11 +00:00
'score': float3(d[4] * d[5])
})
2018-11-23 17:09:47 +00:00
# If no labels add number of detections as incorrect
2019-02-23 22:50:23 +00:00
correct = []
2018-11-23 17:09:47 +00:00
if labels.size(0) == 0:
2018-11-14 15:14:41 +00:00
# correct.extend([0 for _ in range(len(detections))])
2018-11-23 17:09:47 +00:00
mAPs.append(0), mR.append(0), mP.append(0)
2018-11-14 15:14:41 +00:00
continue
else:
2018-11-23 17:09:47 +00:00
target_cls = labels[:, 0]
2018-11-14 15:14:41 +00:00
# Extract target boxes as (x1, y1, x2, y2)
target_boxes = xywh2xyxy(labels[:, 1:5]) * img_size
2018-11-14 15:14:41 +00:00
detected = []
for *pred_bbox, conf, obj_conf, obj_pred in detections:
pred_bbox = torch.FloatTensor(pred_bbox).view(1, -1)
# Compute iou with target boxes
iou = bbox_iou(pred_bbox, target_boxes)
# Extract index of largest overlap
best_i = np.argmax(iou)
# If overlap exceeds threshold and classification is correct mark as correct
if iou[best_i] > iou_thres and obj_pred == labels[best_i, 0] and best_i not in detected:
2018-11-14 15:14:41 +00:00
correct.append(1)
detected.append(best_i)
else:
correct.append(0)
# Compute Average Precision (AP) per class
2019-02-23 22:50:23 +00:00
AP, AP_class, R, P = ap_per_class(tp=correct,
conf=detections[:, 4],
pred_cls=detections[:, 6],
2018-11-22 12:52:22 +00:00
target_cls=target_cls)
2018-11-14 15:14:41 +00:00
# Accumulate AP per class
AP_accum_count += np.bincount(AP_class, minlength=nC)
AP_accum += np.bincount(AP_class, minlength=nC, weights=AP)
2018-11-22 12:52:22 +00:00
# Compute mean AP across all classes in this image, and append to image list
mAPs.append(AP.mean())
mR.append(R.mean())
mP.append(P.mean())
2018-11-14 15:14:41 +00:00
2018-11-22 12:52:22 +00:00
# Means of all images
2018-11-14 23:56:03 +00:00
mean_mAP = np.mean(mAPs)
2018-11-22 12:52:22 +00:00
mean_R = np.mean(mR)
mean_P = np.mean(mP)
2018-11-14 15:14:41 +00:00
2019-02-18 13:03:39 +00:00
# Print image mAP and running mean mAP
2019-02-27 11:32:25 +00:00
print(('%11s%11s' + '%11.3g' * 4 + 's') %
(seen, dataloader.nF, mean_P, mean_R, mean_mAP, time.time() - t))
2018-11-14 15:14:41 +00:00
# Print mAP per class
2018-11-22 15:42:58 +00:00
print('%11s' * 5 % ('Image', 'Total', 'P', 'R', 'mAP') + '\n\nmAP Per Class:')
2019-02-27 11:32:25 +00:00
for i, c in enumerate(load_classes(data_cfg_dict['names'])):
2019-02-18 13:03:39 +00:00
print('%15s: %-.4f' % (c, AP_accum[i] / (AP_accum_count[i] + 1E-16)))
2018-11-14 15:14:41 +00:00
2019-02-26 01:53:11 +00:00
# Save JSON
if save_json:
imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataloader.img_files]
with open('results.json', 'w') as file:
json.dump(jdict, file)
2019-02-26 01:55:32 +00:00
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
2019-02-26 01:53:11 +00:00
2019-02-26 14:11:22 +00:00
# https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
cocoGt = COCO('../coco/annotations/instances_val2014.json') # initialize COCO ground truth api
cocoDt = cocoGt.loadRes('results.json') # initialize COCO detections api
2019-02-26 01:53:11 +00:00
cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
cocoEval.params.imgIds = imgIds # [:32] # only evaluate these images
2019-02-26 14:15:39 +00:00
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()
2019-02-26 01:53:11 +00:00
2018-11-22 15:42:58 +00:00
# Return mAP
2018-11-22 12:52:22 +00:00
return mean_mAP, mean_R, mean_P
2018-11-14 15:14:41 +00:00
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='test.py')
parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
2019-02-11 21:44:25 +00:00
parser.add_argument('--cfg', type=str, default='cfg/yolov3.cfg', help='cfg file path')
parser.add_argument('--data-cfg', type=str, default='cfg/coco.data', help='coco.data file path')
2019-02-18 19:42:59 +00:00
parser.add_argument('--weights', type=str, default='weights/yolov3.weights', help='path to weights file')
parser.add_argument('--iou-thres', type=float, default=0.5, help='iou threshold required to qualify as detected')
parser.add_argument('--conf-thres', type=float, default=0.3, help='object confidence threshold')
parser.add_argument('--nms-thres', type=float, default=0.45, help='iou threshold for non-maximum suppression')
2019-02-26 12:52:03 +00:00
parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
parser.add_argument('--img-size', type=int, default=416, help='size of each image dimension')
opt = parser.parse_args()
print(opt, end='\n\n')
2019-02-10 20:10:50 +00:00
with torch.no_grad():
mAP = test(
opt.cfg,
opt.data_cfg,
opt.weights,
opt.batch_size,
opt.img_size,
opt.iou_thres,
opt.conf_thres,
2019-02-26 02:12:04 +00:00
opt.nms_thres,
2019-02-26 12:52:03 +00:00
opt.save_json
2019-02-10 20:10:50 +00:00
)
2019-02-23 22:50:23 +00:00
# Image Total P R mAP # YOLOv3 320
# 32 5000 0.66 0.597 0.591
# 64 5000 0.664 0.62 0.604
# 96 5000 0.653 0.627 0.614
# 128 5000 0.639 0.623 0.607
# 160 5000 0.642 0.63 0.616
# 192 5000 0.651 0.636 0.621
# Image Total P R mAP # YOLOv3 416
# 32 5000 0.635 0.581 0.57
# 64 5000 0.63 0.591 0.578
# 96 5000 0.661 0.632 0.622
# 128 5000 0.659 0.632 0.623
# 160 5000 0.665 0.64 0.633
# 192 5000 0.66 0.637 0.63
# Image Total P R mAP # YOLOv3 608
# 32 5000 0.653 0.606 0.591
# 64 5000 0.653 0.635 0.625
# 96 5000 0.655 0.642 0.633
# 128 5000 0.667 0.651 0.642
# 160 5000 0.663 0.645 0.637
# 192 5000 0.663 0.643 0.634