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.

275 line
12KB

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