val.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. from multiprocessing.pool import ThreadPool
  3. from pathlib import Path
  4. import numpy as np
  5. import torch
  6. import torch.nn.functional as F
  7. from ultralytics.models.yolo.detect import DetectionValidator
  8. from ultralytics.utils import LOGGER, NUM_THREADS, ops
  9. from ultralytics.utils.checks import check_requirements
  10. from ultralytics.utils.metrics import SegmentMetrics, box_iou, mask_iou
  11. from ultralytics.utils.plotting import output_to_target, plot_images
  12. class SegmentationValidator(DetectionValidator):
  13. """
  14. A class extending the DetectionValidator class for validation based on a segmentation model.
  15. Example:
  16. ```python
  17. from ultralytics.models.yolo.segment import SegmentationValidator
  18. args = dict(model='yolov8n-seg.pt', data='coco8-seg.yaml')
  19. validator = SegmentationValidator(args=args)
  20. validator()
  21. ```
  22. """
  23. def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
  24. """Initialize SegmentationValidator and set task to 'segment', metrics to SegmentMetrics."""
  25. super().__init__(dataloader, save_dir, pbar, args, _callbacks)
  26. self.plot_masks = None
  27. self.process = None
  28. self.args.task = 'segment'
  29. self.metrics = SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot)
  30. def preprocess(self, batch):
  31. """Preprocesses batch by converting masks to float and sending to device."""
  32. batch = super().preprocess(batch)
  33. batch['masks'] = batch['masks'].to(self.device).float()
  34. return batch
  35. def init_metrics(self, model):
  36. """Initialize metrics and select mask processing function based on save_json flag."""
  37. super().init_metrics(model)
  38. self.plot_masks = []
  39. if self.args.save_json:
  40. check_requirements('pycocotools>=2.0.6')
  41. self.process = ops.process_mask_upsample # more accurate
  42. else:
  43. self.process = ops.process_mask # faster
  44. def get_desc(self):
  45. """Return a formatted description of evaluation metrics."""
  46. return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Mask(P',
  47. 'R', 'mAP50', 'mAP50-95)')
  48. def postprocess(self, preds):
  49. """Post-processes YOLO predictions and returns output detections with proto."""
  50. p = ops.non_max_suppression(preds[0],
  51. self.args.conf,
  52. self.args.iou,
  53. labels=self.lb,
  54. multi_label=True,
  55. agnostic=self.args.single_cls,
  56. max_det=self.args.max_det,
  57. nc=self.nc)
  58. proto = preds[1][-1] if len(preds[1]) == 3 else preds[1] # second output is len 3 if pt, but only 1 if exported
  59. return p, proto
  60. def update_metrics(self, preds, batch):
  61. """Metrics."""
  62. for si, (pred, proto) in enumerate(zip(preds[0], preds[1])):
  63. idx = batch['batch_idx'] == si
  64. cls = batch['cls'][idx]
  65. bbox = batch['bboxes'][idx]
  66. nl, npr = cls.shape[0], pred.shape[0] # number of labels, predictions
  67. shape = batch['ori_shape'][si]
  68. correct_masks = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
  69. correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
  70. self.seen += 1
  71. if npr == 0:
  72. if nl:
  73. self.stats.append((correct_bboxes, correct_masks, *torch.zeros(
  74. (2, 0), device=self.device), cls.squeeze(-1)))
  75. if self.args.plots:
  76. self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))
  77. continue
  78. # Masks
  79. midx = [si] if self.args.overlap_mask else idx
  80. gt_masks = batch['masks'][midx]
  81. pred_masks = self.process(proto, pred[:, 6:], pred[:, :4], shape=batch['img'][si].shape[1:])
  82. # Predictions
  83. if self.args.single_cls:
  84. pred[:, 5] = 0
  85. predn = pred.clone()
  86. ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,
  87. ratio_pad=batch['ratio_pad'][si]) # native-space pred
  88. # Evaluate
  89. if nl:
  90. height, width = batch['img'].shape[2:]
  91. tbox = ops.xywh2xyxy(bbox) * torch.tensor(
  92. (width, height, width, height), device=self.device) # target boxes
  93. ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,
  94. ratio_pad=batch['ratio_pad'][si]) # native-space labels
  95. labelsn = torch.cat((cls, tbox), 1) # native-space labels
  96. correct_bboxes = self._process_batch(predn, labelsn)
  97. # TODO: maybe remove these `self.` arguments as they already are member variable
  98. correct_masks = self._process_batch(predn,
  99. labelsn,
  100. pred_masks,
  101. gt_masks,
  102. overlap=self.args.overlap_mask,
  103. masks=True)
  104. if self.args.plots:
  105. self.confusion_matrix.process_batch(predn, labelsn)
  106. # Append correct_masks, correct_boxes, pconf, pcls, tcls
  107. self.stats.append((correct_bboxes, correct_masks, pred[:, 4], pred[:, 5], cls.squeeze(-1)))
  108. pred_masks = torch.as_tensor(pred_masks, dtype=torch.uint8)
  109. if self.args.plots and self.batch_i < 3:
  110. self.plot_masks.append(pred_masks[:15].cpu()) # filter top 15 to plot
  111. # Save
  112. if self.args.save_json:
  113. pred_masks = ops.scale_image(pred_masks.permute(1, 2, 0).contiguous().cpu().numpy(),
  114. shape,
  115. ratio_pad=batch['ratio_pad'][si])
  116. self.pred_to_json(predn, batch['im_file'][si], pred_masks)
  117. # if self.args.save_txt:
  118. # save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')
  119. def finalize_metrics(self, *args, **kwargs):
  120. """Sets speed and confusion matrix for evaluation metrics."""
  121. self.metrics.speed = self.speed
  122. self.metrics.confusion_matrix = self.confusion_matrix
  123. def _process_batch(self, detections, labels, pred_masks=None, gt_masks=None, overlap=False, masks=False):
  124. """
  125. Return correct prediction matrix
  126. Args:
  127. detections (array[N, 6]), x1, y1, x2, y2, conf, class
  128. labels (array[M, 5]), class, x1, y1, x2, y2
  129. Returns:
  130. correct (array[N, 10]), for 10 IoU levels
  131. """
  132. if masks:
  133. if overlap:
  134. nl = len(labels)
  135. index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1
  136. gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640)
  137. gt_masks = torch.where(gt_masks == index, 1.0, 0.0)
  138. if gt_masks.shape[1:] != pred_masks.shape[1:]:
  139. gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0]
  140. gt_masks = gt_masks.gt_(0.5)
  141. iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))
  142. else: # boxes
  143. iou = box_iou(labels[:, 1:], detections[:, :4])
  144. return self.match_predictions(detections[:, 5], labels[:, 0], iou)
  145. def plot_val_samples(self, batch, ni):
  146. """Plots validation samples with bounding box labels."""
  147. plot_images(batch['img'],
  148. batch['batch_idx'],
  149. batch['cls'].squeeze(-1),
  150. batch['bboxes'],
  151. batch['masks'],
  152. paths=batch['im_file'],
  153. fname=self.save_dir / f'val_batch{ni}_labels.jpg',
  154. names=self.names,
  155. on_plot=self.on_plot)
  156. def plot_predictions(self, batch, preds, ni):
  157. """Plots batch predictions with masks and bounding boxes."""
  158. plot_images(
  159. batch['img'],
  160. *output_to_target(preds[0], max_det=15), # not set to self.args.max_det due to slow plotting speed
  161. torch.cat(self.plot_masks, dim=0) if len(self.plot_masks) else self.plot_masks,
  162. paths=batch['im_file'],
  163. fname=self.save_dir / f'val_batch{ni}_pred.jpg',
  164. names=self.names,
  165. on_plot=self.on_plot) # pred
  166. self.plot_masks.clear()
  167. def pred_to_json(self, predn, filename, pred_masks):
  168. """Save one JSON result."""
  169. # Example result = {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
  170. from pycocotools.mask import encode # noqa
  171. def single_encode(x):
  172. """Encode predicted masks as RLE and append results to jdict."""
  173. rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]
  174. rle['counts'] = rle['counts'].decode('utf-8')
  175. return rle
  176. stem = Path(filename).stem
  177. image_id = int(stem) if stem.isnumeric() else stem
  178. box = ops.xyxy2xywh(predn[:, :4]) # xywh
  179. box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
  180. pred_masks = np.transpose(pred_masks, (2, 0, 1))
  181. with ThreadPool(NUM_THREADS) as pool:
  182. rles = pool.map(single_encode, pred_masks)
  183. for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())):
  184. self.jdict.append({
  185. 'image_id': image_id,
  186. 'category_id': self.class_map[int(p[5])],
  187. 'bbox': [round(x, 3) for x in b],
  188. 'score': round(p[4], 5),
  189. 'segmentation': rles[i]})
  190. def eval_json(self, stats):
  191. """Return COCO-style object detection evaluation metrics."""
  192. if self.args.save_json and self.is_coco and len(self.jdict):
  193. anno_json = self.data['path'] / 'annotations/instances_val2017.json' # annotations
  194. pred_json = self.save_dir / 'predictions.json' # predictions
  195. LOGGER.info(f'\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')
  196. try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
  197. check_requirements('pycocotools>=2.0.6')
  198. from pycocotools.coco import COCO # noqa
  199. from pycocotools.cocoeval import COCOeval # noqa
  200. for x in anno_json, pred_json:
  201. assert x.is_file(), f'{x} file not found'
  202. anno = COCO(str(anno_json)) # init annotations api
  203. pred = anno.loadRes(str(pred_json)) # init predictions api (must pass string, not Path)
  204. for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'segm')]):
  205. if self.is_coco:
  206. eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files] # im to eval
  207. eval.evaluate()
  208. eval.accumulate()
  209. eval.summarize()
  210. idx = i * 4 + 2
  211. stats[self.metrics.keys[idx + 1]], stats[
  212. self.metrics.keys[idx]] = eval.stats[:2] # update mAP50-95 and mAP50
  213. except Exception as e:
  214. LOGGER.warning(f'pycocotools unable to run: {e}')
  215. return stats