car-detection-bayes/test.py

190 lines
7.1 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-02-10 20:07:26 +00:00
def test(
cfg,
data_cfg,
weights=None,
2019-02-10 20:07:26 +00:00
batch_size=16,
img_size=416,
iou_thres=0.5,
2019-04-02 12:42:29 +00:00
conf_thres=0.1,
nms_thres=0.5,
save_json=False,
model=None
2019-02-10 20:07:26 +00:00
):
if model is None:
device = torch_utils.select_device()
# Initialize model
model = Darknet(cfg, img_size).to(device)
2018-11-14 15:14:41 +00:00
# Load weights
if weights.endswith('.pt'): # pytorch format
model.load_state_dict(torch.load(weights, map_location=device)['model'])
else: # darknet format
2019-03-19 08:38:32 +00:00
_ = load_darknet_weights(model, weights)
2018-11-14 15:14:41 +00:00
if torch.cuda.device_count() > 1:
model = nn.DataParallel(model)
else:
2019-04-02 11:43:18 +00:00
device = next(model.parameters()).device # get model device
# Configure run
data_cfg = parse_data_cfg(data_cfg)
test_path = data_cfg['valid']
2019-04-02 12:19:53 +00:00
# if (os.sep + 'coco' + os.sep) in test_path: # COCO dataset probable
# save_json = True # use pycocotools
2018-11-14 15:14:41 +00:00
2019-03-21 20:41:12 +00:00
# Dataloader
dataset = LoadImagesAndLabels(test_path, img_size=img_size)
dataloader = DataLoader(dataset,
batch_size=batch_size,
2019-04-02 14:15:25 +00:00
num_workers=4,
pin_memory=False,
collate_fn=dataset.collate_fn)
2018-11-14 15:14:41 +00:00
model.eval()
seen = 0
2018-11-22 12:52:22 +00:00
print('%11s' * 5 % ('Image', 'Total', 'P', 'R', 'mAP'))
mP, mR, mAP, mAPj = 0.0, 0.0, 0.0, 0.0
jdict, tdict, stats, AP, AP_class = [], [], [], [], []
2019-02-26 13:57:28 +00:00
coco91class = coco80_to_coco91_class()
for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc='Calculating mAP')):
targets = targets.to(device)
imgs = imgs.to(device)
output = model(imgs)
2019-02-10 20:10:50 +00:00
output = non_max_suppression(output, conf_thres=conf_thres, nms_thres=nms_thres)
2018-11-14 15:14:41 +00:00
# Per image
for si, pred in enumerate(output):
labels = targets[targets[:, 0] == si, 1:]
2019-04-02 11:56:54 +00:00
correct, detected = [], []
tcls = torch.Tensor()
2019-02-23 22:50:23 +00:00
seen += 1
2018-11-14 15:14:41 +00:00
if pred is None:
2019-04-02 12:41:52 +00:00
if len(labels):
tcls = labels[:, 0].cpu() # target classes
stats.append((correct, torch.Tensor(), torch.Tensor(), tcls))
2018-11-14 15:14:41 +00:00
continue
2019-04-02 11:43:18 +00:00
if save_json: # add to json pred dictionary
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
scale_coords(img_size, box, shapes[si]) # 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 di, d in enumerate(pred):
2019-02-26 13:57:28 +00:00
jdict.append({
'image_id': image_id,
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]],
'score': float(d[4])
2019-02-26 01:53:11 +00:00
})
2019-04-02 12:02:35 +00:00
if len(labels):
2018-11-14 15:14:41 +00:00
# Extract target boxes as (x1, y1, x2, y2)
2019-04-02 11:56:54 +00:00
tbox = xywh2xyxy(labels[:, 1:5]) * img_size # target boxes
tcls = labels[:, 0] # target classes
2018-11-14 15:14:41 +00:00
2019-04-02 11:43:18 +00:00
for *pbox, pconf, pcls_conf, pcls in pred:
if pcls not in tcls:
correct.append(0)
continue
# Best iou, index between pred and targets
2019-04-02 11:43:18 +00:00
iou, bi = bbox_iou(pbox, tbox).max(0)
# If iou > threshold and class is correct mark as correct
if iou > iou_thres and bi not in detected:
2018-11-14 15:14:41 +00:00
correct.append(1)
detected.append(bi)
2018-11-14 15:14:41 +00:00
else:
correct.append(0)
2019-04-02 12:02:35 +00:00
else:
# If no labels add number of detections as incorrect
correct.extend([0] * len(pred))
2018-11-14 15:14:41 +00:00
2019-04-02 11:43:18 +00:00
# Append Statistics (correct, conf, pcls, tcls)
2019-04-02 11:56:54 +00:00
stats.append((correct, pred[:, 4].cpu(), pred[:, 6].cpu(), tcls.cpu()))
2018-11-14 15:14:41 +00:00
# Compute means
stats_np = [np.concatenate(x, 0) for x in list(zip(*stats))]
if len(stats_np):
AP, AP_class, R, P = ap_per_class(*stats_np)
mP, mR, mAP = P.mean(), R.mean(), AP.mean()
2018-11-14 15:14:41 +00:00
# Print P, R, mAP
print(('%11s%11s' + '%11.3g' * 3) % (seen, len(dataset), mP, mR, mAP))
2018-11-14 15:14:41 +00:00
# Print mAP per class
if len(stats_np):
print('\nmAP Per Class:')
names = load_classes(data_cfg['names'])
for c, a in zip(AP_class, AP):
print('%15s: %-.4f' % (names[c], a))
2018-11-14 15:14:41 +00:00
2019-02-26 01:53:11 +00:00
# Save JSON
if save_json and mAP and len(jdict):
2019-03-21 20:41:12 +00:00
imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataset.img_files]
2019-02-26 01:53:11 +00:00
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 pred 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()
mAP = cocoEval.stats[1] # update mAP to pycocotools mAP
# F1 score = harmonic mean of precision and recall
# F1 = 2 * (mP * mR) / (mP + mR)
2019-02-26 01:53:11 +00:00
2018-11-22 15:42:58 +00:00
# Return mAP
return mP, mR, mAP
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')
2019-04-02 14:06:15 +00:00
parser.add_argument('--data-cfg', type=str, default='data/coco.data', help='coco.data file path')
2019-04-02 14:12:35 +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.001, help='object confidence threshold')
parser.add_argument('--nms-thres', type=float, default=0.5, 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,
opt.save_json
)