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.

290 lines
13KB

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