μ½˜ν…μΈ λ‘œ κ±΄λ„ˆλ›°κΈ°

μ°Έμ‘° ultralytics/engine/results.py

μ°Έκ³ 

이 νŒŒμΌμ€ https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/engine/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)

λ°μ΄ν„°μ˜ μ§€μ •λœ μΈλ±μŠ€κ°€ μžˆλŠ” λ² μ΄μŠ€ν…μ„œλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€ 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

Bλ°•μŠ€, 마슀크 및 ν‚€ν¬μΈνŠΈμ™€ 같은 예츑.

ν•„μˆ˜
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()

CPU λ©”λͺ¨λ¦¬μ— tensor 사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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()

GPU λ©”λͺ¨λ¦¬μ— tensor 사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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)

μ§€μ •λœ μž₯μΉ˜μ™€ dtype이 ν¬ν•¨λœ tensor 사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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

μ „μ²˜λ¦¬, μΆ”λ‘  및 ν›„μ²˜λ¦¬ 속도 사전(ms/이미지).

names dict

클래슀 이름 사전.

path str

이미지 파일의 κ²½λ‘œμž…λ‹ˆλ‹€.

λ©”μ†Œλ“œ:

이름 μ„€λͺ…
update

μƒˆλ‘œμš΄ 탐지 결과둜 개체 속성을 μ—…λ°μ΄νŠΈν•©λ‹ˆλ‹€.

cpu

CPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” λͺ¨λ“  ν…μ„œκ°€ ν¬ν•¨λœ κ²°κ³Ό 객체의 볡사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

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 tojson(self, normalize=False):
        """Convert the object to JSON format."""
        if self.probs is not None:
            LOGGER.warning("Warning: Classify task do not support `tojson` yet.")
            return

        import json

        # Create list of detection dictionaries
        results = []
        data = self.boxes.data.cpu().tolist()
        h, w = self.orig_shape if normalize else (1, 1)
        for i, row in enumerate(data):  # xyxy, track_id if tracking, conf, class_id
            box = {"x1": row[0] / w, "y1": row[1] / h, "x2": row[2] / w, "y2": row[3] / h}
            conf = row[-2]
            class_id = int(row[-1])
            name = self.names[class_id]
            result = {"name": name, "class": class_id, "confidence": conf, "box": box}
            if self.boxes.is_track:
                result["track_id"] = int(row[-3])  # track ID
            if self.masks:
                x, y = self.masks.xy[i][:, 0], self.masks.xy[i][:, 1]  # numpy array
                result["segments"] = {"x": (x / w).tolist(), "y": (y / h).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).tolist(), "y": (y / h).tolist(), "visible": visible.tolist()}
            results.append(result)

        # Convert detections to JSON
        return json.dumps(results, 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)

Results 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
orig_img ndarray

원본 이미지가 널빀지 λ°°μ—΄λ‘œ ν‘œμ‹œλ©λ‹ˆλ‹€.

ν•„μˆ˜
path str

이미지 파일의 κ²½λ‘œμž…λ‹ˆλ‹€.

ν•„μˆ˜
names dict

클래슀 이름 μ‚¬μ „μž…λ‹ˆλ‹€.

ν•„μˆ˜
boxes tensor

각 탐지에 λŒ€ν•œ λ°”μš΄λ”© λ°•μŠ€ μ’Œν‘œμ˜ 2D tensor .

None
masks tensor

탐지 마슀크의 3D tensor , 각 λ§ˆμŠ€ν¬λŠ” 이진 μ΄λ―Έμ§€μž…λ‹ˆλ‹€.

None
probs tensor

λΆ„λ₯˜ μž‘μ—…μ— λŒ€ν•œ 각 클래슀의 1D tensor ν™•λ₯ μž…λ‹ˆλ‹€.

None
keypoints tensor

각 탐지에 λŒ€ν•œ ν‚€ν¬μΈνŠΈ μ’Œν‘œμ˜ 2D tensor .

None
obb tensor

