рд╕рд╛рдордЧреНрд░реА рдкрд░ рдЬрд╛рдПрдВ

рдХреЗ рд▓рд┐рдП рд╕рдВрджрд░реНрдн ultralytics/engine/results.py

рдиреЛрдЯ

рдпрд╣ рдлрд╝рд╛рдЗрд▓ рдпрд╣рд╛рдБ рдЙрдкрд▓рдмреНрдз рд╣реИ https://github.com/ultralytics/ultralytics/рдмреВрдБрдж/рдореБрдЦреНрдп/ultralytics/рдЗрдВрдЬрди/results.pyред рдпрджрд┐ рдЖрдк рдХреЛрдИ рд╕рдорд╕реНрдпрд╛ рджреЗрдЦрддреЗ рд╣реИрдВ рддреЛ рдХреГрдкрдпрд╛ рдкреБрд▓ рдЕрдиреБрд░реЛрдз рдХрд╛ рдпреЛрдЧрджрд╛рди рдХрд░рдХреЗ рдЗрд╕реЗ рдареАрдХ рдХрд░рдиреЗ рдореЗрдВ рдорджрдж рдХрд░реЗрдВ ЁЯЫая╕Пред ЁЯЩП рдзрдиреНрдпрд╡рд╛рдж !



ultralytics.engine.results.BaseTensor

рдХрд╛ рд░реВрдк: SimpleClass

рдиреАрдВрд╡ tensor рдЖрд╕рд╛рди рд╣реЗрд░рдлреЗрд░ рдФрд░ рдбрд┐рд╡рд╛рдЗрд╕ рд╣реИрдВрдбрд▓рд┐рдВрдЧ рдХреЗ рд▓рд┐рдП рдЕрддрд┐рд░рд┐рдХреНрдд рддрд░реАрдХреЛрдВ рдХреЗ рд╕рд╛рде рд╡рд░реНрдЧред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class BaseTensor(SimpleClass):
    """Base tensor class with additional methods for easy manipulation and device handling."""

    def __init__(self, data, orig_shape) -> None:
        """
        Initialize BaseTensor with data and original shape.

        Args:
            data (torch.Tensor | np.ndarray): Predictions, such as bboxes, masks and keypoints.
            orig_shape (tuple): Original shape of image.
        """
        assert isinstance(data, (torch.Tensor, np.ndarray))
        self.data = data
        self.orig_shape = orig_shape

    @property
    def shape(self):
        """Return the shape of the data tensor."""
        return self.data.shape

    def cpu(self):
        """Return a copy of the tensor on CPU memory."""
        return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu(), self.orig_shape)

    def numpy(self):
        """Return a copy of the tensor as a numpy array."""
        return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.numpy(), self.orig_shape)

    def cuda(self):
        """Return a copy of the tensor on GPU memory."""
        return self.__class__(torch.as_tensor(self.data).cuda(), self.orig_shape)

    def to(self, *args, **kwargs):
        """Return a copy of the tensor with the specified device and dtype."""
        return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape)

    def __len__(self):  # override len(results)
        """Return the length of the data tensor."""
        return len(self.data)

    def __getitem__(self, idx):
        """Return a BaseTensor with the specified index of the data tensor."""
        return self.__class__(self.data[idx], self.orig_shape)

shape property

рдбреЗрдЯрд╛ рдХрд╛ рдЖрдХрд╛рд░ рд▓реМрдЯрд╛рдирд╛ tensor.

__getitem__(idx)

рдбреЗрдЯрд╛ рдХреЗ рдирд┐рд░реНрджрд┐рд╖реНрдЯ рд╕реВрдЪрдХрд╛рдВрдХ рдХреЗ рд╕рд╛рде рдПрдХ BaseTensor рд▓реМрдЯрд╛рдПрдВ tensor.

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __getitem__(self, idx):
    """Return a BaseTensor with the specified index of the data tensor."""
    return self.__class__(self.data[idx], self.orig_shape)

__init__(data, orig_shape)

рдбреЗрдЯрд╛ рдФрд░ рдореВрд▓ рдЖрдХрд╛рд░ рдХреЗ рд╕рд╛рде BaseTensor рдХреЛ рдкреНрд░рд╛рд░рдВрдн рдХрд░реЗрдВред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
data Tensor | ndarray

рднрд╡рд┐рд╖реНрдпрд╡рд╛рдгрд┐рдпрд╛рдВ, рдЬреИрд╕реЗ bboxes, рдорд╛рд╕реНрдХ рдФрд░ рдХреАрдкреЙрдЗрдВрдЯред

рдЖрд╡рд╢реНрдпрдХ
orig_shape tuple

рдЫрд╡рд┐ рдХрд╛ рдореВрд▓ рдЖрдХрд╛рд░ред

рдЖрд╡рд╢реНрдпрдХ
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __init__(self, data, orig_shape) -> None:
    """
    Initialize BaseTensor with data and original shape.

    Args:
        data (torch.Tensor | np.ndarray): Predictions, such as bboxes, masks and keypoints.
        orig_shape (tuple): Original shape of image.
    """
    assert isinstance(data, (torch.Tensor, np.ndarray))
    self.data = data
    self.orig_shape = orig_shape

__len__()

рдбреЗрдЯрд╛ рдХреА рд▓рдВрдмрд╛рдИ рд▓реМрдЯрд╛рдПрдВ tensor.

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __len__(self):  # override len(results)
    """Return the length of the data tensor."""
    return len(self.data)

cpu()

рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рдПрдВ tensor CPU рдореЗрдореЛрд░реА рдкрд░ред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def cpu(self):
    """Return a copy of the tensor on CPU memory."""
    return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu(), self.orig_shape)

cuda()

рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рдПрдВ tensor GPU рдореЗрдореЛрд░реА рдкрд░ред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def cuda(self):
    """Return a copy of the tensor on GPU memory."""
    return self.__class__(torch.as_tensor(self.data).cuda(), self.orig_shape)

numpy()

рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рдПрдВ tensor рдПрдХ рд╕реБрдиреНрди рд╕рд░рдгреА рдХреЗ рд░реВрдк рдореЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def numpy(self):
    """Return a copy of the tensor as a numpy array."""
    return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.numpy(), self.orig_shape)

to(*args, **kwargs)

рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рдПрдВ tensor рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдФрд░ dType рдХреЗ рд╕рд╛рдеред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def to(self, *args, **kwargs):
    """Return a copy of the tensor with the specified device and dtype."""
    return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape)



ultralytics.engine.results.Results

рдХрд╛ рд░реВрдк: SimpleClass

рдЕрдиреБрдорд╛рди рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЗ рднрдВрдбрд╛рд░рдг рдФрд░ рд╣реЗрд░рдлреЗрд░ рдХреЗ рд▓рд┐рдП рдПрдХ рд╡рд░реНрдЧред

рд╡рд┐рд╢реЗрд╖рддрд╛рдПрдБ:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
orig_img ndarray

рдПрдХ рд╕реБрдиреНрди рд╕рд░рдгреА рдХреЗ рд░реВрдк рдореЗрдВ рдореВрд▓ рдЫрд╡рд┐ред

orig_shape tuple

рдореВрд▓ рдЫрд╡рд┐ рдЖрдХреГрддрд┐ (рдКрдБрдЪрд╛рдИ, рдЪреМрдбрд╝рд╛рдИ) рд╕реНрд╡рд░реВрдк рдореЗрдВ.

boxes Boxes

рдбрд┐рдЯреЗрдХреНрд╢рди рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ рд╡рд╛рд▓реА рдСрдмреНрдЬреЗрдХреНрдЯред

masks Masks

рдбрд┐рдЯреЗрдХреНрд╢рди рдорд╛рд╕реНрдХ рдпреБрдХреНрдд рд╡рд╕реНрддреБред

probs Probs

рд╡рд░реНрдЧреАрдХрд░рдг рдХрд╛рд░реНрдпреЛрдВ рдХреЗ рд▓рд┐рдП рд╡рд░реНрдЧ рд╕рдВрднрд╛рд╡рдирд╛рдУрдВ рд╡рд╛рд▓реА рд╡рд╕реНрддреБред

keypoints Keypoints

рдСрдмреНрдЬреЗрдХреНрдЯ рдЬрд┐рд╕рдореЗрдВ рдкреНрд░рддреНрдпреЗрдХ рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЗ рд▓рд┐рдП рдкрддрд╛ рд▓рдЧрд╛рдпрд╛ рдЧрдпрд╛ рдХреАрдкреЙрдЗрдВрдЯ рд╣реИред

speed dict

