─░├žeri─če ge├ž

Referans i├žin ultralytics/models/rtdetr/predict.py

Not

Bu dosya https://github.com/ultralytics/ultralytics/blob/main/ ultralytics/models/rtdetr/predict .py adresinde mevcuttur. Bir sorun tespit ederseniz l├╝tfen bir ├çekme ─░ste─či ­čŤá´ŞĆ ile katk─▒da bulunarak d├╝zeltilmesine yard─▒mc─▒ olun. Te┼čekk├╝rler ­čÖĆ!



ultralytics.models.rtdetr.predict.RTDETRPredictor

├ťsler: BasePredictor

RT-DETR (Real-Time Detection Transformer) kullanarak tahminler yapmak i├žin BasePredictor s─▒n─▒f─▒n─▒ geni┼čleten Predictor Baidu'nun RT-DETR modeli.

Bu s─▒n─▒f, Vision Transformers'─▒n g├╝c├╝nden yararlanarak ger├žek zamanl─▒ nesne alg─▒lamas─▒ sa─člarken y├╝ksek do─čruluk. Verimli hibrit kodlama ve IoU fark─▒ndal─▒ sorgu se├žimi gibi temel ├Âzellikleri destekler.

├ľrnek
from ultralytics.utils import ASSETS
from ultralytics.models.rtdetr import RTDETRPredictor

args = dict(model='rtdetr-l.pt', source=ASSETS)
predictor = RTDETRPredictor(overrides=args)
predictor.predict_cli()

Nitelikler:

─░sim Tip A├ž─▒klama
imgsz int

├ç─▒kar─▒m i├žin g├Âr├╝nt├╝ boyutu (kare ve ├Âl├žek dolgulu olmal─▒d─▒r).

args dict

├ľng├Âr├╝c├╝ i├žin ba─č─▒ms─▒z de─či┼čken ge├žersiz k─▒lmalar─▒.

Kaynak kodu ultralytics/models/rtdetr/predict.py
class RTDETRPredictor(BasePredictor):
    """
    RT-DETR (Real-Time Detection Transformer) Predictor extending the BasePredictor class for making predictions using
    Baidu's RT-DETR model.

    This class leverages the power of Vision Transformers to provide real-time object detection while maintaining
    high accuracy. It supports key features like efficient hybrid encoding and IoU-aware query selection.

    Example:
        ```python
        from ultralytics.utils import ASSETS
        from ultralytics.models.rtdetr import RTDETRPredictor

        args = dict(model='rtdetr-l.pt', source=ASSETS)
        predictor = RTDETRPredictor(overrides=args)
        predictor.predict_cli()
        ```

    Attributes:
        imgsz (int): Image size for inference (must be square and scale-filled).
        args (dict): Argument overrides for the predictor.
    """

    def postprocess(self, preds, img, orig_imgs):
        """
        Postprocess the raw predictions from the model to generate bounding boxes and confidence scores.

        The method filters detections based on confidence and class if specified in `self.args`.

        Args:
            preds (list): List of [predictions, extra] from the model.
            img (torch.Tensor): Processed input images.
            orig_imgs (list or torch.Tensor): Original, unprocessed images.

        Returns:
            (list[Results]): A list of Results objects containing the post-processed bounding boxes, confidence scores,
                and class labels.
        """
        if not isinstance(preds, (list, tuple)):  # list for PyTorch inference but list[0] Tensor for export inference
            preds = [preds, None]

        nd = preds[0].shape[-1]
        bboxes, scores = preds[0].split((4, nd - 4), dim=-1)

        if not isinstance(orig_imgs, list):  # input images are a torch.Tensor, not a list
            orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)

        results = []
        for i, bbox in enumerate(bboxes):  # (300, 4)
            bbox = ops.xywh2xyxy(bbox)
            score, cls = scores[i].max(-1, keepdim=True)  # (300, 1)
            idx = score.squeeze(-1) > self.args.conf  # (300, )
            if self.args.classes is not None:
                idx = (cls == torch.tensor(self.args.classes, device=cls.device)).any(1) & idx
            pred = torch.cat([bbox, score, cls], dim=-1)[idx]  # filter
            orig_img = orig_imgs[i]
            oh, ow = orig_img.shape[:2]
            pred[..., [0, 2]] *= ow
            pred[..., [1, 3]] *= oh
            img_path = self.batch[0][i]
            results.append(Results(orig_img, path=img_path, names=self.model.names, boxes=pred))
        return results

    def pre_transform(self, im):
        """
        Pre-transforms the input images before feeding them into the model for inference. The input images are
        letterboxed to ensure a square aspect ratio and scale-filled. The size must be square(640) and scaleFilled.

        Args:
            im (list[np.ndarray] |torch.Tensor): Input images of shape (N,3,h,w) for tensor, [(h,w,3) x N] for list.

        Returns:
            (list): List of pre-transformed images ready for model inference.
        """
        letterbox = LetterBox(self.imgsz, auto=False, scaleFill=True)
        return [letterbox(image=x) for x in im]