각 탐지에 λŒ€ν•œ λ°©ν–₯이 μ§€μ •λœ λ°”μš΄λ”© λ°•μŠ€ μ’Œν‘œμ˜ 2D 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()

λͺ¨λ“  ν…μ„œκ°€ ν¬ν•¨λœ Results 객체의 볡사본을 널 λ°°μ—΄λ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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 이미지에 감지 κ²°κ³Όλ₯Ό ν”Œλ‘―ν•©λ‹ˆλ‹€. 널 λ°°μ—΄(cv2) λ˜λŠ” PIL 이미지λ₯Ό λ°›μ•„λ“€μž…λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
conf bool

탐지 신뒰도 점수λ₯Ό ν‘œμ‹œν• μ§€ μ—¬λΆ€μž…λ‹ˆλ‹€.

True
line_width float

경계 μƒμžμ˜ μ„  λ„ˆλΉ„μž…λ‹ˆλ‹€. μ—†μŒμΈ 경우 이미지 크기에 맞게 μ‘°μ •λ©λ‹ˆλ‹€.

None
font_size float

ν…μŠ€νŠΈμ˜ κΈ€κΌ΄ ν¬κΈ°μž…λ‹ˆλ‹€. μ—†μŒμΈ 경우 이미지 크기에 맞게 μ‘°μ •λ©λ‹ˆλ‹€.

None
font str

ν…μŠ€νŠΈμ— μ‚¬μš©ν•  κΈ€κΌ΄μž…λ‹ˆλ‹€.

'Arial.ttf'
pil bool

이미지λ₯Ό PIL μ΄λ―Έμ§€λ‘œ λ°˜ν™˜ν• μ§€ μ—¬λΆ€μž…λ‹ˆλ‹€.

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

μ €μž₯이 True인 경우 이미지λ₯Ό μ €μž₯ν•  파일 μ΄λ¦„μž…λ‹ˆλ‹€.

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_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)

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)

개체λ₯Ό JSON ν˜•μ‹μœΌλ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/engine/results.py
def tojson(self, normalize=False):
    """Convert the object to JSON format."""
    if self.probs is not None:
        LOGGER.warning("Warning: Classify task do not support `tojson` yet.")
        return

    import json

    # Create list of detection dictionaries
    results = []
    data = self.boxes.data.cpu().tolist()
    h, w = self.orig_shape if normalize else (1, 1)
    for i, row in enumerate(data):  # xyxy, track_id if tracking, conf, class_id
        box = {"x1": row[0] / w, "y1": row[1] / h, "x2": row[2] / w, "y2": row[3] / h}
        conf = row[-2]
        class_id = int(row[-1])
        name = self.names[class_id]
        result = {"name": name, "class": class_id, "confidence": conf, "box": box}
        if self.boxes.is_track:
            result["track_id"] = int(row[-3])  # track ID
        if self.masks:
            x, y = self.masks.xy[i][:, 0], self.masks.xy[i][:, 1]  # numpy array
            result["segments"] = {"x": (x / w).tolist(), "y": (y / h).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).tolist(), "y": (y / h).tolist(), "visible": visible.tolist()}
        results.append(result)

    # Convert detections to JSON
    return json.dumps(results, 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

탐지 μƒμžλ₯Ό κ΄€λ¦¬ν•˜μ—¬ μƒμž μ’Œν‘œ, 신뒰도 점수, 클래슀 μ‹λ³„μž 및 선택적 좔적 ID에 μ•‘μ„ΈμŠ€ν•  수 μžˆμŠ΅λ‹ˆλ‹€. λ°•μŠ€ μ’Œν‘œμ— λŒ€ν•΄ μ ˆλŒ€ ν˜•μ‹ 및 μ •κ·œν™”λœ ν˜•μ‹μ„ λͺ¨λ‘ μ§€μ›ν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
data Tensor

탐지 μƒμž 및 κ΄€λ ¨ 데이터가 ν¬ν•¨λœ μ›μ‹œ tensor .

orig_shape tuple

μ •κ·œν™”μ— μ‚¬μš©λ˜λŠ” νŠœν”Œ(높이, λ„ˆλΉ„)λ‘œμ„œμ˜ 원본 이미지 ν¬κΈ°μž…λ‹ˆλ‹€.

is_track bool

좔적 IDκ°€ λ°•μŠ€ 데이터에 ν¬ν•¨λ˜λŠ”μ§€ μ—¬λΆ€λ₯Ό λ‚˜νƒ€λƒ…λ‹ˆλ‹€.

속성

xyxy (torch.Tensor | numpy.ndarray): x1, y1, x2, y2] ν˜•μ‹μ˜ λ°•μŠ€. conf (torch.Tensor | numpy.ndarray): 각 μƒμžμ— λŒ€ν•œ 신뒰도 점수. cls (torch.Tensor | numpy.ndarray): 각 μƒμžμ— λŒ€ν•œ 클래슀 λ ˆμ΄λΈ”. id (torch.Tensor | numpy.ndarray, 선택 사항): μ‚¬μš© κ°€λŠ₯ν•œ 경우 각 μƒμžμ— λŒ€ν•œ 좔적 ID. 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

