§
    >²¸jâ ã                  óÊ  — d dl mZ d dlZd dlmZ d dlmZmZ d dlm	Z	 d dl
mZmZ d dlZd dlm
Z d dlmZmZ d dlmZmZ d d	lmZmZ d d
lmZ d dlmZmZmZ d dl m!Z!m"Z"m#Z# d dl$m%Z%m&Z&m'Z' d dl(m)Z)m*Z*m+Z+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZM d dlNmOZO d dlPmQZQmRZRmSZS d dlTmUZUmVZVmWZW e G d„ d¦  «        ¦   «         ZXd1d„ZYd2d„ZZ ed d!¬"¦  «        d3d%„¦   «         Z[ ed d!¬"¦  «        d&e6j\        fd4d+„¦   «         Z] ed d!¬"¦  «        d2d,„¦   «         Z^d5d.„Z_ ee_d d!¬/¦  «        d5d0„¦   «         Z`dS )6é    )ÚannotationsN)ÚIterator)Ú	dataclassÚfield)Úreduce)ÚAnyÚcast)Ú
deprecatedÚvoid)ÚCLASS_NAME_DATA_FIELDÚORIENTED_BOX_COORDINATES)Údetection_areaÚdetection_iou©ÚCompactMask)Ú%process_transformers_detection_resultÚ+process_transformers_v4_segmentation_resultÚ+process_transformers_v5_segmentation_result)Ú_DetectionDataTypeÚ_DetectionDataValueTypeÚ_MetadataType)Ú_oriented_box_anchorsÚ_sort_box_cornersÚxyxyxyxy_to_xyxy)Úmask_to_xyxyÚpolygon_to_maskÚrle_to_maskÚxywh_to_xyxy)Úextract_ultralytics_masksÚget_data_itemÚis_data_equalÚis_metadata_equalÚ
merge_dataÚmerge_metadataÚprocess_roboflow_result)	ÚOverlapMetricÚbox_non_max_mergeÚbox_non_max_suppressionÚbox_soft_non_max_suppressionÚmask_non_max_mergeÚmask_non_max_suppressionÚmask_soft_non_max_suppressionÚoriented_box_non_max_mergeÚ oriented_box_non_max_suppression)Úcalculate_masks_centroids)ÚLMMÚVLMÚ_validate_vlm_parametersÚfrom_deepseek_vl_2Úfrom_florence_2Úfrom_google_gemini_2_0Úfrom_google_gemini_2_5Úfrom_google_gemini_3_5Úfrom_moondreamÚfrom_paligemmaÚfrom_qwen_2_5_vlÚfrom_qwen_3_vl)ÚPosition)ÚSupervisionWarningsÚget_instance_variablesÚwarn_deprecated)Ú_validate_dataÚ_validate_detections_fieldsÚ_validate_resolutionc                  ó\  — e Zd ZU dZded<   dZded<   dZded<   dZd	ed
<   dZd	ed<    e	e
¬¦  «        Zded<    e	e
¬¦  «        Zded<   dyd„Zdzd„Zd{d„Zd|d„Zed}d„¦   «         Zed~d „¦   «         Zedd"„¦   «         Zed€d'„¦   «         Zed�d)„¦   «         Zed‚d+„¦   «         Ze	 dƒd„d/„¦   «         Zed…d1„¦   «         Zed2d3œd†d7„¦   «         Zed‡d:„¦   «         Zedˆd<„¦   «         Ze	 dƒd‰d?„¦   «         ZedŠdA„¦   «         Zed‹dG„¦   «         ZedŒdJ„¦   «         Z ed�dM„¦   «         Z!edŽdO„¦   «         Z"ed�dP„¦   «         Z#d�dQ„Z$ed‘dT„¦   «         Z%d’dX„Z&d“d\„Z'd”d_„Z(d•db„Z)d–de„Z*e+d—df„¦   «         Z,e+d—dg„¦   «         Z-e+d—dh„¦   «         Z.d�di„Z/d˜dm„Z0dnd2e1j2        fd™ds„Z3	 	 	 dšd›dw„Z4dnd2e1j2        fd™dx„Z5dS )œÚ
Detectionsa#  
    The `sv.Detections` class in the Supervision library standardizes results from
    various object detection and segmentation models into a consistent format. This
    class simplifies data manipulation and filtering, providing a uniform API for
    integration with Supervision [trackers](/trackers/), [annotators](/latest/detection/annotators/), and [tools](/detection/tools/line_zone/).

    === "RF-DETR"

        [RF-DETR](https://github.com/roboflow/rf-detr)'s `predict` method returns a
        `sv.Detections` object directly, so no conversion step is needed.

        ```python
        from supervision import _cv2 as cv2
        import supervision as sv
        from rfdetr import RFDETRMedium

        model = RFDETRMedium()
        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        detections = model.predict(image[:, :, ::-1])
        ```

    === "Inference"

        Use [`sv.Detections.from_inference`](/detection/core/#supervision.detection.core.Detections.from_inference)
        method, which accepts model results from both detection and segmentation models.

        ```python
        from supervision import _cv2 as cv2
        import supervision as sv
        from inference import get_model

        model = get_model(model_id="rfdetr-small")
        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        results = model.infer(image)[0]
        detections = sv.Detections.from_inference(results)
        ```

    === "Ultralytics"

        Use [`sv.Detections.from_ultralytics`](/detection/core/#supervision.detection.core.Detections.from_ultralytics)
        method, which accepts model results from both detection and segmentation models.

        ```python
        from supervision import _cv2 as cv2
        import supervision as sv
        from ultralytics import YOLO

        model = YOLO("yolov8n.pt")
        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        results = model(image)[0]
        detections = sv.Detections.from_ultralytics(results)
        ```

    === "Transformers"

        Use [`sv.Detections.from_transformers`](/detection/core/#supervision.detection.core.Detections.from_transformers)
        method, which accepts model results from both detection and segmentation models.

        ```python
        import torch
        import supervision as sv
        from PIL import Image
        from transformers import DetrImageProcessor, DetrForObjectDetection

        processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
        model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

        image = Image.open("<SOURCE_IMAGE_PATH>")
        inputs = processor(images=image, return_tensors="pt")

        with torch.no_grad():
            outputs = model(**inputs)

        width, height = image.size
        target_size = torch.tensor([[height, width]])
        results = processor.post_process_object_detection(
            outputs=outputs, target_sizes=target_size)[0]
        detections = sv.Detections.from_transformers(
            transformers_results=results,
            id2label=model.config.id2label)
        ```

    Attributes:
        xyxy: An array of shape `(n, 4)` containing
            the bounding boxes coordinates in format `[x1, y1, x2, y2]`
        mask: An array of shape `(n, H, W)` containing the segmentation masks
            (`bool` data type), or `None` when masks are not available, or as
            :class:`~supervision.detection.compact_mask.CompactMask`.
        confidence: An array of shape `(n,)` containing the confidence scores
            of the detections, or `None` when confidence values are not available.
        class_id: An array of shape `(n,)` containing the class ids of the
            detections, or `None` when class ids are not available.
        tracker_id: An array of shape `(n,)` containing the tracker ids of the
            detections, or `None` when tracker ids are not available.
        data: A dictionary containing additional
            data where each key is a string representing the data type, and the value
            is either a NumPy array or a list of corresponding data.
        metadata: A dictionary containing collection-level metadata
            that applies to the entire set of detections. This may include information such
            as the video name, camera parameters, timestamp, or other global metadata.
    únpt.NDArray[np.number]ÚxyxyNz*npt.NDArray[np.bool_] | CompactMask | NoneÚmaskznpt.NDArray[np.floating] | NoneÚ
confidenceznpt.NDArray[np.integer] | NoneÚclass_idÚ
tracker_id)Údefault_factoryr   Údatar   ÚmetadataÚreturnÚNonec                ól   — t          | j        | j        | j        | j        | j        | j        ¬¦  «         d S )N©rF   rG   rH   rI   rJ   rL   )rA   rF   rG   rH   rI   rJ   rL   ©Úselfs    új/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/detection/core.pyÚ__post_init__zDetections.__post_init__Ê   sA   € Ý#Ø”Ø”Ø”Ø”]Ø”Ø”ð	
ñ 	
ô 	
ð 	
ð 	
ð 	
ó    Úintc                ó*   — t          | j        ¦  «        S )zL
        Returns the number of detections in the Detections object.
        ©ÚlenrF   rR   s    rT   Ú__len__zDetections.__len__Ô   s   € õ �4”9‰~Œ~ÐrV   ú’Iterator[tuple[npt.NDArray[np.number], npt.NDArray[np.bool_] | None, np.generic | None, np.generic | None, np.generic | None, _DetectionDataType]]c           
   #  óB  K  — t          t          | j        ¦  «        ¦  «        D ]z}| j        |         | j        �| j        |         nd| j        �| j        |         nd| j        �| j        |         nd| j        �| j        |         ndt          | j        |¦  «        fV — Œ{dS )z�
        Iterates over the Detections object and yield a tuple of
        `(xyxy, mask, confidence, class_id, tracker_id, data)` for each detection.
        N)	ÚrangerZ   rF   rG   rH   rI   rJ   r    rL   )rS   Úis     rT   Ú__iter__zDetections.__iter__Ú   s¸   è è € õ  •s˜4œ9‘~”~Ñ&Ô&ð 	ð 	ˆAà”	˜!”Ø $¤	Ð 5�”	˜!”�¸4Ø&*¤oÐ&A�” Ô"Ð"ÀtØ$(¤MÐ$=�”˜aÔ Ð À4Ø&*¤oÐ&A�” Ô"Ð"ÀtÝ˜dœi¨Ñ+Ô+ðð ð ð ð ð	ð 	rV   ÚotherÚobjectÚboolc                ó°  — t          |t          ¦  «        st          S d	d„}d
d„}t          t	          j        | j        |j        ¦  «         || j        |j        ¦  «         || j        |j        ¦  «         || j	        |j	        ¦  «         || j
        |j
        ¦  «        t          | j        |j        ¦  «        t          | j        |j        ¦  «        g¦  «        S )NÚaúnpt.NDArray[np.generic] | NoneÚbrN   rc   c                óV   — | �|€| |u S t          t          j        | |¦  «        ¦  «        S ©N)rc   ÚnpÚarray_equal©re   rg   s     rT   Úarray_equal_or_nonez.Detections.__eq__.<locals>.array_equal_or_noneø   s0   € ð ˆy˜A˜IØ˜A�v�Ý�œ q¨!Ñ,Ô,Ñ-Ô-Ð-rV   ú,npt.NDArray[np.generic] | CompactMask | Nonec                óö   — | �|€| |u S t          | t          ¦  «        rt          | |k    ¦  «        S t          |t          ¦  «        rt          || k    ¦  «        S t          t          j        | |¦  «        ¦  «        S ri   )Ú
isinstancer   rc   rj   rk   rl   s     rT   Ú
mask_equalz%Detections.__eq__.<locals>.mask_equal   st   € ð ˆy˜A˜IØ˜A�v�Ý˜!�[Ñ)Ô)ð $Ý˜A šF‘|”|Ð#Ý˜!�[Ñ)Ô)ð $Ý˜A šF‘|”|Ð#Ý�œ q¨!Ñ,Ô,Ñ-Ô-Ð-rV   )re   rf   rg   rf   rN   rc   )re   rn   rg   rn   rN   rc   )rp   rD   ÚNotImplementedÚallrj   rk   rF   rG   rI   rH   rJ   r!   rL   r"   rM   )rS   ra   rm   rq   s       rT   Ú__eq__zDetections.__eq__ô   sá   € Ý˜%¥Ñ,Ô,ð 	"Ý!Ð!ð	.ð 	.ð 	.ð 	.ð
	.ð 
	.ð 
	.ð 
	.õ å”˜tœy¨%¬*Ñ5Ô5Ø�
˜4œ9 e¤jÑ1Ô1Ø#Ð# D¤M°5´>ÑBÔBØ#Ð# D¤O°UÔ5EÑFÔFØ#Ð# D¤O°UÔ5EÑFÔFÝ˜dœi¨¬Ñ4Ô4Ý! $¤-°´Ñ@Ô@ðñ

ô 

ð 
	
rV   Úyolov5_resultsr   c                ó  — |j         d                              ¦   «                              ¦   «                              ¦   «         } | |dd…dd…f         |dd…df         |dd…df                              t          ¦  «        ¬¦  «        S )aŒ  
        Creates a Detections instance from a
        [YOLOv5](https://github.com/ultralytics/yolov5) inference result.

        Args:
            yolov5_results: The output Detections instance from YOLOv5.

        Returns:
            A new Detections object.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import torch
            import supervision as sv

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
            result = model(image)
            detections = sv.Detections.from_yolov5(result)
            ```
        r   Né   é   ©rF   rH   rI   )ÚpredÚcpuÚnumpyÚastyperW   )Úclsru   Úyolov5_detections_predictionss      rT   Úfrom_yolov5zDetections.from_yolov5  s‘   € ð0 )7Ô(;¸AÔ(>×(BÒ(BÑ(DÔ(D×(HÒ(HÑ(JÔ(J×(PÒ(PÑ(RÔ(RÐ%àˆsØ.¨q¨q¨q°"°1°"¨uÔ5Ø4°Q°Q°Q¸°TÔ:Ø2°1°1°1°a°4Ô8×?Ò?ÅÑDÔDð
ñ 
ô 
ð 	
rV   Úultralytics_resultsc           
     ó\  ‡— t          ‰d¦  «        �rh‰j        ��`‰j        j                             ¦   «                              ¦   «                              t          ¦  «        }t          j        ˆfd„|D ¦   «         ¦  «        }‰j        j	                             ¦   «                              ¦   «         } | ‰j        j
                             ¦   «                              ¦   «         ‰j        j                             ¦   «                              ¦   «         |‰j        j        �B‰j        j                             ¦   «                              ¦   «                              ¦   «         ndt          |t          |i¬¦  «        S t          ‰d¦  «        r–‰j        €�t!          ‰¦  «        }|€=|                      ¦   «         }t          t          j        dt$          ¬¦  «        i|_        |S  | t)          |¦  «        |t          j        t-          |¦  «        t          ¬¦  «        ¬¦  «        S t          ‰d¦  «        �r?‰j        ��7‰j        j                             ¦   «                              ¦   «                              t          ¦  «        }t          j        ˆfd	„|D ¦   «         ¦  «        } | ‰j        j
                             ¦   «                              ¦   «         ‰j        j                             ¦   «                              ¦   «         |t!          ‰¦  «        ‰j        j        �B‰j        j                             ¦   «                              ¦   «                              ¦   «         ndt          |i¬
¦  «        S |                      ¦   «         }t          t          j        dt$          ¬¦  «        i|_        |S )a´  
        Creates a `sv.Detections` instance from a
        [YOLOv8](https://github.com/ultralytics/ultralytics) inference result.

        !!! Note

            `from_ultralytics` is compatible with
            [detection](https://docs.ultralytics.com/tasks/detect/),
            [segmentation](https://docs.ultralytics.com/tasks/segment/), and
            [OBB](https://docs.ultralytics.com/tasks/obb/) models.

        Args:
            ultralytics_results: The output Results instance from Ultralytics.

        Returns:
            A new Detections object.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from ultralytics import YOLO

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = YOLO('yolov8s.pt')
            results = model(image)[0]
            detections = sv.Detections.from_ultralytics(results)
            ```
        ÚobbNc                ó*   •— g | ]}‰j         |         ‘ŒS © ©Únames©Ú.0r_   r�   s     €rT   ú
<listcomp>z/Detections.from_ultralytics.<locals>.<listcomp>Z  ó"   ø€ Ð#SÐ#SÐ#SÀQÐ$7Ô$=¸aÔ$@Ð#SÐ#SÐ#SrV   )rF   rH   rI   rJ   rL   Úboxesr   ©Údtype)rF   rG   rI   c                ó*   •— g | ]}‰j         |         ‘ŒS r…   r†   rˆ   s     €rT   rŠ   z/Detections.from_ultralytics.<locals>.<listcomp>|  r‹   rV   ©rF   rH   rI   rG   rJ   rL   )Úhasattrrƒ   r~   r{   r|   r}   rW   rj   ÚarrayÚxyxyxyxyrF   ÚconfÚidr   r   rŒ   r   ÚemptyÚstrrL   r   ÚzerosrZ   )r~   r�   rI   Úclass_namesÚoriented_box_coordinatesÚmasksr–   s    `     rT   Úfrom_ultralyticszDetections.from_ultralytics8  sB  ø€ õ@ Ð&¨Ñ.Ô.ñ 	Ð3FÔ3JÑ3VØ*Ô.Ô2×6Ò6Ñ8Ô8×>Ò>Ñ@Ô@×GÒGÍÑLÔLˆHÝœ(Ð#SÐ#SÐ#SÐ#SÈ(Ð#SÑ#SÔ#SÑTÔTˆKØ':Ô'>Ô'G×'KÒ'KÑ'MÔ'M×'SÒ'SÑ'UÔ'UÐ$Ø�3Ø(Ô,Ô1×5Ò5Ñ7Ô7×=Ò=Ñ?Ô?Ø.Ô2Ô7×;Ò;Ñ=Ô=×CÒCÑEÔEØ!ð +Ô.Ô1Ð=ð (Ô+Ô.×2Ò2Ñ4Ô4×8Ò8Ñ:Ô:×@Ò@ÑBÔBÐBàõ -Ð.FÝ)¨;ððñ ô ð õ Ð&¨Ñ0Ô0ð 
	Ð5HÔ5NÐ5VÝ-Ð.AÑBÔBˆEØˆ}ØŸ	š	™œ�Ý3µR´X¸aÅsÐ5KÑ5KÔ5KÐL�”
Ø�Ø�3Ý! %Ñ(Ô(ØÝœ¥# e¡*¤*µCÐ8Ñ8Ô8ðñ ô ð õ Ð'¨Ñ1Ô1ñ	à#Ô)Ñ5à*Ô0Ô4×8Ò8Ñ:Ô:×@Ò@ÑBÔB×IÒIÍ#ÑNÔNˆHÝœ(Ð#SÐ#SÐ#SÐ#SÈ(Ð#SÑ#SÔ#SÑTÔTˆKØ�3Ø(Ô.Ô3×7Ò7Ñ9Ô9×?Ò?ÑAÔAØ.Ô4Ô9×=Ò=Ñ?Ô?×EÒEÑGÔGØ!Ý.Ð/BÑCÔCð +Ô0Ô3Ð?ð (Ô-Ô0×4Ò4Ñ6Ô6×:Ò:Ñ<Ô<×BÒBÑDÔDÐDàå+¨[Ð9ðñ ô ð ð —	’	‘”ˆÝ+­R¬X°a½sÐ-CÑ-CÔ-CÐDˆŒ
ØˆrV   Úyolo_nas_resultsc                ó  — t          j        |j        j        ¦  «        j        d         dk    r|                      ¦   «         S  | |j        j        |j        j        |j        j                             t          ¦  «        ¬¦  «        S )as  
        Creates a Detections instance from a
        [YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS.md)
        inference result.

        Args:
            yolo_nas_results: The output Results instance from YOLO-NAS.
                ImageDetectionPrediction is coming from
                'super_gradients.training.models.prediction_results'.

        Returns:
            A new Detections object.

        Example:
            ```python
            from supervision import _cv2 as cv2
            from super_gradients.training import models
            import supervision as sv

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = models.get('yolo_nas_l', pretrained_weights="coco")

            result = list(model.predict(image, conf=0.35))[0]
            detections = sv.Detections.from_yolo_nas(result)
            ```
        r   ry   )
rj   ÚasarrayÚ
predictionÚbboxes_xyxyÚshaper–   rH   Úlabelsr}   rW   )r~   r�   s     rT   Úfrom_yolo_naszDetections.from_yolo_nasŽ  sx   € õ8 Œ:Ð&Ô1Ô=Ñ>Ô>ÔDÀQÔGÈ1ÒLÐLØ—9’9‘;”;ÐàˆsØ!Ô,Ô8Ø'Ô2Ô=Ø%Ô0Ô7×>Ò>½sÑCÔCð
ñ 
ô 
ð 	
rV   Útensorflow_resultsúdict[str, Any]Úresolution_whútuple[int, int]c                ó¶  — |d         d                               ¦   «                              ¦   «         }|dd…ddgfxx         |d         z  cc<   |dd…ddgfxx         |d         z  cc<   |dd…g d¢f         } | ||d         d                               ¦   «         |d	         d                               ¦   «                              t          ¦  «        ¬
¦  «        S )aÖ  
        Creates a Detections instance from a
        [Tensorflow Hub](https://www.tensorflow.org/hub/tutorials/tf2_object_detection)
        inference result.

        Args:
            tensorflow_results: Raw output dict from a TensorFlow Hub
                object-detection model. Must contain:
                ``"detection_boxes"`` (shape ``[1, N, 4]``, normalized
                ``[ymin, xmin, ymax, xmax]``), ``"detection_scores"``
                (shape ``[1, N]``), and ``"detection_classes"``
                (shape ``[1, N]``).
            resolution_wh: The input image resolution as `(width, height)`.
                Bounding boxes from Tensorflow are normalized and are scaled
                to absolute coordinates using this resolution.

        Returns:
            A new Detections object.

        Note:
            TensorFlow Hub object-detection models return bounding boxes
            normalized as ``[ymin, xmin, ymax, xmax]``. This method rescales
            them to absolute pixel coordinates and reorders them to ``xyxy``
            (``[xmin, ymin, xmax, ymax]``) before constructing the
            :class:`Detections` object.

        Example:
            ```python
            import tensorflow as tf
            import tensorflow_hub as hub
            import numpy as np
            from supervision import _cv2 as cv2

            module_handle = "https://tfhub.dev/tensorflow/centernet/hourglass_512x512_kpts/1"
            model = hub.load(module_handle)
            img = np.array(cv2.imread("<SOURCE_IMAGE_PATH>"))
            result = model(img)
            detections = sv.Detections.from_tensorflow(
                result, resolution_wh=(img.shape[1], img.shape[0])
            )
            ```
        Údetection_boxesr   Né   é   é   )r¬   r   r­   r«   Údetection_scoresÚdetection_classesry   )r|   Úcopyr}   rW   )r~   r¥   r§   rŒ   s       rT   Úfrom_tensorflowzDetections.from_tensorflow³  sû   € ðf #Ð#4Ô5°aÔ8×>Ò>Ñ@Ô@×EÒEÑGÔGˆØˆaˆaˆa�!�Q�ˆiÐÐÔ˜M¨!Ô,Ñ,ÐÐÑØˆaˆaˆa�!�Q�ˆiÐÐÔ˜M¨!Ô,Ñ,ÐÐÑØ�a�a�a˜˜˜�oÔ&ˆØˆsØØ)Ð*<Ô=¸aÔ@×FÒFÑHÔHØ'Ð(;Ô<¸QÔ?×EÒEÑGÔG×NÒNÍsÑSÔSð
