
    /jK                        d dl mZ d dlmZ d dlmZ d dlmZ d dlZ	ddl
mZmZmZmZmZmZmZ d Z ed	          Z ed
          Zg dZdZ G d d          Z G d d          ZdS )    )annotations)abc)repeat)NumberN   )	ltwh2xywh	ltwh2xyxyresample_segments	xywh2ltwh	xywh2xyxy	xyxy2ltwh	xyxy2xywhc                      fd}|S )zOCreate a function that converts input to n-tuple by repeating singleton values.c                v    t          | t          j                  r| nt          t	          |                     S )zDParse input to return n-tuple by repeating singleton values n times.)
isinstancer   Iterabletupler   )xns    _/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/utils/instance.pyparsez_ntuple.<locals>.parse   s.    q#,//HqqU6!Q<<5H5HH     )r   r   s   ` r   _ntupler      s(    I I I I I Lr         )xyxyxywhltwh)Bboxes	Instancesc                  f    e Zd ZdZddd	Zdd
ZddZd dZd!dZd"dZ	e
d#d$d            Zd%dZdS )&r    aF  A class for handling bounding boxes in multiple formats.

    The class supports various bounding box formats like 'xyxy', 'xywh', and 'ltwh' and provides methods for format
    conversion, scaling, and area calculation. Bounding box data should be provided as numpy arrays.

    Attributes:
        bboxes (np.ndarray): The bounding boxes stored in a 2D numpy array with shape (N, 4).
        format (str): The format of the bounding boxes ('xyxy', 'xywh', or 'ltwh').

    Methods:
        convert: Convert bounding box format from one type to another.
        areas: Calculate the area of bounding boxes.
        mul: Multiply bounding box coordinates by scale factor(s).
        add: Add offset to bounding box coordinates.
        concatenate: Concatenate multiple Bboxes objects.

    Examples:
        Create bounding boxes in YOLO format
        >>> bboxes = Bboxes(np.array([[100, 50, 150, 100]]), format="xywh")
        >>> bboxes.convert("xyxy")
        >>> print(bboxes.areas())

    Notes:
        This class does not handle normalization or denormalization of bounding boxes.
    r   bboxes
np.ndarrayformatstrreturnNonec                    |t           v sJ d| dt                        |j        dk    r|dddf         n|}|j        dk    sJ |j        d         dk    sJ || _        || _        dS )a  Initialize the Bboxes class with bounding box data in a specified format.

        Args:
            bboxes (np.ndarray): Array of bounding boxes with shape (N, 4) or (4,).
            format (str): Format of the bounding boxes, one of 'xyxy', 'xywh', or 'ltwh'.
        Invalid bounding box format: , format must be one of r   Nr   r   )_formatsndimshaper#   r%   )selfr#   r%   s      r   __init__zBboxes.__init__>   s     !!!#m6#m#mck#m#m!!!$*K1$4$4aaa&{a|A!####r   c                <   |t           v sJ d| dt                        | j        |k    rdS | j        dk    r|dk    rt          nt          }n4| j        dk    r|dk    rt          nt
          }n|dk    rt          nt          } || j                  | _        || _        dS )zConvert bounding box format from one type to another.

        Args:
            format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
        r*   r+   Nr   r   )	r,   r%   r   r   r   r   r	   r   r#   )r/   r%   funcs      r   convertzBboxes.convertL   s     !!!#m6#m#mck#m#m!!!;&  F[F"" && 0 099iDD[F"" && 0 099iDD && 0 099iDd4;''r   c                    | j         dk    rG| j        dddf         | j        dddf         z
  | j        dddf         | j        dddf         z
  z  n"| j        dddf         | j        dddf         z  S )%Calculate the area of bounding boxes.r   Nr   r      r   )r%   r#   r/   s    r   areaszBboxes.areas^   s     {f$$ [AQQQT!22t{111a47H4;WXWXWXZ[W[K\7\]]QQQT"T[A%66	
r   scaleint | tuple | listc                   t          |t                    rt          |          }t          |t          t          f          sJ t          |          dk    sJ | j        dddfxx         |d         z  cc<   | j        dddfxx         |d         z  cc<   | j        dddfxx         |d         z  cc<   | j        dddfxx         |d         z  cc<   dS )zMultiply bounding box coordinates by scale factor(s).

        Args:
            scale (int | tuple | list): Scale factor(s) for four coordinates. If int, the same scale is applied to all
                coordinates.
        r   Nr   r   r   r6   r   r   	to_4tupler   listlenr#   )r/   r9   s     r   mulz