рдкреНрд░реАрдкреНрд░реЛрд╕реЗрд╕, рдЕрдиреБрдорд╛рди рдФрд░ рдкреЛрд╕реНрдЯрдкреНрд░реЛрд╕реЗрд╕ рдЧрддрд┐ рдХрд╛ рд╢рдмреНрджрдХреЛрд╢ (рдПрдордПрд╕ /

names dict

рд╡рд░реНрдЧ рдХреЗ рдирд╛рдореЛрдВ рдХрд╛ рд╢рдмреНрджрдХреЛрд╢ред

path str

рдЫрд╡рд┐ рдлрд╝рд╛рдЗрд▓ рдХрд╛ рдкрде.

рд╡рд┐рдзрд┐рдпрд╛рдБ:

рдирд╛рдо рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
update

рдСрдмреНрдЬреЗрдХреНрдЯ рд╡рд┐рд╢реЗрд╖рддрд╛рдУрдВ рдХреЛ рдирдП рдбрд┐рдЯреЗрдХреНрд╢рди рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЗ рд╕рд╛рде рдЕрдкрдбреЗрдЯ рдХрд░рддрд╛ рд╣реИред

cpu

CPU рд╕реНрдореГрддрд┐ рдкрд░ рд╕рднреА рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рджреЗрддрд╛ рд╣реИред

numpy

рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд╕рднреА рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде numpy рд╕рд░рдгрд┐рдпреЛрдВ рдХреЗ рд░реВрдк рдореЗрдВ рд▓реМрдЯрд╛рддрд╛ рд╣реИред

cuda

GPU рд╕реНрдореГрддрд┐ рдкрд░ рд╕рднреА рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рджреЗрддрд╛ рд╣реИред

to

рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рдХрд┐рд╕реА рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдФрд░ dtype рдкрд░ рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде рд▓реМрдЯрд╛рддрд╛ рд╣реИ.

new

рд╕рдорд╛рди рдЫрд╡рд┐, рдкрде рдФрд░ рдирд╛рдореЛрдВ рдХреЗ рд╕рд╛рде рдПрдХ рдирдпрд╛ рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рд▓реМрдЯрд╛рддрд╛ рд╣реИ.

plot

рдПрдХ рдЗрдирдкреБрдЯ рдЫрд╡рд┐ рдкрд░ рдкреНрд▓реЙрдЯ рдХрд╛ рдкрддрд╛ рд▓рдЧрд╛рдиреЗ рдХрд╛ рдкрд░рд┐рдгрд╛рдо рд╣реИ, рдПрдХ рдПрдиреЛрдЯреЗрдЯ рдХреА рдЧрдИ рдЫрд╡рд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИред

show

рд╕реНрдХреНрд░реАрди рдкрд░ рдПрдиреЛрдЯреЗрдЯ рдХрд┐рдП рдЧрдП рдкрд░рд┐рдгрд╛рдо рджрд┐рдЦрд╛рдПрдВред

save

рдПрдиреЛрдЯреЗрдЯ рдХрд┐рдП рдЧрдП рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЛ рдлрд╝рд╛рдЗрд▓ рдореЗрдВ рд╕рд╣реЗрдЬреЗрдВред

verbose

рдкреНрд░рддреНрдпреЗрдХ рдХрд╛рд░реНрдп рдХреЗ рд▓рд┐рдП рдПрдХ рд▓реЙрдЧ рд╕реНрдЯреНрд░рд┐рдВрдЧ рджреЗрддрд╛ рд╣реИ, рдбрд┐рдЯреЗрдХреНрд╢рди рдФрд░ рд╡рд░реНрдЧреАрдХрд░рдг рдХрд╛ рд╡рд┐рд╡рд░рдг рджреЗрддрд╛ рд╣реИред

save_txt

рдкрддрд╛ рд▓рдЧрд╛рдиреЗ рдХреЗ рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЛ рдПрдХ рдкрд╛рда рдлрд╝рд╛рдЗрд▓ рдореЗрдВ рд╕рд╣реЗрдЬрддрд╛ рд╣реИред

save_crop

рдлрд╕рд▓реА рдкрд╣рдЪрд╛рди рдЫрд╡рд┐рдпреЛрдВ рдХреЛ рд╕рд╣реЗрдЬрддрд╛ рд╣реИред

tojson

рдкрддрд╛ рд▓рдЧрд╛рдиреЗ рдХреЗ рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЛ JSON рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдХрдирд╡рд░реНрдЯ рдХрд░рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class Results(SimpleClass):
    """
    A class for storing and manipulating inference results.

    Attributes:
        orig_img (numpy.ndarray): Original image as a numpy array.
        orig_shape (tuple): Original image shape in (height, width) format.
        boxes (Boxes, optional): Object containing detection bounding boxes.
        masks (Masks, optional): Object containing detection masks.
        probs (Probs, optional): Object containing class probabilities for classification tasks.
        keypoints (Keypoints, optional): Object containing detected keypoints for each object.
        speed (dict): Dictionary of preprocess, inference, and postprocess speeds (ms/image).
        names (dict): Dictionary of class names.
        path (str): Path to the image file.

    Methods:
        update(boxes=None, masks=None, probs=None, obb=None): Updates object attributes with new detection results.
        cpu(): Returns a copy of the Results object with all tensors on CPU memory.
        numpy(): Returns a copy of the Results object with all tensors as numpy arrays.
        cuda(): Returns a copy of the Results object with all tensors on GPU memory.
        to(*args, **kwargs): Returns a copy of the Results object with tensors on a specified device and dtype.
        new(): Returns a new Results object with the same image, path, and names.
        plot(...): Plots detection results on an input image, returning an annotated image.
        show(): Show annotated results to screen.
        save(filename): Save annotated results to file.
        verbose(): Returns a log string for each task, detailing detections and classifications.
        save_txt(txt_file, save_conf=False): Saves detection results to a text file.
        save_crop(save_dir, file_name=Path("im.jpg")): Saves cropped detection images.
        tojson(normalize=False): Converts detection results to JSON format.
    """

    def __init__(self, orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None, obb=None) -> None:
        """
        Initialize the Results class.

        Args:
            orig_img (numpy.ndarray): The original image as a numpy array.
            path (str): The path to the image file.
            names (dict): A dictionary of class names.
            boxes (torch.tensor, optional): A 2D tensor of bounding box coordinates for each detection.
            masks (torch.tensor, optional): A 3D tensor of detection masks, where each mask is a binary image.
            probs (torch.tensor, optional): A 1D tensor of probabilities of each class for classification task.
            keypoints (torch.tensor, optional): A 2D tensor of keypoint coordinates for each detection.
            obb (torch.tensor, optional): A 2D tensor of oriented bounding box coordinates for each detection.
        """
        self.orig_img = orig_img
        self.orig_shape = orig_img.shape[:2]
        self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None  # native size boxes
        self.masks = Masks(masks, self.orig_shape) if masks is not None else None  # native size or imgsz masks
        self.probs = Probs(probs) if probs is not None else None
        self.keypoints = Keypoints(keypoints, self.orig_shape) if keypoints is not None else None
        self.obb = OBB(obb, self.orig_shape) if obb is not None else None
        self.speed = {"preprocess": None, "inference": None, "postprocess": None}  # milliseconds per image
        self.names = names
        self.path = path
        self.save_dir = None
        self._keys = "boxes", "masks", "probs", "keypoints", "obb"

    def __getitem__(self, idx):
        """Return a Results object for the specified index."""
        return self._apply("__getitem__", idx)

    def __len__(self):
        """Return the number of detections in the Results object."""
        for k in self._keys:
            v = getattr(self, k)
            if v is not None:
                return len(v)

    def update(self, boxes=None, masks=None, probs=None, obb=None):
        """Update the boxes, masks, and probs attributes of the Results object."""
        if boxes is not None:
            self.boxes = Boxes(ops.clip_boxes(boxes, self.orig_shape), self.orig_shape)
        if masks is not None:
            self.masks = Masks(masks, self.orig_shape)
        if probs is not None:
            self.probs = probs
        if obb is not None:
            self.obb = OBB(obb, self.orig_shape)

    def _apply(self, fn, *args, **kwargs):
        """
        Applies a function to all non-empty attributes and returns a new Results object with modified attributes. This
        function is internally called by methods like .to(), .cuda(), .cpu(), etc.

        Args:
            fn (str): The name of the function to apply.
            *args: Variable length argument list to pass to the function.
            **kwargs: Arbitrary keyword arguments to pass to the function.

        Returns:
            Results: A new Results object with attributes modified by the applied function.
        """
        r = self.new()
        for k in self._keys:
            v = getattr(self, k)
            if v is not None:
                setattr(r, k, getattr(v, fn)(*args, **kwargs))
        return r

    def cpu(self):
        """Return a copy of the Results object with all tensors on CPU memory."""
        return self._apply("cpu")

    def numpy(self):
        """Return a copy of the Results object with all tensors as numpy arrays."""
        return self._apply("numpy")

    def cuda(self):
        """Return a copy of the Results object with all tensors on GPU memory."""
        return self._apply("cuda")

    def to(self, *args, **kwargs):
        """Return a copy of the Results object with tensors on the specified device and dtype."""
        return self._apply("to", *args, **kwargs)

    def new(self):
        """Return a new Results object with the same image, path, and names."""
        return Results(orig_img=self.orig_img, path=self.path, names=self.names)

    def plot(
        self,
        conf=True,
        line_width=None,
        font_size=None,
        font="Arial.ttf",
        pil=False,
        img=None,
        im_gpu=None,
        kpt_radius=5,
        kpt_line=True,
        labels=True,
        boxes=True,
        masks=True,
        probs=True,
        show=False,
        save=False,
        filename=None,
    ):
        """
        Plots the detection results on an input RGB image. Accepts a numpy array (cv2) or a PIL Image.

        Args:
            conf (bool): Whether to plot the detection confidence score.
            line_width (float, optional): The line width of the bounding boxes. If None, it is scaled to the image size.
            font_size (float, optional): The font size of the text. If None, it is scaled to the image size.
            font (str): The font to use for the text.
            pil (bool): Whether to return the image as a PIL Image.
            img (numpy.ndarray): Plot to another image. if not, plot to original image.
            im_gpu (torch.Tensor): Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting.
            kpt_radius (int, optional): Radius of the drawn keypoints. Default is 5.
            kpt_line (bool): Whether to draw lines connecting keypoints.
            labels (bool): Whether to plot the label of bounding boxes.
            boxes (bool): Whether to plot the bounding boxes.
            masks (bool): Whether to plot the masks.
            probs (bool): Whether to plot classification probability
            show (bool): Whether to display the annotated image directly.
            save (bool): Whether to save the annotated image to `filename`.
            filename (str): Filename to save image to if save is True.

        Returns:
            (numpy.ndarray): A numpy array of the annotated image.

        Example:
            ```python
            from PIL import Image
            from ultralytics import YOLO

            model = YOLO('yolov8n.pt')
            results = model('bus.jpg')  # results list
            for r in results:
                im_array = r.plot()  # plot a BGR numpy array of predictions
                im = Image.fromarray(im_array[..., ::-1])  # RGB PIL image
                im.show()  # show image
                im.save('results.jpg')  # save image
            ```
        """
        if img is None and isinstance(self.orig_img, torch.Tensor):
            img = (self.orig_img[0].detach().permute(1, 2, 0).contiguous() * 255).to(torch.uint8).cpu().numpy()

        names = self.names
        is_obb = self.obb is not None
        pred_boxes, show_boxes = self.obb if is_obb else self.boxes, boxes
        pred_masks, show_masks = self.masks, masks
        pred_probs, show_probs = self.probs, probs
        annotator = Annotator(
            deepcopy(self.orig_img if img is None else img),
            line_width,
            font_size,
            font,
            pil or (pred_probs is not None and show_probs),  # Classify tasks default to pil=True
            example=names,
        )

        # Plot Segment results
        if pred_masks and show_masks:
            if im_gpu is None:
                img = LetterBox(pred_masks.shape[1:])(image=annotator.result())
                im_gpu = (
                    torch.as_tensor(img, dtype=torch.float16, device=pred_masks.data.device)
                    .permute(2, 0, 1)
                    .flip(0)
                    .contiguous()
                    / 255
                )
            idx = pred_boxes.cls if pred_boxes else range(len(pred_masks))
            annotator.masks(pred_masks.data, colors=[colors(x, True) for x in idx], im_gpu=im_gpu)

        # Plot Detect results
        if pred_boxes is not None and show_boxes:
            for d in reversed(pred_boxes):
                c, conf, id = int(d.cls), float(d.conf) if conf else None, None if d.id is None else int(d.id.item())
                name = ("" if id is None else f"id:{id} ") + names[c]
                label = (f"{name} {conf:.2f}" if conf else name) if labels else None
                box = d.xyxyxyxy.reshape(-1, 4, 2).squeeze() if is_obb else d.xyxy.squeeze()
                annotator.box_label(box, label, color=colors(c, True), rotated=is_obb)

        # Plot Classify results
        if pred_probs is not None and show_probs:
            text = ",\n".join(f"{names[j] if names else j} {pred_probs.data[j]:.2f}" for j in pred_probs.top5)
            x = round(self.orig_shape[0] * 0.03)
            annotator.text([x, x], text, txt_color=(255, 255, 255))  # TODO: allow setting colors

        # Plot Pose results
        if self.keypoints is not None:
            for k in reversed(self.keypoints.data):
                annotator.kpts(k, self.orig_shape, radius=kpt_radius, kpt_line=kpt_line)

        # Show results
        if show:
            annotator.show(self.path)

        # Save results
        if save:
            annotator.save(filename)

        return annotator.result()

    def show(self, *args, **kwargs):
        """Show annotated results image."""
        self.plot(show=True, *args, **kwargs)

    def save(self, filename=None, *args, **kwargs):
        """Save annotated results image."""
        if not filename:
            filename = f"results_{Path(self.path).name}"
        self.plot(save=True, filename=filename, *args, **kwargs)
        return filename

    def verbose(self):
        """Return log string for each task."""
        log_string = ""
        probs = self.probs
        boxes = self.boxes
        if len(self) == 0:
            return log_string if probs is not None else f"{log_string}(no detections), "
        if probs is not None:
            log_string += f"{', '.join(f'{self.names[j]} {probs.data[j]:.2f}' for j in probs.top5)}, "
        if boxes:
            for c in boxes.cls.unique():
                n = (boxes.cls == c).sum()  # detections per class
                log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
        return log_string

    def save_txt(self, txt_file, save_conf=False):
        """
        Save predictions into txt file.

        Args:
            txt_file (str): txt file path.
            save_conf (bool): save confidence score or not.
        """
        is_obb = self.obb is not None
        boxes = self.obb if is_obb else self.boxes
        masks = self.masks
        probs = self.probs
        kpts = self.keypoints
        texts = []
        if probs is not None:
            # Classify
            [texts.append(f"{probs.data[j]:.2f} {self.names[j]}") for j in probs.top5]
        elif boxes:
            # Detect/segment/pose
            for j, d in enumerate(boxes):
                c, conf, id = int(d.cls), float(d.conf), None if d.id is None else int(d.id.item())
                line = (c, *(d.xyxyxyxyn.view(-1) if is_obb else d.xywhn.view(-1)))
                if masks:
                    seg = masks[j].xyn[0].copy().reshape(-1)  # reversed mask.xyn, (n,2) to (n*2)
                    line = (c, *seg)
                if kpts is not None:
                    kpt = torch.cat((kpts[j].xyn, kpts[j].conf[..., None]), 2) if kpts[j].has_visible else kpts[j].xyn
                    line += (*kpt.reshape(-1).tolist(),)
                line += (conf,) * save_conf + (() if id is None else (id,))
                texts.append(("%g " * len(line)).rstrip() % line)

        if texts:
            Path(txt_file).parent.mkdir(parents=True, exist_ok=True)  # make directory
            with open(txt_file, "a") as f:
                f.writelines(text + "\n" for text in texts)

    def save_crop(self, save_dir, file_name=Path("im.jpg")):
        """
        Save cropped predictions to `save_dir/cls/file_name.jpg`.

        Args:
            save_dir (str | pathlib.Path): Save path.
            file_name (str | pathlib.Path): File name.
        """
        if self.probs is not None:
            LOGGER.warning("WARNING тЪая╕П Classify task do not support `save_crop`.")
            return
        if self.obb is not None:
            LOGGER.warning("WARNING тЪая╕П OBB task do not support `save_crop`.")
            return
        for d in self.boxes:
            save_one_box(
                d.xyxy,
                self.orig_img.copy(),
                file=Path(save_dir) / self.names[int(d.cls)] / f"{Path(file_name)}.jpg",
                BGR=True,
            )

    def summary(self, normalize=False, decimals=5):
        """Convert the results to a summarized format."""
        # Create list of detection dictionaries
        results = []
        if self.probs is not None:
            class_id = self.probs.top1
            results.append(
                {
                    "name": self.names[class_id],
                    "class": class_id,
                    "confidence": round(self.probs.top1conf.item(), decimals),
                }
            )
            return results

        data = self.boxes or self.obb
        is_obb = self.obb is not None
        h, w = self.orig_shape if normalize else (1, 1)
        for i, row in enumerate(data):  # xyxy, track_id if tracking, conf, class_id
            class_id, conf = int(row.cls), round(row.conf.item(), decimals)
            box = (row.xyxyxyxy if is_obb else row.xyxy).squeeze().reshape(-1, 2).tolist()
            xy = {}
            for j, b in enumerate(box):
                xy[f"x{j + 1}"] = round(b[0] / w, decimals)
                xy[f"y{j + 1}"] = round(b[1] / h, decimals)
            result = {"name": self.names[class_id], "class": class_id, "confidence": conf, "box": xy}
            if data.is_track:
                result["track_id"] = int(row.id.item())  # track ID
            if self.masks:
                result["segments"] = {
                    "x": (self.masks.xy[i][:, 0] / w).round(decimals).tolist(),
                    "y": (self.masks.xy[i][:, 1] / h).round(decimals).tolist(),
                }
            if self.keypoints is not None:
                x, y, visible = self.keypoints[i].data[0].cpu().unbind(dim=1)  # torch Tensor
                result["keypoints"] = {
                    "x": (x / w).numpy().round(decimals).tolist(),  # decimals named argument required
                    "y": (y / h).numpy().round(decimals).tolist(),
                    "visible": visible.numpy().round(decimals).tolist(),
                }
            results.append(result)

        return results

    def tojson(self, normalize=False, decimals=5):
        """Convert the results to JSON format."""
        import json

        return json.dumps(self.summary(normalize=normalize, decimals=decimals), indent=2)

__getitem__(idx)

рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдЕрдиреБрдХреНрд░рдордгрд┐рдХрд╛ рдХреЗ рд▓рд┐рдП рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рд▓реМрдЯрд╛рдПрдБ.

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __getitem__(self, idx):
    """Return a Results object for the specified index."""
    return self._apply("__getitem__", idx)

__init__(orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None, obb=None)

рдкрд░рд┐рдгрд╛рдо рд╡рд░реНрдЧ рдХреЛ рдкреНрд░рд╛рд░рдВрдн рдХрд░реЗрдВред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
orig_img ndarray

рдПрдХ numpy рд╕рд░рдгреА рдХреЗ рд░реВрдк рдореЗрдВ рдореВрд▓ рдЫрд╡рд┐ред

рдЖрд╡рд╢реНрдпрдХ
path str

рдЫрд╡рд┐ рдлрд╝рд╛рдЗрд▓ рдХрд╛ рдкрде.

рдЖрд╡рд╢реНрдпрдХ
names dict

рд╡рд░реНрдЧ рдХреЗ рдирд╛рдореЛрдВ рдХрд╛ рдПрдХ рд╢рдмреНрджрдХреЛрд╢ред

рдЖрд╡рд╢реНрдпрдХ
boxes tensor

рдПрдХ 2 рдбреА tensor рдкреНрд░рддреНрдпреЗрдХ рдкрд╣рдЪрд╛рди рдХреЗ рд▓рд┐рдП рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдХреАред

None
masks tensor

рдПрдХ 3 рдбреА tensor рдбрд┐рдЯреЗрдХреНрд╢рди рдорд╛рд╕реНрдХ рдХреА, рдЬрд╣рд╛рдВ рдкреНрд░рддреНрдпреЗрдХ рдорд╛рд╕реНрдХ рдПрдХ рдмрд╛рдЗрдирд░реА рдЗрдореЗрдЬ рд╣реИред

None
probs tensor

рдПрдХ 1 рдбреА tensor рд╡рд░реНрдЧреАрдХрд░рдг рдХрд╛рд░реНрдп рдХреЗ рд▓рд┐рдП рдкреНрд░рддреНрдпреЗрдХ рд╡рд░реНрдЧ рдХреА рд╕рдВрднрд╛рд╡рдирд╛рдУрдВ рдХрд╛ред

None
keypoints tensor

рдПрдХ 2 рдбреА tensor рдкреНрд░рддреНрдпреЗрдХ рдкрд╣рдЪрд╛рди рдХреЗ рд▓рд┐рдП рдХреАрдкреЙрдЗрдВрдЯ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдХрд╛ред

None
obb tensor

рдПрдХ 2 рдбреА tensor рдкреНрд░рддреНрдпреЗрдХ рдкрд╣рдЪрд╛рди рдХреЗ рд▓рд┐рдП рдЙрдиреНрдореБрдЦ рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдХрд╛ред

None
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __init__(self, orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None, obb=None) -> None:
    """
    Initialize the Results class.

    Args:
        orig_img (numpy.ndarray): The original image as a numpy array.
        path (str): The path to the image file.
        names (dict): A dictionary of class names.
        boxes (torch.tensor, optional): A 2D tensor of bounding box coordinates for each detection.
        masks (torch.tensor, optional): A 3D tensor of detection masks, where each mask is a binary image.
        probs (torch.tensor, optional): A 1D tensor of probabilities of each class for classification task.
        keypoints (torch.tensor, optional): A 2D tensor of keypoint coordinates for each detection.
        obb (torch.tensor, optional): A 2D tensor of oriented bounding box coordinates for each detection.
    """
    self.orig_img = orig_img
    self.orig_shape = orig_img.shape[:2]
    self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None  # native size boxes
    self.masks = Masks(masks, self.orig_shape) if masks is not None else None  # native size or imgsz masks
    self.probs = Probs(probs) if probs is not None else None
    self.keypoints = Keypoints(keypoints, self.orig_shape) if keypoints is not None else None
    self.obb = OBB(obb, self.orig_shape) if obb is not None else None
    self.speed = {"preprocess": None, "inference": None, "postprocess": None}  # milliseconds per image
    self.names = names
    self.path = path
    self.save_dir = None
    self._keys = "boxes", "masks", "probs", "keypoints", "obb"

__len__()

рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдореЗрдВ рдбрд┐рдЯреЗрдХреНрд╢рди рдХреА рд╕рдВрдЦреНрдпрд╛ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __len__(self):
    """Return the number of detections in the Results object."""
    for k in self._keys:
        v = getattr(self, k)
        if v is not None:
            return len(v)

cpu()

CPU рд╕реНрдореГрддрд┐ рдкрд░ рд╕рднреА рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def cpu(self):
    """Return a copy of the Results object with all tensors on CPU memory."""
    return self._apply("cpu")

cuda()

GPU рд╕реНрдореГрддрд┐ рдкрд░ рд╕рднреА рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def cuda(self):
    """Return a copy of the Results object with all tensors on GPU memory."""
    return self._apply("cuda")

new()

рд╕рдорд╛рди рдЫрд╡рд┐, рдкрде рдФрд░ рдирд╛рдореЛрдВ рдХреЗ рд╕рд╛рде рдПрдХ рдирдпрд╛ рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def new(self):
    """Return a new Results object with the same image, path, and names."""
    return Results(orig_img=self.orig_img, path=self.path, names=self.names)

numpy()

рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рдХреЛ рд╕рднреА рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде numpy рд╕рд░рдгрд┐рдпреЛрдВ рдХреЗ рд░реВрдк рдореЗрдВ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def numpy(self):
    """Return a copy of the Results object with all tensors as numpy arrays."""
    return self._apply("numpy")

plot(conf=True, line_width=None, font_size=None, font='Arial.ttf', pil=False, img=None, im_gpu=None, kpt_radius=5, kpt_line=True, labels=True, boxes=True, masks=True, probs=True, show=False, save=False, filename=None)

рдЗрдирдкреБрдЯ RGB рдЫрд╡рд┐ рдкрд░ рдкрддрд╛ рд▓рдЧрд╛рдиреЗ рдХреЗ рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЛ рдкреНрд▓реЙрдЯ рдХрд░рддрд╛ рд╣реИред рдПрдХ numpy рд╕рд░рдгреА (cv2) рдпрд╛ рдПрдХ PIL рдЫрд╡рд┐ рд╕реНрд╡реАрдХрд╛рд░ рдХрд░рддрд╛ рд╣реИред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
conf bool

рдХреНрдпрд╛ рдбрд┐рдЯреЗрдХреНрд╢рди рдХреЙрдиреНрдлрд┐рдбреЗрдВрд╕ рд╕реНрдХреЛрд░ рдХреЛ рдкреНрд▓реЙрдЯ рдХрд░рдирд╛ рд╣реИред

True
line_width float

рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ рдХреА рд▓рд╛рдЗрди рдЪреМрдбрд╝рд╛рдИред рдпрджрд┐ рдХреЛрдИ рдирд╣реАрдВ, рддреЛ рдЗрд╕реЗ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рддрдХ рдмрдврд╝рд╛рдпрд╛ рдЬрд╛рддрд╛ рд╣реИред

None
font_size float

рдкрд╛рда рдХрд╛ рдлрд╝реЙрдиреНрдЯ рдЖрдХрд╛рд░. рдпрджрд┐ рдХреЛрдИ рдирд╣реАрдВ, рддреЛ рдЗрд╕реЗ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рддрдХ рдмрдврд╝рд╛рдпрд╛ рдЬрд╛рддрд╛ рд╣реИред

None
font str

рдкрд╛рда рдХреЗ рд▓рд┐рдП рдЙрдкрдпреЛрдЧ рдХрд┐рдпрд╛ рдЬрд╛рдиреЗ рд╡рд╛рд▓рд╛ рдлрд╝реЙрдиреНрдЯ.

'Arial.ttf'
pil bool

рдЫрд╡рд┐ рдХреЛ рдкреАрдЖрдИрдПрд▓ рдЫрд╡рд┐ рдХреЗ рд░реВрдк рдореЗрдВ рд╡рд╛рдкрд╕ рдХрд░рдирд╛ рд╣реИ рдпрд╛ рдирд╣реАрдВред

False
img ndarray

рдХрд┐рд╕реА рдЕрдиреНрдп рдЫрд╡рд┐ рдХреЗ рд▓рд┐рдП рдкреНрд▓реЙрдЯ рдХрд░реЗрдВред рдпрджрд┐ рдирд╣реАрдВ, рддреЛ рдореВрд▓ рдЫрд╡рд┐ рдХреЗ рд▓рд┐рдП рдкреНрд▓реЙрдЯ рдХрд░реЗрдВред

None
im_gpu Tensor

рддреЗрдЬреА рд╕реЗ рдореБрдЦреМрдЯрд╛ рд╕рд╛рдЬрд┐рд╢ рд░рдЪрдиреЗ рдХреЗ рд▓рд┐рдП рдЖрдХрд╛рд░ (1, 3, 640, 640) рдХреЗ рд╕рд╛рде GPU рдореЗрдВ рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд рдЫрд╡рд┐ред

None
kpt_radius int

рдЦреАрдВрдЪреЗ рдЧрдП рдХреАрдкреЙрдЗрдВрдЯреНрд╕ рдХреА рддреНрд░рд┐рдЬреНрдпрд╛ред рдбрд┐рдлрд╝реЙрд▓реНрдЯ 5 рд╣реИред

5
kpt_line bool

рдХреНрдпрд╛ рдХреАрдкреЙрдЗрдВрдЯреНрд╕ рдХреЛ рдЬреЛрдбрд╝рдиреЗ рд╡рд╛рд▓реА рд░реЗрдЦрд╛рдПрдБ рдЦреАрдВрдЪрдиреА рд╣реИрдВред

True
labels bool

рдЪрд╛рд╣реЗ рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ рдХреЗ рд▓реЗрдмрд▓ рдХреЛ рдкреНрд▓реЙрдЯ рдХрд░рдирд╛ рд╣реЛред

True
boxes bool

рдЪрд╛рд╣реЗ рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ рдХреА рд╕рд╛рдЬрд┐рд╢ рд░рдЪреА рдЬрд╛рдПред

True
masks bool

рдЪрд╛рд╣реЗ рдорд╛рд╕реНрдХ рдХреА рд╕рд╛рдЬрд┐рд╢ рд░рдЪреА рдЬрд╛рдПред

True
probs bool

рд╡рд░реНрдЧреАрдХрд░рдг рдХреА рд╕рдВрднрд╛рд╡рдирд╛ рдХреА рд╕рд╛рдЬрд┐рд╢ рд░рдЪреА рдЬрд╛рдП рдпрд╛ рдирд╣реАрдВ

True
show bool

рдПрдиреЛрдЯреЗрдЯ рдХреА рдЧрдИ рдЫрд╡рд┐ рдХреЛ рд╕реАрдзреЗ рдкреНрд░рджрд░реНрд╢рд┐рдд рдХрд░рдирд╛ рд╣реИ рдпрд╛ рдирд╣реАрдВред

False
save bool

рдПрдиреЛрдЯреЗрдЯ рдХреА рдЧрдИ рдЫрд╡рд┐ рдХреЛ рд╕рд╣реЗрдЬрдиреЗ рдХреЗ рд▓рд┐рдП рдпрд╛ рдирд╣реАрдВ filename.

False
filename str

рдЫрд╡рд┐ рдХреЛ рд╕рд╣реЗрдЬрдиреЗ рдХреЗ рд▓рд┐рдП рдлрд╝рд╛рдЗрд▓ рдирд╛рдо рдпрджрд┐ рд╕рд╣реЗрдЬреЗрдВ рд╕рддреНрдп рд╣реИред

None

рджреЗрддрд╛:

рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
ndarray

рдПрдиреЛрдЯреЗрдЯ рдХреА рдЧрдИ рдЫрд╡рд┐ рдХреА рдПрдХ рд╕реБрдиреНрди рд╕рд░рдгреАред

рдЙрджрд╛рд╣рд░рдг
from PIL import Image
from ultralytics import YOLO

model = YOLO('yolov8n.pt')
results = model('bus.jpg')  # results list
for r in results:
    im_array = r.plot()  # plot a BGR numpy array of predictions
    im = Image.fromarray(im_array[..., ::-1])  # RGB PIL image
    im.show()  # show image
    im.save('results.jpg')  # save image
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def plot(
    self,
    conf=True,
    line_width=None,
    font_size=None,
    font="Arial.ttf",
    pil=False,
    img=None,
    im_gpu=None,
    kpt_radius=5,
    kpt_line=True,
    labels=True,
    boxes=True,
    masks=True,
    probs=True,
    show=False,
    save=False,
    filename=None,
):
    """
    Plots the detection results on an input RGB image. Accepts a numpy array (cv2) or a PIL Image.

    Args:
        conf (bool): Whether to plot the detection confidence score.
        line_width (float, optional): The line width of the bounding boxes. If None, it is scaled to the image size.
        font_size (float, optional): The font size of the text. If None, it is scaled to the image size.
        font (str): The font to use for the text.
        pil (bool): Whether to return the image as a PIL Image.
        img (numpy.ndarray): Plot to another image. if not, plot to original image.
        im_gpu (torch.Tensor): Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting.
        kpt_radius (int, optional): Radius of the drawn keypoints. Default is 5.
        kpt_line (bool): Whether to draw lines connecting keypoints.
        labels (bool): Whether to plot the label of bounding boxes.
        boxes (bool): Whether to plot the bounding boxes.
        masks (bool): Whether to plot the masks.
        probs (bool): Whether to plot classification probability
        show (bool): Whether to display the annotated image directly.
        save (bool): Whether to save the annotated image to `filename`.
        filename (str): Filename to save image to if save is True.

    Returns:
        (numpy.ndarray): A numpy array of the annotated image.

    Example:
        ```python
        from PIL import Image
        from ultralytics import YOLO

        model = YOLO('yolov8n.pt')
        results = model('bus.jpg')  # results list
        for r in results:
            im_array = r.plot()  # plot a BGR numpy array of predictions
            im = Image.fromarray(im_array[..., ::-1])  # RGB PIL image
            im.show()  # show image
            im.save('results.jpg')  # save image
        ```
    """
    if img is None and isinstance(self.orig_img, torch.Tensor):
        img = (self.orig_img[0].detach().permute(1, 2, 0).contiguous() * 255).to(torch.uint8).cpu().numpy()

    names = self.names
    is_obb = self.obb is not None
    pred_boxes, show_boxes = self.obb if is_obb else self.boxes, boxes
    pred_masks, show_masks = self.masks, masks
    pred_probs, show_probs = self.probs, probs
    annotator = Annotator(
        deepcopy(self.orig_img if img is None else img),
        line_width,
        font_size,
        font,
        pil or (pred_probs is not None and show_probs),  # Classify tasks default to pil=True
        example=names,
    )

    # Plot Segment results
    if pred_masks and show_masks:
        if im_gpu is None:
            img = LetterBox(pred_masks.shape[1:])(image=annotator.result())
            im_gpu = (
                torch.as_tensor(img, dtype=torch.float16, device=pred_masks.data.device)
                .permute(2, 0, 1)
                .flip(0)
                .contiguous()
                / 255
            )
        idx = pred_boxes.cls if pred_boxes else range(len(pred_masks))
        annotator.masks(pred_masks.data, colors=[colors(x, True) for x in idx], im_gpu=im_gpu)

    # Plot Detect results
    if pred_boxes is not None and show_boxes:
        for d in reversed(pred_boxes):
            c, conf, id = int(d.cls), float(d.conf) if conf else None, None if d.id is None else int(d.id.item())
            name = ("" if id is None else f"id:{id} ") + names[c]
            label = (f"{name} {conf:.2f}" if conf else name) if labels else None
            box = d.xyxyxyxy.reshape(-1, 4, 2).squeeze() if is_obb else d.xyxy.squeeze()
            annotator.box_label(box, label, color=colors(c, True), rotated=is_obb)

    # Plot Classify results
    if pred_probs is not None and show_probs:
        text = ",\n".join(f"{names[j] if names else j} {pred_probs.data[j]:.2f}" for j in pred_probs.top5)
        x = round(self.orig_shape[0] * 0.03)
        annotator.text([x, x], text, txt_color=(255, 255, 255))  # TODO: allow setting colors

    # Plot Pose results
    if self.keypoints is not None:
        for k in reversed(self.keypoints.data):
            annotator.kpts(k, self.orig_shape, radius=kpt_radius, kpt_line=kpt_line)

    # Show results
    if show:
        annotator.show(self.path)

    # Save results
    if save:
        annotator.save(filename)

    return annotator.result()

save(filename=None, *args, **kwargs)

рдПрдиреЛрдЯреЗрдЯ рдХрд┐рдП рдЧрдП рдкрд░рд┐рдгрд╛рдо рдЫрд╡рд┐ рд╕рд╣реЗрдЬреЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def save(self, filename=None, *args, **kwargs):
    """Save annotated results image."""
    if not filename:
        filename = f"results_{Path(self.path).name}"
    self.plot(save=True, filename=filename, *args, **kwargs)
    return filename

save_crop(save_dir, file_name=Path('im.jpg'))

рдлрд╕рд▓реА рдкреВрд░реНрд╡рд╛рдиреБрдорд╛рдиреЛрдВ рдХреЛ рдЗрди рдкрд░ рд╕рд╣реЗрдЬреЗрдВ save_dir/cls/file_name.jpg.

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
save_dir str | Path

рд░рд╛рд╕реНрддрд╛ рдмрдЪрд╛рдУред

рдЖрд╡рд╢реНрдпрдХ
file_name str | Path

рдлрд╝рд╛рдЗрд▓ рдХрд╛ рдирд╛рдо.

Path('im.jpg')
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def save_crop(self, save_dir, file_name=Path("im.jpg")):
    """
    Save cropped predictions to `save_dir/cls/file_name.jpg`.

    Args:
        save_dir (str | pathlib.Path): Save path.
        file_name (str | pathlib.Path): File name.
    """
    if self.probs is not None:
        LOGGER.warning("WARNING тЪая╕П Classify task do not support `save_crop`.")
        return
    if self.obb is not None:
        LOGGER.warning("WARNING тЪая╕П OBB task do not support `save_crop`.")
        return
    for d in self.boxes:
        save_one_box(
            d.xyxy,
            self.orig_img.copy(),
            file=Path(save_dir) / self.names[int(d.cls)] / f"{Path(file_name)}.jpg",
            BGR=True,
        )

save_txt(txt_file, save_conf=False)

txt рдлрд╝рд╛рдЗрд▓ рдореЗрдВ рднрд╡рд┐рд╖реНрдпрд╡рд╛рдгрд┐рдпреЛрдВ рд╕рд╣реЗрдЬреЗрдВ.

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
txt_file str

txt рдлрд╝рд╛рдЗрд▓ рдкрдеред

рдЖрд╡рд╢реНрдпрдХ
save_conf bool

рдХреЙрдиреНрдлрд┐рдбреЗрдВрд╕ рд╕реНрдХреЛрд░ рд╕реЗрд╡ рдХрд░реЗрдВ рдпрд╛ рдирд╣реАрдВред

False
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def save_txt(self, txt_file, save_conf=False):
    """
    Save predictions into txt file.

    Args:
        txt_file (str): txt file path.
        save_conf (bool): save confidence score or not.
    """
    is_obb = self.obb is not None
    boxes = self.obb if is_obb else self.boxes
    masks = self.masks
    probs = self.probs
    kpts = self.keypoints
    texts = []
    if probs is not None:
        # Classify
        [texts.append(f"{probs.data[j]:.2f} {self.names[j]}") for j in probs.top5]
    elif boxes:
        # Detect/segment/pose
        for j, d in enumerate(boxes):
            c, conf, id = int(d.cls), float(d.conf), None if d.id is None else int(d.id.item())
            line = (c, *(d.xyxyxyxyn.view(-1) if is_obb else d.xywhn.view(-1)))
            if masks:
                seg = masks[j].xyn[0].copy().reshape(-1)  # reversed mask.xyn, (n,2) to (n*2)
                line = (c, *seg)
            if kpts is not None:
                kpt = torch.cat((kpts[j].xyn, kpts[j].conf[..., None]), 2) if kpts[j].has_visible else kpts[j].xyn
                line += (*kpt.reshape(-1).tolist(),)
            line += (conf,) * save_conf + (() if id is None else (id,))
            texts.append(("%g " * len(line)).rstrip() % line)

    if texts:
        Path(txt_file).parent.mkdir(parents=True, exist_ok=True)  # make directory
        with open(txt_file, "a") as f:
            f.writelines(text + "\n" for text in texts)

show(*args, **kwargs)

рдПрдиреЛрдЯреЗрдЯ рдХрд┐рдП рдЧрдП рдкрд░рд┐рдгрд╛рдо рдЫрд╡рд┐ рджрд┐рдЦрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def show(self, *args, **kwargs):
    """Show annotated results image."""
    self.plot(show=True, *args, **kwargs)

summary(normalize=False, decimals=5)

рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЛ рд╕рд╛рд░рд╛рдВрд╢рд┐рдд рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдХрдирд╡рд░реНрдЯ рдХрд░реЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def summary(self, normalize=False, decimals=5):
    """Convert the results to a summarized format."""
    # Create list of detection dictionaries
    results = []
    if self.probs is not None:
        class_id = self.probs.top1
        results.append(
            {
                "name": self.names[class_id],
                "class": class_id,
                "confidence": round(self.probs.top1conf.item(), decimals),
            }
        )
        return results

    data = self.boxes or self.obb
    is_obb = self.obb is not None
    h, w = self.orig_shape if normalize else (1, 1)
    for i, row in enumerate(data):  # xyxy, track_id if tracking, conf, class_id
        class_id, conf = int(row.cls), round(row.conf.item(), decimals)
        box = (row.xyxyxyxy if is_obb else row.xyxy).squeeze().reshape(-1, 2).tolist()
        xy = {}
        for j, b in enumerate(box):
            xy[f"x{j + 1}"] = round(b[0] / w, decimals)
            xy[f"y{j + 1}"] = round(b[1] / h, decimals)
        result = {"name": self.names[class_id], "class": class_id, "confidence": conf, "box": xy}
        if data.is_track:
            result["track_id"] = int(row.id.item())  # track ID
        if self.masks:
            result["segments"] = {
                "x": (self.masks.xy[i][:, 0] / w).round(decimals).tolist(),
                "y": (self.masks.xy[i][:, 1] / h).round(decimals).tolist(),
            }
        if self.keypoints is not None:
            x, y, visible = self.keypoints[i].data[0].cpu().unbind(dim=1)  # torch Tensor
            result["keypoints"] = {
                "x": (x / w).numpy().round(decimals).tolist(),  # decimals named argument required
                "y": (y / h).numpy().round(decimals).tolist(),
                "visible": visible.numpy().round(decimals).tolist(),
            }
        results.append(result)

    return results

to(*args, **kwargs)

рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдФрд░ dtype рдкрд░ рдЯреЗрдВрд╕рд░ рдХреЗ рд╕рд╛рде рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def to(self, *args, **kwargs):
    """Return a copy of the Results object with tensors on the specified device and dtype."""
    return self._apply("to", *args, **kwargs)

tojson(normalize=False, decimals=5)

рдкрд░рд┐рдгрд╛рдореЛрдВ рдХреЛ JSON рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдмрджрд▓реЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def tojson(self, normalize=False, decimals=5):
    """Convert the results to JSON format."""
    import json

    return json.dumps(self.summary(normalize=normalize, decimals=decimals), indent=2)

update(boxes=None, masks=None, probs=None, obb=None)

рдкрд░рд┐рдгрд╛рдо рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЗ рдмреЙрдХреНрд╕, рдорд╛рд╕реНрдХ рдФрд░ рдЬрд╛рдВрдЪ рд╡рд┐рд╢реЗрд╖рддрд╛рдУрдВ рдХреЛ рдЕрдкрдбреЗрдЯ рдХрд░реЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def update(self, boxes=None, masks=None, probs=None, obb=None):
    """Update the boxes, masks, and probs attributes of the Results object."""
    if boxes is not None:
        self.boxes = Boxes(ops.clip_boxes(boxes, self.orig_shape), self.orig_shape)
    if masks is not None:
        self.masks = Masks(masks, self.orig_shape)
    if probs is not None:
        self.probs = probs
    if obb is not None:
        self.obb = OBB(obb, self.orig_shape)

verbose()

рдкреНрд░рддреНрдпреЗрдХ рдХрд╛рд░реНрдп рдХреЗ рд▓рд┐рдП рд▓реЙрдЧ рд╕реНрдЯреНрд░рд┐рдВрдЧ рд▓реМрдЯрд╛рдПрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def verbose(self):
    """Return log string for each task."""
    log_string = ""
    probs = self.probs
    boxes = self.boxes
    if len(self) == 0:
        return log_string if probs is not None else f"{log_string}(no detections), "
    if probs is not None:
        log_string += f"{', '.join(f'{self.names[j]} {probs.data[j]:.2f}' for j in probs.top5)}, "
    if boxes:
        for c in boxes.cls.unique():
            n = (boxes.cls == c).sum()  # detections per class
            log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
    return log_string



ultralytics.engine.results.Boxes

рдХрд╛ рд░реВрдк: BaseTensor

рдбрд┐рдЯреЗрдХреНрд╢рди рдмреЙрдХреНрд╕ рдХрд╛ рдкреНрд░рдмрдВрдзрди рдХрд░рддрд╛ рд╣реИ, рдмреЙрдХреНрд╕ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ, рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ рд╕реНрдХреЛрд░, рдХрдХреНрд╖рд╛ рдХреА рдЖрд╕рд╛рди рдкрд╣реБрдВрдЪ рдФрд░ рд╣реЗрд░рдлреЗрд░ рдкреНрд░рджрд╛рди рдХрд░рддрд╛ рд╣реИ рдкрд╣рдЪрд╛рдирдХрд░реНрддрд╛, рдФрд░ рд╡реИрдХрд▓реНрдкрд┐рдХ рдЯреНрд░реИрдХрд┐рдВрдЧ рдЖрдИрдбреАред рдмреЙрдХреНрд╕ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдХреЗ рд▓рд┐рдП рдХрдИ рдкреНрд░рд╛рд░реВрдкреЛрдВ рдХрд╛ рд╕рдорд░реНрдерди рдХрд░рддрд╛ рд╣реИ, рдЬрд┐рд╕рдореЗрдВ рдкреВрд░реНрдг рдФрд░ рджреЛрдиреЛрдВ рд╢рд╛рдорд┐рд▓ рд╣реИрдВ рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд рд░реВрдкред

рд╡рд┐рд╢реЗрд╖рддрд╛рдПрдБ:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
data Tensor

рдХрдЪреНрдЪрд╛ tensor рдЬрд┐рд╕рдореЗрдВ рдбрд┐рдЯреЗрдХреНрд╢рди рдмреЙрдХреНрд╕ рдФрд░ рдЙрдирдХреЗ рд╕рдВрдмрдВрдзрд┐рдд рдбреЗрдЯрд╛ рд╢рд╛рдорд┐рд▓ рд╣реИрдВред

orig_shape tuple

рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рдПрдХ рдЯрдкрд▓ (рдКрдВрдЪрд╛рдИ, рдЪреМрдбрд╝рд╛рдИ) рдХреЗ рд░реВрдк рдореЗрдВ, рд╕рд╛рдорд╛рдиреНрдпреАрдХрд░рдг рдХреЗ рд▓рд┐рдП рдЙрдкрдпреЛрдЧ рдХрд┐рдпрд╛ рдЬрд╛рддрд╛ рд╣реИред

is_track bool

рдЗрдВрдЧрд┐рдд рдХрд░рддрд╛ рд╣реИ рдХрд┐ рдЯреНрд░реИрдХрд┐рдВрдЧ рдЖрдИрдбреА рдмреЙрдХреНрд╕ рдбреЗрдЯрд╛ рдореЗрдВ рд╢рд╛рдорд┐рд▓ рд╣реИрдВ рдпрд╛ рдирд╣реАрдВ.

рдЧреБрдг

xyxy (torch.Tensor | numpy.ndarray): [x1, y1, x2, y2] рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдмреЙрдХреНрд╕ред рдХреЙрдиреНрдл (torch.Tensor | numpy.ndarray): рдкреНрд░рддреНрдпреЗрдХ рдмреЙрдХреНрд╕ рдХреЗ рд▓рд┐рдП рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ рд╕реНрдХреЛрд░ред рд╕реАрдПрд▓рдПрд╕ (torch.Tensor | numpy.ndarray): рдкреНрд░рддреНрдпреЗрдХ рдмреЙрдХреНрд╕ рдХреЗ рд▓рд┐рдП рдХреНрд▓рд╛рд╕ рд▓реЗрдмрд▓ред рдЖрдИрдбреА (torch.Tensor | numpy.ndarray, рд╡реИрдХрд▓реНрдкрд┐рдХ): рдкреНрд░рддреНрдпреЗрдХ рдмреЙрдХреНрд╕ рдХреЗ рд▓рд┐рдП рдЯреНрд░реИрдХрд┐рдВрдЧ рдЖрдИрдбреА, рдпрджрд┐ рдЙрдкрд▓рдмреНрдз рд╣реЛред xywh (torch.Tensor | numpy.ndarray): [x, y, рдЪреМрдбрд╝рд╛рдИ, рдКрдВрдЪрд╛рдИ] рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдмреЙрдХреНрд╕, рдорд╛рдВрдЧ рдкрд░ рдЧрдгрдирд╛ рдХреА рдЬрд╛рддреА рд╣реИред xyxyn (torch.Tensor | numpy.ndarray): рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд [x1, y1, x2, y2] рдмрдХреНрд╕реЗ, orig_shape. xywhn (torch.Tensor | numpy.ndarray): рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд [x, y, рдЪреМрдбрд╝рд╛рдИ, рдКрдВрдЪрд╛рдИ] рдмрдХреНрд╕реЗ, рд╕рд╛рдкреЗрдХреНрд╖ orig_shape.

рд╡рд┐рдзрд┐рдпрд╛рдБ:

рдирд╛рдо рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
cpu

рдмрдХреНрд╕реЗ рдХреЛ CPU рд╕реНрдореГрддрд┐ рдореЗрдВ рд▓реЗ рдЬрд╛рддрд╛ рд╣реИред

numpy

рдмрдХреНрд╕реЛрдВ рдХреЛ рдПрдХ numpy рд╕рд░рдгреА рд╕реНрд╡рд░реВрдк рдореЗрдВ рдХрдирд╡рд░реНрдЯ рдХрд░рддрд╛ рд╣реИ.

cuda

рдмреЙрдХреНрд╕ рдХреЛ CUDA (GPU) рд╕реНрдореГрддрд┐ рдореЗрдВ рд▓реЗ рдЬрд╛рддрд╛ рд╣реИред

to

рдмрдХреНрд╕реЛрдВ рдХреЛ рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдкрд░ рд▓реЗ рдЬрд╛рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class Boxes(BaseTensor):
    """
    Manages detection boxes, providing easy access and manipulation of box coordinates, confidence scores, class
    identifiers, and optional tracking IDs. Supports multiple formats for box coordinates, including both absolute and
    normalized forms.

    Attributes:
        data (torch.Tensor): The raw tensor containing detection boxes and their associated data.
        orig_shape (tuple): The original image size as a tuple (height, width), used for normalization.
        is_track (bool): Indicates whether tracking IDs are included in the box data.

    Properties:
        xyxy (torch.Tensor | numpy.ndarray): Boxes in [x1, y1, x2, y2] format.
        conf (torch.Tensor | numpy.ndarray): Confidence scores for each box.
        cls (torch.Tensor | numpy.ndarray): Class labels for each box.
        id (torch.Tensor | numpy.ndarray, optional): Tracking IDs for each box, if available.
        xywh (torch.Tensor | numpy.ndarray): Boxes in [x, y, width, height] format, calculated on demand.
        xyxyn (torch.Tensor | numpy.ndarray): Normalized [x1, y1, x2, y2] boxes, relative to `orig_shape`.
        xywhn (torch.Tensor | numpy.ndarray): Normalized [x, y, width, height] boxes, relative to `orig_shape`.

    Methods:
        cpu(): Moves the boxes to CPU memory.
        numpy(): Converts the boxes to a numpy array format.
        cuda(): Moves the boxes to CUDA (GPU) memory.
        to(device, dtype=None): Moves the boxes to the specified device.
    """

    def __init__(self, boxes, orig_shape) -> None:
        """
        Initialize the Boxes class.

        Args:
            boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes, with
                shape (num_boxes, 6) or (num_boxes, 7). The last two columns contain confidence and class values.
                If present, the third last column contains track IDs.
            orig_shape (tuple): Original image size, in the format (height, width).
        """
        if boxes.ndim == 1:
            boxes = boxes[None, :]
        n = boxes.shape[-1]
        assert n in {6, 7}, f"expected 6 or 7 values but got {n}"  # xyxy, track_id, conf, cls
        super().__init__(boxes, orig_shape)
        self.is_track = n == 7
        self.orig_shape = orig_shape

    @property
    def xyxy(self):
        """Return the boxes in xyxy format."""
        return self.data[:, :4]

    @property
    def conf(self):
        """Return the confidence values of the boxes."""
        return self.data[:, -2]

    @property
    def cls(self):
        """Return the class values of the boxes."""
        return self.data[:, -1]

    @property
    def id(self):
        """Return the track IDs of the boxes (if available)."""
        return self.data[:, -3] if self.is_track else None

    @property
    @lru_cache(maxsize=2)  # maxsize 1 should suffice
    def xywh(self):
        """Return the boxes in xywh format."""
        return ops.xyxy2xywh(self.xyxy)

    @property
    @lru_cache(maxsize=2)
    def xyxyn(self):
        """Return the boxes in xyxy format normalized by original image size."""
        xyxy = self.xyxy.clone() if isinstance(self.xyxy, torch.Tensor) else np.copy(self.xyxy)
        xyxy[..., [0, 2]] /= self.orig_shape[1]
        xyxy[..., [1, 3]] /= self.orig_shape[0]
        return xyxy

    @property
    @lru_cache(maxsize=2)
    def xywhn(self):
        """Return the boxes in xywh format normalized by original image size."""
        xywh = ops.xyxy2xywh(self.xyxy)
        xywh[..., [0, 2]] /= self.orig_shape[1]
        xywh[..., [1, 3]] /= self.orig_shape[0]
        return xywh

cls property

рдмрдХреНрд╕реЛрдВ рдХреЗ рд╡рд░реНрдЧ рдорд╛рди рд▓реМрдЯрд╛рдПрдВред

conf property

рдмрдХреНрд╕реЗ рдХреЗ рд╡рд┐рд╢реНрд╡рд╛рд╕ рдореВрд▓реНрдпреЛрдВ рдХреЛ рд╡рд╛рдкрд╕ рдХрд░реЗрдВред

id property

рдмреЙрдХреНрд╕ рдХреА рдЯреНрд░реИрдХ рдЖрдИрдбреА рд▓реМрдЯрд╛рдПрдВ (рдпрджрд┐ рдЙрдкрд▓рдмреНрдз рд╣реЛ)ред

xywh cached property

рдмрдХреНрд╕реЛрдВ рдХреЛ xywh рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рд▓реМрдЯрд╛рдПрдВред

xywhn cached property

рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рджреНрд╡рд╛рд░рд╛ рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд xywh рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдмрдХреНрд╕реЗ рд▓реМрдЯрд╛рдПрдВред

xyxy property

рдмрдХреНрд╕реЛрдВ рдХреЛ xyxy рд╕реНрд╡рд░реВрдк рдореЗрдВ рд▓реМрдЯрд╛рдПрдВред

xyxyn cached property

рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рджреНрд╡рд╛рд░рд╛ рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд xyxy рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдмрдХреНрд╕реЗ рд▓реМрдЯрд╛рдПрдВред

__init__(boxes, orig_shape)

Boxes рдХреНрд▓рд╛рд╕ рдХреЛ рдЗрдирд┐рд╢рд┐рдпрд▓рд╛рдЗрдЬрд╝ рдХрд░реЗрдВред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
boxes Tensor | ndarray

рдПрдХ tensor рдпрд╛ рд╕реБрдиреНрди рд╕рд░рдгреА рдЬрд┐рд╕рдореЗрдВ рдбрд┐рдЯреЗрдХреНрд╢рди рдмреЙрдХреНрд╕ рд╣реЛрддреЗ рд╣реИрдВ, рдХреЗ рд╕рд╛рде рдЖрдХрд╛рд░ (num_boxes, 6) рдпрд╛ (num_boxes, 7)ред рдЕрдВрддрд┐рдо рджреЛ рд╕реНрддрдВрднреЛрдВ рдореЗрдВ рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ рдФрд░ рд╡рд░реНрдЧ рдорд╛рди рд╣реЛрддреЗ рд╣реИрдВред рдпрджрд┐ рдореМрдЬреВрдж рд╣реИ, рддреЛ рддреАрд╕рд░реЗ рдЕрдВрддрд┐рдо рд╕реНрддрдВрдн рдореЗрдВ рдЯреНрд░реИрдХ рдЖрдИрдбреА рд╣реИрдВред

рдЖрд╡рд╢реНрдпрдХ
orig_shape tuple

рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░, рдкреНрд░рд╛рд░реВрдк рдореЗрдВ (рдКрдВрдЪрд╛рдИ, рдЪреМрдбрд╝рд╛рдИ)ред

рдЖрд╡рд╢реНрдпрдХ
рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __init__(self, boxes, orig_shape) -> None:
    """
    Initialize the Boxes class.

    Args:
        boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes, with
            shape (num_boxes, 6) or (num_boxes, 7). The last two columns contain confidence and class values.
            If present, the third last column contains track IDs.
        orig_shape (tuple): Original image size, in the format (height, width).
    """
    if boxes.ndim == 1:
        boxes = boxes[None, :]
    n = boxes.shape[-1]
    assert n in {6, 7}, f"expected 6 or 7 values but got {n}"  # xyxy, track_id, conf, cls
    super().__init__(boxes, orig_shape)
    self.is_track = n == 7
    self.orig_shape = orig_shape



ultralytics.engine.results.Masks

рдХрд╛ рд░реВрдк: BaseTensor

рдбрд┐рдЯреЗрдХреНрд╢рди рдорд╛рд╕реНрдХ рдХреЗ рднрдВрдбрд╛рд░рдг рдФрд░ рд╣реЗрд░рдлреЗрд░ рдХреЗ рд▓рд┐рдП рдПрдХ рд╡рд░реНрдЧред

рд╡рд┐рд╢реЗрд╖рддрд╛рдПрдБ:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
xy list

рдкрд┐рдХреНрд╕реЗрд▓ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдореЗрдВ рдЦрдВрдбреЛрдВ рдХреА рдПрдХ рд╕реВрдЪреАред

xyn list

рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд рдЦрдВрдбреЛрдВ рдХреА рдПрдХ рд╕реВрдЪреАред

рд╡рд┐рдзрд┐рдпрд╛рдБ:

рдирд╛рдо рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
cpu

рдорд╛рд╕реНрдХ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor CPU рдореЗрдореЛрд░реА рдкрд░ред

numpy

рдорд╛рд╕реНрдХ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor рдПрдХ рд╕реБрдиреНрди рд╕рд░рдгреА рдХреЗ рд░реВрдк рдореЗрдВред

cuda

рдорд╛рд╕реНрдХ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor GPU рдореЗрдореЛрд░реА рдкрд░ред

to

рдорд╛рд╕реНрдХ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдФрд░ dType рдХреЗ рд╕рд╛рдеред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class Masks(BaseTensor):
    """
    A class for storing and manipulating detection masks.

    Attributes:
        xy (list): A list of segments in pixel coordinates.
        xyn (list): A list of normalized segments.

    Methods:
        cpu(): Returns the masks tensor on CPU memory.
        numpy(): Returns the masks tensor as a numpy array.
        cuda(): Returns the masks tensor on GPU memory.
        to(device, dtype): Returns the masks tensor with the specified device and dtype.
    """

    def __init__(self, masks, orig_shape) -> None:
        """Initialize the Masks class with the given masks tensor and original image shape."""
        if masks.ndim == 2:
            masks = masks[None, :]
        super().__init__(masks, orig_shape)

    @property
    @lru_cache(maxsize=1)
    def xyn(self):
        """Return normalized segments."""
        return [
            ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=True)
            for x in ops.masks2segments(self.data)
        ]

    @property
    @lru_cache(maxsize=1)
    def xy(self):
        """Return segments in pixel coordinates."""
        return [
            ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=False)
            for x in ops.masks2segments(self.data)
        ]