μƒμžλ₯Ό 숫자 λ°°μ—΄ ν˜•μ‹μœΌλ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.

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

μƒμžμ˜ νŠΈλž™ IDλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€(κ°€λŠ₯ν•œ 경우).

xywh cached property

μƒμžλ₯Ό xywh ν˜•μ‹μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

xywhn cached property

원본 이미지 크기둜 μ •κ·œν™”λœ xywh ν˜•μ‹μ˜ μƒμžλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

xyxy property

μƒμžλ₯Ό xyxy ν˜•μ‹μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

xyxyn cached property

원본 이미지 크기둜 μ •κ·œν™”λœ xyxy ν˜•μ‹μ˜ μƒμžλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

__init__(boxes, orig_shape)

Boxes 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
boxes Tensor | ndarray

탐지 μƒμžλ₯Ό ν¬ν•¨ν•˜λŠ” tensor λ˜λŠ” numpy λ°°μ—΄λ‘œ, λ‹€μŒμ„ ν¬ν•¨ν•©λ‹ˆλ‹€. λͺ¨μ–‘ (num_boxes, 6) λ˜λŠ” (num_boxes, 7). λ§ˆμ§€λ§‰ 두 μ—΄μ—λŠ” 신뒰도 및 클래슀 값이 ν¬ν•¨λ©λ‹ˆλ‹€. μžˆλŠ” 경우 μ„Έ 번째 λ§ˆμ§€λ§‰ μ—΄μ—λŠ” νŠΈλž™ IDκ°€ ν¬ν•¨λ©λ‹ˆλ‹€.

ν•„μˆ˜
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

CPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” tensor 마슀크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

numpy

tensor 마슀크λ₯Ό 널 λ°°μ—΄λ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

cuda

GPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” 마슀크 tensor λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

to

μ§€μ •λœ μž₯치 및 dtype이 ν¬ν•¨λœ tensor 마슀크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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

μ’Œν‘œκ°€ [0, 1] λ²”μœ„μΈ xy의 μ •κ·œν™”λœ λ²„μ „μž…λ‹ˆλ‹€.

conf Tensor

ν‚€ν¬μΈνŠΈμ™€ κ΄€λ ¨λœ 신뒰도 κ°’(μ‚¬μš© κ°€λŠ₯ν•œ 경우), 그렇지 μ•ŠμœΌλ©΄ μ—†μŒ.

λ©”μ†Œλ“œ:

이름 μ„€λͺ…
cpu

CPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” ν‚€ν¬μΈνŠΈ tensor 의 볡사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

numpy

tensor ν‚€ν¬μΈνŠΈμ˜ 사본을 널 λ°°μ—΄λ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

cuda

GPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” ν‚€ν¬μΈνŠΈ tensor 의 볡사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

to

μ§€μ •λœ μž₯치 및 dtype이 ν¬ν•¨λœ tensor ν‚€ν¬μΈνŠΈμ˜ 볡사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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)

감지 ν‚€ν¬μΈνŠΈμ™€ 원본 이미지 크기둜 ν‚€ν¬μΈνŠΈ 개체λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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

CPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” probs tensor 의 볡사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

numpy

probs tensor 의 사본을 널 λ°°μ—΄λ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

cuda

GPU λ©”λͺ¨λ¦¬μ— μžˆλŠ” tensor ν”„λ‘œλΈŒμ˜ 사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

to

μ§€μ •λœ μž₯치 및 dtype이 ν¬ν•¨λœ probs tensor 의 사본을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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)

λΆ„λ₯˜ ν™•λ₯ κ³Ό μ΄λ―Έμ§€μ˜ 원본 λͺ¨μ–‘(선택 사항)으둜 Probs 클래슀λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ 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) ν˜•μ‹μ„ μ‚¬μš©ν•©λ‹ˆλ‹€. λ§ˆμ§€λ§‰ 두 μ—΄μ—λŠ” 신뒰도 및 클래슀 값이 ν¬ν•¨λ©λ‹ˆλ‹€. μžˆλŠ” 경우, λ§ˆμ§€λ§‰ μ„Έ 번째 μ—΄μ—λŠ” νŠΈλž™ IDκ°€ ν¬ν•¨λ˜κ³  μ™Όμͺ½μ—μ„œ λ‹€μ„― 번째 μ—΄μ—λŠ” νšŒμ „μ΄ ν¬ν•¨λ©λ‹ˆλ‹€.

ν•„μˆ˜
orig_shape tuple

원본 이미지 크기, ν˜•μ‹(높이, λ„ˆλΉ„)μž…λ‹ˆλ‹€.

ν•„μˆ˜

속성:

이름 μœ ν˜• μ„€λͺ…
xywhr Tensor | ndarray

x_center, y_center, λ„ˆλΉ„, 높이, νšŒμ „] ν˜•μ‹μ˜ λ°•μŠ€μž…λ‹ˆλ‹€.

conf Tensor | ndarray

μƒμžμ˜ 신뒰도 κ°’μž…λ‹ˆλ‹€.

cls Tensor | ndarray

μƒμžμ˜ 클래슀 κ°’μž…λ‹ˆλ‹€.

id Tensor | ndarray

μƒμžμ˜ νŠΈλž™ ID(μ‚¬μš© κ°€λŠ₯ν•œ 경우).

xyxyxyxyn Tensor | ndarray

νšŒμ „λœ μƒμžλŠ” 원본 이미지 크기에 따라 μ •κ·œν™”λœ xyxyxyxy ν˜•μ‹μž…λ‹ˆλ‹€.

xyxyxyxy Tensor | ndarray

νšŒμ „λœ μƒμžλŠ” xyxyxyxy ν˜•μ‹μž…λ‹ˆλ‹€.

xyxy Tensor | ndarray

κ°€λ‘œ μƒμžλŠ” xyxyxyxy ν˜•μ‹μž…λ‹ˆλ‹€.

data Tensor

μ›μ‹œ OBB tensor ( boxes).

λ©”μ†Œλ“œ:

이름 μ„€λͺ…
cpu

개체λ₯Ό CPU λ©”λͺ¨λ¦¬λ‘œ μ΄λ™ν•©λ‹ˆλ‹€.

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

μƒμžμ˜ νŠΈλž™ IDλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€(κ°€λŠ₯ν•œ 경우).

xywhr property

νšŒμ „λœ μƒμžλ₯Ό xywhr ν˜•μ‹μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

xyxy cached property

κ°€λ‘œ μƒμžλ₯Ό (N, 4) xyxy ν˜•μ‹μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

torch 및 숫자 μƒμžλ₯Ό λͺ¨λ‘ ν—ˆμš©ν•©λ‹ˆλ‹€.

xyxyxyxy cached property

μƒμžλ₯Ό (N, 4, 2) xyxyxyxy ν˜•μ‹μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

xyxyxyxyn cached property

μƒμžλ₯Ό (N, 4, 2) xyxyxyxy ν˜•μ‹μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

__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-01-05
μž‘μ„±μž: glenn-jocher (4), Laughing-q (1)