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.

288 satır
13KB

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