Bboxes.mulf   s     eV$$ 	%e$$E%%/////5zzQAAAqDU1X%AAAqDU1X%AAAqDU1X%AAAqDU1X%r   offsetc                   t          |t                    rt          |          }t          |t          t          f          sJ t          |          dk    sJ | j        dddfxx         |d         z  cc<   | j        dddfxx         |d         z  cc<   | j        dddfxx         |d         z  cc<   | j        dddfxx         |d         z  cc<   dS )zAdd offset to bounding box coordinates.

        Args:
            offset (int | tuple | list): Offset(s) for four coordinates. If int, the same offset is applied to all
                coordinates.
        r   Nr   r   r   r6   r<   )r/   rA   s     r   addz
Bboxes.addv   s    ff%% 	'v&&F&5$-000006{{aAAAqDVAY&AAAqDVAY&AAAqDVAY&AAAqDVAY&r   intc                *    t          | j                  S )z$Return the number of bounding boxes.r?   r#   r7   s    r   __len__zBboxes.__len__       4;r   r   
boxes_listlist[Bboxes]axisc                :   t          |t          t          f          sJ |s | t          j        d                    S t          d |D                       sJ t          |          dk    r|d         S  | t          j        d |D             |                    S )a  Concatenate a list of Bboxes objects into a single Bboxes object.

        Args:
            boxes_list (list[Bboxes]): A list of Bboxes objects to concatenate.
            axis (int, optional): The axis along which to concatenate the bounding boxes.

        Returns:
            (Bboxes): A new Bboxes object containing the concatenated bounding boxes.

        Notes:
            The input should be a list or tuple of Bboxes objects.
        r   c              3  @   K   | ]}t          |t                    V  d S N)r   r    ).0boxs     r   	<genexpr>z%Bboxes.concatenate.<locals>.<genexpr>   s,      AAs:c6**AAAAAAr   r   c                    g | ]	}|j         
S r   r#   rO   bs     r   
<listcomp>z&Bboxes.concatenate.<locals>.<listcomp>   s    "@"@"@18"@"@"@r   rK   )r   r>   r   npemptyallr?   concatenate)clsrI   rK   s      r   r[   zBboxes.concatenate   s     *tUm44444 	$3rx{{###AAjAAAAAAAAz??aa= s2>"@"@Z"@"@"@tLLLMMMr   indexint | np.ndarray | slicec                    t          |t                    r.t          | j        |                             dd                    S | j        |         }|j        dk    sJ d| d            t          |          S )a  Retrieve a specific bounding box or a set of bounding boxes using indexing.

        Args:
            index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired bounding boxes.

        Returns:
            (Bboxes): A new Bboxes object containing the selected bounding boxes.

        Notes:
            When using boolean indexing, make sure to provide a boolean array with the same length as the number of
            bounding boxes.
        r   r   zIndexing on Bboxes with z failed to return a matrix!)r   rD   r    r#   reshaper-   )r/   r]   rU   s      r   __getitem__zBboxes.__getitem__   st     eS!! 	=$+e,44Q;;<<<Kv{{{YuYYY{{{ayyr   N)r   )r#   r$   r%   r&   r'   r(   r%   r&   r'   r(   r'   r$   )r9   r:   r'   r(   )rA   r:   r'   r(   r'   rD   r   )rI   rJ   rK   rD   r'   r    )r]   r^   r'   r    )__name__
__module____qualname____doc__r0   r3   r8   r@   rC   rG   classmethodr[   rb   r   r   r   r    r    #   s         4       $
 
 
 
& & & & ' ' ' '         N N N N [N,     r   r    c                      e Zd ZdZ	 	 	 	 d0d1dZd2dZed3d            Zd4d5dZd6dZ	d6dZ
d7d Zd8d#Zd9d$Zd:d%Zd6d&Zd3d'Zd;d<d(Zd=d)Zed>d?d-            Zed3d.            Zd@d/ZdS )Ar!   a  Container for bounding boxes, segments, and keypoints of detected objects in an image.

    This class provides a unified interface for handling different types of object annotations including bounding boxes,
    segmentation masks, and keypoints. It supports various operations like scaling, normalization, clipping, and format
    conversion.

    Attributes:
        _bboxes (Bboxes): Internal object for handling bounding box operations.
        keypoints (np.ndarray): Keypoints with shape (N, 17, 3) in format (x, y, visible).
        normalized (bool): Flag indicating whether the bounding box coordinates are normalized.
        segments (np.ndarray): Segments array with shape (N, M, 2) after resampling.

    Methods:
        convert_bbox: Convert bounding box format.
        scale: Scale coordinates by given factors.
        denormalize: Convert normalized coordinates to absolute coordinates.
        normalize: Convert absolute coordinates to normalized coordinates.
        add_padding: Add padding to coordinates.
        flipud: Flip coordinates vertically.
        fliplr: Flip coordinates horizontally.
        clip: Clip coordinates to stay within image boundaries.
        remove_zero_area_boxes: Remove boxes with zero area.
        update: Update instance variables.
        concatenate: Concatenate multiple Instances objects.

    Examples:
        Create instances with bounding boxes and segments
        >>> instances = Instances(
        ...     bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]),
        ...     segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])],
        ...     keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]),
        ... )
    Nr   Tr#   r$   segments	keypointsbbox_formatr&   
