You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

324 lines
15KB

  1. import argparse
  2. import glob
  3. import json
  4. import os
  5. from pathlib import Path
  6. import numpy as np
  7. import torch
  8. import yaml
  9. from tqdm import tqdm
  10. from models.experimental import attempt_load
  11. from utils.datasets import create_dataloader
  12. from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, compute_loss, \
  13. non_max_suppression, scale_coords, xyxy2xywh, clip_coords, plot_images, xywh2xyxy, box_iou, output_to_target, \
  14. ap_per_class, set_logging, increment_dir
  15. from utils.torch_utils import select_device, time_synchronized
  16. def test(data,
  17. weights=None,
  18. batch_size=16,
  19. imgsz=640,
  20. conf_thres=0.001,
  21. iou_thres=0.6, # for NMS
  22. save_json=False,
  23. single_cls=False,
  24. augment=False,
  25. verbose=False,
  26. model=None,
  27. dataloader=None,
  28. save_dir=Path(''), # for saving images
  29. save_txt=False, # for auto-labelling
  30. save_conf=False,
  31. plots=True,
  32. log_imgs=0): # number of logged images
  33. # Initialize/load model and set device
  34. training = model is not None
  35. if training: # called by train.py
  36. device = next(model.parameters()).device # get model device
  37. else: # called directly
  38. set_logging()
  39. device = select_device(opt.device, batch_size=batch_size)
  40. save_txt = opt.save_txt # save *.txt labels
  41. # Directories
  42. if save_dir == Path('runs/test'): # if default
  43. os.makedirs('runs/test', exist_ok=True) # make base
  44. save_dir = Path(increment_dir(save_dir / 'exp', opt.name)) # increment run
  45. os.makedirs(save_dir / 'labels' if save_txt else save_dir, exist_ok=True) # make new dir
  46. # Load model
  47. model = attempt_load(weights, map_location=device) # load FP32 model
  48. imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size
  49. # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
  50. # if device.type != 'cpu' and torch.cuda.device_count() > 1:
  51. # model = nn.DataParallel(model)
  52. # Half
  53. half = device.type != 'cpu' # half precision only supported on CUDA
  54. if half:
  55. model.half()
  56. # Configure
  57. model.eval()
  58. with open(data) as f:
  59. data = yaml.load(f, Loader=yaml.FullLoader) # model dict
  60. check_dataset(data) # check
  61. nc = 1 if single_cls else int(data['nc']) # number of classes
  62. iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
  63. niou = iouv.numel()
  64. # Logging
  65. log_imgs = min(log_imgs, 100) # ceil
  66. try:
  67. import wandb # Weights & Biases
  68. except ImportError:
  69. log_imgs = 0
  70. # Dataloader
  71. if not training:
  72. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  73. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  74. path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images
  75. dataloader = create_dataloader(path, imgsz, batch_size, model.stride.max(), opt,
  76. hyp=None, augment=False, cache=False, pad=0.5, rect=True)[0]
  77. seen = 0
  78. names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
  79. coco91class = coco80_to_coco91_class()
  80. s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
  81. p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
  82. loss = torch.zeros(3, device=device)
  83. jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
  84. for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
  85. img = img.to(device, non_blocking=True)
  86. img = img.half() if half else img.float() # uint8 to fp16/32
  87. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  88. targets = targets.to(device)
  89. nb, _, height, width = img.shape # batch size, channels, height, width
  90. whwh = torch.Tensor([width, height, width, height]).to(device)
  91. # Disable gradients
  92. with torch.no_grad():
  93. # Run model
  94. t = time_synchronized()
  95. inf_out, train_out = model(img, augment=augment) # inference and training outputs
  96. t0 += time_synchronized() - t
  97. # Compute loss
  98. if training: # if model has loss hyperparameters
  99. loss += compute_loss([x.float() for x in train_out], targets, model)[1][:3] # box, obj, cls
  100. # Run NMS
  101. t = time_synchronized()
  102. output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres)
  103. t1 += time_synchronized() - t
  104. # Statistics per image
  105. for si, pred in enumerate(output):
  106. labels = targets[targets[:, 0] == si, 1:]
  107. nl = len(labels)
  108. tcls = labels[:, 0].tolist() if nl else [] # target class
  109. seen += 1
  110. if pred is None:
  111. if nl:
  112. stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
  113. continue
  114. # Append to text file
  115. if save_txt:
  116. gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
  117. x = pred.clone()
  118. x[:, :4] = scale_coords(img[si].shape[1:], x[:, :4], shapes[si][0], shapes[si][1]) # to original
  119. for *xyxy, conf, cls in x:
  120. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  121. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  122. with open(str(save_dir / 'labels' / Path(paths[si]).stem) + '.txt', 'a') as f:
  123. f.write(('%g ' * len(line) + '\n') % line)
  124. # W&B logging
  125. if len(wandb_images) < log_imgs:
  126. box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
  127. "class_id": int(cls),
  128. "box_caption": "%s %.3f" % (names[cls], conf),
  129. "scores": {"class_score": conf},
  130. "domain": "pixel"} for *xyxy, conf, cls in pred.clone().tolist()]
  131. boxes = {"predictions": {"box_data": box_data, "class_labels": names}}
  132. wandb_images.append(wandb.Image(img[si], boxes=boxes))
  133. # Clip boxes to image bounds
  134. clip_coords(pred, (height, width))
  135. # Append to pycocotools JSON dictionary
  136. if save_json:
  137. # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
  138. image_id = Path(paths[si]).stem
  139. box = pred[:, :4].clone() # xyxy
  140. scale_coords(img[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
  141. box = xyxy2xywh(box) # xywh
  142. box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
  143. for p, b in zip(pred.tolist(), box.tolist()):
  144. jdict.append({'image_id': int(image_id) if image_id.isnumeric() else image_id,
  145. 'category_id': coco91class[int(p[5])],
  146. 'bbox': [round(x, 3) for x in b],
  147. 'score': round(p[4], 5)})
  148. # Assign all predictions as incorrect
  149. correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
  150. if nl:
  151. detected = [] # target indices
  152. tcls_tensor = labels[:, 0]
  153. # target boxes
  154. tbox = xywh2xyxy(labels[:, 1:5]) * whwh
  155. # Per target class
  156. for cls in torch.unique(tcls_tensor):
  157. ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
  158. pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
  159. # Search for detections
  160. if pi.shape[0]:
  161. # Prediction to target ious
  162. ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices
  163. # Append detections
  164. detected_set = set()
  165. for j in (ious > iouv[0]).nonzero(as_tuple=False):
  166. d = ti[i[j]] # detected target
  167. if d.item() not in detected_set:
  168. detected_set.add(d.item())
  169. detected.append(d)
  170. correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
  171. if len(detected) == nl: # all targets already located in image
  172. break
  173. # Append statistics (correct, conf, pcls, tcls)
  174. stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
  175. # Plot images
  176. if plots and batch_i < 1:
  177. f = save_dir / f'test_batch{batch_i}_gt.jpg' # filename
  178. plot_images(img, targets, paths, str(f), names) # ground truth
  179. f = save_dir / f'test_batch{batch_i}_pred.jpg'
  180. plot_images(img, output_to_target(output, width, height), paths, str(f), names) # predictions
  181. # W&B logging
  182. if wandb_images:
  183. wandb.log({"outputs": wandb_images})
  184. # Compute statistics
  185. stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
  186. if len(stats) and stats[0].any():
  187. p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, fname=save_dir / 'precision-recall_curve.png')
  188. p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, AP@0.5, AP@0.5:0.95]
  189. mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
  190. nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
  191. else:
  192. nt = torch.zeros(1)
  193. # Print results
  194. pf = '%20s' + '%12.3g' * 6 # print format
  195. print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
  196. # Print results per class
  197. if verbose and nc > 1 and len(stats):
  198. for i, c in enumerate(ap_class):
  199. print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
  200. # Print speeds
  201. t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
  202. if not training:
  203. print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
  204. # Save JSON
  205. if save_json and len(jdict):
  206. w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
  207. file = save_dir / f"detections_val2017_{w}_results.json" # predicted annotations file
  208. print('\nCOCO mAP with pycocotools... saving %s...' % file)
  209. with open(file, 'w') as f:
  210. json.dump(jdict, f)
  211. try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
  212. from pycocotools.coco import COCO
  213. from pycocotools.cocoeval import COCOeval
  214. imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files]
  215. cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api
  216. cocoDt = cocoGt.loadRes(str(file)) # initialize COCO pred api
  217. cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
  218. cocoEval.params.imgIds = imgIds # image IDs to evaluate
  219. cocoEval.evaluate()
  220. cocoEval.accumulate()
  221. cocoEval.summarize()
  222. map, map50 = cocoEval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
  223. except Exception as e:
  224. print('ERROR: pycocotools unable to run: %s' % e)
  225. # Return results
  226. print('Results saved to %s' % save_dir)
  227. model.float() # for training
  228. maps = np.zeros(nc) + map
  229. for i, c in enumerate(ap_class):
  230. maps[c] = ap[i]
  231. return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
  232. if __name__ == '__main__':
  233. parser = argparse.ArgumentParser(prog='test.py')
  234. parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
  235. parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
  236. parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
  237. parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
  238. parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
  239. parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS')
  240. parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
  241. parser.add_argument('--task', default='val', help="'val', 'test', 'study'")
  242. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  243. parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
  244. parser.add_argument('--augment', action='store_true', help='augmented inference')
  245. parser.add_argument('--verbose', action='store_true', help='report mAP by class')
  246. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  247. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  248. parser.add_argument('--save-dir', type=str, default='runs/test', help='directory to save results')
  249. parser.add_argument('--name', default='', help='name to append to --save-dir: i.e. runs/{N} -> runs/{N}_{name}')
  250. opt = parser.parse_args()
  251. opt.save_json |= opt.data.endswith('coco.yaml')
  252. opt.data = check_file(opt.data) # check file
  253. print(opt)
  254. if opt.task in ['val', 'test']: # run normally
  255. test(opt.data,
  256. opt.weights,
  257. opt.batch_size,
  258. opt.img_size,
  259. opt.conf_thres,
  260. opt.iou_thres,
  261. opt.save_json,
  262. opt.single_cls,
  263. opt.augment,
  264. opt.verbose,
  265. save_dir=Path(opt.save_dir),
  266. save_txt=opt.save_txt,
  267. save_conf=opt.save_conf,
  268. )
  269. elif opt.task == 'study': # run over a range of settings and save/plot
  270. for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
  271. f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to
  272. x = list(range(320, 800, 64)) # x axis
  273. y = [] # y axis
  274. for i in x: # img-size
  275. print('\nRunning %s point %s...' % (f, i))
  276. r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json)
  277. y.append(r + t) # results and times
  278. np.savetxt(f, y, fmt='%10.4g') # save
  279. os.system('zip -r study.zip study_*.txt')
  280. # utils.general.plot_study_txt(f, x) # plot