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.

test.py 12KB

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