ñ 
ô 
ð 	
rV   Údeepsparse_resultsc                ó°  — t          j        |j        d         ¦  «        j        d         dk    r|                      ¦   «         S  | t          j        |j        d         ¦  «        t          j        |j        d         ¦  «        t          j        |j        d         ¦  «                             t          ¦  «                             t          ¦  «        ¬¦  «        S )aã  
        Creates a Detections instance from a
        [DeepSparse](https://github.com/neuralmagic/deepsparse)
        inference result.

        Args:
            deepsparse_results: The output Results instance from DeepSparse.

        Returns:
            A new Detections object.

        Example:
            ```python
            import supervision as sv
            from deepsparse import Pipeline

            yolo_pipeline = Pipeline.create(
                task="yolo",
                model_path = "zoo:cv/detection/yolov5-l/pytorch/ultralytics/coco/pruned80_quant-none"
             )
            result = yolo_pipeline(<SOURCE IMAGE PATH>)
            detections = sv.Detections.from_deepsparse(result)
            ```
        r   ry   )rj   rŸ   rŒ   r¢   r–   r’   Úscoresr£   r}   ÚfloatrW   )r~   r²   s     rT   Úfrom_deepsparsezDetections.from_deepsparseð  s°   € õ6 Œ:Ð(Ô.¨qÔ1Ñ2Ô2Ô8¸Ô;¸qÒ@Ð@Ø—9’9‘;”;ÐàˆsÝ”Ð,Ô2°1Ô5Ñ6Ô6Ý”xÐ 2Ô 9¸!Ô <Ñ=Ô=Ý”XÐ0Ô7¸Ô:Ñ;Ô;×BÒBÅ5ÑIÔI×PÒPÕQTÑUÔUð
ñ 
ô 
ð 	
rV   Úmmdet_resultsc                óÖ  —  | |j         j                             ¦   «                              ¦   «         |j         j                             ¦   «                              ¦   «         |j         j                             ¦   «                              ¦   «                              t          ¦  «        d|j         v r0|j         j                             ¦   «                              ¦   «         nd¬¦  «        S )a+  
        Creates a Detections instance from a
        [mmdetection](https://github.com/open-mmlab/mmdetection) and
        [mmyolo](https://github.com/open-mmlab/mmyolo) inference result.

        Args:
            mmdet_results: The output Results instance from MMDetection.

        Returns:
            A new Detections object.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from mmdet.apis import init_detector, inference_detector

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = init_detector("<CONFIG_PATH>", "<WEIGHTS_PATH>", device="<DEVICE>")

            result = inference_detector(model, image)
            detections = sv.Detections.from_mmdetection(result)
            ```
        r›   N)rF   rH   rI   rG   )	Úpred_instancesÚbboxesr{   r|   r´   r£   r}   rW   r›   )r~   r·   s     rT   Úfrom_mmdetectionzDetections.from_mmdetection  sÇ   € ð6 ˆsØÔ-Ô4×8Ò8Ñ:Ô:×@Ò@ÑBÔBØ$Ô3Ô:×>Ò>Ñ@Ô@×FÒFÑHÔHØ"Ô1Ô8×<Ò<Ñ>Ô>×DÒDÑFÔF×MÒMÍcÑRÔRð ˜mÔ:Ð:Ð:ð Ô,Ô2×6Ò6Ñ8Ô8×>Ò>Ñ@Ô@Ð@àð	
ñ 	
ô 	
ð 		
rV   Útransformers_resultsÚid2labelúdict[int, str] | Nonec                óä   — |j         j        dk    sd|v r | di t          ||¦  «        ¤ŽS d|v sd|v r | di t          ||¦  «        ¤ŽS d|v r | di t	          ||¦  «        ¤ŽS t          d¦  «        ‚)	aA  
        Creates a Detections instance from object detection or panoptic, semantic
        and instance segmentation
        [Transformer](https://github.com/huggingface/transformers) inference result.

        Args:
            transformers_results: Inference results from your Transformers model.
                This can be either a dictionary containing valuable outputs like
                `scores`, `labels`, `boxes`, `masks`, `segments_info`, and
                `segmentation`, or a `torch.Tensor` holding a segmentation map
                where values represent class IDs.
            id2label: A dictionary mapping class IDs to labels, typically part of
                the `transformers` model configuration. If provided, the resulting
                dictionary will include class names.

        Returns:
            A new Detections object.

        Example:
            ```python
            import torch
            import supervision as sv
            from PIL import Image
            from transformers import DetrImageProcessor, DetrForObjectDetection

            processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
            model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

            image = Image.open("<SOURCE_IMAGE_PATH>")
            inputs = processor(images=image, return_tensors="pt")

            with torch.no_grad():
                outputs = model(**inputs)

            width, height = image.size
            target_size = torch.tensor([[height, width]])
            results = processor.post_process_object_detection(
                outputs=outputs, target_sizes=target_size)[0]

            detections = sv.Detections.from_transformers(
                transformers_results=results,
                id2label=model.config.id2label
            )
            ```
        ÚTensorÚsegmentationr›   Ú
png_stringrŒ   z‹The provided Transformers results do not contain any valid fields. Expected fields are 'boxes', 'masks', 'segments_info' or 'segmentation'.Nr…   )Ú	__class__Ú__name__r   r   r   Ú
ValueError)r~   r¼   r½   s      rT   Úfrom_transformerszDetections.from_transformers:  sî   € ðj !Ô*Ô3°xÒ?Ð?ØÐ!5Ð5Ð5à�3ð ð Ý=Ø(¨(ñô ðð ð ð Ð*Ð*Ð*¨lÐ>RÐ.RÐ.RØ�3ð ð Ý=Ø(¨(ñô ðð ð ð Ð*Ð*Ð*Ø�3ð ð Ý7Ð8LÈhÑWÔWðð ð õ
 ð#ñô ð rV   Údetectron2_resultsc                ó  —  | |d         j         j                             ¦   «                              ¦   «         |d         j                             ¦   «                              ¦   «         t          |d         d¦  «        r1|d         j                             ¦   «                              ¦   «         nd|d         j                             ¦   «                              ¦   «                              t          ¦  «        ¬¦  «        S )aë  
        Create a Detections object from the
        [Detectron2](https://github.com/facebookresearch/detectron2) inference result.

        Args:
            detectron2_results: The output of a
                Detectron2 model containing instances with prediction data.

        Returns:
            A Detections object containing the bounding boxes,
                class IDs, and confidences of the predictions.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from detectron2.engine import DefaultPredictor
            from detectron2.config import get_cfg


            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            cfg = get_cfg()
            cfg.merge_from_file("<CONFIG_PATH>")
            cfg.MODEL.WEIGHTS = "<WEIGHTS_PATH>"
            predictor = DefaultPredictor(cfg)

            result = predictor(image)
            detections = sv.Detections.from_detectron2(result)
            ```
        Ú	instancesÚ
pred_masksN)rF   rH   rG   rI   )
Ú
pred_boxesÚtensorr{   r|   r´   r‘   rÊ   Úpred_classesr}   rW   )r~   rÇ   s     rT   Úfrom_detectron2zDetections.from_detectron2‹  sÑ   € ðB ˆsØ# KÔ0Ô;ÔB×FÒFÑHÔH×NÒNÑPÔPØ)¨+Ô6Ô=×AÒAÑCÔC×IÒIÑKÔKõ Ð-¨kÔ:¸LÑIÔIðÐ" ;Ô/Ô:×>Ò>Ñ@Ô@×FÒFÑHÔHÐHàà'¨Ô4ÜŸ#š#™%œ%ßŠU‰WŒWßŠV•C‰[Œ[ð
ñ 
ô 
ð 	
rV   F)Úcompact_masksÚroboflow_resultúdict[str, Any] | AnyrÏ   c               ó   — t          |d¦  «        r|                     dd¬¦  «        }n$t          |d¦  «        r|                     ¦   «         }|rt          |d¬¦  «        \  }}}}}}nt          |¬¦  «        \  }}}}}}t	          j        |¦  «        j        d         dk    r|                      ¦   «         }	||	_        |	S  | ||||||¬¦  «        S )	uõ  
        Create a `sv.Detections` object from the [Roboflow](https://roboflow.com/)
        API inference result or the [Inference](https://inference.roboflow.com/)
        package results. This method extracts bounding boxes, class IDs,
        confidences, and class names from the Roboflow API result and encapsulates
        them into a Detections object.

        Args:
            roboflow_result: The result from the
                Roboflow API or Inference package containing predictions.
            compact_masks: When `True`, return segmentation masks as
                :class:`~supervision.detection.compact_mask.CompactMask`.
                The default `False` preserves the existing dense NumPy mask
                representation.

                Warning:
                    When `compact_masks=True`, the crop policy depends on how
                    each prediction encodes its mask:

                    - Native size-matched COCO-RLE (the RLE `size` equals the
                      image size) is **cropped to the detector bounding box**
                      (`xyxy`). For instance-segmentation models the detector
                      box may not tightly bound the mask, so pixels beyond the
                      box boundary are silently dropped.
                    - Polygon-derived masks (`points`) and size-mismatched
                      COCO-RLE masks (decoded, then resized to the image) are
                      retained **full-frame** and lose no pixels.

                    Because only the box-cropped path is lossy,
                    `from_inference(r)` and
                    `from_inference(r, compact_masks=True)` can return masks
                    with different areas and IoU **only** for native
                    size-matched COCO-RLE predictions. Use `compact_masks=True`
                    only when the memory savings outweigh the boundary loss on
                    that path.

        Returns:
            A Detections object containing the bounding boxes, class IDs,
                and confidences of the predictions.
                `detections.data["class_name"]` is always present as a
                string-dtype NumPy array aligned with the detections; it is
                empty (shape `(0,)`, dtype str) when `predictions` is empty
                or absent. `detections.tracker_id` is `None` when no
                predictions carry a tracker ID, or when only a subset do
                (mixed batch) â€” in that case all tracker IDs are dropped to
                preserve alignment with the bounding boxes. Similarly,
                `detections.mask` is `None` when no predictions include mask
                data, or when only a subset carry masks â€” all masks are dropped
                to preserve xyxy alignment.
                When `compact_masks=True` and all predictions carry mask data,
                `detections.mask` is a
                :class:`~supervision.detection.compact_mask.CompactMask` rather
                than a dense boolean array.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from inference import get_model

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = get_model(model_id="yolov8s-640")

            result = model.infer(image)[0]
            detections = sv.Detections.from_inference(result)
            compact_detections = sv.Detections.from_inference(
                result, compact_masks=True
            )
            ```
        ÚdictT)Úexclude_noneÚby_aliasÚjson)rÐ   rÏ   )rÐ   r   r�   )	r‘   rÓ   rÖ   r%   rj   rŸ   r¢   r–   rL   )
r~   rÐ   rÏ   rF   rH   rI   r›   ÚtrackersrL   Úempty_detections
             rT   Úfrom_inferencezDetections.from_inferenceº  s  € õZ �? FÑ+Ô+ð 	5Ø-×2Ò2ÀÈtÐ2ÑTÔTˆOˆOÝ�_ fÑ-Ô-ð 	5Ø-×2Ò2Ñ4Ô4ˆOð ð 	Ý@WØ /¸tðAñ Aô AÑ=ˆD�*˜h¨¨x¸¸õ AXØ /ðAñ Aô AÑ=ˆD�*˜h¨¨x¸õ Œ:�dÑÔÔ! !Ô$¨Ò)Ð)Ø!Ÿiši™kœkˆOØ#'ˆOÔ Ø"Ð"àˆsØØ!ØØØØð
ñ 
ô 
ð 	
rV   Ú
sam_resultúlist[dict[str, Any]]c                óž  ‡‡	— t          |d„ d¬¦  «        }t          |¦  «        dk    r|                      ¦   «         S t          j        d„ |D ¦   «         ¦  «        }d„ |D ¦   «         }|d         }t          d„ |D ¦   «         ¦  «        rt          j        |d¬¦  «        }n“t          d	„ |D ¦   «         ¦  «        rkt          t          t          t          f         t          d
„ |d         D ¦   «         ¦  «        ¦  «        \  ŠŠ	t          j        ˆˆ	fd„|D ¦   «         d¬¦  «        }nt          d¦  «        ‚t          |¬¦  «        } | ||¬¦  «        S )aS  
        Creates a Detections instance from
        [Segment Anything Model](https://github.com/facebookresearch/segment-anything)
        inference result.

        Args:
            sam_result: The output Results instance from SAM.

        Returns:
            A new Detections object.

        Example:
            ```python
            import supervision as sv
            from segment_anything import (
                sam_model_registry,
                SamAutomaticMaskGenerator
             )

            sam_model_reg = sam_model_registry[MODEL_TYPE]
            sam = sam_model_reg(checkpoint=CHECKPOINT_PATH).to(device=DEVICE)
            mask_generator = SamAutomaticMaskGenerator(sam)
            sam_result = mask_generator.generate(IMAGE)
            detections = sv.Detections.from_sam(sam_result=sam_result)
            ```
        c                ó   — | d         S )NÚarear…   )Úxs    rT   ú<lambda>z%Detections.from_sam.<locals>.<lambda>F  s
   €  a¨¤i€ rV   T©ÚkeyÚreverser   c                ó   — g | ]
}|d          ‘ŒS )Úbboxr…   ©r‰   rG   s     rT   rŠ   z'Detections.from_sam.<locals>.<listcomp>K  s   € ÐIÐIÐI¨$˜˜fœÐIÐIÐIrV   c                ó   — g | ]
}|d          ‘ŒS )rÁ   r…   ræ   s     rT   rŠ   z'Detections.from_sam.<locals>.<listcomp>L  s   € ÐQÐQÐQ°$˜˜nÔ-ÐQÐQÐQrV   c              3  óJ   K  — | ]}t          |t          j        ¦  «        V — Œd S ri   )rp   rj   Úndarray©r‰   rÁ   s     rT   ú	<genexpr>z&Detections.from_sam.<locals>.<genexpr>O  s.   è è € ÐVÐV¸�z˜,­¬
Ñ3Ô3ÐVÐVÐVÐVÐVÐVrV   ©Úaxisc              3  ó@   K  — | ]}t          |t          ¦  «        V — Œd S ri   )rp   rÓ   rê   s     rT   rë   z&Detections.from_sam.<locals>.<genexpr>Q  s,   è è € ÐRÐR°L•˜L­$Ñ/Ô/ÐRÐRÐRÐRÐRÐRrV   c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ri   )rW   ©r‰   Úvs     rT   rë   z&Detections.from_sam.<locals>.<genexpr>S  s(   è è € Ð&RÐ&R°!¥s¨1¡v¤vÐ&RÐ&RÐ&RÐ&RÐ&RÐ&RrV   Úsizec                ó@   •— g | ]}t          |d          ‰‰f¦  «        ‘ŒS )Úcounts)r   )r‰   rÁ   Úimage_heightÚimage_widths     €€rT   rŠ   z'Detections.from_sam.<locals>.<listcomp>V  sE   ø€ ð ð ð ð
 %õ	  Ø$ XÔ.Ø$ lÐ3ñô ðð ð rV   zDSAM segmentations must all be dense arrays or COCO RLE dictionaries.)Úxywh)rF   rG   )ÚsortedrZ   r–   rj   r’   rs   Ústackr	   ÚtuplerW   rÅ   r   )
r~   rÚ   Úsorted_generated_masksr÷   ÚsegmentationsÚfirst_segmentationrG   rF   rõ   rö   s
           @@rT   Úfrom_samzDetections.from_sam(  s¤  øø€ õ: "(ØÐ/Ð/¸ð"
ñ "
ô "
Ðõ Ð%Ñ&Ô&¨!Ò+Ð+Ø—9’9‘;”;ÐåŒxÐIÐIÐ2HÐIÑIÔIÑJÔJˆØQÐQÐ:PÐQÑQÔQˆØ*¨1Ô-ÐåÐVÐVÈÐVÑVÔVÑVÔVð 	Ý”8˜M°Ð2Ñ2Ô2ˆDˆDÝÐRÐRÀMÐRÑRÔRÑRÔRð 	Ý(,Ý•c�3�h”¥Ð&RÐ&RÐ7IÈ&Ô7QÐ&RÑ&RÔ&RÑ!RÔ!Rñ)ô )Ñ%ˆL˜+õ ”8ðð ð ð ð ð
 )6ðñ ô ð ð	ñ 	ô 	ˆDˆDõ ØVñô ð õ  Ð&Ñ&Ô&ˆØˆs˜ 4Ð(Ñ(Ô(Ð(rV   Úsam3_resultc           	     ó(  — t          |¦  «        \  }}g }g }g }t          |t          ¦  «        r)|                     dg ¦  «        }|sd|v r|d         ddœg}n7t	          |dg ¦  «        }|s$t          |d¦  «        rt	          |d¦  «        ddœg}t          |¦  «        D �]×\  }	}
t          |
t          ¦  «        r-|
                     dg ¦  «        }|
                     d|	¦  «        }n"t	          |
dg ¦  «        }t	          |
d|	¦  «        }|D �]i}t          |t          ¦  «        rK|                     d¦  «        }|r|dk    rŒ6|                     dg ¦  «        }|                     d	d
¦  «        }n<t	          |dd¦  «        }|r|dk    rŒ}t	          |dg ¦  «        }t	          |d	d
¦  «        }|sŒ¢t          j        ||ft          ¬¦  «        }|D ]h}t          j
        |t          j        ¬¦  «        }t          |||f¬¦  «        }|                     t          d¬¦  «        }t          j        |||¬¦  «         Œi|                     |¦  «         |                     |¦  «         |                     |¦  «         �Œk�ŒÙ|s|                      ¦   «         S t          j        |d¬¦  «        }t%          |¦  «        } | |                     t          j        ¦  «        |t          j
        |t          j        ¬¦  «        t          j
        |t(          ¬¦  «        ¬¦  «        S )aq  
        Creates a Detections instance from
        [SAM 3](https://github.com/facebookresearch/sam3) inference result.
        Supports both PVS and PCS SAM3 segmentation formats.

        Args:
            sam3_result: The output result from SAM 3 inference, either
                Sam3PromptResult from inference package or dict containing
                prompt_results with polygon predictions.
            resolution_wh: The width and height of the image used for mask
                generation.

        Returns:
            A new Detections object. The `class_id` field contains the prompt
                index for each polygon.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from inference.models.sam3 import SegmentAnything3
            from inference.core.entities.requests.sam3 import Sam3Prompt

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = SegmentAnything3(
                model_id="sam3/sam3_final",
                api_key="<ROBOFLOW_API_KEY>"
            )

            prompts = [
                Sam3Prompt(type="text", text="car"),
                Sam3Prompt(type="text", text="tire"),
            ]

            result = model.segment_image(
                image=image,
                prompts=prompts,
                output_prob_thresh=0.5,
                format="polygon"
            )

            height, width = image.shape[:2]
            detections = sv.Detections.from_sam3(
                sam3_result=result,
                resolution_wh=(width, height)
            )
            ```
        Úprompt_resultsÚpredictionsr   )r  Úprompt_indexr  ÚformatÚpolygonr›   rH   g      ð?Nr�   )r  r§   F©r°   )Úoutrì   )rF   rG   rH   rI   )rB   rp   rÓ   ÚgetÚgetattrr‘   Ú	enumeraterj   r˜   rc   r’   Úint32r   r}   Ú
