
    |hvH                         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y)    )abc)repeat)Number)ListN   )	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                 f    t        | t        j                        r| S t        t	        |             S )zDParse input to return n-tuple by repeating singleton values n times.)
isinstancer   Iterabletupler   )xns    Y/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/instance.pyparsez_ntuple.<locals>.parse   s&    q#,,/qHU6!Q<5HH     )r   r   s   ` r   _ntupler      s    I Lr         )xyxyxywhltwh)Bboxes	Instancesc                   b    e Zd ZdZdddZd Zd Zd Zd Zd	 Z	e
dd
ed    dd fd       ZddZy)r    aK  
    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.
    returnNc                     |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 || _        || _        y)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shapebboxesformat)selfr*   r+   s      r   __init__zBboxes.__init__>   sx     !m%B6(Jbckbl#mm!$*KK1$4a&{{a||A!###r   c                 8   |t         v sJ d| dt                 | j                  |k(  ry| j                  dk(  r|dk(  rt        nt        }n2| j                  dk(  r|dk(  rt        nt
        }n|dk(  rt        nt        } || j                        | _        || _        y)z
        Convert 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.convertM   s     !m%B6(Jbckbl#mm!;;& [[F" && 09iD[[F" && 09iD && 09iD4;;'r   c                    | j                   dk(  rO| j                  dddf   | j                  dddf   z
  | j                  dddf   | j                  dddf   z
  z  S | 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QT!22t{{1a47H4;;WXZ[W[K\7\]	
 QT"T[[A%66	
r   c                 z   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<   y)z
        Multiply 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   r3   r   r   	to_4tupler   listlenr*   )r,   scales     r   mulz
Bboxes.mulh   s     eV$e$E%%///5zQAqDU1X%AqDU1X%AqDU1X%AqDU1X%r   c                 z   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<   y)z
        Add 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   r3   r7   )r,   offsets     r   addz
Bboxes.addy   s     ff%v&F&5$-0006{aAqDVAY&AqDVAY&AqDVAY&AqDVAY&r   c                 ,    t        | j                        S )z$Return the number of bounding boxes.r:   r*   r4   s    r   __len__zBboxes.__len__       4;;r   
boxes_listc                 .   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 cg c]  }|j                   c}|            S c c}w )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                y wN)r   r    ).0boxs     r   	<genexpr>z%Bboxes.concatenate.<locals>.<genexpr>   s     As:c6*A   r   axis)	r   r9   r   npemptyallr:   concatenater*   )clsrD   rM   bs       r   rQ   zBboxes.concatenate   s     *tUm444rxx{##AjAAAAz?aa= 2>>Z"@188"@tLMM"@s   2Bc                     t        |t              r(t        | j                  |   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   intr    r*   reshaper(   )r,   indexrS   s      r   __getitem__zBboxes.__getitem__   sg     eS!$++e,44Q;<<KKvv{Y6ug=XYY{ayr   )r   r#   Nr   )r#   r    )__name__
__module____qualname____doc__r-   r0   r5   r<   r?   rB   classmethodr   rQ   rY   r   r   r   r    r    "   sT    6&
&"'"  NT(^ N N N.r   r    c                       e Zd ZdZdddZd Zed        ZddZd Z	d	 Z
d
 ZddZd Zd Zd Zd ZddZd Zedded    dd fd       Zed        Zy)r!   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#   c                 R    t        ||      | _        || _        || _        || _        y)a  
        Initialize the Instances object with bounding boxes, segments, and keypoints.

        Args:
            bboxes (np.ndarray): Bounding boxes with shape (N, 4).
            segments (List | 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    _bboxes	keypoints
normalizedsegments)r,   r*   rf   rd   bbox_formatre   s         r   r-   zInstances.__init__   s'     VK@"$ r   c                 <    | j                   j                  |       y)z
        Convert bounding box format.

        Args:
            format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
        r+   N)rc   r0   )r,   r+   s     r   convert_bboxzInstances.convert_bbox   s     	F+r   c                 6    | j                   j                         S )r2   )rc   r5   r4   s    r   
bbox_areaszInstances.bbox_areas   s     ||!!##r   c                    | j                   j                  ||||f       |ry| 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<   yy)z
        Scale 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.
        r;   N.r   .r   )rc   r<   rf   rd   )r,   scale_wscale_h	bbox_onlys       r   r;   zInstances.scale   s     	'7CDf(f(>>%NN6"g-"NN6"g-" &r   c                 <   | j                   sy| j                  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| _         y)z
        Convert normalized coordinates to absolute coordinates.

        Args:
            w (int): Image width.
            h (int): Image height.
        Nrn   ro   rp   Fre   rc   r<   rf   rd   r,   whs      r   denormalizezInstances.denormalize  s     1a|,f"f">>%NN6"a'"NN6"a'"r   c                 T   | j                   ry| j                  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| _         y)z
        Convert absolute coordinates to normalized coordinates.

        Args:
            w (int): Image width.
            h (int): Image height.
        Nr   rn   ro   rp   Tru   rv   s      r   	normalizezInstances.normalize!  s     ??Aq1ua!eQU;<f"f">>%NN6"a'"NN6"a'"r   c                 <   | j                   rJ d       | j                  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<   yy)z
        Add padding to coordinates.

        Args:
            padw (int): Padding width.
            padh (int): Padding height.
        z1you should add padding with absolute coordinates.)r>   ro   rp   N)re   rc   r?   rf   rd   )r,   padwpadhs      r   add_paddingzInstances.add_padding3  s     ??W$WW"tT4 89f%f%>>%NN6"d*"NN6"d*" &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*   rf   rd   rg   re   )r:   rf   rd   r*   rc   r+   r!   re   )r,   rX   rf   rd   r*   rg   s         r   rY   zInstances.__getitem__C  sy     ,/t}}+=4=='4==-1^^-GDNN5)T	U#ll))#
 	