xy cached property

рдкрд┐рдХреНрд╕реЗрд▓ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдореЗрдВ рд╕реЗрдЧрдореЗрдВрдЯ рд▓реМрдЯрд╛рдПрдВ.

xyn cached property

рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд рдЦрдВрдб рд▓реМрдЯрд╛рдПрдВред

__init__(masks, orig_shape)

рджрд┐рдП рдЧрдП рдорд╛рд╕реНрдХ рдХреЗ рд╕рд╛рде рдорд╛рд╕реНрдХ рд╡рд░реНрдЧ рдХреЛ рдкреНрд░рд╛рд░рдВрдн рдХрд░реЗрдВ tensor рдФрд░ рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░ред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __init__(self, masks, orig_shape) -> None:
    """Initialize the Masks class with the given masks tensor and original image shape."""
    if masks.ndim == 2:
        masks = masks[None, :]
    super().__init__(masks, orig_shape)



ultralytics.engine.results.Keypoints

рдХрд╛ рд░реВрдк: BaseTensor

рдкрддрд╛ рд▓рдЧрд╛рдиреЗ рд╡рд╛рд▓реЗ рдХреАрдкреЙрдЗрдВрдЯреНрд╕ рдХреЛ рд╕реНрдЯреЛрд░ рдХрд░рдиреЗ рдФрд░ рд╣реЗрд░рдлреЗрд░ рдХрд░рдиреЗ рдХреЗ рд▓рд┐рдП рдПрдХ рдХреНрд▓рд╛рд╕ред