logical_orÚappendr–   rù   r   Úfloat32rW   )r~   rÿ   r§   ÚwidthÚheightr›   ÚconfidencesÚ	class_idsr  r_   Úprompt_resultr  r  r    Úprediction_formatrÊ   rH   Ú	full_maskÚpolyr  rG   Úmasks_nprF   s                          rT   Ú	from_sam3zDetections.from_sam3g  sh  € õh -¨]Ñ;Ô;‰ˆˆvàˆØˆØˆ	å�k¥4Ñ(Ô(ð 	Ø(Ÿ_š_Ð-=¸rÑBÔBˆNØ!ð  m°{Ð&BÐ&Bà$/°Ô$>ÐPQÐRÐRð"�øõ % [Ð2BÀBÑGÔGˆNØ!ð ¥g¨k¸=Ñ&IÔ&Ið õ (/¨{¸MÑ'JÔ'JØ()ðð ð"�õ !*¨.Ñ 9Ô 9ð $	/ñ $	/ÑˆAˆ}Ý˜-­Ñ.Ô.ð IØ+×/Ò/°¸rÑBÔB�Ø,×0Ò0°ÀÑCÔC��å% m°]ÀBÑGÔG�Ý& }°nÀaÑHÔH�à)ð /ñ /�
Ý˜j­$Ñ/Ô/ð HØ(2¯ª°xÑ(@Ô(@Ð%Ø(ð !Ð->À)Ò-KÐ-KØ Ø!+§¢°¸Ñ!<Ô!<�JØ!+§¢°¸cÑ!BÔ!B�J�Jå(/°
¸HÀdÑ(KÔ(KÐ%Ø(ð !Ð->À)Ò-KÐ-KØ Ý!(¨°W¸bÑ!AÔ!A�JÝ!(¨°\À3Ñ!GÔ!G�Jà!ð Øå35´8¸VÀU¸OÕSWÐ3XÑ3XÔ3X�	Ø&ð Bð B�DÝ œh tµ2´8Ð<Ñ<Ô<�GÝ*Ø '¸¸v°ðñ ô �Dð  Ÿ;š;¥t°%˜;Ñ8Ô8�DÝ”M )¨T°yÐAÑAÔAÐAÐAà—’˜YÑ'Ô'Ð'Ø×"Ò" :Ñ.Ô.Ð.Ø× Ò  Ñ.Ô.Ð.Ñ.ñ9/ð< ð 	Ø—9’9‘;”;Ðå”8˜E¨Ð*Ñ*Ô*ˆÝ˜HÑ%Ô%ˆàˆsØ—’�RœZÑ(Ô(ØÝ”x µ2´:Ð>Ñ>Ô>Ý”X˜i­sÐ3Ñ3Ô3ð	
ñ 
ô 
ð 	
rV   Úazure_resultÚ	class_mapc                óº  — d|v rt          d|d         d         › �¦  «        ‚g g g }}}|du }|€i }d„ |                     ¦   «         D ¦   «         }|d         d         D �]}|d         }	|d	         }
|	d
         }|	d         }||	d         z   }||	d         z   }d}d}t          |
d„ d¬¦  «        D ]@}|d         }|                     |d¦  «        }|r|€t	          |¦  «        }|||<   |�|}|} nŒA|€|
rt          j        dt          d¬¦  «         Œ²|                     ||||g¦  «         |                     |d         ¦  «         |                     t          t          |¦  «        ¦  «         �Œt	          |¦  «        dk    rt                               ¦   «         S  | t          j        |¦  «        t          j        |¦  «        t          j        |¦  «        ¬¦  «        S )aš  
        Creates a Detections instance from [Azure Image Analysis 4.0](
        https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/
        concept-object-detection-40).

        Args:
            azure_result: The result from Azure Image Analysis. It should
                contain detected objects and their bounding box coordinates.
            class_map: A mapping of class IDs to class names. If None, a new
                mapping is created dynamically.

        Returns:
            A new Detections object.

        Example:
            ```python
            import requests
            import supervision as sv

            image = open(input, "rb").read()

            endpoint = "https://.cognitiveservices.azure.com/"
            subscription_key = ""

            headers = {
                "Content-Type": "application/octet-stream",
                "Ocp-Apim-Subscription-Key": subscription_key
             }

            response = requests.post(endpoint,
                headers=self.headers,
                data=image
             ).json()

            detections = sv.Detections.from_azure_analyze_image(response)
            ```
        ÚerrorzAzure API returned an error ÚmessageNc                ó   — i | ]\  }}||“Œ	S r…   r…   ©r‰   râ   Úvalues      rT   ú
<dictcomp>z7Detections.from_azure_analyze_image.<locals>.<dictcomp>  s   € Ð'WÐ'WÐ'W±z°s¸E¨¨sÐ'WÐ'WÐ'WrV   ÚobjectsResultÚvaluesÚboundingBoxÚtagsrß   ÚyÚwÚhc                ó   — | d         S )NrH   r…   )Ú	candidates    rT   rà   z5Detections.from_azure_analyze_image.<locals>.<lambda>'  s   € ¨I°lÔ,C€ rV   Trá   ÚnamezPAzure detection skipped because none of its tags matched the provided class_map.r«   )ÚcategoryÚ
stacklevelrH   r   )rF   rI   rH   )rÅ   Úitemsrø   r  rZ   ÚwarningsÚwarnr=   r  r	   rW   rD   r–   rj   r’   )r~   r  r  rF   r  r  Úis_dynamic_mappingÚinverted_mapÚ	detectionrå   r%  Úx0Úy0Úx1Úy1Úselected_tagÚselected_class_idÚtagÚ
class_nameÚclass_id_vals                       rT   Úfrom_azure_analyze_imagez#Detections.from_azure_analyze_imageä  sS  € ðR �lÐ"Ð"ÝØQ¨|¸GÔ/DÀYÔ/OÐQÐQñô ð ð (*¨2¨r˜9ˆkˆà&¨$Ð.ÐØÐØˆIà'WÐ'WÀYÇ_Â_ÑEVÔEVÐ'WÑ'WÔ'Wˆà% oÔ6°xÔ@ð '	;ñ '	;ˆIØ˜]Ô+ˆDà˜VÔ$ˆDà�c”ˆBØ�c”ˆBØ�d˜3”i‘ˆBØ�d˜3”i‘ˆBà26ˆLØ,0ÐÝØÐCÐCÈTðñ ô ð ð �ð ! œ[�
Ø+×/Ò/°
¸DÑAÔA�à%ð <¨,Ð*>Ý#& |Ñ#4Ô#4�LØ/;�L Ñ,àÐ+Ø#&�LØ(4Ð%Ø�Eð ,ð
 Ð#Øð Ý”Mð2å!4Ø#$ð	ñ ô ð ð à�KŠK˜˜R  RÐ(Ñ)Ô)Ð)Ø×Ò˜|¨LÔ9Ñ:Ô:Ð:Ø×Ò�T¥#Ð'8Ñ9Ô9Ñ:Ô:Ð:Ñ:åˆt‰9Œ9˜Š>ˆ>Ý×#Ò#Ñ%Ô%Ð%àˆsÝ”˜$‘”Ý”X˜iÑ(Ô(Ý”x Ñ,Ô,ð
ñ 
ô 
ð 	
rV   Úpaddledet_resultc                óD  — t          j        |d         dd…dd…f         ¦  «        j        d         dk    r|                      ¦   «         S  | |d         dd…dd…f         |d         dd…df         |d         dd…df                              t
          ¦  «        ¬¦  «        S )aG  
        Creates a Detections instance from
            [PaddleDetection](https://github.com/PaddlePaddle/PaddleDetection)
            inference result.

        Args:
            paddledet_result: The output Results instance from PaddleDet.

        Returns:
            A new Detections object.

        Example:
            ```python
            import supervision as sv
            import paddle
            from ppdet.engine import Trainer
            from ppdet.core.workspace import load_config

            weights = ()
            config = ()

            cfg = load_config(config)
            trainer = Trainer(cfg, mode='test')
            trainer.load_weights(weights)

            paddledet_result = trainer.predict([images])[0]

            detections = sv.Detections.from_paddledet(paddledet_result)
            ```
        rå   Nr«   é   r   r¬   ry   )rj   rŸ   r¢   r–   r}   rW   )r~   r>  s     rT   Úfrom_paddledetzDetections.from_paddledetL  s±   € õB Œ:Ð& vÔ.¨q¨q¨q°!°A°#¨vÔ6Ñ7Ô7Ô=¸aÔ@ÀAÒEÐEØ—9’9‘;”;ÐàˆsØ! &Ô)¨!¨!¨!¨Q¨q¨S¨&Ô1Ø'¨Ô/°°°°1°Ô5Ø% fÔ-¨a¨a¨a°¨dÔ3×:Ò:½3Ñ?Ô?ð
ñ 
ô 
ð 	
rV   Úlmmú	LMM | strÚresultústr | dict[str, Any]Úkwargsc                óÒ  — t          d¦  «         t          |t          ¦  «        rt          |j        ¦  «        }nŸt          |t
          ¦  «        rj	 t          |                     ¦   «         ¦  «        }n2# t          $ r% t          d|› dd„ t          D ¦   «         › �¦  «        ‚w xY wt          |j        ¦  «        }n t          dt          |¦  «        › d�¦  «        ‚ | j	        d||dœ|¤ŽS )	uÀB  
        !!! deprecated "Deprecated"
            `Detections.from_lmm` is **deprecated** and will be removed in `supervision-0.31.0`.
            Please use `Detections.from_vlm` instead.

        Creates a Detections object from the given result string based on the specified
        Large Multimodal Model (LMM).

        | Name                | Enum (sv.LMM)        | Tasks                   | Required parameters         | Optional parameters |
        |---------------------|----------------------|-------------------------|-----------------------------|---------------------|
        | PaliGemma           | `PALIGEMMA`          | detection               | `resolution_wh`             | `classes`           |
        | PaliGemma 2         | `PALIGEMMA`          | detection               | `resolution_wh`             | `classes`           |
        | Qwen2.5-VL          | `QWEN_2_5_VL`        | detection               | `resolution_wh`, `input_wh` | `classes`           |
        | Qwen3-VL            | `QWEN_3_VL`          | detection               | `resolution_wh`             | `classes`           |
        | Google Gemini 2.0   | `GOOGLE_GEMINI_2_0`  | detection               | `resolution_wh`             | `classes`           |
        | Google Gemini 2.5   | `GOOGLE_GEMINI_2_5`  | detection, segmentation | `resolution_wh`             | `classes`           |
        | Google Gemini 3.5   | `GOOGLE_GEMINI_3_5`  | detection, segmentation | `resolution_wh`             | `classes`           |
        | Moondream           | `MOONDREAM`          | detection               | `resolution_wh`             |                     |
        | DeepSeek-VL2        | `DEEPSEEK_VL_2`      | detection               | `resolution_wh`             | `classes`           |
        | Qwen3-VL            | `QWEN_3_VL`          | detection               | `resolution_wh`             | `classes`           |

        Args:
            lmm: The type of LMM (Large Multimodal Model) to use.
            result: The result string containing the detection data.
            **kwargs: Additional keyword arguments required by the specified LMM.

        Returns:
            A new Detections object.

        Raises:
            ValueError: If the LMM is invalid, required arguments are missing, or
                disallowed arguments are provided.
            ValueError: If the specified LMM is not supported.

        !!! example "PaliGemma"
            ```python

            import supervision as sv

            paligemma_result = "<loc0256><loc0256><loc0768><loc0768> cat"
            detections = sv.Detections.from_lmm(
                sv.LMM.PALIGEMMA,
                paligemma_result,
                resolution_wh=(1000, 1000),
                classes=['cat', 'dog']
            )
            detections.xyxy
            # array([[250., 250., 750., 750.]])

            detections.class_id
            # array([0])

            detections.data
            # {'class_name': array(['cat'], dtype='<U10')}
            ```

        !!! example "Qwen2.5-VL"

            ??? tip "Prompt engineering"

                To get the best results from Qwen2.5-VL, use clear and descriptive prompts
                that specify exactly what you want to detect.

                **For general object detection, use this comprehensive prompt:**

                ```
                Detect all objects in the image and return their locations and labels.
                ```

                **For specific object detection with detailed descriptions:**

                ```
                Detect the red object that is leading in this image and return its location and label.
                ```

                **For simple, targeted detection:**

                ```
                leading blue truck
                ```

                **Additional effective prompts:**

                ```
                Find all people and vehicles in this scene
                ```

                ```
                Locate all animals in the image
                ```

                ```
                Identify traffic signs and their positions
                ```

                **Tips for better results:**

                - Use descriptive language that clearly specifies what to look for
                - Include color, size, or position descriptors when targeting specific objects
                - Be specific about the type of objects you want to detect
                - The model responds well to both detailed instructions and concise phrases
                - Results are returned in JSON format with `bbox_2d` coordinates and `label` fields


            ```python
            import supervision as sv

            qwen_2_5_vl_result = """```json
            [
                {"bbox_2d": [139, 768, 315, 954], "label": "cat"},
                {"bbox_2d": [366, 679, 536, 849], "label": "dog"}
            ]
            ```"""
            detections = sv.Detections.from_lmm(
                sv.LMM.QWEN_2_5_VL,
                qwen_2_5_vl_result,
                input_wh=(1000, 1000),
                resolution_wh=(1000, 1000),
                classes=['cat', 'dog'],
            )
            detections.xyxy
            # array([[139., 768., 315., 954.], [366., 679., 536., 849.]])

            detections.class_id
            # array([0, 1])

            detections.data
            # {'class_name': array(['cat', 'dog'], dtype='<U10')}

            detections.class_id
            # array([0, 1])
            ```

        !!! example "Qwen3-VL"

            ```python
            import supervision as sv

            qwen_3_vl_result = """```json
            [
                {"bbox_2d": [139, 768, 315, 954], "label": "cat"},
                {"bbox_2d": [366, 679, 536, 849], "label": "dog"}
            ]
            ```"""
            detections = sv.Detections.from_lmm(
                sv.LMM.QWEN_3_VL,
                qwen_3_vl_result,
                resolution_wh=(1000, 1000),
                classes=['cat', 'dog'],
            )
            detections.xyxy
            # array([[139., 768., 315., 954.], [366., 679., 536., 849.]])

            detections.class_id
            # array([0, 1])

            detections.data
            # {'class_name': array(['cat', 'dog'], dtype='<U10')}

            detections.class_id
            # array([0, 1])
            ```

        !!! example "Gemini 2.0"

            ??? tip "Prompt engineering"

                From Gemini 2.0 onwards, models are further trained to detect objects in
                an image and get their bounding box coordinates. The coordinates,
                relative to image dimensions, scale to [0, 1000]. You need to convert
                these normalized coordinates back to pixel coordinates using your
                original image size.

                According to the Gemini API documentation on image prompts (see
                https://ai.google.dev/gemini-api/docs/vision#image-input), when using a
                single image with text, the recommended approach is to place the text
                prompt after the image part in the contents array. This ordering has
                been shown to produce significantly better results in practice.

                For example, when calling the Gemini API directly, you can structure
                the request like this, with the image part first and the text prompt
                second in the `parts` list:

                ```json
                {
                  "model": "models/gemini-2.0-flash",
                  "contents": [
                    {
                      "role": "user",
                      "parts": [
                        {
                          "inline_data": {
                            "mime_type": "image/png",
                            "data": "<BASE64_IMAGE_BYTES>"
                          }
                        },
                        {
                          "text": "Detect all the cats and dogs in the image..."
                        }
                      ]
                    }
                  ]
                }
                ```
                To get the best results from Google Gemini 2.0, use the following prompt.

                ```
                Detect all the cats and dogs in the image. The box_2d should be
                [ymin, xmin, ymax, xmax] normalized to 0-1000.
                ```

            ```python
            import supervision as sv

            gemini_response_text = """```json
                [
                    {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1},
                    {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2}
                ]
            ```"""

            detections = sv.Detections.from_lmm(
                sv.LMM.GOOGLE_GEMINI_2_0,
                gemini_response_text,
                resolution_wh=(1000, 1000),
                classes=['cat', 'dog'],
            )

            detections.xyxy
            # array([[543., 40., 728., 200.], [653., 352., 820., 522.]])

            detections.data
            # {'class_name': array(['cat', 'dog'], dtype='<U26')}

            detections.class_id
            # array([0, 1])
            ```

        !!! example "Gemini 2.5"

            ??? tip "Prompt engineering"

                To get the best results from Google Gemini 2.5, use the following prompt.

                This prompt is designed to detect all visible objects in the image,
                including small, distant, or partially visible ones, and to return
                tight bounding boxes.

                According to the Gemini API documentation on image prompts, when using
                a single image with text, the recommended approach is to place the text
                prompt after the image part in the `contents` array. See the official
                Gemini vision docs for details:
                https://ai.google.dev/gemini-api/docs/vision#multi-part-input

                For example, using the `google-generativeai` client:

                ```python
                from google.generativeai import types

                response = model.generate_content(
                    contents=[
                        types.Part.from_image(image_bytes),
                        "Carefully examine this image and detect ALL visible objects, including "
                        "small, distant, or partially visible ones.",
                    ],
                    generation_config=generation_config,
                    safety_settings=safety_settings,
                )
                ```

                This ordering (image first, then text) has been shown to produce
                significantly better results in practice.

                ```
                Carefully examine this image and detect ALL visible objects, including
                small, distant, or partially visible ones.

                IMPORTANT: Focus on finding as many objects as possible, even if you are
                only moderately confident.

                Make sure each bounding box is as tight as possible.

                Valid object classes: {class_list}

                For each detected object, provide:
                - "label": the exact class name from the list above
                - "confidence": your certainty (between 0.0 and 1.0)
                - "box_2d": the bounding box [ymin, xmin, ymax, xmax] normalized to 0-1000
                - "mask": the binary mask of the object as a base64-encoded string

                Detect everything that matches the valid classes. Do not be
                conservative; include objects even with moderate confidence.

                Return a JSON array, for example:
                [
                    {
                        "label": "person",
                        "confidence": 0.95,
                        "box_2d": [100, 200, 300, 400],
                        "mask": "..."
                    },
                    {
                        "label": "kite",
                        "confidence": 0.80,
                        "box_2d": [50, 150, 250, 350],
                        "mask": "..."
                    }
                ]
                ```

                When using the google-genai library, it is recommended to set
                thinking_budget=0 in thinking_config for more direct and faster responses.

                ```python
                from google.generativeai import types

                model.generate_content(
                    ...,
                    generation_config=generation_config,
                    safety_settings=safety_settings,
                    thinking_config=types.ThinkingConfig(
                        thinking_budget=0
                    )
                )
                ```

                For a shorter prompt focused only on segmentation masks, you can use:

                ```
                Return a JSON list of segmentation masks. Each entry should include the
                2D bounding box in the "box_2d" key, the segmentation mask in the "mask"
                key, and the text label in the "label" key. Use descriptive labels.
                ```

            ```python
            import supervision as sv

            gemini_response_text = """```json
                [
                    {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1},
                    {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2}
                ]
            ```"""

            detections = sv.Detections.from_lmm(
                sv.LMM.GOOGLE_GEMINI_2_5,
                gemini_response_text,
                resolution_wh=(1000, 1000),
                classes=['cat', 'dog'],
            )

            detections.xyxy
            # array([[543., 40., 728., 200.], [653., 352., 820., 522.]])

            detections.data
            # {'class_name': array(['cat', 'dog'], dtype='<U26')}

            detections.class_id
            # array([0, 1])
            ```

        !!! example "Moondream"


            ??? tip "Prompt engineering"

                To get the best results from Moondream, use optimized prompts that leverage
                its object detection capabilities effectively.

                **For general object detection, use this simple prompt:**

                ```
                objects
                ```

                This single-word prompt instructs Moondream to detect all visible objects
                and return them in the proper JSON format with normalized coordinates.


            ```python
            import supervision as sv

            moondream_result = {
                'objects': [
                    {
                        'x_min': 0.5704046934843063,
                        'y_min': 0.20069346576929092,
                        'x_max': 0.7049859315156937,
                        'y_max': 0.3012596592307091
                    },
                    {
                        'x_min': 0.6210969910025597,
                        'y_min': 0.3300672620534897,
                        'x_max': 0.8417936339974403,
                        'y_max': 0.4961046129465103
                    }
                ]
            }

            detections = sv.Detections.from_lmm(
                sv.LMM.MOONDREAM,
                moondream_result,
                resolution_wh=(1000, 1000),
            )

            detections.xyxy
            # array([[1752.28,  818.82, 2165.72, 1229.14],
            #        [1908.01, 1346.67, 2585.99, 2024.11]])
            ```

        !!! example "DeepSeek-VL2"


            ??? tip "Prompt engineering"

                To get the best results from DeepSeek-VL2, use optimized prompts that leverage
                its object detection and visual grounding capabilities effectively.

                **For general object detection, use the following user prompt:**

                ```
                <image>\n<|ref|>The giraffe at the front<|/ref|>
                ```

                **For visual grounding, use the following user prompt:**

                ```
                <image>\n<|grounding|>Detect the giraffes
                ```

            ```python
            from PIL import Image
            import supervision as sv

            deepseek_vl2_result = "<|ref|>The giraffe at the back<|/ref|><|det|>[[580, 270, 999, 904]]<|/det|><|ref|>The giraffe at the front<|/ref|><|det|>[[26, 31, 632, 998]]<|/det|><|endâ–�ofâ–�sentence|>"

            detections = sv.Detections.from_vlm(
                vlm=sv.VLM.DEEPSEEK_VL_2, result=deepseek_vl2_result, resolution_wh=image.size
            )

            detections.xyxy
            # array([[ 420,  293,  724,  982],
            #        [  18,   33,  458, 1084]])

            detections.class_id
            # array([0, 1])

            detections.data
            # {'class_name': array(['The giraffe at the back', 'The giraffe at the front'], dtype='<U24')}
            ```
        zŽ`Detections.from_lmm` is deprecated since `supervision-0.26.0` and will be removed in `supervision-0.31.0`. Use `Detections.from_vlm` instead.zInvalid LMM string 'z'. Must be one of c                ó   — g | ]	}|j         ‘Œ