r   c                    | j                   j                  dk(  ro| j                  dddf   j                         }| j                  dddf   j                         }||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<   yy)z`
        Flip coordinates vertically.

        Args:
            h (int): Image height.
        r   Nr   r3   rp   rc   r+   r*   copyrf   rd   )r,   rx   y1y2s       r   flipudzInstances.flipud]       <<&(QT"'')BQT"'')B !BDKK1 !BDKK1 !DKK1$5 5DKK1 !DMM&$9 9f>>%%&)?%?DNN6" &r   c                    | j                   j                  dk(  ro| j                  dddf   j                         }| j                  dddf   j                         }||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<   yy)za
        Flip coordinates horizontally.

        Args:
            w (int): Image width.
        r   Nr   r   ro   r   )r,   rw   x1x2s       r   fliplrzInstances.fliplro  r   r   c                    | j                   j                  }| j                  d       | j                  ddddgf   j	                  d|      | j                  ddddgf<   | j                  ddddgf   j	                  d|      | j                  ddddgf<   |dk7  r| j                  |       | j
                  d   j	                  d|      | j
                  d<   | j
                  d	   j	                  d|      | j
                  d	<   | j                  d
| j                  d   | j                  d   dk  | j                  d   |kD  z  | j                  d	   dk  z  | j                  d	   |kD  z  <   | j                  d   j	                  d|      | j                  d<   | j                  d	   j	                  d|      | j                  d	<   yy)z
        Clip coordinates to stay within image boundaries.

        Args:
            w (int): Image width.
            h (int): Image height.
        r   ri   Nr   r   r   r3   ro   rp   g        ).r   )rc   r+   rj   r*   cliprf   rd   )r,   rw   rx   
ori_formats       r   r   zInstances.clip  s    \\((
(!%QAY!7!<!<Q!BA1vI!%QAY!7!<!<Q!BA1vIZ0 $f 5 : :1a @f $f 5 : :1a @f>>%  NN6"'!+>>&)A-/>>&)A-/ >>&)A-/ &*^^F%;%@%@A%FDNN6"%)^^F%;%@%@A%FDNN6" &r   c                     | j                   dkD  }t        |      s]| j                  |   | _        t        | j                        r| j                  |   | _        | j
                  | j
                  |   | _        |S )z
        Remove 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   )rl   rP   rc   r:   rf   rd   )r,   goods     r   remove_zero_area_boxesz Instances.remove_zero_area_boxes  sd     "4y<<-DL4==! $d 3~~)!%!5r   c                 v    t        || j                  j                        | _        ||| _        ||| _        yy)z
        Update instance variables.

        Args:
            bboxes (np.ndarray): New bounding boxes.
            segments (np.ndarray, optional): New segments.
            keypoints (np.ndarray, optional): New keypoints.
        ri   N)r    rc   r+   rf   rd   )r,   r*   rf   rd   s       r   updatezInstances.update  s;     fT\\-@-@A$DM &DN !r   c                 ,    t        | j                        S )zReturn the number of instances.rA   r4   s    r   rB   zInstances.__len__  rC   r   instances_listc           
      (   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 cg c]  }|j                   c}|      }|D cg c]  }|j                  j                  d    }	}t        t        |	            dkD  rt!        |	      }
t        j                  |D cg c]^  }t        |j                        rt#        t        |j                        |
      n't        j$                  d|
dft        j&                        ` c}|      }n/t        j                  |D cg c]  }|j                   c}|      }|r/t        j                  |D cg c]  }|j                   c}|      nd} | |||||      S c c}w c c}w c c}w c c}w c c}w )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                y wrG   )r   r!   )rH   instances     r   rJ   z(Instances.concatenate.<locals>.<genexpr>  s     Rx:h	2RrK   r   NrL   r   )dtype)r   r9   r   rN   rO   rP   r:   rd   rc   r+   re   rQ   r*   rf   r)   	frozensetmaxr
   zerosfloat32)rR   r   rM   use_keypointrg   re   ins	cat_boxesrS   seg_lenmax_lencat_segmentscat_keypointss                r   rQ   zInstances.concatenate  s   " .4-888rxx{##R>RRRR~!#!!$$%a(22$>$Q'//66#A&11
NN.#I3CJJ#IPTU	0>?11::##A&??y!"Q&'lG>>
 ,	  1:: &d1::&6@1gq/DE L >>~*N!1::*NUYZL\h^'L'LSWXnr9lM;
SS! $J? +O'Ls   )G;	 H  A#H H
Hc                 .    | j                   j                  S )zReturn bounding boxes.)rc   r*   r4   s    r   r*   zInstances.bboxes  s     ||"""r   )NNr   TrZ   )F)r#   r!   )NNr[   )r\   r]   r^   r_   r-   rj   propertyrl   r;   ry   r{   r   rY   r   r   r   r   r   rB   r`   r   rQ   r*   r   r   r   r!   r!      s    !F! , $ $.$ $$+ 
4@$@$G6 '  ,Tk): ,T{ ,T ,T\ # #r   r!   )collectionsr   	itertoolsr   numbersr   typingr   numpyrN   opsr   r	   r
   r   r   r   r   r   	to_2tupler8   r'   __all__r    r!   r   r   r   <module>r      s]         d d d AJ	AJ	
 $
!V Vrv# v#r   