normalizedboolr'   r(   c                \    t          ||          | _        || _        || _        || _        dS )a  Initialize the Instances object with bounding boxes, segments, and keypoints.

        Args:
            bboxes (np.ndarray): Bounding boxes with shape (N, 4).
            segments (np.ndarray, optional): Segmentation masks.
            keypoints (np.ndarray, optional): Keypoints with shape (N, 17, 3) in format (x, y, visible).
            bbox_format (str): Format of bboxes.
            normalized (bool): Whether the coordinates are normalized.
        )r#   r%   N)r    _bboxesrn   rp   rm   )r/   r#   rm   rn   ro   rp   s         r   r0   zInstances.__init__   s1    " VK@@@"$ r   r%   c                <    | j                             |           dS )zConvert bounding box format.

        Args:
            format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
        r%   N)rs   r3   )r/   r%   s     r   convert_bboxzInstances.convert_bbox   s#     	F+++++r   c                4    | j                                         S )r5   )rs   r8   r7   s    r   
bbox_areaszInstances.bbox_areas   s     |!!###r   Fscale_wfloatscale_h	bbox_onlyc                   | j                             ||||f           |rdS | j        dxx         |z  cc<   | j        dxx         |z  cc<   | j        ,| j        dxx         |z  cc<   | j        dxx         |z  cc<   dS dS )zScale coordinates by given factors.

        Args:
            scale_w (float): Scale factor for width.
            scale_h (float): Scale factor for height.
            bbox_only (bool, optional): Whether to scale only bounding boxes.
        r9   N.r   .r   )rs   r@   rm   rn   )r/   ry   r{   r|   s       r   r9   zInstances.scale   s     	'7CDDD 	Ff(f(>%N6"""g-"""N6"""g-""""" &%r   wrD   hc                   | j         sdS | j                            ||||f           | j        dxx         |z  cc<   | j        dxx         |z  cc<   | j        *| j        dxx         |z  cc<   | j        dxx         |z  cc<   d| _         dS )zConvert normalized coordinates to absolute coordinates.

        Args:
            w (int): Image width.
            h (int): Image height.
        Nr~   r   r   Frp   rs   r@   rm   rn   r/   r   r   s      r   denormalizezInstances.denormalize  s      	F1a|,,,f"f">%N6"""a'"""N6"""a'"""r   c                2   | j         rdS | j                            d|z  d|z  d|z  d|z  f           | j        dxx         |z  cc<   | j        dxx         |z  cc<   | j        *| j        dxx         |z  cc<   | j        dxx         |z  cc<   d| _         dS )zConvert absolute coordinates to normalized coordinates.

        Args:
            w (int): Image width.
            h (int): Image height.
        Nr   r~   r   r   Tr   r   s      r   	normalizezInstances.normalize  s     ? 	FAq1ua!eQU;<<<f"f">%N6"""a'"""N6"""a'"""r   padwpadhc                    | j         r