рд╡рд┐рд╢реЗрд╖рддрд╛рдПрдБ:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
xy Tensor

рдкреНрд░рддреНрдпреЗрдХ рдкрд╣рдЪрд╛рди рдХреЗ рд▓рд┐рдП x, y рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рд╡рд╛рд▓реЗ рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХрд╛ рдПрдХ рд╕рдВрдЧреНрд░рд╣ред

xyn Tensor

рд╕реАрдорд╛ рдореЗрдВ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рдХреЗ рд╕рд╛рде xy рдХрд╛ рдПрдХ рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд рд╕рдВрд╕реНрдХрд░рдг [0, 1]ред

conf Tensor

рдпрджрд┐ рдЙрдкрд▓рдмреНрдз рд╣реЛ рддреЛ рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рд╕реЗ рдЬреБрдбрд╝реЗ рд╡рд┐рд╢реНрд╡рд╛рд╕ рдорд╛рди, рдЕрдиреНрдпрдерд╛ рдХреЛрдИ рдирд╣реАрдВред

рд╡рд┐рдзрд┐рдпрд╛рдБ:

рдирд╛рдо рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
cpu

рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor CPU рдореЗрдореЛрд░реА рдкрд░ред

numpy

рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor рдПрдХ рд╕реБрдиреНрди рд╕рд░рдгреА рдХреЗ рд░реВрдк рдореЗрдВред

