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 *
|
|
|
|
|
2018-12-05 13:31:08 +00:00
|
|
|
|
2019-02-10 20:07:26 +00:00
|
|
|
def test(
|
|
|
|
cfg,
|
|
|
|
data_cfg,
|
2019-03-30 17:45:04 +00:00
|
|
|
weights=None,
|
2019-02-10 20:07:26 +00:00
|
|
|
batch_size=16,
|
|
|
|
img_size=416,
|
|
|
|
iou_thres=0.5,
|
2019-04-14 21:22:35 +00:00
|
|
|
conf_thres=0.001,
|
2019-03-30 17:45:04 +00:00
|
|
|
nms_thres=0.5,
|
2019-03-17 21:45:39 +00:00
|
|
|
save_json=False,
|
|
|
|
model=None
|
2019-02-10 20:07:26 +00:00
|
|
|
):
|
2019-03-17 21:45:39 +00:00
|
|
|
if model is None:
|
2019-03-30 17:45:04 +00:00
|
|
|
device = torch_utils.select_device()
|
|
|
|
|
2019-03-17 21:45:39 +00:00
|
|
|
# Initialize model
|
2019-03-25 13:59:38 +00:00
|
|
|
model = Darknet(cfg, img_size).to(device)
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-03-17 21:45:39 +00:00
|
|
|
# Load weights
|
|
|
|
if weights.endswith('.pt'): # pytorch format
|
2019-03-25 13:59:38 +00:00
|
|
|
model.load_state_dict(torch.load(weights, map_location=device)['model'])
|
2019-03-17 21:45:39 +00:00
|
|
|
else: # darknet format
|
2019-03-19 08:38:32 +00:00
|
|
|
_ = load_darknet_weights(model, weights)
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-03-30 17:45:04 +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
|
2019-03-25 13:59:38 +00:00
|
|
|
|
|
|
|
# Configure run
|
|
|
|
data_cfg = parse_data_cfg(data_cfg)
|
2019-04-05 13:34:42 +00:00
|
|
|
nc = int(data_cfg['classes']) # number of classes
|
|
|
|
test_path = data_cfg['valid'] # path to test images
|
|
|
|
names = load_classes(data_cfg['names']) # class names
|
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)
|
2019-03-25 13:59:38 +00:00
|
|
|
dataloader = DataLoader(dataset,
|
|
|
|
batch_size=batch_size,
|
2019-04-06 15:06:37 +00:00
|
|
|
num_workers=4,
|
2019-04-15 17:25:36 +00:00
|
|
|
pin_memory=True,
|
2019-03-25 13:59:38 +00:00
|
|
|
collate_fn=dataset.collate_fn)
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-03-30 17:45:04 +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-04-05 13:51:06 +00:00
|
|
|
print(('%20s' + '%10s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP', 'F1'))
|
2019-04-05 13:34:42 +00:00
|
|
|
loss, p, r, f1, mp, mr, map, mf1 = 0., 0., 0., 0., 0., 0., 0., 0.
|
|
|
|
jdict, stats, ap, ap_class = [], [], [], []
|
|
|
|
for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc='Computing mAP')):
|
2019-03-25 13:59:38 +00:00
|
|
|
targets = targets.to(device)
|
|
|
|
imgs = imgs.to(device)
|
|
|
|
|
2019-04-09 10:24:01 +00:00
|
|
|
# Plot images with bounding boxes
|
|
|
|
if batch_i == 0 and not os.path.exists('test_batch0.jpg'):
|
|
|
|
plot_images(imgs=imgs, targets=targets, fname='test_batch0.jpg')
|
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
# Run model
|
|
|
|
inf_out, train_out = model(imgs) # inference and training outputs
|
|
|
|
|
|
|
|
# Compute loss
|
2019-04-17 14:11:26 +00:00
|
|
|
if hasattr(model, 'hyp'): # if model has loss hyperparameters
|
|
|
|
loss_i, _ = compute_loss(train_out, targets, model)
|
|
|
|
loss += loss_i.item()
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
# Run NMS
|
|
|
|
output = non_max_suppression(inf_out, conf_thres=conf_thres, nms_thres=nms_thres)
|
|
|
|
|
|
|
|
# Statistics per image
|
2019-03-30 17:45:04 +00:00
|
|
|
for si, pred in enumerate(output):
|
2019-03-17 21:45:39 +00:00
|
|
|
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
|
|
|
|
2019-03-30 17:45:04 +00:00
|
|
|
if pred is None:
|
2019-04-10 14:17:08 +00:00
|
|
|
if nl:
|
|
|
|
stats.append(([], torch.Tensor(), torch.Tensor(), tcls))
|
2018-11-14 15:14:41 +00:00
|
|
|
continue
|
|
|
|
|
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])
|
2019-03-30 17:45:04 +00:00
|
|
|
box = pred[:, :4].clone() # xyxy
|
2019-03-25 13:59:38 +00:00
|
|
|
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
|
2019-03-30 17:45:04 +00:00
|
|
|
for di, d in enumerate(pred):
|
2019-02-26 13:57:28 +00:00
|
|
|
jdict.append({
|
2019-03-30 17:45:04 +00:00
|
|
|
'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]],
|
2019-03-30 17:45:04 +00:00
|
|
|
'score': float(d[4])
|
2019-02-26 01:53:11 +00:00
|
|
|
})
|
|
|
|
|
2019-04-10 14:17:08 +00:00
|
|
|
# Assign all predictions as incorrect
|
|
|
|
correct = [0] * len(pred)
|
|
|
|
if nl:
|
|
|
|
detected = []
|
2019-04-02 11:56:54 +00:00
|
|
|
tbox = xywh2xyxy(labels[:, 1:5]) * img_size # target boxes
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-04-10 14:17:08 +00:00
|
|
|
# Search for correct predictions
|
|
|
|
for i, (*pbox, pconf, pcls_conf, pcls) in enumerate(pred):
|
|
|
|
|
|
|
|
# Break if all targets already located in image
|
|
|
|
if len(detected) == nl:
|
|
|
|
break
|
|
|
|
|
|
|
|
# Continue if predicted class not among image classes
|
|
|
|
if pcls.item() not in tcls:
|
2019-03-30 17:45:04 +00:00
|
|
|
continue
|
|
|
|
|
2019-03-17 21:45:39 +00:00
|
|
|
# Best iou, index between pred and targets
|
2019-04-02 11:43:18 +00:00
|
|
|
iou, bi = bbox_iou(pbox, tbox).max(0)
|
2019-03-17 21:45:39 +00:00
|
|
|
|
|
|
|
# If iou > threshold and class is correct mark as correct
|
2019-04-18 21:02:54 +00:00
|
|
|
if iou > iou_thres and bi not in detected and pcls == tcls[bi]:
|
2019-04-10 14:17:08 +00:00
|
|
|
correct[i] = 1
|
2019-03-17 21:45:39 +00:00
|
|
|
detected.append(bi)
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-04-10 14:17:08 +00:00
|
|
|
# Append statistics (correct, conf, pcls, tcls)
|
|
|
|
stats.append((correct, pred[:, 4].cpu(), pred[:, 6].cpu(), tcls))
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
# Compute statistics
|
2019-04-18 19:18:54 +00:00
|
|
|
stats = [np.concatenate(x, 0) for x in list(zip(*stats))] # to numpy
|
|
|
|
nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
|
|
|
|
if len(stats):
|
|
|
|
p, r, ap, f1, ap_class = ap_per_class(*stats)
|
2019-04-05 13:34:42 +00:00
|
|
|
mp, mr, map, mf1 = p.mean(), r.mean(), ap.mean(), f1.mean()
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
# Print results
|
2019-04-05 13:54:59 +00:00
|
|
|
pf = '%20s' + '%10.3g' * 6 # print format
|
2019-04-05 13:51:06 +00:00
|
|
|
print(pf % ('all', seen, nt.sum(), mp, mr, map, mf1), end='\n\n')
|
2018-11-14 15:14:41 +00:00
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
# Print results per class
|
2019-04-18 19:18:54 +00:00
|
|
|
if 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
|
|
|
|
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):
|
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
|
2019-03-30 17:45:04 +00:00
|
|
|
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()
|
2019-04-05 13:34:42 +00:00
|
|
|
map = cocoEval.stats[1] # update mAP to pycocotools mAP
|
2019-02-26 01:53:11 +00:00
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
# Return results
|
2019-04-11 16:26:52 +00:00
|
|
|
return mp, mr, map, mf1, loss / len(dataloader)
|
2018-11-14 15:14:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2018-12-05 13:31:08 +00:00
|
|
|
parser = argparse.ArgumentParser(prog='test.py')
|
2019-04-11 10:47:58 +00:00
|
|
|
parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
|
2019-04-03 12:25:31 +00:00
|
|
|
parser.add_argument('--cfg', type=str, default='cfg/yolov3-spp.cfg', help='cfg file path')
|
2019-04-18 20:55:50 +00:00
|
|
|
parser.add_argument('--data-cfg', type=str, default='data/coco_100img.data', help='coco.data file path')
|
|
|
|
parser.add_argument('--weights', type=str, default='weights/recall_issue.pt', help='path to weights file')
|
2018-12-05 13:31:08 +00:00
|
|
|
parser.add_argument('--iou-thres', type=float, default=0.5, help='iou threshold required to qualify as detected')
|
2019-03-30 17:45:04 +00:00
|
|
|
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')
|
2018-12-05 13:31:08 +00:00
|
|
|
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-03-25 13:59:38 +00:00
|
|
|
opt.save_json
|
|
|
|
)
|