val.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. from pathlib import Path
  3. import cv2
  4. import numpy as np
  5. import torch
  6. from ultralytics.data import YOLODataset
  7. from ultralytics.data.augment import Compose, Format, v8_transforms
  8. from ultralytics.models.yolo.detect import DetectionValidator
  9. from ultralytics.utils import colorstr, ops
  10. __all__ = 'RTDETRValidator', # tuple or list
  11. # TODO: Temporarily RT-DETR does not need padding.
  12. class RTDETRDataset(YOLODataset):
  13. def __init__(self, *args, data=None, **kwargs):
  14. super().__init__(*args, data=data, use_segments=False, use_keypoints=False, **kwargs)
  15. # NOTE: add stretch version load_image for rtdetr mosaic
  16. def load_image(self, i):
  17. """Loads 1 image from dataset index 'i', returns (im, resized hw)."""
  18. im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i]
  19. if im is None: # not cached in RAM
  20. if fn.exists(): # load npy
  21. im = np.load(fn)
  22. else: # read image
  23. im = cv2.imread(f) # BGR
  24. if im is None:
  25. raise FileNotFoundError(f'Image Not Found {f}')
  26. h0, w0 = im.shape[:2] # orig hw
  27. im = cv2.resize(im, (self.imgsz, self.imgsz), interpolation=cv2.INTER_LINEAR)
  28. # Add to buffer if training with augmentations
  29. if self.augment:
  30. self.ims[i], self.im_hw0[i], self.im_hw[i] = im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
  31. self.buffer.append(i)
  32. if len(self.buffer) >= self.max_buffer_length:
  33. j = self.buffer.pop(0)
  34. self.ims[j], self.im_hw0[j], self.im_hw[j] = None, None, None
  35. return im, (h0, w0), im.shape[:2]
  36. return self.ims[i], self.im_hw0[i], self.im_hw[i]
  37. def build_transforms(self, hyp=None):
  38. """Temporary, only for evaluation."""
  39. if self.augment:
  40. hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0
  41. hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0
  42. transforms = v8_transforms(self, self.imgsz, hyp, stretch=True)
  43. else:
  44. # transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), auto=False, scaleFill=True)])
  45. transforms = Compose([])
  46. transforms.append(
  47. Format(bbox_format='xywh',
  48. normalize=True,
  49. return_mask=self.use_segments,
  50. return_keypoint=self.use_keypoints,
  51. batch_idx=True,
  52. mask_ratio=hyp.mask_ratio,
  53. mask_overlap=hyp.overlap_mask))
  54. return transforms
  55. class RTDETRValidator(DetectionValidator):
  56. """
  57. A class extending the DetectionValidator class for validation based on an RT-DETR detection model.
  58. Example:
  59. ```python
  60. from ultralytics.models.rtdetr import RTDETRValidator
  61. args = dict(model='rtdetr-l.pt', data='coco8.yaml')
  62. validator = RTDETRValidator(args=args)
  63. validator()
  64. ```
  65. """
  66. def build_dataset(self, img_path, mode='val', batch=None):
  67. """
  68. Build an RTDETR Dataset.
  69. Args:
  70. img_path (str): Path to the folder containing images.
  71. mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
  72. batch (int, optional): Size of batches, this is for `rect`. Defaults to None.
  73. """
  74. return RTDETRDataset(
  75. img_path=img_path,
  76. imgsz=self.args.imgsz,
  77. batch_size=batch,
  78. augment=False, # no augmentation
  79. hyp=self.args,
  80. rect=False, # no rect
  81. cache=self.args.cache or None,
  82. prefix=colorstr(f'{mode}: '),
  83. data=self.data)
  84. def postprocess(self, preds):
  85. """Apply Non-maximum suppression to prediction outputs."""
  86. bs, _, nd = preds[0].shape
  87. bboxes, scores = preds[0].split((4, nd - 4), dim=-1)
  88. bboxes *= self.args.imgsz
  89. outputs = [torch.zeros((0, 6), device=bboxes.device)] * bs
  90. for i, bbox in enumerate(bboxes): # (300, 4)
  91. bbox = ops.xywh2xyxy(bbox)
  92. score, cls = scores[i].max(-1) # (300, )
  93. # Do not need threshold for evaluation as only got 300 boxes here.
  94. # idx = score > self.args.conf
  95. pred = torch.cat([bbox, score[..., None], cls[..., None]], dim=-1) # filter
  96. # sort by confidence to correctly get internal metrics.
  97. pred = pred[score.argsort(descending=True)]
  98. outputs[i] = pred # [idx]
  99. return outputs
  100. def update_metrics(self, preds, batch):
  101. """Metrics."""
  102. for si, pred in enumerate(preds):
  103. idx = batch['batch_idx'] == si
  104. cls = batch['cls'][idx]
  105. bbox = batch['bboxes'][idx]
  106. nl, npr = cls.shape[0], pred.shape[0] # number of labels, predictions
  107. shape = batch['ori_shape'][si]
  108. correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
  109. self.seen += 1
  110. if npr == 0:
  111. if nl:
  112. self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))
  113. if self.args.plots:
  114. self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))
  115. continue
  116. # Predictions
  117. if self.args.single_cls:
  118. pred[:, 5] = 0
  119. predn = pred.clone()
  120. predn[..., [0, 2]] *= shape[1] / self.args.imgsz # native-space pred
  121. predn[..., [1, 3]] *= shape[0] / self.args.imgsz # native-space pred
  122. # Evaluate
  123. if nl:
  124. tbox = ops.xywh2xyxy(bbox) # target boxes
  125. tbox[..., [0, 2]] *= shape[1] # native-space pred
  126. tbox[..., [1, 3]] *= shape[0] # native-space pred
  127. labelsn = torch.cat((cls, tbox), 1) # native-space labels
  128. # NOTE: To get correct metrics, the inputs of `_process_batch` should always be float32 type.
  129. correct_bboxes = self._process_batch(predn.float(), labelsn)
  130. # TODO: maybe remove these `self.` arguments as they already are member variable
  131. if self.args.plots:
  132. self.confusion_matrix.process_batch(predn, labelsn)
  133. self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1))) # (conf, pcls, tcls)
  134. # Save
  135. if self.args.save_json:
  136. self.pred_to_json(predn, batch['im_file'][si])
  137. if self.args.save_txt:
  138. file = self.save_dir / 'labels' / f'{Path(batch["im_file"][si]).stem}.txt'
  139. self.save_one_txt(predn, self.args.save_conf, shape, file)