cuda

рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor GPU рдореЗрдореЛрд░реА рдкрд░ред

to

рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреА рдПрдХ рдкреНрд░рддрд┐рд▓рд┐рдкрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдФрд░ dType рдХреЗ рд╕рд╛рдеред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class Keypoints(BaseTensor):
    """
    A class for storing and manipulating detection keypoints.

    Attributes:
        xy (torch.Tensor): A collection of keypoints containing x, y coordinates for each detection.
        xyn (torch.Tensor): A normalized version of xy with coordinates in the range [0, 1].
        conf (torch.Tensor): Confidence values associated with keypoints if available, otherwise None.

    Methods:
        cpu(): Returns a copy of the keypoints tensor on CPU memory.
        numpy(): Returns a copy of the keypoints tensor as a numpy array.
        cuda(): Returns a copy of the keypoints tensor on GPU memory.
        to(device, dtype): Returns a copy of the keypoints tensor with the specified device and dtype.
    """

    @smart_inference_mode()  # avoid keypoints < conf in-place error
    def __init__(self, keypoints, orig_shape) -> None:
        """Initializes the Keypoints object with detection keypoints and original image size."""
        if keypoints.ndim == 2:
            keypoints = keypoints[None, :]
        if keypoints.shape[2] == 3:  # x, y, conf
            mask = keypoints[..., 2] < 0.5  # points with conf < 0.5 (not visible)
            keypoints[..., :2][mask] = 0
        super().__init__(keypoints, orig_shape)
        self.has_visible = self.data.shape[-1] == 3

    @property
    @lru_cache(maxsize=1)
    def xy(self):
        """Returns x, y coordinates of keypoints."""
        return self.data[..., :2]

    @property
    @lru_cache(maxsize=1)
    def xyn(self):
        """Returns normalized x, y coordinates of keypoints."""
        xy = self.xy.clone() if isinstance(self.xy, torch.Tensor) else np.copy(self.xy)
        xy[..., 0] /= self.orig_shape[1]
        xy[..., 1] /= self.orig_shape[0]
        return xy

    @property
    @lru_cache(maxsize=1)
    def conf(self):
        """Returns confidence values of keypoints if available, else None."""
        return self.data[..., 2] if self.has_visible else None