J d            | j                            ||||f           | j        dxx         |z  cc<   | j        dxx         |z  cc<   | j        ,| j        dxx         |z  cc<   | j        dxx         |z  cc<   dS dS )zAdd padding to coordinates.

        Args:
            padw (int): Padding width.
            padh (int): Padding height.
        z1you should add padding with absolute coordinates.)rA   r   r   N)rp   rs   rC   rm   rn   )r/   r   r   s      r   add_paddingzInstances.add_padding.  s     ?WW$WWW"tT4 8999f%f%>%N6"""d*"""N6"""d*""""" &%r   r]   r^   c                    t          | j                  r| j        |         n| j        }| j        | j        |         nd}| j        |         }| j        j        }t          ||||| j                  S )a  Retrieve a specific instance or a set of instances using indexing.

        Args:
            index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired instances.

        Returns:
            (Instances): A new Instances object containing the selected boxes, segments, and keypoints if present.

        Notes:
            When using boolean indexing, make sure to provide a boolean array with the same length as the number of
            instances.
        N)r#   rm   rn   ro   rp   )r?   rm   rn   r#   rs   r%   r!   rp   )r/   r]   rm   rn   r#   ro   s         r   rb   zInstances.__getitem__=  s|     ,/t}+=+=P4=''4=-1^-GDN5))T	U#l)#
 
 
 	
r   c                   | j         j        dk    ri| j        dddf                                         }| j        dddf                                         }||z
  | j        dddf<   ||z
  | j        dddf<   n || j        dddf         z
  | j        dddf<   || j        d         z
  | j        d<   | j        || j        d         z
  | j        d<   dS dS )zWFlip coordinates vertically.

        Args:
            h (int): Image height.
        r   Nr   r6   r   rs   r%   r#   copyrm   rn   )r/   r   y1y2s       r   flipudzInstances.flipudV       <&((QQQT"''))BQQQT"''))B !BDK1 !BDK1 !DK1$5 5DK1 !DM&$9 9f>%%&)?%?DN6""" &%r   c                   | j         j        dk    ri| j        dddf                                         }| j        dddf                                         }||z
  | j        dddf<   ||z
  | j        dddf<   n || j        dddf         z
  | j        dddf<   || j        d         z
  | j        d<   | j        || j        d         z
  | j        d<   dS dS )zXFlip coordinates horizontally.

        Args:
            w (int): Image width.
        r   Nr   r   r   r   )r/   r   x1x2s       r   fliplrzInstances.fliplrg  r   r   c                Z   | j         j        }|                     d           | j        ddddgf                             d|          | j        ddddgf<   | j        ddddgf                             d|          | j        ddddgf<   |dk    r|                     |           | j        d                             d|          | j        d<   | j        d	                             d|          | j        d	<   | j        d
| j        d         | j        d         dk     | j        d         |k    z  | j        d	         dk     z  | j        d	         |k    z  <   | j        d                             d|          | j        d<   | j        d	                             d|          | j        d	<   dS dS )zClip coordinates to stay within image boundaries.

        Args:
            w (int): Image width.
            h (int): Image height.
        r   ru   Nr   r   r   r6   r   r   g        ).r   )rs   r%   rv   r#   cliprm   rn   )r/   r   r   
