greenhouse/test.py

222 lines
8.8 KiB
Python
Raw Normal View History

2018-08-26 10:51:39 +02:00
import argparse
2019-02-26 02:53:11 +01:00
import json
2018-10-10 17:07:21 +02:00
2019-03-21 22:41:12 +02:00
from torch.utils.data import DataLoader
2018-08-26 10:51:39 +02:00
from models import *
from utils.datasets import *
from utils.utils import *
2019-07-15 17:00:04 +02:00
def test(cfg,
2019-07-20 15:10:31 +02:00
data,
2019-07-15 17:00:04 +02:00
weights=None,
batch_size=16,
img_size=416,
iou_thres=0.5,
conf_thres=0.001,
nms_thres=0.5,
save_json=False,
model=None):
# Initialize/load model and set device
if model is None:
2019-09-16 14:31:07 +02:00
device = torch_utils.select_device(opt.device)
2019-07-21 21:28:38 +02:00
verbose = True
# Initialize model
model = Darknet(cfg, img_size).to(device)
2018-11-14 15:14:41 +00:00
# Load weights
2019-09-19 18:05:04 +02:00
attempt_download(weights)
if weights.endswith('.pt'): # pytorch format
model.load_state_dict(torch.load(weights, map_location=device)['model'])
else: # darknet format
2019-03-19 10:38:32 +02: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 13:43:18 +02:00
device = next(model.parameters()).device # get model device
2019-07-21 21:28:38 +02:00
verbose = False
# Configure run
2019-07-20 15:10:31 +02:00
data = parse_data_cfg(data)
nc = int(data['classes']) # number of classes
test_path = data['valid'] # path to test images
names = load_classes(data['names']) # class names
2018-11-14 15:14:41 +00:00
2019-03-21 22:41:12 +02:00
# Dataloader
2019-04-24 21:23:54 +02:00
dataset = LoadImagesAndLabels(test_path, img_size, batch_size)
dataloader = DataLoader(dataset,
batch_size=batch_size,
2019-09-19 02:10:55 +02:00
num_workers=min([os.cpu_count(), batch_size, 16]),
2019-04-15 19:25:36 +02:00
pin_memory=True,
collate_fn=dataset.collate_fn)
2018-11-14 15:14:41 +00:00
seen = 0
2019-04-05 15:34:42 +02:00
model.eval()
2019-02-26 14:57:28 +01:00
coco91class = coco80_to_coco91_class()
2019-08-24 16:43:43 +02:00
s = ('%20s' + '%10s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP', 'F1')
2019-08-04 00:12:46 +02:00
p, r, f1, mp, mr, map, mf1 = 0., 0., 0., 0., 0., 0., 0.
loss = torch.zeros(3)
2019-04-05 15:34:42 +02:00
jdict, stats, ap, ap_class = [], [], [], []
2019-07-12 14:28:46 +02:00
for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
targets = targets.to(device)
imgs = imgs.to(device)
2019-04-26 14:14:28 +02:00
_, _, height, width = imgs.shape # batch size, channels, height, width
2019-04-09 12:24:01 +02:00
# Plot images with bounding boxes
if batch_i == 0 and not os.path.exists('test_batch0.jpg'):
2019-07-07 23:24:34 +02:00
plot_images(imgs=imgs, targets=targets, paths=paths, fname='test_batch0.jpg')
2019-04-09 12:24:01 +02:00
2019-04-05 15:34:42 +02:00
# Run model
inf_out, train_out = model(imgs) # inference and training outputs
# Compute loss
2019-04-17 16:11:26 +02:00
if hasattr(model, 'hyp'): # if model has loss hyperparameters
2019-08-24 16:43:43 +02:00
loss += compute_loss(train_out, targets, model)[1][:3].cpu() # GIoU, obj, cls
2018-11-14 15:14:41 +00:00
2019-04-05 15:34:42 +02:00
# Run NMS
2019-08-01 00:09:45 +02:00
output = non_max_suppression(inf_out, conf_thres=conf_thres, nms_thres=nms_thres)
2019-04-05 15:34:42 +02:00
# Statistics per image
for si, pred in enumerate(output):
labels = targets[targets[:, 0] == si, 1:]
2019-04-10 16:17:08 +02:00
nl = len(labels)
tcls = labels[:, 0].tolist() if nl else [] # target class
2019-02-23 23:50:23 +01:00
seen += 1
2018-11-14 15:14:41 +00:00
if pred is None:
2019-04-10 16:17:08 +02:00
if nl:
stats.append(([], torch.Tensor(), torch.Tensor(), tcls))
2018-11-14 15:14:41 +00:00
continue
2019-06-01 18:29:14 +02: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-04-05 15:34:42 +02:00
# Append to pycocotools JSON dictionary
if save_json:
2019-02-26 14:57:28 +01:00
# [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
2019-04-02 13:43:18 +02:00
image_id = int(Path(paths[si]).stem.split('_')[-1])
box = pred[:, :4].clone() # xyxy
2019-07-20 17:05:09 +02:00
scale_coords(imgs[si].shape[1:], box, shapes[si]) # to original shape
2019-02-26 14:57:28 +01:00
box = xyxy2xywh(box) # xywh
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
for di, d in enumerate(pred):
2019-07-15 17:00:04 +02:00
jdict.append({'image_id': image_id,
'category_id': coco91class[int(d[6])],
2019-07-20 17:14:07 +02:00
'bbox': [floatn(x, 3) for x in box[di]],
'score': floatn(d[4], 5)})
2019-02-26 02:53:11 +01:00
2019-07-20 17:05:09 +02:00
# Clip boxes to image bounds
clip_coords(pred, (height, width))
2019-04-10 16:17:08 +02:00
# Assign all predictions as incorrect
correct = [0] * len(pred)
if nl:
detected = []
2019-04-26 14:14:28 +02:00
tcls_tensor = labels[:, 0]
# target boxes
tbox = xywh2xyxy(labels[:, 1:5])
2019-04-26 14:17:04 +02:00
tbox[:, [0, 2]] *= width
tbox[:, [1, 3]] *= height
2018-11-14 15:14:41 +00:00
2019-04-10 16:17:08 +02: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
2019-04-26 23:25:00 +02:00
if pcls.item() not in tcls:
continue
# Best iou, index between pred and targets
2019-04-26 23:33:13 +02:00
m = (pcls == tcls_tensor).nonzero().view(-1)
iou, bi = bbox_iou(pbox, tbox[m]).max(0)
# If iou > threshold and class is correct mark as correct
2019-04-26 23:33:13 +02:00
if iou > iou_thres and m[bi] not in detected: # and pcls == tcls[bi]:
2019-04-10 16:17:08 +02:00
correct[i] = 1
2019-04-26 23:33:13 +02:00
detected.append(m[bi])
2018-11-14 15:14:41 +00:00
2019-04-10 16:17:08 +02: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 15:34:42 +02:00
# Compute statistics
2019-04-18 21:18:54 +02:00
stats = [np.concatenate(x, 0) for x in list(zip(*stats))] # to numpy
if len(stats):
p, r, ap, f1, ap_class = ap_per_class(*stats)
2019-04-05 15:34:42 +02:00
mp, mr, map, mf1 = p.mean(), r.mean(), ap.mean(), f1.mean()
2019-07-16 23:14:10 +02: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 15:34:42 +02:00
# Print results
2019-08-24 16:43:43 +02:00
pf = '%20s' + '%10.3g' * 6 # print format
2019-05-21 17:37:34 +02:00
print(pf % ('all', seen, nt.sum(), mp, mr, map, mf1))
2018-11-14 15:14:41 +00:00
2019-04-05 15:34:42 +02:00
# Print results per class
2019-07-20 17:31:21 +02:00
if verbose and nc > 1 and len(stats):
2019-04-05 15:34:42 +02:00
for i, c in enumerate(ap_class):
2019-04-05 15:51:06 +02: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 02:53:11 +01:00
# Save JSON
2019-04-05 15:34:42 +02:00
if save_json and map and len(jdict):
2019-08-28 16:15:10 +02:00
try:
imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataset.img_files]
with open('results.json', 'w') as file:
json.dump(jdict, file)
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
# 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
cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
cocoEval.params.imgIds = imgIds # [:32] # only evaluate these images
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()
map = cocoEval.stats[1] # update mAP to pycocotools mAP
except:
2019-08-28 16:18:18 +02:00
print('WARNING: missing dependency pycocotools from requirements.txt. Can not compute official COCO mAP.')
2019-02-26 02:53:11 +01:00
2019-04-05 15:34:42 +02:00
# Return results
2019-05-13 14:41:17 +02:00
maps = np.zeros(nc) + map
2019-05-10 14:15:09 +02:00
for i, c in enumerate(ap_class):
maps[c] = ap[i]
2019-08-04 00:12:46 +02:00
return (mp, mr, map, mf1, *(loss / len(dataloader)).tolist()), maps
2018-11-14 15:14:41 +00:00
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='test.py')
2019-04-03 14:25:31 +02:00
parser.add_argument('--cfg', type=str, default='cfg/yolov3-spp.cfg', help='cfg file path')
2019-07-20 15:04:41 +02:00
parser.add_argument('--data', type=str, default='data/coco.data', help='coco.data file path')
2019-04-18 23:05:19 +02:00
parser.add_argument('--weights', type=str, default='weights/yolov3-spp.weights', help='path to weights file')
2019-08-31 18:58:30 +02:00
parser.add_argument('--batch-size', type=int, default=16, help='size of each image batch')
parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
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 13:52:03 +01:00
parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
2019-09-16 14:31:07 +02:00
parser.add_argument('--device', default='', help='device id (i.e. 0 or 0,1) or cpu')
opt = parser.parse_args()
2019-05-03 18:14:16 +02:00
print(opt)
2019-02-10 21:10:50 +01:00
with torch.no_grad():
2019-08-24 20:55:01 +02:00
test(opt.cfg,
opt.data,
opt.weights,
opt.batch_size,
opt.img_size,
opt.iou_thres,
opt.conf_thres,
opt.nms_thres,
opt.save_json)