conf cached property

рдпрджрд┐ рдЙрдкрд▓рдмреНрдз рд╣реЛ рддреЛ рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреЗ рд╡рд┐рд╢реНрд╡рд╛рд╕ рдорд╛рди рд▓реМрдЯрд╛рддрд╛ рд╣реИ, рдЕрдиреНрдпрдерд╛ рдХреЛрдИ рдирд╣реАрдВред

xy cached property

рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреЗ x, y рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рд▓реМрдЯрд╛рддрд╛ рд╣реИ.

xyn cached property

рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд x, y рдореБрдЦреНрдп рдмрд┐рдВрджреБрдУрдВ рдХреЗ рдирд┐рд░реНрджреЗрд╢рд╛рдВрдХ рджреЗрддрд╛ рд╣реИред

__init__(keypoints, orig_shape)

Keypoints рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЛ рдбрд┐рдЯреЗрдХреНрд╢рди рдХреАрдкреЙрдЗрдВрдЯ рдФрд░ рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рдХреЗ рд╕рд╛рде рдЗрдирд┐рд╢рд┐рдпрд▓рд╛рдЗрдЬрд╝ рдХрд░рддрд╛ рд╣реИред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
@smart_inference_mode()  # avoid keypoints < conf in-place error
def __init__(self, keypoints, orig_shape) -> None:
    """Initializes the Keypoints object with detection keypoints and original image size."""
    if keypoints.ndim == 2:
        keypoints = keypoints[None, :]
    if keypoints.shape[2] == 3:  # x, y, conf
        mask = keypoints[..., 2] < 0.5  # points with conf < 0.5 (not visible)
        keypoints[..., :2][mask] = 0
    super().__init__(keypoints, orig_shape)
    self.has_visible = self.data.shape[-1] == 3