S r…   )r   ©r‰   Úms     rT   rŠ   z'Detections.from_lmm.<locals>.<listcomp>O  s   € Ð-Ð-Ð- A˜œÐ-Ð-Ð-rV   zInvalid type for 'lmm': z. Must be LMM or str.)ÚvlmrD  r…   )
r?   rp   r0   r1   r   r—   ÚlowerrÅ   ÚtypeÚfrom_vlm)r~   rB  rD  rF  rK  Úlmm_enums         rT   Úfrom_lmmzDetections.from_lmmv  s"  € õP 	ð1ñ	
ô 	
ð 	
õ �c�3ÑÔð 	Ý�c”i‘.”.ˆCˆCå˜�SÑ!Ô!ð 	ðÝ˜sŸyšy™{œ{Ñ+Ô+��øÝð ð ð Ý ð0¨3ð 0ð 0Ø-Ð-­Ð-Ñ-Ô-ð0ð 0ñô ð ðøøøõ
 �h”nÑ%Ô%ˆCˆCõ ØK­4°©9¬9ÐKÐKÐKñô ð ð ˆsŒ|Ð= ¨FÐ=Ð=°fÐ=Ð=Ð=s   Á!A2 Á2/B!rK  ú	VLM | strc                ó¼
  — t          |||¦  «        }|t          j        k    rlt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t          |fi |¤Ž\  }}}t          |¦  «        }t          |i} | |||¬¦  «        S |t          j
        k    r•t          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t          |fi |¤Ž\  }}}t          |¦  «        }t          |i}t          j        t          |¦  «        t          ¬¦  «        } | ||||¬¦  «        S |t          j        k    r•t          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t#          |fi |¤Ž\  }}}t          |¦  «        }t          |i}t          j        t          |¦  «        t          ¬¦  «        } | ||||¬¦  «        S |t          j        k    rlt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t'          |fi |¤Ž\  }}}t          |¦  «        }t          |i} | |||¬¦  «        S |t          j        k    rÎt          |t*          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t-          |fi |¤Ž\  }}	}
}t          |¦  «        }t          |¦  «        dk    r=|                      ¦   «         }t          t          j        dt          ¬¦  «        i|_        |S i }|	�
|	|t          <   |�
||t2          <    | ||
|¬	¦  «        S |t          j        k    rlt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t7          |fi |¤Ž\  }}}t          |¦  «        }t          |i} | |||¬¦  «        S |t          j        k    r]t          |t*          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t;          |fi |¤Ž}t          |¦  «        } | |¬
¦  «        S |t          j        k    rˆt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t?          |fi |¤Ž}t          |d         ¦  «        }t          |d         i} | ||d         |d         |d         |¬¦  «        S |t          j         k    rˆt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚tC          |fi |¤Ž}t          |d         ¦  «        }t          |d         i} | ||d         |d         |d         |¬¦  «        S t          d|› d�¦  «        ‚)u(?  

        Creates a Detections object from the given result string based on the specified
        Vision Language Model (VLM).

        | Name                | Enum (sv.VLM)        | Tasks                   | Required parameters         | Optional parameters |
        |---------------------|----------------------|-------------------------|-----------------------------|---------------------|
        | PaliGemma           | `PALIGEMMA`          | detection               | `resolution_wh`             | `classes`           |
        | PaliGemma 2         | `PALIGEMMA`          | detection               | `resolution_wh`             | `classes`           |
        | Qwen2.5-VL          | `QWEN_2_5_VL`        | detection               | `resolution_wh`, `input_wh` | `classes`           |
        | Qwen3-VL            | `QWEN_3_VL`          | detection               | `resolution_wh`             | `classes`           |
        | Google Gemini 2.0   | `GOOGLE_GEMINI_2_0`  | detection               | `resolution_wh`             | `classes`           |
        | Google Gemini 2.5   | `GOOGLE_GEMINI_2_5`  | detection, segmentation | `resolution_wh`             | `classes`           |
        | Google Gemini 3.5   | `GOOGLE_GEMINI_3_5`  | detection, segmentation | `resolution_wh`             | `classes`           |
        | Moondream           | `MOONDREAM`          | detection               | `resolution_wh`             |                     |
        | DeepSeek-VL2        | `DEEPSEEK_VL_2`      | detection               | `resolution_wh`             | `classes`           |

        Args:
            vlm: The type of VLM (Vision Language Model) to use.
            result: The result string containing the detection data.
            **kwargs: Additional keyword arguments required by the specified VLM.

        Returns:
            A new Detections object.

        Raises:
            ValueError: If the VLM is invalid, required arguments are missing, or
                disallowed arguments are provided.
            ValueError: If the specified VLM is not supported.

        !!! example "PaliGemma"
            ```pycon
            >>> import supervision as sv

            >>> paligemma_result = "<loc0256><loc0256><loc0768><loc0768> cat"
            >>> detections = sv.Detections.from_vlm(
            ...     sv.VLM.PALIGEMMA,
            ...     paligemma_result,
            ...     resolution_wh=(1000, 1000),
            ...     classes=['cat', 'dog']
            ... )
            >>> detections.xyxy
            array([[250., 250., 750., 750.]])
            >>> detections.class_id
            array([0])
            >>> detections.data
            {'class_name': array(['cat'], dtype='<U4')}

            ```

        !!! example "Qwen2.5-VL"

            ??? tip "Prompt engineering"

                To get the best results from Qwen2.5-VL, use clear and descriptive prompts
                that specify exactly what you want to detect.

                **For general object detection, use this comprehensive prompt:**

                ```
                Detect all objects in the image and return their locations and labels.
                ```

                **For specific object detection with detailed descriptions:**

                ```
                Detect the red object that is leading in this image and return its location and label.
                ```

                **For simple, targeted detection:**

                ```
                leading blue truck
                ```

                **Additional effective prompts:**

                ```
                Find all people and vehicles in this scene
                ```

                ```
                Locate all animals in the image
                ```

                ```
                Identify traffic signs and their positions
                ```

                **Tips for better results:**

                - Use descriptive language that clearly specifies what to look for
                - Include color, size, or position descriptors when targeting specific objects
                - Be specific about the type of objects you want to detect
                - The model responds well to both detailed instructions and concise phrases
                - Results are returned in JSON format with `bbox_2d` coordinates and `label` fields


            ```pycon
            >>> import supervision as sv

            >>> qwen_2_5_vl_result = """```json
            ... [
            ...     {"bbox_2d": [139, 768, 315, 954], "label": "cat"},
            ...     {"bbox_2d": [366, 679, 536, 849], "label": "dog"}
            ... ]
            ... ```"""
            >>> detections = sv.Detections.from_vlm(
            ...     sv.VLM.QWEN_2_5_VL,
            ...     qwen_2_5_vl_result,
            ...     input_wh=(1000, 1000),
            ...     resolution_wh=(1000, 1000),
            ...     classes=['cat', 'dog'],
            ... )
            >>> detections.xyxy
            array([[139., 768., 315., 954.],
                   [366., 679., 536., 849.]])
            >>> detections.class_id
            array([0, 1])
            >>> detections.data
            {'class_name': array(['cat', 'dog'], dtype='<U3')}

            ```

        !!! example "Qwen3-VL"

            ```pycon
            >>> import supervision as sv

            >>> qwen_3_vl_result = """```json
            ... [
            ...     {"bbox_2d": [139, 768, 315, 954], "label": "cat"},
            ...     {"bbox_2d": [366, 679, 536, 849], "label": "dog"}
            ... ]
            ... ```"""
            >>> detections = sv.Detections.from_vlm(
            ...     sv.VLM.QWEN_3_VL,
            ...     qwen_3_vl_result,
            ...     resolution_wh=(1000, 1000),
            ...     classes=['cat', 'dog'],
            ... )
            >>> detections.xyxy
            array([[139., 768., 315., 954.],
                   [366., 679., 536., 849.]])
            >>> detections.class_id
            array([0, 1])
            >>> detections.data
            {'class_name': array(['cat', 'dog'], dtype='<U3')}

            ```

        !!! example "Gemini 2.0"

            ??? tip "Prompt engineering"

                From Gemini 2.0 onwards, models are further trained to detect objects in
                an image and get their bounding box coordinates. The coordinates,
                relative to image dimensions, scale to [0, 1000]. You need to convert
                these normalized coordinates back to pixel coordinates based on your
                original image size.
                According to the [Gemini API documentation on image prompts](
                https://ai.google.dev/gemini-api/docs/vision?lang=python#image_prompts), when using
                a single image with text, the recommended approach is to place the text
                prompt after the image part in the `contents` array (for example,
                `contents=[image_part, text_part]`). This ordering has been shown to
                produce significantly better results in practice.

                To get the best results from Google Gemini 2.0, use the following prompt.

                ```
                Detect all the cats and dogs in the image. The box_2d should be
                [ymin, xmin, ymax, xmax] normalized to 0-1000.
                ```

            ```pycon
            >>> import supervision as sv

            >>> gemini_response_text = """```json
            ...     [
            ...         {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1},
            ...         {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2}
            ...     ]
            ... ```"""

            >>> detections = sv.Detections.from_vlm(
            ...     sv.VLM.GOOGLE_GEMINI_2_0,
            ...     gemini_response_text,
            ...     resolution_wh=(1000, 1000),
            ...     classes=['cat', 'dog'],
            ... )
            >>> detections.xyxy
            array([[ 40., 543., 200., 728.],
                   [352., 653., 522., 820.]])
            >>> detections.data
            {'class_name': array(['cat', 'dog'], dtype='<U3')}
            >>> detections.class_id
            array([0, 1])

            ```

        !!! example "Gemini 2.5"

            ??? tip "Prompt engineering"

                To get the best results from Google Gemini 2.5, use the following prompt.

                This prompt is designed to detect all visible objects in the image,
                including small, distant, or partially visible ones, and to return
                tight bounding boxes.

                According to the [Gemini API documentation on image prompts](
                https://ai.google.dev/gemini-api/docs/vision?hl=en),
                when using a single image with text, place the text prompt after the image
                part in the `contents` array. For example, with the `google-genai` client:

                ```python
                response = model.generate_content(
                    [
                        {
                            "role": "user",
                            "parts": [
                                types.Part.from_bytes(image_bytes, mime_type="image/png"),
                                types.Part.from_text(prompt),
                            ],
                        }
                    ]
                )
                ```

                This ordering has been shown to produce significantly better results in practice.

                ```
                Carefully examine this image and detect ALL visible objects, including
                small, distant, or partially visible ones.

                IMPORTANT: Focus on finding as many objects as possible, even if you are
                only moderately confident.

                Make sure each bounding box is as tight as possible.

                Valid object classes: {class_list}

                For each detected object, provide:
                - "label": the exact class name from the list above
                - "confidence": your certainty (between 0.0 and 1.0)
                - "box_2d": the bounding box [ymin, xmin, ymax, xmax] normalized to 0-1000
                - "mask": the binary mask of the object as a base64-encoded string

                Detect everything that matches the valid classes. Do not be
                conservative; include objects even with moderate confidence.

                Return a JSON array, for example:
                [
                    {
                        "label": "person",
                        "confidence": 0.95,
                        "box_2d": [100, 200, 300, 400],
                        "mask": "..."
                    },
                    {
                        "label": "kite",
                        "confidence": 0.80,
                        "box_2d": [50, 150, 250, 350],
                        "mask": "..."
                    }
                ]
                ```

                When using the google-genai library, it is recommended to set
                thinking_budget=0 in thinking_config for more direct and faster responses.

                ```python
                from google.generativeai import types

                model.generate_content(
                    ...,
                    generation_config=generation_config,
                    safety_settings=safety_settings,
                    thinking_config=types.ThinkingConfig(
                        thinking_budget=0
                    )
                )
                ```

                For a shorter prompt focused only on segmentation masks, you can use:

                ```
                Return a JSON list of segmentation masks. Each entry should include the
                2D bounding box in the "box_2d" key, the segmentation mask in the "mask"
                key, and the text label in the "label" key. Use descriptive labels.
                ```

            ```pycon
            >>> import supervision as sv

            >>> gemini_response_text = """```json
            ...     [
            ...         {"box_2d": [543, 40, 728, 200], "label": "cat", "id": 1},
            ...         {"box_2d": [653, 352, 820, 522], "label": "dog", "id": 2}
            ...     ]
            ... ```"""

            >>> detections = sv.Detections.from_vlm(
            ...     sv.VLM.GOOGLE_GEMINI_2_5,
            ...     gemini_response_text,
            ...     resolution_wh=(1000, 1000),
            ...     classes=['cat', 'dog'],
            ... )
            >>> detections.xyxy
            array([[ 40., 543., 200., 728.],
                   [352., 653., 522., 820.]])
            >>> detections.data
            {'class_name': array(['cat', 'dog'], dtype='<U3')}
            >>> detections.class_id
            array([0, 1])

            ```

        !!! example "Moondream"


            ??? tip "Prompt engineering"

                To get the best results from Moondream, use optimized prompts that leverage
                its object detection capabilities effectively.

                **For general object detection, use this simple prompt:**

                ```
                objects
                ```

                This single-word prompt instructs Moondream to detect all visible objects
                and return them in the proper JSON format with normalized coordinates.


            ```pycon
            >>> import supervision as sv

            >>> moondream_result = {
            ...     'objects': [
            ...         {
            ...             'x_min': 0.5704046934843063,
            ...             'y_min': 0.20069346576929092,
            ...             'x_max': 0.7049859315156937,
            ...             'y_max': 0.3012596592307091
            ...         },
            ...         {
            ...             'x_min': 0.6210969910025597,
            ...             'y_min': 0.3300672620534897,
            ...             'x_max': 0.8417936339974403,
            ...             'y_max': 0.4961046129465103
            ...         }
            ...     ]
            ... }

            >>> detections = sv.Detections.from_vlm(
            ...     sv.VLM.MOONDREAM,
            ...     moondream_result,
            ...     resolution_wh=(1000, 1000),
            ... )
            >>> detections.xyxy  # doctest: +ELLIPSIS
            array([[570.404..., 200.693..., 704.985..., 301.259...],
                   [621.096..., 330.067..., 841.793..., 496.104...]])

            ```

        !!! example "DeepSeek-VL2"


            ??? tip "Prompt engineering"

                To get the best results from DeepSeek-VL2, use optimized prompts that leverage
                its object detection and visual grounding capabilities effectively.

                **For general object detection, use the following user prompt:**

                ```
                <image>\n<|ref|>The giraffe at the front<|/ref|>
                ```

                **For visual grounding, use the following user prompt:**

                ```
                <image>\n<|grounding|>Detect the giraffes
                ```

            ```pycon
            >>> import supervision as sv

            >>> deepseek_vl2_result = "<|ref|>The giraffe at the back<|/ref|><|det|>[[580, 270, 999, 904]]<|/det|><|ref|>The giraffe at the front<|/ref|><|det|>[[26, 31, 632, 998]]<|/det|><|endâ–�ofâ–�sentence|>"

            >>> detections = sv.Detections.from_vlm(
            ...     vlm=sv.VLM.DEEPSEEK_VL_2,
            ...     result=deepseek_vl2_result,
            ...     resolution_wh=(1000, 1000),
            ... )
            >>> detections.xyxy
            array([[ 580.58057 ,  270.27026 , 1000.      ,  904.9049  ],
                   [  26.026026,   31.03103 ,  632.6326  ,  998.999   ]],
                  dtype=float32)
            >>> detections.class_id
            array([0, 1])
            >>> detections.data
            {'class_name': array(['The giraffe at the back', 'The giraffe at the front'],
                  dtype='<U24')}

            ```

        zInvalid VLM result type: z. Must be str.)rF   rI   rL   r�   )rF   rI   rH   rL   z. Must be dict.r   N)rF   rG   rL   ©rF   r«   r¬   rw   r­   )rF   rI   rG   rH   rL   zUnsupported VLM value: ú.)"r2   r1   Ú	PALIGEMMArp   r—   rÅ   rM  r9   r   r   ÚQWEN_2_5_VLr:   rj   ÚonesrZ   rµ   Ú	QWEN_3_VLr;   ÚDEEPSEEK_VL_2r3   Ú
FLORENCE_2rÓ   r4   r–   rL   r   ÚGOOGLE_GEMINI_2_0r5   Ú	MOONDREAMr8   ÚGOOGLE_GEMINI_2_5r6   ÚGOOGLE_GEMINI_3_5r7   )r~   rK  rD  rF  rF   rI   r;  rL   Úconfidence_arrr£   rG   r“   r–   Úgemini_resultÚgemini_xyxys                  rT   rN  zDetections.from_vlmZ  s6  € õ~ ' s¨F°FÑ;Ô;ˆà•#”-ÒÐÝ˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ *8¸Ð)IÐ)IÀ&Ð)IÐ)IÑ&ˆD�(˜JÝ$ TÑ*Ô*ˆDå% zð(ˆDð �3˜D¨8¸$Ð?Ñ?Ô?Ð?à•#”/Ò!Ð!Ý˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ *:¸&Ð)KÐ)KÀFÐ)KÐ)KÑ&ˆD�(˜JÝ$ TÑ*Ô*ˆDÝ)¨:Ð6ˆDÝ<>¼GÝ�D‘	”	¥ð=ñ =ô =ˆNð �3Ø H¸Èdðñ ô ð ð •#”-ÒÐÝ˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ *8¸Ð)IÐ)IÀ&Ð)IÐ)IÑ&ˆD�(˜JÝ$ TÑ*Ô*ˆDÝ)¨:Ð6ˆDÝœW¥S¨¡Y¤YµeÐ<Ñ<Ô<ˆNØ�3Ø H¸Èdðñ ô ð ð •#Ô#Ò#Ð#Ý˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ *<¸FÐ)MÐ)MÀfÐ)MÐ)MÑ&ˆD�(˜JÝ$ TÑ*Ô*ˆDÝ)¨:Ð6ˆDØ�3˜D¨8¸$Ð?Ñ?Ô?Ð?à•#”.Ò Ð Ý˜f¥dÑ+Ô+ð Ý ØMµ°V±´ÐMÐMÐMñô ð õ ,;¸6Ð+LÐ+LÀVÐ+LÐ+LÑ(ˆD�&˜$ Ý$ TÑ*Ô*ˆDÝ�4‰yŒy˜AŠ~ˆ~ØŸ	š	™œ�Ý3µR´X¸aÅsÐ5KÑ5KÔ5KÐL�”
Ø�àˆDØÐ!Ø.4�Õ*Ñ+ØÐ#Ø19�Õ-Ñ.à�3˜D t°$Ð7Ñ7Ô7Ð7à•#Ô'Ò'Ð'Ý˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ *@ÀÐ)QÐ)QÈ&Ð)QÐ)QÑ&ˆD�(˜JÝ$ TÑ*Ô*ˆDÝ)¨:Ð6ˆDØ�3˜D¨8¸$Ð?Ñ?Ô?Ð?à•#”-ÒÐÝ˜f¥dÑ+Ô+ð Ý ØMµ°V±´ÐMÐMÐMñô ð õ " &Ð3Ð3¨FÐ3Ð3ˆDÝ$ TÑ*Ô*ˆDØ�3˜D�>‘>”>Ð!à•#Ô'Ò'Ð'Ý˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ 3°6ÐDÐD¸VÐDÐDˆMÝ+¨M¸!Ô,<Ñ=Ô=ˆKÝ)¨=¸Ô+;Ð<ˆDØ�3Ø Ø& qÔ)Ø" 1Ô%Ø(¨Ô+Øðñ ô ð ð •#Ô'Ò'Ð'Ý˜f¥cÑ*Ô*ð Ý ØLµ°V±´ÐLÐLÐLñô ð õ 3°6ÐDÐD¸VÐDÐDˆMÝ+¨M¸!Ô,<Ñ=Ô=ˆKÝ)¨=¸Ô+;Ð<ˆDØ�3Ø Ø& qÔ)Ø" 1Ô%Ø(¨Ô+Øðñ ô ð õ Ð9°3Ð9Ð9Ð9Ñ:Ô:Ð:rV   Úeasyocr_resultsú	list[Any]c                óö  — t          |¦  «        dk    r|                      ¦   «         S t          |d         t          ¦  «        rt	          d¦  «        ‚t          j        d„ |D ¦   «         t
          j        ¬¦  «        }|j        dk    s|j	        dd…         dk    rt	          d	¦  «        ‚t          j
        t          j        |d¬
