val.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import torch
  3. from ultralytics.data import YOLODataset
  4. from ultralytics.data.augment import Compose, Format, v8_transforms
  5. from ultralytics.models.yolo.detect import DetectionValidator
  6. from ultralytics.utils import colorstr, ops
  7. __all__ = ("RTDETRValidator",) # tuple or list
  8. class RTDETRDataset(YOLODataset):
  9. """
  10. Real-Time DEtection and TRacking (RT-DETR) dataset class extending the base YOLODataset class.
  11. This specialized dataset class is designed for use with the RT-DETR object detection model and is optimized for
  12. real-time detection and tracking tasks.
  13. """
  14. def __init__(self, *args, data=None, **kwargs):
  15. """Initialize the RTDETRDataset class by inheriting from the YOLODataset class."""
  16. super().__init__(*args, data=data, **kwargs)
  17. # NOTE: add stretch version load_image for RTDETR mosaic
  18. def load_image(self, i, rect_mode=False):
  19. """Loads 1 image from dataset index 'i', returns (im, resized hw)."""
  20. return super().load_image(i=i, rect_mode=rect_mode)
  21. def build_transforms(self, hyp=None):
  22. """Temporary, only for evaluation."""
  23. if self.augment:
  24. hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0
  25. hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0
  26. transforms = v8_transforms(self, self.imgsz, hyp, stretch=True)
  27. else:
  28. # transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), auto=False, scaleFill=True)])
  29. transforms = Compose([])
  30. transforms.append(
  31. Format(
  32. bbox_format="xywh",
  33. normalize=True,
  34. return_mask=self.use_segments,
  35. return_keypoint=self.use_keypoints,
  36. batch_idx=True,
  37. mask_ratio=hyp.mask_ratio,
  38. mask_overlap=hyp.overlap_mask,
  39. )
  40. )
  41. return transforms
  42. class RTDETRValidator(DetectionValidator):
  43. """
  44. RTDETRValidator extends the DetectionValidator class to provide validation capabilities specifically tailored for
  45. the RT-DETR (Real-Time DETR) object detection model.
  46. The class allows building of an RTDETR-specific dataset for validation, applies Non-maximum suppression for
  47. post-processing, and updates evaluation metrics accordingly.
  48. Example:
  49. ```python
  50. from ultralytics.models.rtdetr import RTDETRValidator
  51. args = dict(model='rtdetr-l.pt', data='coco8.yaml')
  52. validator = RTDETRValidator(args=args)
  53. validator()
  54. ```
  55. Note:
  56. For further details on the attributes and methods, refer to the parent DetectionValidator class.
  57. """
  58. def build_dataset(self, img_path, mode="val", batch=None):
  59. """
  60. Build an RTDETR Dataset.
  61. Args:
  62. img_path (str): Path to the folder containing images.
  63. mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
  64. batch (int, optional): Size of batches, this is for `rect`. Defaults to None.
  65. """
  66. return RTDETRDataset(
  67. img_path=img_path,
  68. is_train_on_platform=self.args.is_train_on_platform,
  69. imgsz=self.args.imgsz,
  70. batch_size=batch,
  71. augment=False, # no augmentation
  72. hyp=self.args,
  73. rect=False, # no rect
  74. cache=self.args.cache or None,
  75. prefix=colorstr(f"{mode}: "),
  76. data=self.data,
  77. )
  78. def postprocess(self, preds):
  79. """Apply Non-maximum suppression to prediction outputs."""
  80. if not isinstance(preds, (list, tuple)): # list for PyTorch inference but list[0] Tensor for export inference
  81. preds = [preds, None]
  82. bs, _, nd = preds[0].shape
  83. bboxes, scores = preds[0].split((4, nd - 4), dim=-1)
  84. bboxes *= self.args.imgsz
  85. outputs = [torch.zeros((0, 6), device=bboxes.device)] * bs
  86. for i, bbox in enumerate(bboxes): # (300, 4)
  87. bbox = ops.xywh2xyxy(bbox)
  88. score, cls = scores[i].max(-1) # (300, )
  89. # Do not need threshold for evaluation as only got 300 boxes here
  90. # idx = score > self.args.conf
  91. pred = torch.cat([bbox, score[..., None], cls[..., None]], dim=-1) # filter
  92. # Sort by confidence to correctly get internal metrics
  93. pred = pred[score.argsort(descending=True)]
  94. outputs[i] = pred # [idx]
  95. return outputs
  96. def _prepare_batch(self, si, batch):
  97. """Prepares a batch for training or inference by applying transformations."""
  98. idx = batch["batch_idx"] == si
  99. cls = batch["cls"][idx].squeeze(-1)
  100. bbox = batch["bboxes"][idx]
  101. ori_shape = batch["ori_shape"][si]
  102. imgsz = batch["img"].shape[2:]
  103. ratio_pad = batch["ratio_pad"][si]
  104. if len(cls):
  105. bbox = ops.xywh2xyxy(bbox) # target boxes
  106. bbox[..., [0, 2]] *= ori_shape[1] # native-space pred
  107. bbox[..., [1, 3]] *= ori_shape[0] # native-space pred
  108. return {"cls": cls, "bbox": bbox, "ori_shape": ori_shape, "imgsz": imgsz, "ratio_pad": ratio_pad}
  109. def _prepare_pred(self, pred, pbatch):
  110. """Prepares and returns a batch with transformed bounding boxes and class labels."""
  111. predn = pred.clone()
  112. predn[..., [0, 2]] *= pbatch["ori_shape"][1] / self.args.imgsz # native-space pred
  113. predn[..., [1, 3]] *= pbatch["ori_shape"][0] / self.args.imgsz # native-space pred
  114. return predn.float()