predict.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import torch
  3. from ultralytics.data.augment import LetterBox
  4. from ultralytics.engine.predictor import BasePredictor
  5. from ultralytics.engine.results import Results
  6. from ultralytics.utils import ops
  7. class RTDETRPredictor(BasePredictor):
  8. """
  9. RT-DETR (Real-Time Detection Transformer) Predictor extending the BasePredictor class for making predictions using
  10. Baidu's RT-DETR model.
  11. This class leverages the power of Vision Transformers to provide real-time object detection while maintaining
  12. high accuracy. It supports key features like efficient hybrid encoding and IoU-aware query selection.
  13. Example:
  14. ```python
  15. from ultralytics.utils import ASSETS
  16. from ultralytics.models.rtdetr import RTDETRPredictor
  17. args = dict(model='rtdetr-l.pt', source=ASSETS)
  18. predictor = RTDETRPredictor(overrides=args)
  19. predictor.predict_cli()
  20. ```
  21. Attributes:
  22. imgsz (int): Image size for inference (must be square and scale-filled).
  23. args (dict): Argument overrides for the predictor.
  24. """
  25. def postprocess(self, preds, img, orig_imgs):
  26. """
  27. Postprocess the raw predictions from the model to generate bounding boxes and confidence scores.
  28. The method filters detections based on confidence and class if specified in `self.args`.
  29. Args:
  30. preds (list): List of [predictions, extra] from the model.
  31. img (torch.Tensor): Processed input images.
  32. orig_imgs (list or torch.Tensor): Original, unprocessed images.
  33. Returns:
  34. (list[Results]): A list of Results objects containing the post-processed bounding boxes, confidence scores,
  35. and class labels.
  36. """
  37. if not isinstance(preds, (list, tuple)): # list for PyTorch inference but list[0] Tensor for export inference
  38. preds = [preds, None]
  39. nd = preds[0].shape[-1]
  40. bboxes, scores = preds[0].split((4, nd - 4), dim=-1)
  41. if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
  42. orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
  43. results = []
  44. for i, bbox in enumerate(bboxes): # (300, 4)
  45. bbox = ops.xywh2xyxy(bbox)
  46. score, cls = scores[i].max(-1, keepdim=True) # (300, 1)
  47. idx = score.squeeze(-1) > self.args.conf # (300, )
  48. if self.args.classes is not None:
  49. idx = (cls == torch.tensor(self.args.classes, device=cls.device)).any(1) & idx
  50. pred = torch.cat([bbox, score, cls], dim=-1)[idx] # filter
  51. orig_img = orig_imgs[i]
  52. oh, ow = orig_img.shape[:2]
  53. pred[..., [0, 2]] *= ow
  54. pred[..., [1, 3]] *= oh
  55. img_path = self.batch[0][i]
  56. results.append(Results(orig_img, path=img_path, names=self.model.names, boxes=pred))
  57. return results
  58. def pre_transform(self, im):
  59. """
  60. Pre-transforms the input images before feeding them into the model for inference. The input images are
  61. letterboxed to ensure a square aspect ratio and scale-filled. The size must be square(640) and scaleFilled.
  62. Args:
  63. im (list[np.ndarray] |torch.Tensor): Input images of shape (N,3,h,w) for tensor, [(h,w,3) x N] for list.
  64. Returns:
  65. (list): List of pre-transformed images ready for model inference.
  66. """
  67. letterbox = LetterBox(self.imgsz, auto=False, scaleFill=True)
  68. return [letterbox(image=x) for x in im]