¦  «        t          j        |d¬
¦  «        f¦  «        }t          j        d„ |D ¦   «         ¦  «        }t          j        d„ |D ¦   «         ¦  «        }t          |t          |i} | |                     t
          j        ¦  «        |                     t
          j        ¦  «        |¬¦  «        S )aÂ  
        Create a Detections object from the
        [EasyOCR](https://github.com/JaidedAI/EasyOCR) result.

        Results are placed in the `data` field with the key `"class_name"`.
        When EasyOCR returns quadrilateral corners, the original corners are
        preserved in ``ORIENTED_BOX_COORDINATES``. Call EasyOCR with
        ``detail=1`` so bounding boxes are available; ``detail=0`` returns text
        strings only and cannot be converted into detections.

        Args:
            easyocr_results: The output Results instance from EasyOCR.

        Returns:
            A new Detections object.

        Example:
            ```python
            import supervision as sv
            import easyocr

            reader = easyocr.Reader(['en'])
            results = reader.readtext("<SOURCE_IMAGE_PATH>")
            detections = sv.Detections.from_easyocr(results)
            detected_text = detections["class_name"]
            ```
        r   zrEasyOCR results produced with detail=0 do not include bounding boxes. Call reader.readtext(..., detail=1) instead.c                ó   — g | ]
}|d          ‘ŒS ©r   r…   ©r‰   rD  s     rT   rŠ   z+Detections.from_easyocr.<locals>.<listcomp>œ  s   € ÐAÐAÐA v˜ œÐAÐAÐArV   r�   r­   r¬   N©rw   r«   z>EasyOCR results must contain four corner points per detection.rì   c                óX   — g | ]'}t          |¦  «        d k    r|d          r|d          nd‘Œ(S )r«   r   )rZ   rg  s     rT   rŠ   z+Detections.from_easyocr.<locals>.<listcomp>£  sF   € ð ð ð àõ ! ™[œ[¨1š_˜_°¸´˜_��q”	�	Àðð ð rV   c                ó   — g | ]
}|d          ‘ŒS )r¬   r…   rg  s     rT   rŠ   z+Detections.from_easyocr.<locals>.<listcomp>¨  s   € ÐEÐEÐE¨6˜V AœYÐEÐEÐErV   )rF   rH   rL   )rZ   r–   rp   r—   rÅ   rj   r’   r  Úndimr¢   ÚhstackÚminÚmaxr   r   r}   )r~   rb  rå   rF   rH   Úocr_textrL   s          rT   Úfrom_easyocrzDetections.from_easyocrv  s…  € õ: ˆÑÔ 1Ò$Ð$Ø—9’9‘;”;Ðå�o aÔ(­#Ñ.Ô.ð 	ÝðFñô ð õ
 ŒxÐAÐA°ÐAÑAÔAÍÌÐTÑTÔTˆØŒ9˜Š>ˆ>˜TœZ¨¨¨œ^¨vÒ5Ð5ÝØPñô ð õ Œy�"œ& ¨AÐ.Ñ.Ô.µ´°tÀ!Ð0DÑ0DÔ0DÐEÑFÔFˆÝ”Xðð à-ðñ ô ñ
ô 
ˆ
õ ”8ÐEÐE°_ÐEÑEÔEÑFÔFˆõ " 8Ý$ dð$
ˆð ˆsØ—’�RœZÑ(Ô(Ø!×(Ò(­¬Ñ4Ô4Øð
ñ 
ô 
ð 	
rV   Úncnn_resultsc           	     óþ  — g g g }}}t          |¦  «        dk    r|                      ¦   «         S |D ]Þ}|j        }|                     |j                             t          j        ¦  «        |j                             t          j        ¦  «        |j	                             t          j        ¦  «        |j
                             t          j        ¦  «        g¦  «         |                     |j        ¦  «         |                     |j        ¦  «         Œß | t          t          j        |t          j        ¬¦  «        ¦  «        t          j        |t          j        ¬¦  «        t          j        |t          ¬¦  «        ¬¦  «        S )al  
        Creates a Detections instance from the
        [ncnn](https://github.com/Tencent/ncnn) inference result.
        Supports object detection models.

        Args:
            ncnn_results: The output Results instance from ncnn.

        Returns:
            A new Detections object.

        Example:
            ```python
            from supervision import _cv2 as cv2
            from ncnn.model_zoo import get_model
            import supervision as sv

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = get_model(
                "yolov8s",
                target_size=640
                prob_threshold=0.5,
                nms_threshold=0.45,
                num_threads=4,
                use_gpu=True,
                )
            result = model(image)
            detections = sv.Detections.from_ncnn(result)
            ```
        r   r�   ry   )rZ   r–   Úrectr  rß   r}   rj   r  r&  r'  r(  ÚprobÚlabelr   r’   rW   )r~   rq  r÷   r  r  Úncnn_resultrs  s          rT   Ú	from_ncnnzDetections.from_ncnn´  s?  € ðB (*¨2¨r˜9ˆkˆåˆ|ÑÔ Ò!Ð!Ø—9’9‘;”;Ðà'ð 	0ð 	0ˆKØÔ#ˆDØ�KŠKà”F—M’M¥"¤*Ñ-Ô-Ø”F—M’M¥"¤*Ñ-Ô-Ø”F—M’M¥"¤*Ñ-Ô-Ø”F—M’M¥"¤*Ñ-Ô-ð	ñô ð ð ×Ò˜{Ô/Ñ0Ô0Ð0Ø×Ò˜[Ô.Ñ/Ô/Ð/Ð/àˆsÝ�bœh tµ2´:Ð>Ñ>Ô>Ñ?Ô?Ý”x µ2´:Ð>Ñ>Ô>Ý”X˜i­sÐ3Ñ3Ô3ð
ñ 
ô 
ð 	
rV   c                óÈ   —  | t          j        dt           j        ¬¦  «        t          j        g t           j        ¬¦  «        t          j        g t          ¬¦  «        ¬¦  «        S )aŒ  
        Create an empty Detections object with no bounding boxes,
            confidences, or class IDs.

        Returns:
            An empty Detections object.

        Example:
            ```pycon
            >>> from supervision import Detections
            >>> empty_detections = Detections.empty()
            >>> empty_detections.xyxy.shape
            (0, 4)

            ```
        )r   rw   r�   ry   )rj   r–   r  r’   rW   )r~   s    rT   r–   zDetections.emptyî  sW   € ð$ ˆsÝ”˜&­¬
Ð3Ñ3Ô3Ý”x ­"¬*Ð5Ñ5Ô5Ý”X˜b­Ð,Ñ,Ô,ð
ñ 
ô 
ð 	
rV   c                ó2   — t          | j        ¦  «        dk    S )ap  
        Check whether the `Detections` object has zero bounding boxes.

        Returns:
            `True` if there are no detections, `False` otherwise.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[10, 20, 110, 120]]),
            ...     class_id=np.array([1]),
            ...     tracker_id=np.array([1]),
            ... )
            >>> filtered = detections[detections.class_id == 99]
            >>> filtered.is_empty()
            True

            ```
        r   rY   rR   s    rT   Úis_emptyzDetections.is_empty	  s   € õ, �4”9‰~Œ~ Ò"Ð"rV   Údetections_listúlist[Detections]c           	     ó‚  ‡— d„ ‰D ¦   «         Št          ‰¦  «        dk    rt                               ¦   «         S ‰D ]5}t          |j        |j        |j        |j        |j        |j	        ¬¦  «         Œ6t          j        d„ ‰D ¦   «         ¦  «        }dˆfd„}dˆfd„}t          t          j        t          j                 t           z  dz   |¦   «         ¦  «        }t          t          j        t          j                 dz   |d¦  «        ¦  «        }t          t          j        t          j                 dz   |d¦  «        ¦  «        }t          t          j        t          j                 dz   |d¦  «        ¦  «        }	t'          d„ ‰D ¦   «         ¦  «        }
d„ ‰D ¦   «         }t)          |¦  «        } | |||||	|
|¬¦  «        S )uŒ  
        Merge a list of Detections objects into a single Detections object.

        This method takes a list of Detections objects and combines their
        respective fields (`xyxy`, `mask`, `confidence`, `class_id`, and `tracker_id`)
        into a single Detections object.

        For example, if merging Detections with 3 and 4 detected objects, this method
        will return a Detections with 7 objects (7 entries in `xyxy`, `mask`, etc).

        !!! Note

            When merging, empty `Detections` objects are ignored.

        !!! Note

            **Mask merge policy** â€” the output mask type follows these rules:

            * All inputs carry
              [`CompactMask`][supervision.detection.compact_mask.CompactMask]
              â†’ result mask is `CompactMask`.
            * Mixed dense `ndarray` + `CompactMask` inputs â†’ dense masks are converted
              to `CompactMask` via
              [`CompactMask.from_dense`][supervision.detection.compact_mask.CompactMask.from_dense];
              result is `CompactMask`. No full `(N, H, W)` stack is allocated.

              !!! warning "Lossy conversion"

                  `from_dense` crops each dense mask to its detection bounding box
                  (`xyxy`). **True pixels outside the bounding box are silently
                  discarded.** This matches the behaviour of
                  `Detections.from_inference(compact_masks=True)`. If pixel-perfect
                  preservation is required, ensure all inputs are already `CompactMask`
                  or use the all-dense path (no `CompactMask` inputs).

            * All inputs carry dense `ndarray` â†’ result is `ndarray` (backward
              compatible).
            * The pairwise merge path used by
              [`with_nms`][supervision.detection.core.Detections.with_nms] /
              [`with_nmm`][supervision.detection.core.Detections.with_nmm]
              (`merge_inner_detection_object_pair`) does **not** preserve `CompactMask`
              â€” mixed inputs materialise to a dense `ndarray` on that path.

        Args:
            detections_list: A list of Detections objects to merge.

        Returns:
            A single Detections object containing the merged data from the input list.

        Raises:
            ValueError: If some `Detections` have a `mask` and others do not.
            ValueError: If `CompactMask` inputs have different `image_shape` values.
            ValueError: If a dense mask `(H, W)` shape differs from the `CompactMask`
                `image_shape` when mixing mask types.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> detections_1 = sv.Detections(
            ...     xyxy=np.array([[15, 15, 100, 100], [200, 200, 300, 300]]),
            ...     class_id=np.array([1, 2]),
            ...     data={'feature_vector': np.array([0.1, 0.2])}
            ... )
            >>> detections_2 = sv.Detections(
            ...     xyxy=np.array([[30, 30, 120, 120]]),
            ...     class_id=np.array([1]),
            ...     data={'feature_vector': np.array([0.3])}
            ... )
            >>> merged_detections = sv.Detections.merge([detections_1, detections_2])
            >>> merged_detections.xyxy
            array([[ 15,  15, 100, 100],
                   [200, 200, 300, 300],
                   [ 30,  30, 120, 120]])
            >>> merged_detections.class_id
            array([1, 2, 1])
            >>> merged_detections.data['feature_vector']
            array([0.1, 0.2, 0.3])

            ```

        Compact mask merge example:

            ```python
            import numpy as np
            import supervision as sv
            from supervision.detection.compact_mask import CompactMask

            H, W = 720, 1280
            masks_a = np.zeros((2, H, W), dtype=bool)
            masks_a[0, 100:200, 100:300] = True
            xyxy_a = np.array([[100., 100., 299., 199.], [400., 300., 600., 500.]])
            cm_a = CompactMask.from_dense(masks_a, xyxy_a, image_shape=(H, W))

            det_compact = sv.Detections(
                xyxy=xyxy_a, mask=cm_a, class_id=np.array([0, 1])
            )

            masks_b = np.zeros((1, H, W), dtype=bool)
            masks_b[0, 50:100, 50:150] = True
            xyxy_b = np.array([[50., 50., 149., 99.]])
            det_dense = sv.Detections(xyxy=xyxy_b, mask=masks_b, class_id=np.array([2]))

            # Dense mask is converted to CompactMask; no (N, H, W) stack allocated.
            merged = sv.Detections.merge([det_compact, det_dense])
            assert isinstance(merged.mask, CompactMask)
            assert len(merged) == 3
            ```
        c                ó:   — g | ]}|                      ¦   «         °|‘ŒS r…   )rz  ©r‰   Ú
detectionss     rT   rŠ   z$Detections.merge.<locals>.<listcomp>�	  s9   € ð 
ð 
ð 
Ø%À
×@SÒ@SÑ@UÔ@Uð
Øð
ð 
ð 
rV   r   rQ   c                ó   — g | ]	}|j         ‘Œ
S r…   rS  ©r‰   Úds     rT   rŠ   z$Detections.merge.<locals>.<listcomp>ž	  s   € Ð:Ð:Ð: Q˜!œ&Ð:Ð:Ð:rV   rN   rn   c                 óV  •— d„ ‰D ¦   «         } t          d„ | D ¦   «         ¦  «        rd S t          d„ | D ¦   «         ¦  «        rt          d¦  «        ‚t          d„ | D ¦   «         ¦  «        r2t          j        t          t          t                   | ¦  «        ¦  «        S t          d„ | D ¦   «         ¦  «        rFt          t          j        t          j
                 t          j        d„ | D ¦   «         ¦  «        ¦  «        S d„ | D ¦   «         }t          |¦  «        d	k    rt          d
t          |¦  «        › �¦  «        ‚t          t          |¦  «        ¦  «        }g }t!          ‰| ¦  «        D ]¯\  }}t#          |t          ¦  «        r|                     |¦  «         Œ0t          j        |t(          ¬¦  «        }|j        d	d …         |k    r#t          d|j        d	d …         › d|› d�¦  «        ‚|                     t          j        ||j        |¦  «        ¦  «         Œ°t          j        |¦  «        S )Nc                ó   — g | ]	}|j         ‘Œ
S r…   ©rG   r‚  s     rT   rŠ   z@Detections.merge.<locals>.stack_mask_or_none.<locals>.<listcomp>¡	  s   € Ð5Ð5Ð5 �Q”VÐ5Ð5Ð5rV   c              3  ó   K  — | ]}|d u V — Œ	d S ri   r…   rI  s     rT   rë   z?Detections.merge.<locals>.stack_mask_or_none.<locals>.<genexpr>¢	  ó&   è è € Ð,Ð, �1˜�9Ð,Ð,Ð,Ð,Ð,Ð,rV   c              3  ó   K  — | ]}|d u V — Œ	d S ri   r…   rI  s     rT   rë   z?Detections.merge.<locals>.stack_mask_or_none.<locals>.<genexpr>¤	  rˆ  rV   z-All or none of the 'mask' fields must be Nonec              3  ó@   K  — | ]}t          |t          ¦  «        V — Œd S ri   ©rp   r   rI  s     rT   rë   z?Detections.merge.<locals>.stack_mask_or_none.<locals>.<genexpr>¦	  s,   è è € Ð=Ð=°!•:˜a¥Ñ-Ô-Ð=Ð=Ð=Ð=Ð=Ð=rV   c              3  óB   K  — | ]}t          |t          ¦  «         V — Œd S ri   r‹  rI  s     rT   rë   z?Detections.merge.<locals>.stack_mask_or_none.<locals>.<genexpr>¨	  s/   è è € ÐAÐA°a•z !¥[Ñ1Ô1Ð1ÐAÐAÐAÐAÐAÐArV   c                ó6   — g | ]}t          j        |¦  «        ‘ŒS r…   )rj   rŸ   rI  s     rT   rŠ   z@Detections.merge.<locals>.stack_mask_or_none.<locals>.<listcomp>«	  s    € Ð7UÐ7UÐ7UÈ!½¼
À1¹¼Ð7UÐ7UÐ7UrV   c                óF   — h | ]}t          |t          ¦  «        ¯|j        ’ŒS r…   )rp   r   Úimage_shaperI  s     rT   ú	<setcomp>z?Detections.merge.<locals>.stack_mask_or_none.<locals>.<setcomp>¯	  s9   € ð $ð $ð $Ø"#µ
¸1½kÑ0JÔ0Jð$Ø”ð$ð $ð $rV   r¬   z>Cannot merge CompactMask objects with different image shapes: r�   zDense mask shape z( does not match CompactMask image_shape rT  )rs   ÚanyrÅ   r   Úmerger	   ÚlistÚnptÚNDArrayrj   ÚgenericÚvstackrZ   rø   ÚnextÚiterÚziprp   r  rŸ   rc   r¢   Ú
from_denserF   )r›   Úcompact_image_shapesr�  Úcompact_listrƒ  rJ  Údenser{  s          €rT   Ústack_mask_or_nonez,Detections.merge.<locals>.stack_mask_or_none 	  sz  ø€ Ø5Ð5 _Ð5Ñ5Ô5ˆEÝÐ,Ð, eÐ,Ñ,Ô,Ñ,Ô,ð Ø�tÝÐ,Ð, eÐ,Ñ,Ô,Ñ,Ô,ð RÝ Ð!PÑQÔQÐQÝÐ=Ð=°uÐ=Ñ=Ô=Ñ=Ô=ð IÝ"Ô(­­dµ;Ô.?ÀÑ)GÔ)GÑHÔHÐHÝÐAÐA¸5ÐAÑAÔAÑAÔAð åÝ”K¥¤
Ô+­R¬YÐ7UÐ7UÈuÐ7UÑ7UÔ7UÑ-VÔ-Vñô ð ð
$ð $Ø',ð$ñ $ô $Ð õ Ð'Ñ(Ô(¨AÒ-Ð-Ý ð6ÝÐ2Ñ3Ô3ð6ð 6ñô ð õ ,0µÐ5IÑ0JÔ0JÑ+KÔ+KˆKØ.0ˆLÝ˜O¨UÑ3Ô3ð ð ‘��1Ý˜a¥Ñ-Ô-ð Ø ×'Ò'¨Ñ*Ô*Ð*Ð*åœJ qµÐ5Ñ5Ô5�EØ”{ 1 2 2”¨+Ò5Ð5Ý(ðF°´¸A¸B¸B´ð Fð FØ7BðFð Fð Fñô ð ð !×'Ò'Ý#Ô.¨u°a´f¸kÑJÔJñô ð ð õ Ô$ \Ñ2Ô2Ð2rV   r+  r—   rf   c                ó(  •‡ — ˆ fd„‰D ¦   «         }t          d„ |D ¦   «         ¦  «        rd S t          d„ |D ¦   «         ¦  «        rt          d‰ › d�¦  «        ‚t          t          j        t          j                 t          j        |¦  «        ¦  «        S )Nc                ó0   •— g | ]}t          |‰¦  «        ‘ŒS r…   )r	  )r‰   rƒ  r+  s     €rT   rŠ   z;Detections.merge.<locals>.stack_or_none.<locals>.<listcomp>É	  s#   ø€ Ð@Ð@Ð@¨1•g˜a Ñ&Ô&Ð@Ð@Ð@rV   c              3  ó   K  — | ]}|d u V — Œ	d S ri   r…   rð   s     rT   rë   z:Detections.merge.<locals>.stack_or_none.<locals>.<genexpr>Ê	  ó&   è è € Ð-Ð- �1˜�9Ð-Ð-Ð-Ð-Ð-Ð-rV   c              3  ó   K  — | ]}|d u V — Œ	d S ri   r…   rð   s     rT   rë   z:Detections.merge.<locals>.stack_or_none.<locals>.<genexpr>Ì	  r£  rV   zAll or none of the 'z' fields must be None)	rs   r‘  rÅ   r	   r”  r•  rj   r–  rl  )r+  r#  r{  s   ` €rT   Ústack_or_nonez'Detections.merge.<locals>.stack_or_noneÈ	  sž   øø€ Ø@Ð@Ð@Ð@°Ð@Ñ@Ô@ˆFÝÐ-Ð- fÐ-Ñ-Ô-Ñ-Ô-ð Ø�tÝÐ-Ð- fÐ-Ñ-Ô-Ñ-Ô-ð UÝ Ð!S¸Ð!SÐ!SÐ!SÑTÔTÐTÝ�œ¥B¤JÔ/µ´¸6Ñ1BÔ1BÑCÔCÐCrV   NrH   rI   rJ   c                ó   — g | ]	}|j         ‘Œ
S r…   )rL   r‚  s     rT   rŠ   z$Detections.merge.<locals>.<listcomp>Õ	  s   € Ð;Ð;Ð; a˜1œ6Ð;Ð;Ð;rV   c                ó   — g | ]	}|j         ‘Œ
S r…   ©rM   r  s     rT   rŠ   z$Detections.merge.<locals>.<listcomp>×	  s   € ÐOÐOÐO°˜Ô,ÐOÐOÐOrV   ©rF   rG   rH   rI   rJ   rL   rM   )rN   rn   )r+  r—   rN   rf   )rZ   rD   r–   rA   rF   rG   rH   rI   rJ   rL   rj   r—  r	   r”  r•  Úbool_r   ÚfloatingÚintegerr#   r$   )r~   r{  r€  rF   rŸ  r¥  rG   rH   rI   rJ   rL   Úmetadata_listrM   s    `           rT   r’  zDetections.merge	  s  ø€ ð^
ð 
Ø)8ð
ñ 
ô 
ˆõ ˆÑÔ 1Ò$Ð$Ý×#Ò#Ñ%Ô%Ð%à)ð 	ð 	ˆJÝ'Ø”_Ø”_Ø%Ô0Ø#Ô,Ø%Ô0Ø”_ðñ ô ð ð õ ŒyÐ:Ð:¨/Ð:Ñ:Ô:Ñ;Ô;ˆð&	3ð &	3ð &	3ð &	3ð &	3ð &	3ðP	Dð 	Dð 	Dð 	Dð 	Dð 	Dõ •C”K¥¤Ô)­KÑ7¸$Ñ>Ð@RÐ@RÑ@TÔ@TÑUÔUˆÝ�#œ+¥b¤kÔ2°TÑ9¸=¸=ÈÑ;VÔ;VÑWÔWˆ
Ý�œ¥B¤JÔ/°$Ñ6¸¸ÀjÑ8QÔ8QÑRÔRˆÝ�#œ+¥b¤jÔ1°DÑ8¸-¸-ÈÑ:UÔ:UÑVÔVˆ
åÐ;Ð;¨?Ð;Ñ;Ô;Ñ<Ô<ˆàOÐO¸ÐOÑOÔOˆÝ! -Ñ0Ô0ˆàˆsØØØ!ØØ!ØØð
ñ 
ô 
ð 	
rV   Úanchorr<   únpt.NDArray[np.generic]c           	     óÂ  — t           | j        v rj|t          j        k    rZt	          t
          j        t          j                 t          t          j
        | j        t                    ¦  «        |¦  «        ¦  «        S | j        }dd„}|t          j        k    r@ ||dd…df         |dd…d	f         z   d	z  |dd…d