postprocess(preds, img, orig_imgs)

S─▒n─▒rlay─▒c─▒ kutular ve g├╝ven puanlar─▒ olu┼čturmak i├žin modelden gelen ham tahminleri sonradan i┼čleyin.

Y├Ântem, tespitleri g├╝ven ve s─▒n─▒f temelinde filtreler. self.args.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
preds list

Modelden [tahminler, ekstra] listesi.

gerekli
img Tensor

─░┼členmi┼č giri┼č g├Âr├╝nt├╝leri.

gerekli
orig_imgs list or Tensor

Orijinal, i┼členmemi┼č g├Âr├╝nt├╝ler.

gerekli

─░ade:

Tip A├ž─▒klama
list[Results]

─░┼členmi┼č s─▒n─▒rlay─▒c─▒ kutular─▒, g├╝ven puanlar─▒n─▒ i├žeren Sonu├žlar nesnelerinin listesi, ve s─▒n─▒f etiketleri.

Kaynak kodu ultralytics/models/rtdetr/predict.py
def postprocess(self, preds, img, orig_imgs):
    """
    Postprocess the raw predictions from the model to generate bounding boxes and confidence scores.

    The method filters detections based on confidence and class if specified in `self.args`.

    Args:
        preds (list): List of [predictions, extra] from the model.
        img (torch.Tensor): Processed input images.
        orig_imgs (list or torch.Tensor): Original, unprocessed images.

    Returns:
        (list[Results]): A list of Results objects containing the post-processed bounding boxes, confidence scores,
            and class labels.
    """
    if not isinstance(preds, (list, tuple)):  # list for PyTorch inference but list[0] Tensor for export inference
        preds = [preds, None]

    nd = preds[0].shape[-1]
    bboxes, scores = preds[0].split((4, nd - 4), dim=-1)

    if not isinstance(orig_imgs, list):  # input images are a torch.Tensor, not a list
        orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)

    results = []
    for i, bbox in enumerate(bboxes):  # (300, 4)
        bbox = ops.xywh2xyxy(bbox)
        score, cls = scores[i].max(-1, keepdim=True)  # (300, 1)
        idx = score.squeeze(-1) > self.args.conf  # (300, )
        if self.args.classes is not None:
            idx = (cls == torch.tensor(self.args.classes, device=cls.device)).any(1) & idx
        pred = torch.cat([bbox, score, cls], dim=-1)[idx]  # filter
        orig_img = orig_imgs[i]
        oh, ow = orig_img.shape[:2]
        pred[..., [0, 2]] *= ow
        pred[..., [1, 3]] *= oh
        img_path = self.batch[0][i]
        results.append(Results(orig_img, path=img_path, names=self.model.names, boxes=pred))
    return results

pre_transform(im)

├ç─▒kar─▒m i├žin modele beslemeden ├Ânce giri┼č g├Âr├╝nt├╝lerini ├Ânceden d├Ân├╝┼čt├╝r├╝r. Giri┼č g├Âr├╝nt├╝leri ┼čunlard─▒r kare en boy oran─▒ sa─člamak i├žin letterboxed ve scale-filled. Boyut kare(640) ve scaleFilled olmal─▒d─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
im list[ndarray] | Tensor

tensor i├žin (N,3,h,w) , liste i├žin [(h,w,3) x N] ┼čeklinde girdi g├Âr├╝nt├╝leri.

gerekli

─░ade:

Tip A├ž─▒klama
list

Model ├ž─▒kar─▒m─▒ i├žin haz─▒r, ├Ânceden d├Ân├╝┼čt├╝r├╝lm├╝┼č g├Âr├╝nt├╝lerin listesi.

Kaynak kodu ultralytics/models/rtdetr/predict.py
def pre_transform(self, im):
    """
    Pre-transforms the input images before feeding them into the model for inference. The input images are
    letterboxed to ensure a square aspect ratio and scale-filled. The size must be square(640) and scaleFilled.

    Args:
        im (list[np.ndarray] |torch.Tensor): Input images of shape (N,3,h,w) for tensor, [(h,w,3) x N] for list.

    Returns:
        (list): List of pre-transformed images ready for model inference.
    """
    letterbox = LetterBox(self.imgsz, auto=False, scaleFill=True)
    return [letterbox(image=x) for x in im]





Created 2023-11-12, Updated 2024-06-02
Authors: glenn-jocher (5), Burhan-Q (1)