Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

280 lines
13KB

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