f         |dd…df         z   d	z  ¦  «        S |t          j        k    r+| j        €t          d¦  «        ‚t          | j        ¬¦  «        S |t          j        k    r0 ||dd…df         |dd…d
f         |dd…df         z   d	z  ¦  «        S |t          j        k    r0 ||dd…d	f         |dd…d
f         |dd…df         z   d	z  ¦  «        S |t          j        k    r0 ||dd…df         |dd…d	f         z   d	z  |dd…df         ¦  «        S |t          j        k    r  ||dd…df         |dd…df         ¦  «        S |t          j        k    r  ||dd…d	f         |dd…df         ¦  «        S |t          j        k    r0 ||dd…df         |dd…d	f         z   d	z  |dd…d
f         ¦  «        S |t          j        k    r  ||dd…df         |dd…d
f         ¦  «        S |t          j        k    r  ||dd…d	f         |dd…d
f         ¦  «        S t          |› d�¦  «        ‚)u;  Compute anchor-point coordinates for each detection.

        The anchor can be any position in the `Position` enum, such as
        `CENTER`, `CENTER_LEFT`, `BOTTOM_RIGHT`, etc.

        Selection order:

        1. If ``data[ORIENTED_BOX_COORDINATES]`` is set and ``anchor`` is not
           ``Position.CENTER_OF_MASS``, coordinates are computed from the
           oriented bounding box corners (result lies on the actual rotated
           body).
        2. If ``anchor`` is ``Position.CENTER_OF_MASS``, the detection mask
           centroid is returned regardless of OBB data presence.
        3. Otherwise, the anchor is derived from the axis-aligned envelope
           (``xyxy``).

        Args:
            anchor: Anchor position to compute. Supported positions are
                defined in the `Position` enum.

        Returns:
            Array of shape `(n, 2)` where each row is the `[x, y]` anchor
            coordinate for the corresponding detection.

        Raises:
            ValueError: If the provided `anchor` is not supported.

        Examples:
            Axis-aligned detection:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[0.0, 0.0, 10.0, 4.0]])
            ... )
            >>> detections.get_anchors_coordinates(sv.Position.BOTTOM_CENTER)
            array([[5., 4.]])

            ```

            Oriented (rotated) detection â€” anchor lies on the rotated body,
            not the axis-aligned envelope:

            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> corners = np.array(
            ...     [[[0.0, 0.0], [10.0, 0.0], [10.0, 4.0], [0.0, 4.0]]]
            ... )
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[0.0, 0.0, 10.0, 4.0]]),
            ...     data={"xyxyxyxy": corners},
            ... )
            >>> detections.get_anchors_coordinates(sv.Position.BOTTOM_CENTER)
            array([[5., 4.]])

            ```
        rß   rE   r&  rN   r¯  c                ó¢   — t          t          j        t          j                 t          j        | |g¦  «                             ¦   «         ¦  «        S ri   )r	   r”  r•  rj   r–  r’   Ú	transpose)rß   r&  s     rT   Úcoordinatesz7Detections.get_anchors_coordinates.<locals>.coordinates*
  s7   € õ �œ¥B¤JÔ/µ´¸1¸a¸&Ñ1AÔ1A×1KÒ1KÑ1MÔ1MÑNÔNÐNrV   Nr   r«   r¬   r­   z>Cannot use `Position.CENTER_OF_MASS` without a detection mask.)r›   z is not supported.)rß   rE   r&  rE   rN   r¯  )r   rL   r<   ÚCENTER_OF_MASSr	   r”  r•  rj   r–  r   rŸ   rF   ÚCENTERrG   rÅ   r/   ÚCENTER_LEFTÚCENTER_RIGHTÚBOTTOM_CENTERÚBOTTOM_LEFTÚBOTTOM_RIGHTÚ
TOP_CENTERÚTOP_LEFTÚ	TOP_RIGHT)rS   r®  rF   r³  s       rT   Úget_anchors_coordinatesz"Detections.get_anchors_coordinatesä	  s`  € õx $ t¤yÐ0Ð0°V½xÔ?VÒ5VÐ5VÝÝ”�BœJÔ'Ý%Ý”J˜tœyÕ)AÔBÑCÔCÀVñô ñô ð ð Œyˆð	Oð 	Oð 	Oð 	Oð
 •X”_Ò$Ð$Ø�;Ø�a�a�a˜�d”˜d 1 1 1 a 4œjÑ(¨AÑ-Ø�a�a�a˜�d”˜d 1 1 1 a 4œjÑ(¨AÑ-ñô ð ð •xÔ.Ò.Ð.ØŒyÐ Ý ØTñô ð õ -°4´9Ð=Ñ=Ô=Ð=Ø•xÔ+Ò+Ð+Ø�;˜t A A A q Dœz¨D°°°°A°¬J¸¸a¸a¸aÀ¸d¼Ñ,CÀqÑ+HÑIÔIÐIØ•xÔ,Ò,Ð,Ø�;˜t A A A q Dœz¨D°°°°A°¬J¸¸a¸a¸aÀ¸d¼Ñ,CÀqÑ+HÑIÔIÐIØ•xÔ-Ò-Ð-Ø�;  Q Q Q¨ T¤
¨T°!°!°!°Q°$¬ZÑ 7¸1Ñ<¸dÀ1À1À1ÀaÀ4¼jÑIÔIÐIØ•xÔ+Ò+Ð+Ø�;˜t A A A q Dœz¨4°°°°1°¬:Ñ6Ô6Ð6Ø•xÔ,Ò,Ð,Ø�;˜t A A A q Dœz¨4°°°°1°¬:Ñ6Ô6Ð6Ø•xÔ*Ò*Ð*Ø�;  Q Q Q¨ T¤
¨T°!°!°!°Q°$¬ZÑ 7¸1Ñ<¸dÀ1À1À1ÀaÀ4¼jÑIÔIÐIØ•xÔ(Ò(Ð(Ø�;˜t A A A q Dœz¨4°°°°1°¬:Ñ6Ô6Ð6Ø•xÔ)Ò)Ð)Ø�;˜t A A A q Dœz¨4°°°°1°¬:Ñ6Ô6Ð6å˜FÐ6Ð6Ð6Ñ7Ô7Ð7rV   râ   r—   ú_DetectionDataValueType | Nonec                ó6   — | j                              |¦  «        S )aG  Get a value from the detection data dictionary.

        Args:
            key: Data field name.

        Returns:
            The stored data value, or `None` when the key is absent.

        Example:
            ```pycon
            >>> import numpy as np
            >>> from supervision import Detections
            >>> detections = Detections(
            ...     xyxy=np.array([[0, 0, 1, 1]]),
            ...     data={"class_name": np.array(["cat"])},
            ... )
            >>> detections.get_data("class_name").tolist()
            ['cat']

            ```
        )rL   r  )rS   râ   s     rT   Úget_datazDetections.get_dataM
  s   € ð, Œy�}Š}˜SÑ!Ô!Ð!rV   ÚindexúCint | np.integer[Any] | slice | list[int] | npt.NDArray[np.generic]c                ó  — t          | ¦  «        dk    �rt          | j        t          ¦  «        r| j        dd…         }n+| j        �"| j        dd…                              ¦   «         }nd}d„ | j                             ¦   «         D ¦   «         }t          | j                             ¦   «         || j	        �| j	                             ¦   «         nd| j
        �| j
                             ¦   «         nd| j        �| j                             ¦   «         nd|t          | j        ¦  «        ¬¦  «        S t          |t          t          j        f¦  «        rt          |¦  «        g}t#          t$          t&          t                   z  t(          j        t          j        t          j        z           z  |¦  «        }d„ t/          | j        |¦  «                             ¦   «         D ¦   «         }t          | j        t          ¦  «        r!| j        t#          t0          |¦  «                 }n<| j        �3| j        t#          t0          |¦  «                                      ¦   «         }nd}t          | j        |                              ¦   «         || j	        �| j	        |                              ¦   «         nd| j
        �| j
        |                              ¦   «         nd| j        �| j        |                              ¦   «         nd|t          | j        ¦  «        ¬¦  «        S )uÐ  Get a subset of the Detections object.

        Args:
            index: Row index, indices, slice, or boolean mask selecting detections.

        Returns:
            A new `Detections` instance containing the selected rows. Always returns
            a fresh copy â€” arrays and metadata are never shared with the original,
            even when the selection is empty or the input has zero detections.

        Example:
            ```pycon
            >>> import numpy as np
            >>> from supervision import Detections
            >>> detections = Detections(xyxy=np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
            >>> detections.select([1]).xyxy.tolist()
            [[1, 1, 2, 2]]

            ```
        r   Nc                ó�   — i | ]C\  }}|t          |t          j        ¦  «        r|                     ¦   «         nt	          |¦  «        “ŒDS r…   ©rp   rj   ré   r°   r“  r  s      rT   r!  z%Detections.select.<locals>.<dictcomp>…
  sQ   € ð ð ð á�C˜ð ¥Z°µr´zÑ%BÔ%BÐS�U—Z’Z‘\”\�\ÍÈUÉÌðð ð rV   r©  c                ó�   — i | ]C\  }}|t          |t          j        ¦  «        r|                     ¦   «         nt	          |¦  «        “ŒDS r…   rÆ  r  s      rT   r!  z%Detections.select.<locals>.<dictcomp>›
  sQ   € ð 
ð 
ð 
á��Uð ¥¨Eµ2´:Ñ!>Ô!>ÐO�—’‘”�ÅDÈÁKÄKð
ð 
ð 
rV   )rZ   rp   rG   r   r°   rL   r.  rD   rF   rH   rI   rJ   rÓ   rM   rW   rj   r¬  r	   Úslicer“  r”  r•  rª  r    r   )rS   rÂ  rG   rL   Úarray_indexs        rT   ÚselectzDetections.selecte
  sÃ  € õ2 ˆt‰9Œ9˜Š>‰>Ý˜$œ)¥[Ñ1Ô1ð Ø”y  ! ”}��Ø”Ð&Ø”y  ! ”}×)Ò)Ñ+Ô+��à�ðð à"&¤)§/¢/Ñ"3Ô"3ðñ ô ˆDõ Ø”Y—^’^Ñ%Ô%Øà.2¬oÐ.I�D”O×(Ò(Ñ*Ô*Ð*Ètà15´Ð1J˜œ×+Ò+Ñ-Ô-Ð-ÐPTà.2¬oÐ.I�D”O×(Ò(Ñ*Ô*Ð*ÈtàÝ˜dœmÑ,Ô,ðñ ô ð õ �e�c¥2¤:Ð.Ñ/Ô/ð 	!Ý˜‘Z”Z�LˆEÝÝ•D�”IÑ¥¤­B¬J½¼Ñ,AÔ BÑBÀEñ