ultralytics.engine.results.Probs

рдХрд╛ рд░реВрдк: BaseTensor

рд╡рд░реНрдЧреАрдХрд░рдг рднрд╡рд┐рд╖реНрдпрд╡рд╛рдгрд┐рдпреЛрдВ рдХреЗ рднрдВрдбрд╛рд░рдг рдФрд░ рд╣реЗрд░рдлреЗрд░ рдХреЗ рд▓рд┐рдП рдПрдХ рд╡рд░реНрдЧред

рд╡рд┐рд╢реЗрд╖рддрд╛рдПрдБ:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
top1 int

рд╢реАрд░реНрд╖ 1 рд╡рд░реНрдЧ рдХрд╛ рд╕реВрдЪрдХрд╛рдВрдХред

top5 list[int]

рд╢реАрд░реНрд╖ 5 рд╡рд░реНрдЧреЛрдВ рдХреЗ рд╕реВрдЪрдХрд╛рдВрдХред

top1conf Tensor

рд╢реАрд░реНрд╖ 1 рд╡рд░реНрдЧ рдХрд╛ рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ред

top5conf Tensor

рд╢реАрд░реНрд╖ 5 рд╡рд░реНрдЧреЛрдВ рдХрд╛ рд╡рд┐рд╢реНрд╡рд╛рд╕ред

рд╡рд┐рдзрд┐рдпрд╛рдБ:

рдирд╛рдо рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
cpu

рдЬрд╛рдВрдЪ рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor CPU рдореЗрдореЛрд░реА рдкрд░ред

numpy

рдЬрд╛рдВрдЪ рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor рдПрдХ рд╕реБрдиреНрди рд╕рд░рдгреА рдХреЗ рд░реВрдк рдореЗрдВред

cuda

рдЬрд╛рдВрдЪ рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor GPU рдореЗрдореЛрд░реА рдкрд░ред

to

рдЬрд╛рдВрдЪ рдХреА рдПрдХ рдкреНрд░рддрд┐ рд▓реМрдЯрд╛рддрд╛ рд╣реИ tensor рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдФрд░ dType рдХреЗ рд╕рд╛рдеред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class Probs(BaseTensor):
    """
    A class for storing and manipulating classification predictions.

    Attributes:
        top1 (int): Index of the top 1 class.
        top5 (list[int]): Indices of the top 5 classes.
        top1conf (torch.Tensor): Confidence of the top 1 class.
        top5conf (torch.Tensor): Confidences of the top 5 classes.

    Methods:
        cpu(): Returns a copy of the probs tensor on CPU memory.
        numpy(): Returns a copy of the probs tensor as a numpy array.
        cuda(): Returns a copy of the probs tensor on GPU memory.
        to(): Returns a copy of the probs tensor with the specified device and dtype.
    """

    def __init__(self, probs, orig_shape=None) -> None:
        """Initialize the Probs class with classification probabilities and optional original shape of the image."""
        super().__init__(probs, orig_shape)

    @property
    @lru_cache(maxsize=1)
    def top1(self):
        """Return the index of top 1."""
        return int(self.data.argmax())

    @property
    @lru_cache(maxsize=1)
    def top5(self):
        """Return the indices of top 5."""
        return (-self.data).argsort(0)[:5].tolist()  # this way works with both torch and numpy.

    @property
    @lru_cache(maxsize=1)
    def top1conf(self):
        """Return the confidence of top 1."""
        return self.data[self.top1]

    @property
    @lru_cache(maxsize=1)
    def top5conf(self):
        """Return the confidences of top 5."""
        return self.data[self.top5]

top1 cached property

рд╢реАрд░реНрд╖ 1 рдХрд╛ рд╕реВрдЪрдХрд╛рдВрдХ рд▓реМрдЯрд╛рдПрдВред

top1conf cached property

рд╢реАрд░реНрд╖ 1 рдХрд╛ рд╡рд┐рд╢реНрд╡рд╛рд╕ рд▓реМрдЯрд╛рдПрдВред

top5 cached property

рд╢реАрд░реНрд╖ 5 рдХреЗ рд╕реВрдЪрдХрд╛рдВрдХреЛрдВ рдХреЛ рд▓реМрдЯрд╛рдПрдВред

top5conf cached property

рд╢реАрд░реНрд╖ 5 рдХреЗ рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ рдХреЛ рд▓реМрдЯрд╛рдПрдВред

__init__(probs, orig_shape=None)

рд╡рд░реНрдЧреАрдХрд░рдг рд╕рдВрднрд╛рд╡рдирд╛рдУрдВ рдФрд░ рдЫрд╡рд┐ рдХреЗ рд╡реИрдХрд▓реНрдкрд┐рдХ рдореВрд▓ рдЖрдХрд╛рд░ рдХреЗ рд╕рд╛рде рдкреНрд░реЛрдмреНрд╕ рд╡рд░реНрдЧ рдХреЛ рдкреНрд░рд╛рд░рдВрдн рдХрд░реЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __init__(self, probs, orig_shape=None) -> None:
    """Initialize the Probs class with classification probabilities and optional original shape of the image."""
    super().__init__(probs, orig_shape)



ultralytics.engine.results.OBB

рдХрд╛ рд░реВрдк: BaseTensor

рдУрд░рд┐рдПрдВрдЯреЗрдб рдмрд╛рдЙрдВрдбрд┐рдВрдЧ рдмреЙрдХреНрд╕ (OBB) рдХреЗ рднрдВрдбрд╛рд░рдг рдФрд░ рд╣реЗрд░рдлреЗрд░ рдХреЗ рд▓рд┐рдП рдПрдХ рд╡рд░реНрдЧред

рдкреИрд░рд╛рдореАрдЯрд░:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо рдЪреВрдХ
boxes Tensor | ndarray

