您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

276 行
12KB

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