ô 
ˆð
ð 
å+¨D¬I°{ÑCÔC×IÒIÑKÔKð
ñ 
ô 
ˆõ �d”i¥Ñ-Ô-ð 	Ø”9�T¥# {Ñ3Ô3Ô4ˆDˆDØŒYÐ"Ø”9�T¥# {Ñ3Ô3Ô4×9Ò9Ñ;Ô;ˆDˆDàˆDÝØ”˜;Ô'×,Ò,Ñ.Ô.Øð ”?Ð.ð ” Ô,×1Ò1Ñ3Ô3Ð3àð 6:´]Ð5N�”˜kÔ*×/Ò/Ñ1Ô1Ð1ÐTXð ”?Ð.ð ” Ô,×1Ò1Ñ3Ô3Ð3ààÝ˜$œ-Ñ(Ô(ð#
ñ 
ô 
ð 	
rV   úIint | np.integer[Any] | slice | list[int] | npt.NDArray[np.generic] | strú7Detections | list[Any] | npt.NDArray[np.generic] | Nonec                ó€   — t          |t          ¦  «        r|                      |¦  «        S |                      |¦  «        S )a[  
        Get a subset of the Detections object or access an item from its data field.

        When provided with an integer, slice, list of integers, or a numpy array, this
        method returns a new Detections object that represents a subset of the original
        detections. When provided with a string, it accesses the corresponding item in
        the data dictionary.

        Args:
            index: The index, indices, or key to access a subset of the Detections
                or an item from the data.

        Returns:
            A subset of the Detections object or an item from the data field.

        Example:
            ```python
            import supervision as sv

            detections = sv.Detections()

            first_detection = detections[0]
            first_10_detections = detections[0:10]
            some_detections = detections[[0, 2, 4]]
            class_0_detections = detections[detections.class_id == 0]
            high_confidence_detections = detections[detections.confidence > 0.5]

            feature_vector = detections['feature_vector']
            ```
        )rp   r—   rÁ  rÊ  )rS   rÂ  s     rT   Ú__getitem__zDetections.__getitem__¹
  s;   € õN �e�SÑ!Ô!ð 	(Ø—=’= Ñ'Ô'Ð'Ø�{Š{˜5Ñ!Ô!Ð!rV   r   ú#npt.NDArray[np.generic] | list[Any]c                ó
  — t          |t          j        t          f¦  «        st	          d¦  «        ‚t          |t          ¦  «        rt          j        |¦  «        }t          ||it          | ¦  «        ¦  «         || j        |<   dS )a«  
        Set a value in the data dictionary of the Detections object.

        Args:
            key: The key in the data dictionary to set.
            value: The value to set for the key.

        Example:
            ```python
            from supervision import _cv2 as cv2
            import supervision as sv
            from ultralytics import YOLO

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = YOLO('yolov8s.pt')

            result = model(image)[0]
            detections = sv.Detections.from_ultralytics(result)

            detections['names'] = [
                 model.model.names[class_id]
                 for class_id
                 in detections.class_id
             ]
            ```

        Raises:
            TypeError: If `value` is not a `np.ndarray` or `list`.
            ValueError: If `value` has a length or shape incompatible with
                the detection count.
        z$Value must be a np.ndarray or a listN)	rp   rj   ré   r“  Ú	TypeErrorr’   r@   rZ   rL   )rS   râ   r   s      rT   Ú__setitem__zDetections.__setitem__ä
  sv   € õ@ ˜%¥"¤*­dÐ!3Ñ4Ô4ð 	DÝÐBÑCÔCÐCå�e�TÑ"Ô"ð 	$Ý”H˜U‘O”OˆEå˜˜U�|¥S¨¡Y¤YÑ/Ô/Ð/ØˆŒ	�#‰ˆˆrV   c                ó    — t          | ¦  «        S )u’  
        Calculate the area of each detection in the set of object detections.

        Selection order:

        1. If ``mask`` is set, return the area of each mask.
        2. Else, if ``data[ORIENTED_BOX_COORDINATES]`` is set, return the area of
           the rotated body (shoelace formula on the four corners).
        3. Otherwise, return the axis-aligned box area (``box_area``).

        **OBB dispatch contract**: presence of ``data[ORIENTED_BOX_COORDINATES]``
        with shape ``(N, 4, 2)`` is the canonical signal that a detection carries
        oriented bounding box geometry. The same presence-of-key check governs
        ``with_nms``, ``with_nmm``, and this property â€” always store OBB corners
        under ``config.ORIENTED_BOX_COORDINATES`` with that shape.

        **Return dtype**: ``float64`` (OBB branch and integer AABB fallback),
        floating input dtype (floating AABB fallback), ``int64`` (mask branch).

        Returns:
            An array containing the area of each detection
                in the format of `(area_1, area_2, ..., area_n)`,
                where n is the number of detections.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> corners = np.array(
            ...     [[[0, 5], [5, 10], [10, 5], [5, 0]]], dtype=np.float32
            ... )
            >>> detections = sv.Detections(
            ...     xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32),
            ...     class_id=np.array([0]),
            ...     data={"xyxyxyxy": corners},
            ... )
            >>> detections.area
            array([50.])

            Mask branch returns ``int64`` pixel counts:

            >>> mask = np.zeros((2, 10, 10), dtype=bool)
            >>> mask[0, :3, :3] = True   # 9 pixels
            >>> mask[1, :5, :5] = True   # 25 pixels
            >>> detections = sv.Detections(
            ...     xyxy=np.array(
            ...         [[0, 0, 10, 10], [0, 0, 10, 10]], dtype=np.float32
            ...     ),
            ...     mask=mask,
            ... )
            >>> detections.area
            array([ 9, 25])

            ```
        )r   rR   s    rT   rÞ   zDetections.area  s   € õr ˜dÑ#Ô#Ð#rV   c                óà  — | j         }t          j        |j        t          j        ¦  «        r�|                     t          ¦  «        }|dd…df         |dd…df         z
  }|dd…df         |dd…df         z
  }t          j        |t          j        ¬¦  «        t          j        |t          j        ¬¦  «        z  S |dd…df         |dd…df         z
  }|dd…df         |dd…df         z
  }||z  S )a‹  
        Calculate the area of each bounding box in the set of object detections.

        Returns:
            An array of floats containing the area of each bounding
            box in the format of `(area_1, area_2, ..., area_n)`,
                where n is the number of detections. Integer coordinates
                produce ``float64``; floating coordinates preserve their dtype.
        Nr«   r   r­   r¬   r�   )	rF   rj   Ú
issubdtyperŽ   r¬  r}   rb   rŸ   Úfloat64)rS   rF   Úinteger_coordinatesÚwidthsÚheightss        rT   Úbox_areazDetections.box_areaH  s
  € ð ŒyˆÝŒ=˜œ¥R¤ZÑ0Ô0ð 		ð #'§+¢+­fÑ"5Ô"5ÐØ(¨¨¨¨A¨Ô.Ð1DÀQÀQÀQÈÀTÔ1JÑJˆFØ)¨!¨!¨!¨Q¨$Ô/Ð2EÀaÀaÀaÈÀdÔ2KÑKˆGÝ”:˜f­B¬JÐ7Ñ7Ô7½"¼*Ø�rœzð;ñ ;ô ;ñ ð ð �a�a�a˜�d”˜d 1 1 1 a 4œjÑ(ˆØ�q�q�q˜!�t”*˜t A A A q DœzÑ)ˆØ˜ÑÐrV   c                ó   — | j         dd…df         | j         dd…df         z
  }| j         dd…df         | j         dd…df         z
  }t          j        |t          j        t          j        ¬¦  «        }t          j        ||||dk    ¬¦  «         |S )a#  
        Compute the aspect ratio (width divided by height) for each bounding box.

        Returns:
            Array of shape `(N,)` containing aspect ratios, where `N` is the
                number of boxes (width / height for each box).

        Examples:
            ```python
            import numpy as np
            import supervision as sv

            xyxy = np.array([
                [10, 10, 50, 50],
                [60, 10, 180, 50],
                [10, 60, 50, 180],
            ])

            detections = sv.Detections(xyxy=xyxy)

            detections.box_aspect_ratio
            # array([1.0, 3.0, 0.33333333])

            ar = detections.box_aspect_ratio
            detections[(ar < 2.0) & (ar > 0.5)].xyxy
            # array([[10., 10., 50., 50.]])
            ```
        Nr«   r   r­   r¬   r�   )r  Úwhere)rF   rj   Ú	full_likeÚnanrÖ  Údivide)rS   rØ  rÙ  Úaspect_ratioss       rT   Úbox_aspect_ratiozDetections.box_aspect_ratioc  s�   € ð< ”˜1˜1˜1˜a˜4” 4¤9¨Q¨Q¨Q°¨T¤?Ñ2ˆØ”)˜A˜A˜A˜q˜D”/ D¤I¨a¨a¨a°¨d¤OÑ3ˆåœ V­R¬V½2¼:ÐFÑFÔFˆÝ
Œ	�&˜' }¸GÀqºLÐIÑIÔIÐIØÐrV   c                ó6  — ddl m} | j        �t          | j        |¦  «        r| S t	          | j        j        d         ¦  «        t	          | j        j        d         ¦  «        f}t          j        t          j        dd|d         dz
  |d         dz
  ggt          j	        ¬¦  «        t          | ¦  «        df¦  «        }|                      | j         |j        | j        ||¬¦  «        | j        | j        | j        | j        t%          | j        ¦  «        ¬¦  «        }|S )	aO  Return a copy of this Detections with masks converted to CompactMask.

        The dense :attr:`mask` field (``NDArray[np.bool_]``) is converted to a
        :class:`~supervision.detection.compact_mask.CompactMask` without changing
        mask pixels. When :attr:`mask` is already a
        :class:`~supervision.detection.compact_mask.CompactMask` or is ``None``,
        the instance is returned unchanged.

        Note:
            The crop boundaries are set to the **full image dimensions**, not the
            detector bounding box. No bbox-crop memory savings apply: the RLE
            sparsity still reduces storage versus a dense array, but the
            ``O(bbox_area)`` savings available from
            ``from_inference(..., compact_masks=True)`` are absent here because
            every crop spans the whole frame. Call
            :meth:`~supervision.detection.compact_mask.CompactMask.repack` on the
            resulting mask to tighten crops to their bounding boxes, at the cost
            of potential pixel loss outside those boxes.

        Returns:
            A new :class:`Detections` instance with ``mask`` set to a
            :class:`~supervision.detection.compact_mask.CompactMask`, or ``self``
            when conversion is not needed.

        Example:
            ```python
            import numpy as np
            import supervision as sv
            detections = sv.Detections(
                xyxy=np.array([[0, 0, 10, 10]]),
                mask=np.ones((1, 20, 20), dtype=bool),
            )
            compact = detections.to_compact_masks()
            ```
        r   r   Nr¬   r«   r�   ©r›   rF   r�  r©  )Ú"supervision.detection.compact_maskr   rG   rp   rW   r¢   rj   Útiler’   rÖ  rZ   rÃ   rF   r›  rH   rI   rJ   rL   rÓ   rM   )rS   r   r�  Úfull_image_xyxyÚnews        rT   Úto_compact_maskszDetections.to_compact_masksˆ  s&  € ðH 	CÐBÐBÐBÐBÐBàŒ9Ð¥
¨4¬9°kÑ BÔ BÐØˆKÝ˜4œ9œ?¨1Ô-Ñ.Ô.µ°D´I´OÀAÔ4FÑ0GÔ0GÐHˆÝœ'ÝŒHØ�Q˜ Aœ¨Ñ*¨K¸¬N¸QÑ,>Ð?Ð@ÍÌ
ðñ ô õ �‰YŒY˜ˆNñ	
ô 
ˆð �nŠnØ”Ø'�Ô'Ø”iØ$Ø'ðñ ô ð
 ”Ø”]Ø”Ø”Ý˜$œ-Ñ(Ô(ð ñ 
ô 
ˆð ˆ
rV   Úclass_agnosticÚoperation_nameúnpt.NDArray[np.floating]c                óD  — |rtt          t          j        t          j                 t          j        | j        t          t          j        | j        ¦  «         	                    dd¦  «        f¦  «        ¦  «        S | j
        €t          d|› d|› d�¦  «        ‚t          t          j        t          j                 t          j        | j        t          t          j        | j        ¦  «         	                    dd¦  «        | j
         	                    dd¦  «        f¦  «        ¦  «        S )z—Stack xyxy + confidence (+ class_id) for NMS/NMM/Soft-NMS dispatch.

        Callers must already have verified `self.confidence is not None`.
        éÿÿÿÿr¬   Nz&Detections class_id must be given for z; to be executed. If you intended to perform class agnostic z set class_agnostic=True.)r	   r”  r•  rj   r«  rl  rF   ré   rH   ÚreshaperI   rÅ   )rS   ré  rê  s      rT   Ú_build_nms_predictionsz!Detections._build_nms_predictionsÆ  s  € ð ð 	ÝÝ”�BœKÔ(Ý”	Ø”Y¥¥R¤Z°´Ñ AÔ A× IÒ IÈ"ÈaÑ PÔ PÐQñô ñô ð ð Œ=Ð Ýð=¸ð =ð =à!ð=ð =ð =ñô ð õ
 ÝŒK�œÔ$ÝŒIà”IÝ�œ T¤_Ñ5Ô5×=Ò=¸bÀ!ÑDÔDØ”M×)Ò)¨"¨aÑ0Ô0ðñô ñ	
ô 	
ð 		
rV   ç      à?Ú	thresholdrµ   Úoverlap_metricr&   c                óš  — t          | ¦  «        dk    r| S | j        €t          d¦  «        ‚|                      |d¦  «        }| j        �t          || j        ||¬¦  «        }nVt          | j        v r6t          |t          j
        | j        t                   ¦  «        ||¬¦  «        }nt          |||¬¦  «        }|                      |¦  «        S )a�  
        Performs non-max suppression on detection set. Dispatch order: (1) if mask
        data present, IoU mask is used; (2) else if oriented-box coordinates
        (``data[ORIENTED_BOX_COORDINATES]``) present, oriented-box IoU is used; (3)
        otherwise, axis-aligned box IoU is used.

        Args:
            threshold: The intersection-over-union threshold
                to use for non-maximum suppression. The lower the value the more
                restrictive the NMS becomes. Defaults to 0.5.
            class_agnostic: Whether to perform class-agnostic
                non-maximum suppression. If True, the class_id of each detection
                will be ignored. Defaults to False.
            overlap_metric: Metric used to compute the degree of
                overlap between pairs of masks or boxes (e.g., IoU, IoS).

        Returns:
            A new Detections object containing the subset of detections
                after non-maximum suppression.

        Raises:
            ValueError: If `confidence` is None and class_agnostic is False.
                If `class_id` is None and class_agnostic is False.
        r   Nz;Detections confidence must be given for NMS to be executed.ÚNMS©r  r›   Úiou_thresholdrò  ©r  Úoriented_boxesrö  rò  ©r  rö  rò  )rZ   rH   rÅ   rï  rG   r+   r   rL   r.   rj   rŸ   r(   rÊ  )rS   rñ  ré  rò  r  Úindicess         rT   Úwith_nmszDetections.with_nmså  sî   € õ< ˆt‰9Œ9˜Š>ˆ>ØˆKàŒ?Ð"ÝØMñô ð ð ×1Ò1°.À%ÑHÔHˆàŒ9Ð Ý.Ø'Ø”iØ'Ø-ð	ñ ô ˆGˆGõ &¨¬Ð2Ð2Ý6Ø'Ý!œz¨$¬)Õ4LÔ*MÑNÔNØ'Ø-ð	ñ ô ˆGˆGõ .Ø'Ø'Ø-ðñ ô ˆGð �{Š{˜7Ñ#Ô#Ð#rV   ÚsigmaÚscore_thresholdúfloat | Nonec                ó”  — t          | ¦  «        dk    r| S | j        €t          d¦  «        ‚|                      |d¦  «        }| j        �t          || j        |¬¦  «        }nt          ||¬¦  «        }|                      t          j	        t          | ¦  «        ¦  «        ¦  «        }||_        |€|S |                     ||k    ¦  «        S )u  
        Performs Gaussian Soft Non-Maximum Suppression on detection set. Dispatch
        order: (1) if mask data present, IoU mask is used; (2) otherwise,
        axis-aligned box IoU is used. Oriented-box detections are not given
        dedicated OBB-IoU treatment and fall back to their axis-aligned `xyxy`.

        Unlike `with_nms`, which discards overlapping detections outright,
        Soft-NMS keeps every detection and instead rescales its confidence by
        `score *= exp(-iou**2 / sigma)` for each higher-scoring, same-category
        overlap. By default (`score_threshold=None`) nothing is dropped â€” the
        method only rescales confidence, despite the "suppression" name; pass
        `score_threshold` to additionally filter the decayed scores into a real
        subset, matching `with_nms`'s return contract.

        Args:
            sigma: Controls the strength of the confidence decay; must be
                greater than `0`. The lower the value the stronger the decay.
                No value of `sigma` reproduces `with_nms`'s hard cutoff â€”
                Soft-NMS never drops detections on its own.
            class_agnostic: Whether to perform class-agnostic Soft-NMS. If
                True, the class_id of each detection will be ignored.
                Defaults to False.
            score_threshold: If given, detections whose decayed confidence is
                at or below this value are dropped, producing a real subset
                (like `with_nms`). If `None` (default), all detections are
                kept, with their confidence rescaled in place on the returned
                copy.

        Returns:
            A new Detections object with decayed confidence scores and,
                if `score_threshold` is given, filtered to a real subset.
                The original `Detections` instance is never modified.

        Raises:
            ValueError: If `confidence` is None.
                If `class_id` is None and class_agnostic is False.
                If `sigma` is not greater than `0`.
        r   Nz@Detections confidence must be given for Soft-NMS to be executed.zSoft-NMS)r  r›   rü  )r  rü  )
rZ   rH   rÅ   rï  rG   r,   r)   rÊ  rj   Úarange)rS   rü  ré  rý  r  Údecayed_confidencerD  s          rT   Úwith_soft_nmszDetections.with_soft_nms$  sã   € õX ˆt‰9Œ9˜Š>ˆ>ØˆKàŒ?Ð"ÝØRñô ð ð ×1Ò1°.À*ÑMÔMˆàŒ9Ð Ý!>Ø'Ø”iØð"ñ "ô "ÐÐõ ">Ø'Øð"ñ "ô "Ðð
 —’�RœY¥s¨4¡y¤yÑ1Ô1Ñ2Ô2ˆØ.ˆÔàÐ"ØˆMØ�}Š}Ð/°/ÒAÑBÔBÐBrV   c                ó  ‡ — t          ‰ ¦  «        dk    r‰ S ‰ j        €t          d¦  «        ‚‰                      |d¦  «        }‰ j        �t          |‰ j        ||¬¦  «        }nVt          ‰ j        v r6t          |t          j
        ‰ j        t                   ¦  «        ||¬¦  «        }nt          |||¬¦  «        }g }|D ]2}ˆ fd„|D ¦   «         }|                     t          |¦  «        ¦  «         Œ3t                               |¦  «        S )	aT  
        Perform non-maximum merging on the current set of object detections.
        Dispatch order: (1) if mask data present, IoU mask is used; (2) else if
        oriented-box coordinates (``data[ORIENTED_BOX_COORDINATES]``) present,
        oriented-box IoU is used; (3) otherwise, axis-aligned box IoU is used.

        Args:
            threshold: The intersection-over-union threshold
                to use for non-maximum merging. Defaults to 0.5.
            class_agnostic: Whether to perform class-agnostic
                non-maximum merging. If True, the class_id of each detection
                will be ignored. Defaults to False.
            overlap_metric: Metric used to compute the degree of
                overlap between pairs of masks or boxes (e.g., IoU, IoS).

        Returns:
            A new Detections object containing the subset of detections
                after non-maximum merging.

        Note:
            For detections carrying oriented bounding box data
            (``data[ORIENTED_BOX_COORDINATES]``), each merge group's output OBB
            is the tightest rectangle at the winner's orientation enclosing all
            corners contributed by every detection in the group. The winner is
            the highest-confidence detection in the group. The axis-aligned
            ``xyxy`` field is updated to the tight bounding box of that rect.
            For zero-rotation OBBs this equals the axis-aligned union exactly;
            for rotated OBBs the merged rect inherits the winner's rotation angle.
            Groups of size 1 keep the original OBB unchanged.

        Raises:
            ValueError: If `confidence` is None or `class_id` is None and
                class_agnostic is False.

        ![non-max-merging](https://media.roboflow.com/supervision-docs/non-max-merging.png){ align=center width="800" }
        r   Nz;Detections confidence must be given for NMM to be executed.ÚNMMrõ  r÷  rù  c                ó:   •— g | ]}‰                      |¦  «        ‘ŒS r…   )rÊ  )r‰   r_   rS   s     €rT   rŠ   z'Detections.with_nmm.<locals>.<listcomp>¸  s#   ø€ Ð9Ð9Ð9¨�T—[’[ ‘^”^Ð9Ð9Ð9rV   )rZ   rH   rÅ   rï  rG   r*   r   rL   r-   rj   rŸ   r'   r  Ú_merge_detection_grouprD   r’  )	rS   rñ  ré  rò  r  Úmerge_groupsrD  Úmerge_groupÚgroups	   `        rT   Úwith_nmmzDetections.with_nmmm  s=  ø€ õT ˆt‰9Œ9˜Š>ˆ>ØˆKàŒ?Ð"ÝØMñô ð ð ×1Ò1°.À%ÑHÔHˆàŒ9Ð Ý-Ø'Ø”iØ'Ø-ð	ñ ô ˆLˆLõ &¨¬Ð2Ð2Ý5Ø'Ý!œz¨$¬)Õ4LÔ*MÑNÔNØ'Ø-ð	ñ ô ˆLˆLõ -Ø'Ø'Ø-ðñ ô ˆLð $&ˆØ'ð 	9ð 	9ˆKØ9Ð9Ð9Ð9¨[Ð9Ñ9Ô9ˆEØ�MŠMÕ0°Ñ7Ô7Ñ8Ô8Ð8Ð8å×Ò Ñ'Ô'Ð'rV   )rN   rO   )rN   rW   )rN   r\   )ra   rb   rN   rc   )ru   r   rN   rD   )r�   r   rN   rD   )r�   r   rN   rD   )r¥   r¦   r§   r¨   rN   rD   )r²   r   rN   rD   )r·   r   rN   rD   ri   )r¼   r¦   r½   r¾   rN   rD   )rÇ   r   rN   rD   )rÐ   rÑ   rÏ   rc   rN   rD   )rÚ   rÛ   rN   rD   )rÿ   rÑ   r§   r¨   rN   rD   )r  r¦   r  r¾   rN   rD   )r>  r   rN   rD   )rB  rC  rD  rE  rF  r   rN   rD   )rK  rQ  rD  rE  rF  r   rN   rD   )rb  rc  rN   rD   )rq  r   rN   rD   )rN   rD   )rN   rc   )r{  r|  rN   rD   )r®  r<   rN   r¯  )râ   r—   rN   r¿  )rÂ  rÃ  rN   rD   )rÂ  rË  rN   rÌ  )râ   r—   r   rÏ  rN   rO   )rN   r¯  )ré  rc   rê  r—   rN   rë  )rñ  rµ   ré  rc   rò  r&   rN   rD   )rð  FN)rü  rµ   ré  rc   rý  rþ  rN   rD   )6rÄ   Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__rG   rH   rI   rJ   r   rÓ   rL   rM   rU   r[   r`   rt   Úclassmethodr€   rœ   r¤   r±   r¶   r»   rÆ   rÎ   rÙ   rþ   r  r=  rA  rP  rN  rp  rw  r–   rz  r’  r¾  rÁ  rÊ  rÎ  rÒ  ÚpropertyrÞ   rÚ  rá  rè  rï  r&   ÚIOUrû  r  r
  r…   rV   rT   rD   rD   Z   sM  € € € € € € ðdð dðL !Ð Ð Ñ Ø7;€DÐ;Ð;Ð;Ñ;Ø26€JÐ6Ð6Ð6Ñ6Ø/3€HÐ3Ð3Ð3Ñ3Ø15€JÐ5Ð5Ð5Ñ5Ø$˜u°TÐ:Ñ:Ô:€DÐ:Ð:Ð:Ñ:Ø#˜e°DÐ9Ñ9Ô9€HÐ9Ð9Ð9Ñ9ð