ori_formats       r   r   zInstances.clipx  s    \(
(((!%QQQAY!7!<!<Q!B!BAAA1vI!%QQQAY!7!<!<Q!B!BAAA1vIZ000 $f 5 : :1a @ @f $f 5 : :1a @ @f>%  N6"'!+>&)A-/>&)A-/ >&)A-/ &*^F%;%@%@A%F%FDN6"%)^F%;%@%@A%F%FDN6""" &%r   c                    | j         dk    }t          |          sX| j        |         | _        | j        &t	          | j                  r| j        |         | _        | j        | j        |         | _        |S )zRemove zero-area boxes, i.e. after clipping some boxes may have zero width or height.

        Returns:
            (np.ndarray): Boolean array indicating which boxes were kept.
        r   )rx   rZ   rs   rm   r?   rn   )r/   goods     r   remove_zero_area_boxesz Instances.remove_zero_area_boxes  sl     "4yy 	6<-DL}(S-?-?( $d 3~)!%!5r   c                n    t          || j        j                  | _        ||| _        |	|| _        dS dS )zUpdate instance variables.

        Args:
            bboxes (np.ndarray): New bounding boxes.
            segments (np.ndarray, optional): New segments.
            keypoints (np.ndarray, optional): New keypoints.
        ru   N)r    rs   r%   rm   rn   )r/   r#   rm   rn   s       r   updatezInstances.update  sC     fT\-@AAA$DM &DNNN ! r   c                *    t          | j                  S )zReturn the number of instances.rF   r7   s    r   rG   zInstances.__len__  rH   r   r   instances_listlist[Instances]c                  
 t          |t          t          f          sJ |s | t          j        d                    S t          d |D                       sJ t          |          dk    r|d         S |d         j        du}|d         j        j	        }|d         j
        }t          j        d |D             |          }d |D             }t          t          |                    dk    r2t          |          
t          j        
fd|D             |          }n t          j        d	 |D             |          }|r t          j        d
 |D             |          nd}	 | |||	||          S )a  Concatenate a list of Instances objects into a single Instances object.

        Args:
            instances_list (list[Instances]): A list of Instances objects to concatenate.
            axis (int, optional): The axis along which the arrays will be concatenated.

        Returns:
            (Instances): A new Instances object containing the concatenated bounding boxes, segments, and keypoints if
                present.

        Notes:
            The `Instances` objects in the list should have the same properties, such as the format of the bounding
            boxes, whether keypoints are present, and if the coordinates are normalized.
        r   c              3  @   K   | ]}t          |t                    V  d S rN   )r   r!   )rO   instances     r   rQ   z(Instances.concatenate.<locals>.<genexpr>  s,      RRx:h	22RRRRRRr   r   Nc                    g | ]	}|j         
S r   rS   )rO   inss     r   rV   z)Instances.concatenate.<locals>.<listcomp>  s    #I#I#I3CJ#I#I#Ir   rW   c                2    g | ]}|j         j        d          S )r   )rm   r.   rT   s     r   rV   z)Instances.concatenate.<locals>.<listcomp>  s"    ???11:#A&???r   c                    g | ][}t          |j                  r"t          t          |j                            n"t	          j        d dft          j                  \S )r   r   )dtype)r?   rm   r
   r>   rX   zerosfloat32)rO   rU   max_lens     r   rV   z)Instances.concatenate.<locals>.<listcomp>  sm         1:E%d1:&6&6@@@1gq/DDD  r   c                    g | ]	}|j         
S r   )rm   rT   s     r   rV   z)Instances.concatenate.<locals>.<listcomp>  s    *N*N*N!1:*N*N*Nr   c                    g | ]	}|j         
S r   )rn   rT   s     r   rV   z)Instances.concatenate.<locals>.<listcomp>  s    'L'L'L'L'L'Lr   )r   r>   r   rX   rY   rZ   r?   rn   rs   r%   rp   r[   	frozensetmax)r\   r   rK   use_keypointro   rp   	cat_boxesseg_lencat_segmentscat_keypointsr   s             @r   r[   zInstances.concatenate  s     .4-88888 	$3rx{{###RR>RRRRRRRR~!##!!$$%a(2$>$Q'/6#A&1
N#I#I.#I#I#IPTUUU	?????y!!""Q&&'llG>    ,	     LL >*N*N~*N*N*NUYZZZL\hr'L'L^'L'L'LSWXXXXnrs9lM;
SSSr   c                    | j         j        S )zReturn bounding boxes.)rs   r#   r7   s    r   r#   zInstances.bboxes  s     |""r   c                   ddi}g }| j                                         D ]D\  }}|                    ||          }|dk    r| j        }||                    | d|           Ed                    d                    |                    S )z7Return a string representation of the Instances object.rs   r#   N=zInstances({})
)__dict__itemsgetr#   appendr%   join)r/   attr_mappartskeyvaluenames         r   __repr__zInstances.__repr__  s     x(---// 	2 	2JC<<S))Dx 00u00111%%dii&6&6777r   )NNr   T)r#   r$   rm   r$   rn   r$   ro   r&   rp   rq   r'   r(   rc   rd   )F)ry   rz   r{   rz   r|   rq   )r   rD   r   rD   r'   r(   )r   rD   r   rD   r'   r(   )r]   r^   r'   r!   )r   rD   r'   r(   )r   rD   r'   r(   )NN)r#   r$   rm   r$   rn   r$   re   rf   )r   r   r'   r!   )r'   r&   )rg   rh   ri   rj   r0   rv   propertyrx   r9   r   r   r   rb   r   r   r   r   r   rG   rk   r[   r#   r   r   r   r   r!   r!      s          J  $ $!! ! ! ! !,, , , , $ $ $ X$. . . . ."       "   "+ + + +
 
 
 
2@ @ @ @"@ @ @ @"G G G G4   ' ' ' ' '        +T +T +T +T [+TZ # # # X#8 8 8 8 8 8r   r!   )
__future__r   collectionsr   	itertoolsr   numbersr   numpyrX   opsr   r	   r
   r   r   r   r   r   	to_2tupler=   r,   __all__r    r!   r   r   r   <module>r      s;   # " " " " "                       d d d d d d d d d d d d d d d d d d   GAJJ	GAJJ	
 $##
!O O O O O O O Od|8 |8 |8 |8 |8 |8 |8 |8 |8 |8r   