рдПрдХ tensor рдпрд╛ рд╕реБрдиреНрди рд╕рд░рдгреА рдЬрд┐рд╕рдореЗрдВ рдбрд┐рдЯреЗрдХреНрд╢рди рдмреЙрдХреНрд╕ рд╣реЛрддреЗ рд╣реИрдВ, рдЖрдХрд╛рд░ рдХреЗ рд╕рд╛рде (num_boxes, 7) рдпрд╛ (num_boxes, 8)ред рдЕрдВрддрд┐рдо рджреЛ рд╕реНрддрдВрднреЛрдВ рдореЗрдВ рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ рдФрд░ рд╡рд░реНрдЧ рдорд╛рди рд╣реЛрддреЗ рд╣реИрдВред рдпрджрд┐ рдореМрдЬреВрдж рд╣реИ, рддреЛ рддреАрд╕рд░реЗ рдЕрдВрддрд┐рдо рдХреЙрд▓рдо рдореЗрдВ рдЯреНрд░реИрдХ рдЖрдИрдбреА рд╣реЛрддреЗ рд╣реИрдВ, рдФрд░ рдмрд╛рдИрдВ рдУрд░ рд╕реЗ рдкрд╛рдВрдЪрд╡реЗрдВ рдХреЙрд▓рдо рдореЗрдВ рд░реЛрдЯреЗрд╢рди рд╣реЛрддрд╛ рд╣реИред

рдЖрд╡рд╢реНрдпрдХ
orig_shape tuple

рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░, рдкреНрд░рд╛рд░реВрдк рдореЗрдВ (рдКрдВрдЪрд╛рдИ, рдЪреМрдбрд╝рд╛рдИ)ред

рдЖрд╡рд╢реНрдпрдХ

рд╡рд┐рд╢реЗрд╖рддрд╛рдПрдБ:

рдирд╛рдо рдкреНрд░рдХрд╛рд░ рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
xywhr Tensor | ndarray

[x_center, y_center, рдЪреМрдбрд╝рд╛рдИ, рдКрдВрдЪрд╛рдИ, рд░реЛрдЯреЗрд╢рди] рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдмреЙрдХреНрд╕ред

conf Tensor | ndarray

рдмрдХреНрд╕реЗ рдХреЗ рдЖрддреНрдорд╡рд┐рд╢реНрд╡рд╛рд╕ рдореВрд▓реНрдпред

cls Tensor | ndarray

рдмрдХреНрд╕реЛрдВ рдХреЗ рд╡рд░реНрдЧ рдорд╛рдиред

id Tensor | ndarray

рдмреЙрдХреНрд╕ рдХреА рдЯреНрд░реИрдХ рдЖрдИрдбреА (рдпрджрд┐ рдЙрдкрд▓рдмреНрдз рд╣реЛ)ред

xyxyxyxyn Tensor | ndarray

xyxyxyxy рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдШреБрдорд╛рдП рдЧрдП рдмрдХреНрд╕реЗ рдореВрд▓ рдЫрд╡рд┐ рдЖрдХрд╛рд░ рджреНрд╡рд╛рд░рд╛ рд╕рд╛рдорд╛рдиреНрдпреАрдХреГрдд рд╣реЛрддреЗ рд╣реИрдВред

xyxyxyxy Tensor | ndarray

xyxyxyxy рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рдШреБрдорд╛рдП рдЧрдП рдмрдХреНрд╕реЗред

xyxy Tensor | ndarray

рдХреНрд╖реИрддрд┐рдЬ рдмрдХреНрд╕реЗ xyxyxyxy рд╕реНрд╡рд░реВрдк рдореЗрдВ.

data Tensor

рдХрдЪреНрдЪрд╛ рдУ.рдмреА.рдмреА. tensor (рдЙрдкрдирд╛рдо рдХреЗ рд▓рд┐рдП boxes).

рд╡рд┐рдзрд┐рдпрд╛рдБ:

рдирд╛рдо рдпрд╛ рдХрд╝рд┐рд╕реНтАНрдо
cpu

рдСрдмреНрдЬреЗрдХреНрдЯ CPU рд╕реНрдореГрддрд┐ рдореЗрдВ рд▓реЗ рдЬрд╛рдПрдБред

numpy

рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЛ рдПрдХ numpy рд╕рд░рдгреА рдореЗрдВ рдХрдирд╡рд░реНрдЯ рдХрд░реЗрдВред

cuda

рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЛ CUDA рд╕реНрдореГрддрд┐ рдореЗрдВ рд▓реЗ рдЬрд╛рдПрдБред

to

рдСрдмреНрдЬреЗрдХреНрдЯ рдХреЛ рдирд┐рд░реНрджрд┐рд╖реНрдЯ рдбрд┐рд╡рд╛рдЗрд╕ рдкрд░ рд▓реЗ рдЬрд╛рдПрдБред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
class OBB(BaseTensor):
    """
    A class for storing and manipulating Oriented Bounding Boxes (OBB).

    Args:
        boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes,
            with shape (num_boxes, 7) or (num_boxes, 8). The last two columns contain confidence and class values.
            If present, the third last column contains track IDs, and the fifth column from the left contains rotation.
        orig_shape (tuple): Original image size, in the format (height, width).

    Attributes:
        xywhr (torch.Tensor | numpy.ndarray): The boxes in [x_center, y_center, width, height, rotation] format.
        conf (torch.Tensor | numpy.ndarray): The confidence values of the boxes.
        cls (torch.Tensor | numpy.ndarray): The class values of the boxes.
        id (torch.Tensor | numpy.ndarray): The track IDs of the boxes (if available).
        xyxyxyxyn (torch.Tensor | numpy.ndarray): The rotated boxes in xyxyxyxy format normalized by orig image size.
        xyxyxyxy (torch.Tensor | numpy.ndarray): The rotated boxes in xyxyxyxy format.
        xyxy (torch.Tensor | numpy.ndarray): The horizontal boxes in xyxyxyxy format.
        data (torch.Tensor): The raw OBB tensor (alias for `boxes`).

    Methods:
        cpu(): Move the object to CPU memory.
        numpy(): Convert the object to a numpy array.
        cuda(): Move the object to CUDA memory.
        to(*args, **kwargs): Move the object to the specified device.
    """

    def __init__(self, boxes, orig_shape) -> None:
        """Initialize the Boxes class."""
        if boxes.ndim == 1:
            boxes = boxes[None, :]
        n = boxes.shape[-1]
        assert n in {7, 8}, f"expected 7 or 8 values but got {n}"  # xywh, rotation, track_id, conf, cls
        super().__init__(boxes, orig_shape)
        self.is_track = n == 8
        self.orig_shape = orig_shape

    @property
    def xywhr(self):
        """Return the rotated boxes in xywhr format."""
        return self.data[:, :5]

    @property
    def conf(self):
        """Return the confidence values of the boxes."""
        return self.data[:, -2]

    @property
    def cls(self):
        """Return the class values of the boxes."""
        return self.data[:, -1]

    @property
    def id(self):
        """Return the track IDs of the boxes (if available)."""
        return self.data[:, -3] if self.is_track else None

    @property
    @lru_cache(maxsize=2)
    def xyxyxyxy(self):
        """Return the boxes in xyxyxyxy format, (N, 4, 2)."""
        return ops.xywhr2xyxyxyxy(self.xywhr)

    @property
    @lru_cache(maxsize=2)
    def xyxyxyxyn(self):
        """Return the boxes in xyxyxyxy format, (N, 4, 2)."""
        xyxyxyxyn = self.xyxyxyxy.clone() if isinstance(self.xyxyxyxy, torch.Tensor) else np.copy(self.xyxyxyxy)
        xyxyxyxyn[..., 0] /= self.orig_shape[1]
        xyxyxyxyn[..., 1] /= self.orig_shape[0]
        return xyxyxyxyn

    @property
    @lru_cache(maxsize=2)
    def xyxy(self):
        """
        Return the horizontal boxes in xyxy format, (N, 4).

        Accepts both torch and numpy boxes.
        """
        x1 = self.xyxyxyxy[..., 0].min(1).values
        x2 = self.xyxyxyxy[..., 0].max(1).values
        y1 = self.xyxyxyxy[..., 1].min(1).values
        y2 = self.xyxyxyxy[..., 1].max(1).values
        xyxy = [x1, y1, x2, y2]
        return np.stack(xyxy, axis=-1) if isinstance(self.data, np.ndarray) else torch.stack(xyxy, dim=-1)

cls property

рдмрдХреНрд╕реЛрдВ рдХреЗ рд╡рд░реНрдЧ рдорд╛рди рд▓реМрдЯрд╛рдПрдВред

conf property

рдмрдХреНрд╕реЗ рдХреЗ рд╡рд┐рд╢реНрд╡рд╛рд╕ рдореВрд▓реНрдпреЛрдВ рдХреЛ рд╡рд╛рдкрд╕ рдХрд░реЗрдВред

id property

рдмреЙрдХреНрд╕ рдХреА рдЯреНрд░реИрдХ рдЖрдИрдбреА рд▓реМрдЯрд╛рдПрдВ (рдпрджрд┐ рдЙрдкрд▓рдмреНрдз рд╣реЛ)ред

xywhr property

рдШреБрдорд╛рдП рдЧрдП рдмрдХреНрд╕реЗ рдХреЛ xywhr рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рд▓реМрдЯрд╛рдПрдВред

xyxy cached property

рдХреНрд╖реИрддрд┐рдЬ рдмрдХреНрд╕реЗ рдХреЛ xyxy рдкреНрд░рд╛рд░реВрдк рдореЗрдВ рд▓реМрдЯрд╛рдПрдВ, (N, 4)ред

рджреЛрдиреЛрдВ рдХреЛ рд╕реНрд╡реАрдХрд╛рд░ рдХрд░рддрд╛ рд╣реИ torch рдФрд░ рд╕реБрдиреНрди рдмрдХреНрд╕реЗред

xyxyxyxy cached property

рдмрдХреНрд╕реЛрдВ рдХреЛ xyxyxyxy рд╕реНрд╡рд░реВрдк, (N, 4, 2) рдореЗрдВ рд▓реМрдЯрд╛рдПрдБ.

xyxyxyxyn cached property

рдмрдХреНрд╕реЛрдВ рдХреЛ xyxyxyxy рд╕реНрд╡рд░реВрдк, (N, 4, 2) рдореЗрдВ рд▓реМрдЯрд╛рдПрдБ.

__init__(boxes, orig_shape)

Boxes рдХреНрд▓рд╛рд╕ рдХреЛ рдЗрдирд┐рд╢рд┐рдпрд▓рд╛рдЗрдЬрд╝ рдХрд░реЗрдВред

рдореЗрдВ рд╕реНрд░реЛрдд рдХреЛрдб ultralytics/engine/results.py
def __init__(self, boxes, orig_shape) -> None:
    """Initialize the Boxes class."""
    if boxes.ndim == 1:
        boxes = boxes[None, :]
    n = boxes.shape[-1]
    assert n in {7, 8}, f"expected 7 or 8 values but got {n}"  # xywh, rotation, track_id, conf, cls
    super().__init__(boxes, orig_shape)
    self.is_track = n == 8
    self.orig_shape = orig_shape





2023-11-12 рдмрдирд╛рдпрд╛ рдЧрдпрд╛, рдЕрдкрдбреЗрдЯ рдХрд┐рдпрд╛ рдЧрдпрд╛ 2024-05-08
рд▓реЗрдЦрдХ: рдмреБрд░рд╣рд╛рди-рдХреНрдпреВ (1), рдЧреНрд▓реЗрди-рдЬреЛрдЪрд░ (4), рд▓рд╛рдлрд┐рдВрдЧ-рдХреНрдпреВ (1)