predict.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import torch
  3. from ultralytics.engine.predictor import BasePredictor
  4. from ultralytics.engine.results import Results
  5. from ultralytics.utils import ops
  6. class NASPredictor(BasePredictor):
  7. """
  8. Ultralytics YOLO NAS Predictor for object detection.
  9. This class extends the `BasePredictor` from Ultralytics engine and is responsible for post-processing the
  10. raw predictions generated by the YOLO NAS models. It applies operations like non-maximum suppression and
  11. scaling the bounding boxes to fit the original image dimensions.
  12. Attributes:
  13. args (Namespace): Namespace containing various configurations for post-processing.
  14. Example:
  15. ```python
  16. from ultralytics import NAS
  17. model = NAS('yolo_nas_s')
  18. predictor = model.predictor
  19. # Assumes that raw_preds, img, orig_imgs are available
  20. results = predictor.postprocess(raw_preds, img, orig_imgs)
  21. ```
  22. Note:
  23. Typically, this class is not instantiated directly. It is used internally within the `NAS` class.
  24. """
  25. def postprocess(self, preds_in, img, orig_imgs):
  26. """Postprocess predictions and returns a list of Results objects."""
  27. # Cat boxes and class scores
  28. boxes = ops.xyxy2xywh(preds_in[0][0])
  29. preds = torch.cat((boxes, preds_in[0][1]), -1).permute(0, 2, 1)
  30. preds = ops.non_max_suppression(
  31. preds,
  32. self.args.conf,
  33. self.args.iou,
  34. agnostic=self.args.agnostic_nms,
  35. max_det=self.args.max_det,
  36. classes=self.args.classes,
  37. )
  38. if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
  39. orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
  40. results = []
  41. for i, pred in enumerate(preds):
  42. orig_img = orig_imgs[i]
  43. pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
  44. img_path = self.batch[0][i]
  45. results.append(Results(orig_img, path=img_path, names=self.model.names, boxes=pred))
  46. return results