ð 
ð 
ð 
ðð ð ð ðð ð ð ð4"
ð "
ð "
ð "
ðH ð
ð 
ð 
ñ „[ð
ð> ðSð Sð Sñ „[ðSðj ð"
ð "
ð "
ñ „[ð"
ðH ð:
ð :
ð :
ñ „[ð:
ðx ð!
ð !
ð !
ñ „[ð!
ðF ð#
ð #
ð #
ñ „[ð#
ðJ ð +/ðNð Nð Nð Nñ „[ðNð` ð,
ð ,
ð ,
ñ „[ð,
ð\ ð
 $ð	k
ð k
ð k
ð k
ð k
ñ „[ðk
ðZ ð<)ð <)ð <)ñ „[ð<)ð| ðz
ð z
ð z
ñ „[ðz
ðx àNRðe
ð e
ð e
ð e
ñ „[ðe
ðN ð'
ð '
ð '
ñ „[ð'
ðR ða>ð a>ð a>ñ „[ða>ðF ðY;ð Y;ð Y;ñ „[ðY;ðv ð;
ð ;
ð ;
ñ „[ð;
ðz ð7
ð 7
ð 7
ñ „[ð7
ðr ð
ð 
ð 
ñ „[ð
ð.#ð #ð #ð #ð0 ðC
ð C
ð C
ñ „[ðC
ðJg8ð g8ð g8ð g8ðR"ð "ð "ð "ð0R
ð R
ð R
ð R
ðh)"ð )"ð )"ð )"ðV'ð 'ð 'ð 'ðR ð8$ð 8$ð 8$ñ „Xð8$ðt ð ð  ð  ñ „Xð ð4 ð"ð "ð "ñ „Xð"ðH<ð <ð <ð <ð|
ð 
ð 
ð 
ðB Ø$Ø(5Ô(9ð	=$ð =$ð =$ð =$ð =$ðB Ø$Ø(,ð	GCð GCð GCð GCð GCðV Ø$Ø(5Ô(9ð	N(ð N(ð N(ð N(ð N(ð N(ð N(rV   rD   Úcorners_listúlist[npt.NDArray[np.number]]rN   rë  c           	     óR  — t          j        d„ | D ¦   «         Ž }t          j        |t           j        ¦  «        r|nt           j        }| d         d         }t          j        | d¬¦  «        }t          j        |t           j        ¦  «        rTt          j        |                     t          ¦  «        |                     t          ¦  «        z
  t           j        ¬¦  «        }nC|                     t           j        d¬¦  «        |                     t           j        d¬¦  «        z
  }|d         |d         z
  }t          t          j        t          |d         ¦  «        t          |d         ¦  «        ¦  «        ¦  «        }t          t          j        |¦  «        ¦  «        t          t          j        |¦  «        ¦  «        }	}t          j        ||	 g|	|ggt           j        ¬¦  «        }
||
z  }t          |dd…df                              ¦   «         ¦  «        }t          |dd…df                              ¦   «         ¦  «        }t          |dd…df                              ¦   «         ¦  «        }t          |dd…df                              ¦   «         ¦  «        }t          j        ||	g|	 |ggt           j        ¬¦  «        }t          j        ||g||g||g||ggt           j        ¬¦  «        |z  }t#          t$          j        t           j                 ||z                        |¦  «        ¦  «        S )	aA  Merge multiple OBB corner arrays using winner-angle projection.

    The first entry in *corners_list* is the winner. Its orientation angle
    (derived from its first edge) defines the local frame in which the
    tightest enclosing axis-aligned rectangle is computed. That rectangle is
    then rotated back to produce the merged OBB.

    Args:
        corners_list: List of (4, 2) corner arrays. First is the winner.

    Returns:
        Merged OBB corners as a (4, 2) floating-point array. Its dtype matches
        floating inputs and is float64 for integer inputs.
    c                ó   — g | ]	}|j         ‘Œ
S r…   r�   )r‰   Úcornerss     rT   rŠ   z&_merge_obb_corners.<locals>.<listcomp>Ï  s   € Ð"MÐ"MÐ"M°W 7¤=Ð"MÐ"MÐ"MrV   r   rì   r�   Fr  r¬   N)rj   Úresult_typerÕ  r«  rÖ  Úconcatenater¬  rŸ   r}   rb   rµ   Úarctan2ÚcosÚsinr’   rm  rn  r	   r”  r•  )r  Úinput_dtypeÚoutput_dtypeÚoriginÚstackedÚall_cornersÚwinner_edgeÚangler  r  Úto_localÚlocal_cornersÚx_minÚx_maxÚy_minÚy_maxÚto_worldÚmergeds                     rT   Ú_merge_obb_cornersr+  ¾  sÅ  € õ" ”.Ð"MÐ"MÀÐ"MÑ"MÔ"MÐN€Kå”} [µ"´+Ñ>Ô>ÐNˆˆÅBÄJð ð ˜!Œ_˜QÔ€FÝŒn˜\°Ð2Ñ2Ô2€Gõ
 
„}�[¥"¤*Ñ-Ô-ð 
Ý”jØ�NŠN�6Ñ"Ô" V§]¢]µ6Ñ%:Ô%:Ñ:Å"Ä*ð
ñ 
ô 
ˆˆð —n’n¥R¤Z°e�nÑ<Ô<¸v¿}º}ÝŒJ˜Uð @Mñ @
ô @
ñ 
ˆð ˜a”. ;¨q¤>Ñ1€KÝ•"”*�U ;¨q¤>Ñ2Ô2µE¸+Àa¼.Ñ4IÔ4IÑJÔJÑKÔK€EÝ•R”V˜E‘]”]Ñ#Ô#¥U­2¬6°%©=¬=Ñ%9Ô%9ˆ€Cõ Œx˜# ˜t˜ s¨C jÐ1½¼ÐDÑDÔD€HØ (Ñ*€MÝ�-    1 Ô%×)Ò)Ñ+Ô+Ñ,Ô,€EÝ�-    1 Ô%×)Ò)Ñ+Ô+Ñ,Ô,€EÝ�-    1 Ô%×)Ò)Ñ+Ô+Ñ,Ô,€EÝ�-    1 Ô%×)Ò)Ñ+Ô+Ñ,Ô,€Eõ Œx˜#˜s˜ s d¨C [Ð1½¼ÐDÑDÔD€Hå
ŒØ�Uˆ^˜e U˜^¨e°U¨^¸eÀU¸^ÐLÝ”*ð	
ñ 	
ô 	
ð ñ		ð õ •”�BœKÔ(¨6°F©?×*BÒ*BÀ<Ñ*PÔ*PÑQÔQÐQrV   r€  r|  c           	     ón	  ‡— t          | ¦  «        dk    r| d         S t          j        d„ | D ¦   «         t          j        ¬¦  «        }t	          t          j        |¦  «        ¦  «        }| |         }t          j        d„ | D ¦   «         ¦  «        }|dd…df         |dd…df         z
  }|dd…df         |dd…df         z
  }|                     t          j        d	¬
¦  «        |                     t          j        d	¬
¦  «        z  }|j        �tt          | 	                    ¦   «         ¦  «        }|dk    rEt          j        t          t          j
        ||¦  «        |z  ¦  «        gt          j        ¬¦  «        }	n
|j        }	nd}	t          |j        v }
|
ràg }| D ]Š}t          j        |j        t                   ¦  «        }|j        dk    s|j        dd…         dk    rt#          d|j        › �¦  «        ‚|                     |d                              dd¦  «        ¦  «         Œ‹t)          |¦  «        }t+          |t          j                 ¦  «        }i |j        ¥t          |t          j                 i¥}nœt          j        |dd…df                              ¦   «         |dd…df                              ¦   «         |dd…df                              ¦   «         |dd…df                              ¦   «         ggt          j        ¬¦  «        }|j        }d„ | D ¦   «         }|�rat3          d„ |D ¦   «         ¦  «        røt5          t6          t8                   |¦  «        }|d         j        Št=          ˆfd„|D ¦   «         ¦  «        rt#          d¦  «        ‚t          j        ‰t@          ¬¦  «        }|D ]}|| !                    ¦   «         d         z  }Œ tE          |t          j                 ¦  «                             t          j        ¦  «        }t9          j#        |t          j                 |‰¬¦  «        }nRd„ |D ¦   «         }t          j$         %                    t          j&        |d¬¦  «        ¦  «        t          j                 }nd}tO          d„ | D ¦   «         ¦  «        }tQ          |||	|j)        |j*        ||¬¦  «        S )aÉ  Merge a group of single-object Detections into one merged detection.

    Used internally by :meth:`Detections.with_nmm` to combine each merge group
    into a single output detection. The highest-confidence detection is the
    "winner" whose class_id, tracker_id, and data fields are preserved.

    Args:
        detections: List of Detections, each containing exactly one object.

    Returns:
        A single merged Detections object of length 1.
    r¬   r   c                ó:   — g | ]}|j         �|j         d         nd‘ŒS )Nr   g        )rH   r‚  s     rT   rŠ   z*_merge_detection_group.<locals>.<listcomp>  s)   € ÐRÐRÐRÀ!˜AœLÐ4ˆŒ�aŒˆ¸#ÐRÐRÐRrV   r�   c                ó(   — g | ]}|j         d          ‘ŒS rf  rS  r‚  s     rT   rŠ   z*_merge_detection_group.<locals>.<listcomp>  s   € Ð7Ð7Ð7 q˜œ œÐ7Ð7Ð7rV   Nr«   r­   Fr  rh  z'corners must have shape (N, 4, 2); got rw   c                ó*   — g | ]}|j         ®	|j         ‘ŒS ri   r†  r‚  s     rT   rŠ   z*_merge_detection_group.<locals>.<listcomp>G  s!   € Ð>Ð>Ð>˜¨1¬6Ð+=ˆQŒVÐ+=Ð+=Ð+=rV   c              3  ó@   K  — | ]}t          |t          ¦  «        V — Œd S ri   r‹  rI  s     rT   rë   z)_merge_detection_group.<locals>.<genexpr>I  s,   è è € Ð9Ð9¨a�z˜!�[Ñ)Ô)Ð9Ð9Ð9Ð9Ð9Ð9rV   c              3  ó.   •K  — | ]}|j         ‰k    V — Œd S ri   )r�  )r‰   rJ  r�  s     €rT   rë   z)_merge_detection_group.<locals>.<genexpr>L  s*   øè è € ÐGÐG°A�1”= KÒ/ÐGÐGÐGÐGÐGÐGrV   z=Cannot merge CompactMask objects with different image shapes.rã  c                ód   — g | ]-}t          |t          ¦  «        r|                     ¦   «         n|‘Œ.S r…   )rp   r   Úto_denserI  s     rT   rŠ   z*_merge_detection_group.<locals>.<listcomp>Z  s@   € ð ð ð ØFG¥
¨1­kÑ :Ô :ÐA�—
’
‘”�Àðð ð rV   rì   c                ó   — g | ]	}|j         ‘Œ
S r…   r¨  r‚  s     rT   rŠ   z*_merge_detection_group.<locals>.<listcomp>a  s   € Ð>Ð>Ð>¨a˜qœzÐ>Ð>Ð>rV   r©  )+rZ   rj   r’   rÖ  rW   Úargmaxr}   rH   rµ   ÚsumÚdotr  r   rL   rŸ   rk  r¢   rÅ   r  rî  r+  r   Únewaxisrm  rn  rs   r	   r“  r   r�  r‘  r˜   rc   r3  r   r›  r  r   r  r$   rD   rI   rJ   )r€  r  Ú
winner_idxÚwinnerÚall_xyxyrØ  rÙ  ÚareasÚ
total_arearH   Úhas_obbr  ÚdetÚcÚmerged_cornersrF   rL   r›   rÏ   Ú
union_maskÚcompact_maskÚ
union_xyxyrG   Údense_masksrM   r�  s                            @rT   r  r  ü  sË  ø€ õ ˆ:�„˜!ÒÐØ˜!Œ}Ðå”(ØRÐRÀzÐRÑRÔRÝŒjðñ ô €Kõ •R”Y˜{Ñ+Ô+Ñ,Ô,€JØ˜
Ô#€Fõ ŒxÐ7Ð7¨JÐ7Ñ7Ô7Ñ8Ô8€HØ�a�a�a˜�dŒ^˜h q q q¨! tœnÑ,€FØ�q�q�q˜!�tŒn˜x¨¨¨¨1¨œ~Ñ-€GØ�MŠM�"œ*¨5ˆMÑ1Ô1°G·N²NÝ
Œ
˜ð 5Cñ 5ô 5ñ €Eð
 ÔÐ$Ý˜5Ÿ9š9™;œ;Ñ'Ô'ˆ
Ø˜Š>ˆ>ÝœÝ•r”v˜e [Ñ1Ô1°JÑ>Ñ?Ô?Ð@Ý”jðñ ô ˆJˆJð
  Ô*ˆJˆJàˆ
õ '¨&¬+Ð5€GØð ØˆØð 	4ð 	4ˆCÝ”
˜3œ8Õ$<Ô=Ñ>Ô>ˆAØŒv˜Š{ˆ{˜aœg a b bœk¨VÒ3Ð3Ý Ð!TÈ1Ì7Ð!TÐ!TÑUÔUÐUØ×Ò  !¤§¢¨Q°Ñ 2Ô 2Ñ3Ô3Ð3Ð3Ý+¨LÑ9Ô9ˆÝ ­r¬zÔ :Ñ;Ô;ˆØT�&”+ÐTÕ7¸ÍÌ
Ô9SÐTÐTˆˆõ Œxð ˜Q˜Q˜Q ˜T”N×&Ò&Ñ(Ô(Ø˜Q˜Q˜Q ˜T”N×&Ò&Ñ(Ô(Ø˜Q˜Q˜Q ˜T”N×&Ò&Ñ(Ô(Ø˜Q˜Q˜Q ˜T”N×&Ò&Ñ(Ô(ð	ðõ ”*ð

ñ 

ô 

ˆð Œ{ˆð ?Ð>˜ZÐ>Ñ>Ô>€EØñ ÝÐ9Ð9°5Ð9Ñ9Ô9Ñ9Ô9ð 	YÝ ¥¥kÔ!2°EÑ:Ô:ˆMØ'¨Ô*Ô6ˆKÝÐGÐGÐGÐG¸ÐGÑGÔGÑGÔGð Ý ØSñô ð õ œ +µTÐ:Ñ:Ô:ˆJØ -ð 9ð 9�Ø˜l×3Ò3Ñ5Ô5°aÔ8Ñ8�
�
Ý% jµ´Ô&<Ñ=Ô=×DÒDÅRÄZÑPÔPˆJÝÔ)Ø ¥¤Ô,ØØ'ðñ ô ˆDˆDðð ØKPðñ ô ˆKõ ”=×'Ò'­¬°{ÈÐ(KÑ(KÔ(KÑLÔLÍRÌZÔXˆDˆDàˆåÐ>Ð>°:Ð>Ñ>Ô>Ñ?Ô?€HåØØØØ”ØÔ$ØØðñ ô ð rV   z0.29.0z0.32.0)Údeprecated_inÚ	remove_inÚdetections_1Údetections_2c           	     ó¬  — t          | ¦  «        dk    st          |¦  «        dk    rt          d¦  «        ‚t          | |¦  «         | j        d         }|j        d         }| j        €
|j        €d}n”| j        €J ‚|j        €J ‚|d         |d         z
  |d         |d         z
  z  }|d         |d         z
  |d         |d         z
  z  }|| j        d         z  ||j        d         z  z   ||z   z  }t          j        |g¦  «        }t          j        |dd…         |dd…         ¦  «        \  }}t          j        |dd…         |dd…         ¦  «        \  }	}
t          j        |||	|
gg¦  «        }| j	        €
|j	        €d}net          j
        t          t          j        t                   | j	        ¦  «        t          t          j        t                   |j	        ¦  «        ¦  «        }| j        �|j        €| }n!| j        d         |j        d         k    r| }n|}t          | j        |j        g¦  «        }t#          ||||j        |j        |j        |¬¦  «        S )aw  
    Merges two Detections objects into a single Detections object.
    Assumes each Detections contains exactly one object.

    A `winning` detection is determined based on the confidence score of the two
    input detections. This winning detection is then used to specify which
    `class_id`, `tracker_id`, and `data` to include in the merged Detections object.

    The resulting `confidence` of the merged object is calculated by the weighted
    contribution of each detection to the merged object.
    The bounding boxes and masks of the two input detections are merged into a
    single bounding box and mask, respectively.

    Args:
        detections_1: The first Detections object.
        detections_2: The second Detections object.

    Returns:
        A new Detections object, with merged attributes.

    Raises:
        ValueError: If the input Detections objects do not have exactly 1 detected
            object.

    Example:
        ```python
        from supervision import _cv2 as cv2
        import supervision as sv
        from inference import get_model

        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        model = get_model(model_id="yolov8s-640")

        result = model.infer(image)[0]
        detections = sv.Detections.from_inference(result)

        merged_detections = merge_object_detection_pair(
            detections[0], detections[1])
        ```
    r¬   z6Both Detections should have exactly 1 detected object.r   Nr«   r­   r©  )rZ   rÅ   Ú%_validate_fields_both_defined_or_nonerF   rH   rj   r’   ÚminimumÚmaximumrG   r  r	   r”  r•  r   r$   rM   rD   rI   rJ   rL   )rH  rI  Úxyxy_1Úxyxy_2Úmerged_confidenceÚdetection_1_areaÚdetections_2_areaÚ	merged_x1Ú	merged_y1Ú	merged_x2Ú	merged_y2Úmerged_xyxyÚmerged_maskÚwinning_detectionrM   s                  rT   Ú!merge_inner_detection_object_pairrZ  n  s‚  € õX ˆ<ÑÔ˜AÒÐ¥ \Ñ!2Ô!2°aÒ!7Ð!7ÝÐQÑRÔRÐRå)¨,¸ÑEÔEÐEàÔ˜qÔ!€FØÔ˜qÔ!€FØÔÐ&¨<Ô+BÐ+JØ ÐÐàÔ&Ð2Ð2Ð2ØÔ&Ð2Ð2Ð2Ø" 1œI¨¨q¬	Ñ1°f¸Q´iÀ&ÈÄ)Ñ6KÑLÐØ# AœY¨°¬Ñ2°v¸a´yÀ6È!Ä9Ñ7LÑMÐà˜|Ô6°qÔ9Ñ9Ø ,Ô"9¸!Ô"<Ñ<ñ=àÐ 1Ñ1ñ3Ðõ œHÐ&7Ð%8Ñ9Ô9Ðåœ: f¨R¨a¨R¤j°&¸¸!¸´*Ñ=Ô=Ñ€IˆyÝœ: f¨Q¨R¨R¤j°&¸¸¸´*Ñ=Ô=Ñ€IˆyÝ”(˜Y¨	°9¸iÐHÐIÑJÔJ€KàÔÐ  \Ô%6Ð%>Øˆˆå”mÝ•”�SÔ! <Ô#4Ñ5Ô5Ý•”�SÔ! <Ô#4Ñ5Ô5ñ
ô 
ˆð
 ÔÐ&¨,Ô*AÐ*IØ(ÐÐØ	Ô	  Ô	# |Ô'>¸qÔ'AÒ	AÐ	AØ(ÐÐà(Ðå˜|Ô4°lÔ6KÐLÑMÔM€HåØØØ$Ø"Ô+Ø$Ô/ØÔ#Øðñ ô ð rV   rð  rñ  rµ   rò  r&   c                óŽ   — | d         }| dd…         D ]1}t          |||¦  «        d         }||k     r nt          ||¦  «        }Œ2|S )á=  
    Given N detections each of length 1 (exactly one object inside), combine them into a
    single detection object of length 1. The contained inner object will be the merged
    result of all the input detections.

    For example, this lets you merge N boxes into one big box, N masks into one mask,
    etc.
    r   r¬   N)r   rZ  )r€  rñ  rò  rH  rI  Úious         rT   Úmerge_inner_detections_objectsr^  Î  sa   € ð ˜a”=€LØ" 1 2 2œð Uð UˆÝ˜L¨,¸ÑGÔGÈÔJˆØ�Š?ˆ?ØˆEÝ8¸À|ÑTÔTˆˆØÐrV   c                ó,   — t          t          | ¦  «        S )r\  )r   rZ  )r€  s    rT   Ú*merge_inner_detections_objects_without_iour`  å  s   € õ Õ3°ZÑ@Ô@Ð@rV   rO   c                ó¨   — t          | ¦  «        }|D ]?}t          | |¦  «        }t          ||¦  «        }|du |du k    rt          d|› d�¦  «        ‚Œ@dS )a  
    Verify that for each optional field in the Detections, both instances either have
    the field set to None or both have it set to non-None values.

    `data` field is ignored.

    Raises:
        ValueError: If one field is None and the other is not, for any of the fields.
    NzField 'z=' should be consistently None or not None in both Detections.)r>   r	  rÅ   )rH  rI  Ú
attributesÚ	attributeÚvalue_1Úvalue_2s         rT   rK  rK  ô  sˆ   € õ (¨Ñ5Ô5€JØð ð ˆ	Ý˜,¨	Ñ2Ô2ˆÝ˜,¨	Ñ2Ô2ˆà�tˆO ¨D Ò1Ð1Ýð˜)ð ð ð ñô ð ð 2ð	ð rV   )ÚtargetrF  rG  c                ó&   — t          | |¦  «         d S ri   )r   )rH  rI  s     rT   Ú$validate_fields_both_defined_or_nonerh    s   € õ 	ˆ�|Ñ$Ô$Ð$Ð$Ð$rV   )r  r  rN   rë  )r€  r|  rN   rD   )rH  rD   rI  rD   rN   rD   )r€  r|  rñ  rµ   rò  r&   rN   rD   )rH  rD   rI  rD   rN   rO   )aÚ
__future__r   r/  Úcollections.abcr   Údataclassesr   r   Ú	functoolsr   Útypingr   r	   r|   rj   Únumpy.typingr”  Ú	deprecater
   r   Úsupervision.configr   r   Ú(supervision.detection._geometry_dispatchr   r   rä  r   Ú(supervision.detection.tools.transformersr   r   r   Ú#supervision.detection.utils._typingr   r   r   Ú!supervision.detection.utils.boxesr   r   r   Ú&supervision.detection.utils.convertersr   r   r   r   Ú$supervision.detection.utils.internalr   r    r!   r"   r#   r$   r%   Ú'supervision.detection.utils.iou_and_nmsr&   r'   r(   r)   r*   r+   r,   r-   r.   Ú!supervision.detection.utils.masksr/   Úsupervision.detection.vlmr0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   Úsupervision.geometry.corer<   Úsupervision.utils.internalr=   r>   r?   Úsupervision.validatorsr@   rA   rB   rD   r+  r  rZ  r  r^  r`  rK  rh  r…   rV   rT   ú<module>r}     s/  ðØ "Ð "Ð "Ð "Ð "Ð "à €€€Ø $Ð $Ð $Ð $Ð $Ð $Ø (Ð (Ð (Ð (Ð (Ð (Ð (Ð (Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð à Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø &Ð &Ð &Ð &Ð &Ð &Ð &Ð &ðð ð ð ð ð ð ð ð SÐ RÐ RÐ RÐ RÐ RÐ RÐ RØ :Ð :Ð :Ð :Ð :Ð :ðð ð ð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ðð ð ð ð ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð /Ð .Ð .Ð .Ð .Ð .ðð ð ð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð ð`1(ð `1(ð `1(ð `1(ð `1(ñ `1(ô `1(ñ „ð`1(ðFc;Rð ;Rð ;Rð ;Rð|oð oð oð oðd €˜(¨hÐ7Ñ7Ô7ð\ð \ð \ñ 8Ô7ð\ð~ €˜(¨hÐ7Ñ7Ô7ð Ø$1Ô$5ðð ð ð ñ 8Ô7ðð, €˜(¨hÐ7Ñ7Ô7ðAð Að Añ 8Ô7ðAðð ð ð ð0 €Ø0ØØðñ ô ð
%ð %ð %ñô ð
%ð %ð %rV   