§
    l¬¸j(ˆ  ã                  ó’  — d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mc mZ d dlmZmZ d dlmZ d dlmZ  G d„ dej        ¦  «        ZdQdRd„Z	 	 	 dSdTd„ZdUd„Zd„ Zd „ Zd!„ Zd"„ ZdVdWd'„ZdXdYd,„Zd-„ Z d.„ Z!d/„ Z"d0„ Z#d1„ Z$d2„ Z%d3„ Z&dZd[d6„Z'd\d9„Z(d]d^d;„Z)d<„ Z*	 	 	 d_d`dB„Z+dadbdD„Z,dE„ Z-dcdddJ„Z.dedL„Z/dM„ Z0dN„ Z1da2dO„ Z3dP„ Z4dS )fé    )ÚannotationsN)ÚNOT_MACOS14ÚTORCH_VERSION)Úcheck_version)Úget_torch_device_backendc                  ó4   — e Zd ZdZddd„Zd	„ Zd
„ Zd„ Zd„ ZdS )ÚProfilea  Ultralytics Profile class for timing code execution.

    Use as a decorator with @Profile() or as a context manager with 'with Profile():'. Provides accurate timing
    measurements with accelerator synchronization support.

    Attributes:
        t (float): Accumulated time in seconds.
        device (torch.device): Device used for model inference.
        accelerator (module): PyTorch device module used for timing synchronization.

    Examples:
        Use as a context manager to time code execution
        >>> with Profile() as dt:
        ...     pass  # slow operation here
        >>> str(dt).startswith("Elapsed time is ")
        True

        Use as a decorator to time function execution
        >>> @Profile()
        ... def slow_function():
        ...     time.sleep(0.1)
    ç        NÚtÚfloatÚdeviceútorch.device | Nonec                óÌ   — || _         || _        t          |d|r(t          |¦  «                             d¦  «        d         nd¦  «        }|dv rt          |¦  «        nd| _        dS )zåInitialize the Profile class.

        Args:
            t (float): Initial accumulated time in seconds.
            device (torch.device, optional): Device used for model inference to enable accelerator synchronization.
        Útypeú:r   N>   ÚnpuÚxpuÚcuda)r   r   ÚgetattrÚstrÚsplitr   Úaccelerator)Úselfr   r   Údevice_types       úe/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/utils/ops.pyÚ__init__zProfile.__init__,   so   € ð ˆŒØˆŒÝ˜f fÈ6Ð.[­c°&©k¬k×.?Ò.?ÀÑ.DÔ.DÀQÔ.GÐ.GÐW[Ñ\Ô\ˆØDOÐSiÐDiÐDiÕ3°KÑ@Ô@Ð@ÐosˆÔÐÐó    c                ó8   — |                       ¦   «         | _        | S )zStart timing.)ÚtimeÚstart©r   s    r   Ú	__enter__zProfile.__enter__8   s   € à—Y’Y‘[”[ˆŒ
Øˆr   c                ór   — |                       ¦   «         | j        z
  | _        | xj        | j        z  c_        dS )zStop timing.N)r   r    Údtr   )r   r   ÚvalueÚ	tracebacks       r   Ú__exit__zProfile.__exit__=   s.   € à—)’)‘+”+ ¤
Ñ*ˆŒØˆŒ�$”'ÑˆŒˆˆr   c                ó   — d| j         › d�S )zIReturn a human-readable string representing the accumulated elapsed time.zElapsed time is z s)r   r!   s    r   Ú__str__zProfile.__str__B   s   € à, $¤&Ð,Ð,Ð,Ð,r   c                ót   — | j         �| j                              | j        ¦  «         t          j        ¦   «         S )z@Get current time with accelerator synchronization if applicable.)r   Úsynchronizer   r   Úperf_counterr!   s    r   r   zProfile.timeF   s3   € àÔÐ'ØÔ×(Ò(¨¬Ñ5Ô5Ð5ÝÔ Ñ"Ô"Ð"r   )r
   N)r   r   r   r   )	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r"   r'   r)   r   © r   r   r	   r	      sx   € € € € € ðð ð.
tð 
tð 
tð 
tð 
tðð ð ð
ð ð ð
-ð -ð -ð#ð #ð #ð #ð #r   r	   é€  Úsegmentú
np.ndarrayÚwidthÚintÚheightÚreturnc                óâ  ‡— t          | ¦  «        st          j        d| j        ¬¦  «        S | dd…df         | dd…df         }}|                     ¦   «         |                     ¦   «         |                     ¦   «         |                     ¦   «         f\  }}}}|dk    r1|dk    r+||k    r%||k    rt          j        ||||g| j        ¬¦  «        S t          j        d¦  «        }	t          j        d|d|f| j        ¬¦  «        }
t          j        ||||f| j        ¬¦  «        }| t          j        | dd¬¦  «        | z
  }}t          j        d	d	¬
¦  «        5  |
|dd…|	f         z
  |dd…|	f         z  }|dd…ddd…f         |dd…dd…df         |dd…ddd…f         z  z   }ddd¦  «         n# 1 swxY w Y   |dd…t          j	        d¦  «        d|	z
  f         }t          j        d|dfd|f||ff| j        ¬¦  «        }|  
                    t          j        ¦  «        Št          j        | |dk    |dk    z  ||k    z  ||k    z           ||dk    |dk    z  |dk    z  ||k    z           |ˆfd„|D ¦   «                  f¦  «        }t          |¦  «        rEt          j        g |                     d¦  «        ¢|                     d¦  «        ¢| j        ¬¦  «        nt          j        d| j        ¬¦  «        S )a�  Convert segment coordinates to bounding box coordinates.

    Converts a single segment label to a box label by finding the minimum and maximum x and y coordinates of the polygon
    clipped to the image, so segments crossing the image boundary keep their visible extent. Segments already inside the
    image return immediately without clipping.

    Args:
        segment (np.ndarray): Segment coordinates in format (N, 2) where N is number of points.
        width (int): Width of the image in pixels.
        height (int): Height of the image in pixels.

    Returns:
        (np.ndarray): Bounding box coordinates in xyxy format [x1, y1, x2, y2].
    é   ©ÚdtypeNr   é   )r   r   r=   r=   éÿÿÿÿ©ÚaxisÚignore)ÚdivideÚinvalid©r   r   c                ó„   •— g | ]<}t          j        ‰t          t          t          |¦  «        ¦  «        d ¦  «        dk    ‘Œ=S )Fr   )Úcv2ÚpointPolygonTestÚtupleÚmapr   )Ú.0ÚpÚcontours     €r   ú
<listcomp>zsegment2box.<locals>.<listcomp>p   s?   ø€ ÐfÐfÐfÐYZ•SÔ)¨'µ5½½UÀA¹¼Ñ3GÔ3GÈÑOÔOÐSTÒTÐfÐfÐfr   )ÚlenÚnpÚzerosr<   ÚminÚmaxÚarrayÚrollÚerrstateÚarangeÚastypeÚfloat32Úconcatenate)r3   r5   r7   ÚxÚyÚxminÚyminÚxmaxÚymaxÚaxesÚboundsÚlimsr    Údeltar   ÚinterÚotherÚcornersÚpointsrL   s                      @r   Úsegment2boxrh   M   s[  ø€ õ ˆw‰<Œ<ð 0ÝŒx˜ ¤Ð/Ñ/Ô/Ð/Ø�1�1�1�a�4Œ=˜' ! ! ! Q $œ-€q€AØŸUšU™WœW a§e¢e¡g¤g¨q¯uªu©w¬w¸¿º¹¼Ð?Ñ€Dˆ$��dØˆq‚y€y�T˜Q’Y�Y 4¨5¢= =°T¸V²^°^ÝŒx˜˜t T¨4Ð0¸¼ÐFÑFÔFÐFÝŒ8�LÑ!Ô!€DÝŒX�q˜%  FÐ+°7´=ÐAÑAÔA€FÝŒ8�V˜V U¨EÐ2¸'¼-ÐHÑHÔH€DØ�BœG G¨R°aÐ8Ñ8Ô8¸7ÑBˆ5€EÝ	Œ˜H¨hÐ	7Ñ	7Ô	7ð Fð FØ�e˜A˜A˜A˜t˜G”nÑ$¨¨a¨a¨a°¨g¬Ñ6ˆØ�a�a�a˜˜q˜q˜q�jÔ! A a a a¨¨¨¨D j¤M°E¸!¸!¸!¸TÀ1À1À1¸*Ô4EÑ$EÑEˆðFð Fð Fñ Fô Fð Fð Fð Fð Fð Fð Føøøð Fð Fð Fð Fð �!�!�!•R”Y˜q‘\”\ 1 t¡8Ð+Ô,€EÝŒh˜ ¨ 
¨Q°¨K¸%À¸ÐIÐQXÔQ^Ð_Ñ_Ô_€GØ�nŠn�RœZÑ(Ô(€GÝŒ^à�Q˜!’V  Q¢Ñ'¨1°ª:Ñ6¸!¸vº+ÑFÔGØ�1˜’6˜a 1šfÑ%¨°!ªÑ4¸ÀºÑFÔGØÐfÐfÐfÐfÐ^eÐfÑfÔfÔgð	
ñô €Fõ ˆv‰;Œ;ð	.�ŒÐ1�6—:’:˜a‘=”=Ð1 6§:¢:¨a¡=¤=Ð1¸¼ÐGÑGÔGÐGåŒX�a˜wœ}Ð-Ñ-Ô-ðs   ÅAF*Æ*F.Æ1F.TFÚ
img1_shapeútuple[int, int]Úboxesútorch.Tensor | np.ndarrayÚ
img0_shapeÚ	ratio_padútuple | NoneÚpaddingÚboolÚxywhc                ó˜  — |€›t          | d         |d         z  | d         |d         z  ¦  «        }|x}}t          | d         t          |d         |z  ¦  «        z
  dz  dz
  ¦  «        }	t          | d         t          |d         |z  ¦  «        z
  dz  dz
  ¦  «        }
n|d         \  }}|d         \  }	}
|rB|dxx         |	z  cc<   |dxx         |
z  cc<   |s |dxx         |	z  cc<   |d	xx         |
z  cc<   |dxx         |z  cc<   |dxx         |z  cc<   |dxx         |z  cc<   |d	xx         |z  cc<   |r|nt          ||¦  «        S )
aG  Rescale bounding boxes from one image shape to another.

    Rescales bounding boxes from img1_shape to img0_shape, accounting for padding and aspect ratio changes. Supports
    both xyxy and xywh box formats.

    Args:
        img1_shape (tuple[int, int]): Shape of the source image (height, width).
        boxes (torch.Tensor | np.ndarray): Bounding boxes to rescale in format (N, 4).
        img0_shape (tuple[int, int]): Shape of the target image (height, width).
        ratio_pad (tuple, optional): Ratio and padding as ((ratio_h, ratio_w), (pad_w, pad_h)).
        padding (bool): Whether boxes are based on YOLO-style augmented images with padding.
        xywh (bool): Whether box format is xywh (True) or xyxy (False).

    Returns:
        (torch.Tensor | np.ndarray): Rescaled bounding boxes in the same format as input.
    Nr   r=   é   çš™™™™™¹?©.r   ©.r=   ©.rt   ©.é   )rQ   ÚroundÚ
clip_boxes)ri   rk   rm   rn   rp   rr   ÚgainÚgain_yÚgain_xÚpad_xÚpad_ys              r   Úscale_boxesr‚   z   s”  € ð0 ÐÝ�:˜a”= :¨a¤=Ñ0°*¸Q´-À*ÈQÄ-Ñ2OÑPÔPˆØÐˆ�Ý�z !”}¥u¨Z¸¬]¸TÑ-AÑ'BÔ'BÑBÀaÑGÈ#ÑMÑNÔNˆÝ�z !”}¥u¨Z¸¬]¸TÑ-AÑ'BÔ'BÑBÀaÑGÈ#ÑMÑNÔNˆˆà" 1œ‰ˆ�Ø  ”|‰ˆˆuàð #ØˆfˆˆŒ˜Ñˆˆ‰ØˆfˆˆŒ˜Ñˆˆ‰Øð 	#Ø�&ˆMˆMŒM˜UÑ"ˆMˆM‰MØ�&ˆMˆMŒM˜UÑ"ˆMˆM‰MØ	ˆ&€M€M„M�VÑ€M€M�MØ	ˆ&€M€M„M�VÑ€M€M�MØ	ˆ&€M€M„M�VÑ€M€M�MØ	ˆ&€M€M„M�VÑ€M€M�MØÐ;ˆ5ˆ5�j¨°
Ñ;Ô;Ð;r   rZ   c                ó¬   — t          |t          j        ¦  «        r!t          |                     ¦   «         ¦  «        }t          j        | |z  ¦  «        |z  S )a	  Return the smallest number >= x that is divisible by the given divisor.

    Args:
        x (int): The number to make divisible.
        divisor (int | torch.Tensor): The divisor.

    Returns:
        (int): The smallest number >= x divisible by the divisor.
    )Ú
isinstanceÚtorchÚTensorr6   rR   ÚmathÚceil)rZ   Údivisors     r   Úmake_divisiblerŠ   ¨   sF   € õ �'�5œ<Ñ(Ô(ð %Ý�g—k’k‘m”mÑ$Ô$ˆÝŒ9�Q˜‘[Ñ!Ô! GÑ+Ð+r   c                ó&  — |dd…         \  }}t          | t          j        ¦  «        �rt          r–| j        j        dk    rt          t          d¦  «        sq| d                              d|¦  «         | d                              d|¦  «         | d                              d|¦  «         | d	                              d|¦  «         nË| d          	                    d|¦  «        | d<   | d          	                    d|¦  «        | d<   | d          	                    d|¦  «        | d<   | d	          	                    d|¦  «        | d	<   nN| d
ddgf          
                    d|¦  «        | d
ddgf<   | d
ddgf          
                    d|¦  «        | d
ddgf<   | S )a  Clip bounding boxes to image boundaries.

    Args:
        boxes (torch.Tensor | np.ndarray): Bounding boxes to clip.
        shape (tuple): Image shape as HWC or HW (supports both).

    Returns:
        (torch.Tensor | np.ndarray): Clipped bounding boxes.
    Nrt   Úmpsú<2.5.0rv   r   rw   rx   ry   .r=   rz   ©r„   r…   r†   r   r   r   r   r   Úclamp_ÚclampÚclip)rk   ÚshapeÚhÚws       r   r|   r|   ·   s”  € ð ��!�Œ9�D€A€qÝ�%�œÑ&Ô&ñ ;Ýð 		6 ¤Ô 1°UÒ :Ð :½}Í]Ð\dÑ?eÔ?eÐ :Ø�&ŒM× Ò   AÑ&Ô&Ð&Ø�&ŒM× Ò   AÑ&Ô&Ð&Ø�&ŒM× Ò   AÑ&Ô&Ð&Ø�&ŒM× Ò   AÑ&Ô&Ð&Ð&à! &œM×/Ò/°°1Ñ5Ô5ˆE�&‰MØ! &œM×/Ò/°°1Ñ5Ô5ˆE�&‰MØ! &œM×/Ò/°°1Ñ5Ô5ˆE�&‰MØ! &œM×/Ò/°°1Ñ5Ô5ˆE�&‰MˆMà" 3¨¨A¨ ;Ô/×4Ò4°Q¸Ñ:Ô:ˆˆc�A�q�6ˆkÑØ" 3¨¨A¨ ;Ô/×4Ò4°Q¸Ñ:Ô:ˆˆc�A�q�6ˆkÑØ€Lr   c                ó  — |dd…         \  }}t          | t          j        ¦  «        r¤t          r^| j        j        dk    rt          t          d¦  «        s9| d                              d|¦  «         | d                              d|¦  «         n}| d          	                    d|¦  «        | d<   | d          	                    d|¦  «        | d<   n>| d          
                    d|¦  «        | d<   | d          
                    d|¦  «        | d<   | S )a	  Clip line coordinates to image boundaries.

    Args:
        coords (torch.Tensor | np.ndarray): Line coordinates to clip.
        shape (tuple): Image shape as HWC or HW (supports both).

    Returns:
        (torch.Tensor | np.ndarray): Clipped coordinates.
    Nrt   rŒ   r�   rv   r   rw   rŽ   )Úcoordsr’   r“   r”   s       r   Úclip_coordsr—   Ó   s  € ð ��!�Œ9�D€A€qÝ�&�%œ,Ñ'Ô'ð 	3Ýð 	8 ¤Ô 2°eÒ ;Ð ;ÅÍmÐ]eÑ@fÔ@fÐ ;Ø�6ŒN×!Ò! ! QÑ'Ô'Ð'Ø�6ŒN×!Ò! ! QÑ'Ô'Ð'Ð'à# Fœ^×1Ò1°!°QÑ7Ô7ˆF�6‰NØ# Fœ^×1Ò1°!°QÑ7Ô7ˆF�6‰NˆNà œ×,Ò,¨Q°Ñ2Ô2ˆˆv‰Ø œ×,Ò,¨Q°Ñ2Ô2ˆˆv‰Ø€Mr   c                ót  — t          | t          t          f¦  «        r t          j        | t          j        ¬¦  «        } | j        d         dk    sJ d| j        › �¦   «         ‚t          | ¦  «        }| d         | d         | d         | d         f\  }}}}||z   d	z  |d<   ||z   d	z  |d<   ||z
  |d<   ||z
  |d<   |S )
až  Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format where (x1, y1) is
    the top-left corner and (x2, y2) is the bottom-right corner.

    Args:
        x (np.ndarray | torch.Tensor | list | tuple): Input bounding box coordinates in (x1, y1, x2, y2) format.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in (x, y, width, height) format.
    r;   r>   r:   ú9input shape last dimension expected 4 but input shape is rv   rw   rx   ry   rt   ©r„   ÚlistrH   rO   ÚasarrayrX   r’   Ú
empty_like)rZ   r[   Úx1Úy1Úx2Úy2s         r   Ú	xyxy2xywhr¢   ë   sÎ   € õ �!•d�E�]Ñ#Ô#ð ,ÝŒJ�q¥¤
Ð+Ñ+Ô+ˆØŒ7�2Œ;˜!ÒÐÐÐbÐYZÔY`ÐbÐbÑÔÐÝ�1‰Œ€AØ�v”Y  &¤	¨1¨V¬9°a¸´iÐ?�N€BˆˆB�Ø�b‘˜A‘€A€f�IØ�b‘˜A‘€A€f�IØ�R‘€A€f�IØ�R‘€A€f�IØ€Hr   c                óH  — t          | t          t          f¦  «        r t          j        | t          j        ¬¦  «        } | j        d         dk    sJ d| j        › �¦   «         ‚t          | ¦  «        }| ddd…f         }| ddd…f         dz  }||z
  |ddd…f<   ||z   |ddd…f<   |S )aÐ  Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is
    the top-left corner and (x2, y2) is the bottom-right corner. Note: ops per 2 channels faster than per channel.

    Args:
        x (np.ndarray | torch.Tensor | list | tuple): Input bounding box coordinates in (x, y, width, height) format.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format.
    r;   r>   r:   r™   .Nrt   rš   )rZ   r[   ÚxyÚwhs       r   Ú	xywh2xyxyr¦     s¼   € õ �!•d�E�]Ñ#Ô#ð ,ÝŒJ�q¥¤
Ð+Ñ+Ô+ˆØŒ7�2Œ;˜!ÒÐÐÐbÐYZÔY`ÐbÐbÑÔÐÝ�1‰Œ€AØ	
ˆ3���ˆ7Œ€BØ	
ˆ3���ˆ7Œ�a‰€BØ�b‘€A€cˆ2ˆAˆ2€g�JØ�b‘€A€cˆ1ˆ2ˆ2€g�JØ€Hr   r”   r“   ÚpadwÚpadhc                ó4  — | j         d         dk    sJ d| j         › �¦   «         ‚t          | ¦  «        }| d         | d         | d         | d         f\  }}}}	|dz  |	dz  }}
|||
z
  z  |z   |d<   |||z
  z  |z   |d<   |||
z   z  |z   |d<   |||z   z  |z   |d<   |S )	aÈ  Convert normalized bounding box coordinates to pixel coordinates.

    Args:
        x (np.ndarray | torch.Tensor): Normalized bounding box coordinates in (x, y, w, h) format.
        w (int): Image width in pixels.
        h (int): Image height in pixels.
        padw (int): Padding width in pixels.
        padh (int): Padding height in pixels.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format.
    r>   r:   r™   rv   rw   rx   ry   rt   )r’   r�   )rZ   r”   r“   r§   r¨   r[   ÚxcÚycÚxwÚxhÚhalf_wÚhalf_hs               r   Ú
xywhn2xyxyr°     sÓ   € ð Œ7�2Œ;˜!ÒÐÐÐbÐYZÔY`ÐbÐbÑÔÐÝ�1‰Œ€AØ�v”Y  &¤	¨1¨V¬9°a¸´iÐ?�N€BˆˆB�Ø˜!‘V˜R !™VˆF€FØ�R˜&‘[Ñ! DÑ(€A€f�IØ�R˜&‘[Ñ! DÑ(€A€f�IØ�R˜&‘[Ñ! DÑ(€A€f�IØ�R˜&‘[Ñ! DÑ(€A€f�IØ€Hr   r
   r‘   Úepsr   c                óH  — |rt          | ||z
  ||z
  f¦  «        } | j        d         dk    sJ d| j        › �¦   «         ‚t          | ¦  «        }| d         | d         | d         | d         f\  }}}}	||z   dz  |z  |d<   ||	z   dz  |z  |d<   ||z
  |z  |d<   |	|z
  |z  |d<   |S )	a`  Convert bounding box coordinates from (x1, y1, x2, y2) format to normalized (x, y, width, height) format. x, y,
    width and height are normalized to image dimensions.

    Args:
        x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x1, y1, x2, y2) format.
        w (int): Image width in pixels.
        h (int): Image height in pixels.
        clip (bool): Whether to clip boxes to image boundaries.
        eps (float): Minimum value for box width and height.

    Returns:
        (np.ndarray | torch.Tensor): Normalized bounding box coordinates in (x, y, width, height) format.
    r>   r:   r™   rv   rw   rx   ry   rt   )r|   r’   r�   )
rZ   r”   r“   r‘   r±   r[   rž   rŸ   r    r¡   s
             r   Ú
xyxy2xywhnr³   .  sØ   € ð ð .Ý�q˜1˜s™7 A¨¡GÐ,Ñ-Ô-ˆØŒ7�2Œ;˜!ÒÐÐÐbÐYZÔY`ÐbÐbÑÔÐÝ�1‰Œ€AØ�v”Y  &¤	¨1¨V¬9°a¸´iÐ?�N€BˆˆB�Ø�r‘'˜Q‘ !Ñ#€A€f�IØ�r‘'˜Q‘ !Ñ#€A€f�IØ�b‘˜A‘€A€f�IØ�b‘˜A‘€A€f�IØ€Hr   c                óæ   — t          | t          j        ¦  «        r|                      ¦   «         nt	          j        | ¦  «        }| d         | d         dz  z
  |d<   | d         | d         dz  z
  |d<   |S )a(  Convert bounding box format from [x, y, w, h] to [x1, y1, w, h] where x1, y1 are top-left coordinates.

    Args:
        x (np.ndarray | torch.Tensor): Input bounding box coordinates in xywh format.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in ltwh format.
    rv   rx   rt   rw   ry   ©r„   r…   r†   ÚclonerO   Úcopy©rZ   r[   s     r   Ú	xywh2ltwhr¹   H  óg   € õ   ¥5¤<Ñ0Ô0Ð@ˆ�Š‰	Œ	ˆ	µb´g¸a±j´j€AØ�&”	˜A˜fœI¨™MÑ)€A€f�IØ�&”	˜A˜fœI¨™MÑ)€A€f�IØ€Hr   c                óÚ   — t          | t          j        ¦  «        r|                      ¦   «         nt	          j        | ¦  «        }| d         | d         z
  |d<   | d         | d         z
  |d<   |S )a  Convert bounding boxes from [x1, y1, x2, y2] to [x1, y1, w, h] format.

    Args:
        x (np.ndarray | torch.Tensor): Input bounding box coordinates in xyxy format.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in ltwh format.
    rx   rv   ry   rw   rµ   r¸   s     r   Ú	xyxy2ltwhr¼   W  ó_   € õ   ¥5¤<Ñ0Ô0Ð@ˆ�Š‰	Œ	ˆ	µb´g¸a±j´j€AØ�&”	˜A˜fœIÑ%€A€f�IØ�&”	˜A˜fœIÑ%€A€f�IØ€Hr   c                óæ   — t          | t          j        ¦  «        r|                      ¦   «         nt	          j        | ¦  «        }| d         | d         dz  z   |d<   | d         | d         dz  z   |d<   |S )a  Convert bounding boxes from [x1, y1, w, h] to [x, y, w, h] where xy1=top-left, xy=center.

    Args:
        x (np.ndarray | torch.Tensor): Input bounding box coordinates.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in xywh format.
    rv   rx   rt   rw   ry   rµ   r¸   s     r   Ú	ltwh2xywhr¿   f  rº   r   c                ó
  — t          | t          j        ¦  «        }|r&|                      ¦   «                              ¦   «         n| }g }|D ]î}t          j        |                     dd¦  «        ¦  «        \  \  }}\  }}}	|	dz  t          j	        z  }
||k     r||}}|
t          j	        dz  z  }
|
dt          j	        z  dz  k    r%|
t          j	        z  }
|
dt          j	        z  dz  k    °%|
t          j	         dz  k     r#|
t          j	        z  }
|
t          j	         dz  k     °#| 
                    |||||
g¦  «         Œït          j        |¦  «                             dd¦  «        }|r!t          j        || j        | j        ¬¦  «        n|S )a  Convert batched Oriented Bounding Boxes (OBB) from [xy1, xy2, xy3, xy4] to [xywh, rotation] format.

    Args:
        x (np.ndarray | torch.Tensor): Input box corners with shape (N, 8) or (N, 4, 2) in [xy1, xy2, xy3, xy4] format.
            Polygons with more than four points are accepted in the same two layouts, (N, 2P) or (N, P, 2), and are
            reduced to their minimum-area rectangle.

    Returns:
        (np.ndarray | torch.Tensor): Converted data in [cx, cy, w, h, rotation] format with shape (N, 5). The
            parameterization is canonical rather than the caller's: w is the longer side and rotation is in radians
            from [-pi/4, 3pi/4), so a box given with w < h comes back with w and h swapped and its angle shifted by
            pi/2 modulo pi.
    r>   rt   é´   rz   r:   é   ©r   r<   )r„   r…   r†   ÚcpuÚnumpyrF   ÚminAreaRectÚreshaperO   ÚpiÚappendrœ   Útensorr   r<   )rZ   Úis_torchrg   ÚrboxesÚptsÚcxÚcyr”   r“   ÚangleÚthetas              r   Úxyxyxyxy2xywhrrÒ   u  sv  € õ ˜!�Uœ\Ñ*Ô*€HØ (Ð/ˆQ�UŠU‰WŒW�]Š]‰_Œ_ˆ_¨a€FØ€FØð -ð -ˆõ #&¤/°#·+²+¸bÀ!Ñ2DÔ2DÑ"EÔ"EÑ‰ˆˆR‘&�1�a˜%à˜‘�bœeÑ#ˆØˆqŠ5ˆ5Ø�aˆqˆAØ•R”U˜Q‘YÑˆEØ�q�2œ5‘y 1‘}Ò$Ð$Ø•R”U‰NˆEð �q�2œ5‘y 1‘}Ò$Ð$à•r”u�f˜q‘jÒ Ð Ø•R”U‰NˆEð •r”u�f˜q‘jÒ Ð à�Š�r˜2˜q ! UÐ+Ñ,Ô,Ð,Ð,ÝŒZ˜ÑÔ×'Ò'¨¨AÑ.Ô.€FØCKÐW�5Œ<˜ q¤x°q´wÐ?Ñ?Ô?Ð?ÐQWÐWr   c                óP  ‡ — t          ‰ t          j        ¦  «        r.t          j        t          j        t          j        t          j        fn-t          j        t          j        t          j        t          j        f\  }}}}‰ ddd…f         }ˆ fd„t          dd¦  «        D ¦   «         \  }}} ||¦  «         ||¦  «        }
}	|dz  |	z  |dz  |
z  g}| dz  |
z  |dz  |	z  g} ||d¦  «        } ||d¦  «        }||z   |z   }||z   |z
  }||z
  |z
  }||z
  |z   } |||||gd¦  «        S )ab  Convert batched Oriented Bounding Boxes (OBB) from [xywh, rotation] to [xy1, xy2, xy3, xy4] format.

    Args:
        x (np.ndarray | torch.Tensor): Boxes in [cx, cy, w, h, rotation] format with shape (N, 5) or (B, N, 5). Rotation
            is in radians and is neither range-checked nor normalized; the box is not canonicalized, so converting the
            (N, 4, 2) corners back with xyxyxyxy2xywhr returns the canonical form of the same rectangle rather than
            these values.

    Returns:
        (np.ndarray | torch.Tensor): Converted corner points with shape (N, 4, 2) or (B, N, 4, 2).
    .Nrt   c              3  ó6   •K  — | ]}‰d ||dz   …f         V — ŒdS ).r=   Nr1   )rJ   ÚirZ   s     €r   ú	<genexpr>z!xywhr2xyxyxyxy.<locals>.<genexpr>«  s4   øè è € Ð:Ð:¨�1�S˜!˜a !™e˜)�^Ô$Ð:Ð:Ð:Ð:Ð:Ð:r   rÂ   r>   éþÿÿÿ)
r„   r…   r†   ÚcosÚsinÚcatÚstackrO   rY   Úrange)rZ   rØ   rÙ   rÚ   rÛ   Úctrr”   r“   rÐ   Ú	cos_valueÚ	sin_valueÚvec1Úvec2Úpt1Úpt2Úpt3Úpt4s   `                r   Úxywhr2xyxyxyxyræ   ˜  sN  ø€ õ �a�œÑ&Ô&ð	8�Œ•E”I�uœy­%¬+Ð6Ð6åŒf•b”f�bœn­b¬hÐ7ñ €Cˆˆc�5ð ˆC��!�ˆGŒ*€CØ:Ð:Ð:Ð:­e°A°q©k¬kÐ:Ñ:Ô:�K€A€qˆ%Ø˜3˜u™:œ: s s¨5¡z¤zˆy€IØ�‰E�IÑ˜q 1™u yÑ0Ð1€DØˆB�‰F�YÑ  A¡¨	Ñ 1Ð2€DØˆ3ˆt�R‰=Œ=€DØˆ3ˆt�R‰=Œ=€DØ
�‰*�tÑ
€CØ
�‰*�tÑ
€CØ
�‰*�tÑ
€CØ
�‰*�tÑ
€CØˆ5�#�s˜C Ð% rÑ*Ô*Ð*r   c                óÚ   — t          | t          j        ¦  «        r|                      ¦   «         nt	          j        | ¦  «        }| d         | d         z   |d<   | d         | d         z   |d<   |S )a  Convert bounding box from [x1, y1, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right.

    Args:
        x (np.ndarray | torch.Tensor): Input bounding box coordinates.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in xyxy format.
    rx   rv   ry   rw   rµ   r¸   s     r   Ú	ltwh2xyxyrè   ¸  r½   r   c                óP  — g }| D ]m}|j         \  }}|                     |                     ¦   «         |                     ¦   «         |                     ¦   «         |                     ¦   «         g¦  «         Œnt	          t          j        |¦  «                             dd¦  «        ¦  «        S )zýConvert segment coordinates to bounding box labels in xywh format.

    Args:
        segments (list[np.ndarray]): List of segments, each an (N, 2) array of [x, y] points.

    Returns:
        (np.ndarray): Bounding box coordinates in xywh format.
    r>   r:   )ÚTrÉ   rQ   rR   r¢   rO   rS   rÇ   )Úsegmentsrk   ÚsrZ   r[   s        r   Úsegments2boxesrí   Ç  s‡   € ð €EØð ;ð ;ˆØŒs‰ˆˆ1Ø�Š�a—e’e‘g”g˜qŸušu™wœw¨¯ª©¬°·²±´Ð9Ñ:Ô:Ð:Ð:Ý•R”X˜e‘_”_×,Ò,¨R°Ñ3Ô3Ñ4Ô4Ð4r   éè  Únc           	     ó¬  ‡‡‡— t          | ¦  «        D �]?\  }Št          ‰¦  «        |k    rŒt          j        ‰‰dd…dd…f         fd¬¦  «        Št          j        dt          ‰¦  «        dz
  t          ‰¦  «        |k     r|t          ‰¦  «        z
  n|¦  «        Št          j        t          ‰¦  «        ¦  «        Št          ‰¦  «        |k     r)t          j        ‰t          j        ‰‰¦  «        ‰¦  «        n‰Št          j        ˆˆˆfd„t          d¦  «        D ¦   «         t          j	        ¬¦  «         
                    dd¦  «        j        | |<   �ŒA| S )	a2  Resample segments to n points each using linear interpolation.

    Args:
        segments (list): List of (N, 2) arrays where N is the number of points in each segment.
        n (int): Number of points to resample each segment to.

    Returns:
        (list): Resampled segments with n points each.
    r   r=   Nr?   c           	     óP   •— g | ]"}t          j        ‰‰‰d d …|f         ¦  «        ‘Œ#S )N)rO   Úinterp)rJ   rÕ   rì   rZ   Úxps     €€€r   rM   z%resample_segments.<locals>.<listcomp>é  s3   ø€ ÐHÐHÐH¸!�BœI a¨¨Q¨q¨q¨q°!¨t¬WÑ5Ô5ÐHÐHÐHr   rt   r;   r>   )Ú	enumeraterN   rO   rY   ÚlinspacerV   ÚinsertÚsearchsortedrÜ   rX   rÇ   rê   )rë   rï   rÕ   rì   rZ   ró   s      @@@r   Úresample_segmentsrø   ×  s:  øøø€ õ ˜(Ñ#Ô#ð 	
ñ 	
‰ˆˆ1Ýˆq‰6Œ6�QŠ;ˆ;ØÝŒN˜A˜q  1  a a a œy˜>°Ð2Ñ2Ô2ˆÝŒK˜�3˜q™6œ6 A™:µS¸±V´V¸a²Z°Z q­3¨q©6¬6¡z zÀQÑGÔGˆÝŒY•s˜1‘v”vÑÔˆÝ8;¸A¹¼Àº
¸
�BŒI�a�œ¨¨BÑ/Ô/°Ñ4Ô4Ð4ÈˆåŒNÐHÐHÐHÐHÐHÐH½uÀQ¹x¼xÐHÑHÔHÕPRÔPZÐ[Ñ[Ô[×cÒcÐdeÐgiÑjÔjÔlð 	�‰‰ð €Or   Úmasksútorch.Tensorc                ó°  — |j         | j         k    r|                     | j         ¦  «        }| j        \  }}}t          j        |dd…dd…df         dd¦  «        \  }}}}t          j        || j         |j        ¬¦  «        dddd…f         }	t          j        || j         |j        ¬¦  «        ddd…df         }
| |	|k    |	|k     z  z  } | |
|k    |
|k     z  z  } | S )a  Crop masks to bounding box regions.

    Args:
        masks (torch.Tensor): Masks with shape (N, H, W).
        boxes (torch.Tensor): Bounding box coordinates with shape (N, 4) in xyxy pixel format.

    Returns:
        (torch.Tensor): Cropped masks.
    Nr:   r=   rÃ   )r   Útor’   r…   ÚchunkrV   r<   )rù   rk   Ú_r“   r”   rž   rŸ   r    r¡   ÚrÚcs              r   Ú	crop_maskr  î  sè   € ð „|�u”|Ò#Ð#Ø—’˜œÑ&Ô&ˆØŒk�G€A€qˆ!Ý”[  q q q¨!¨!¨!¨T zÔ!2°A°qÑ9Ô9�N€BˆˆB�ÝŒ�Q˜uœ|°2´8Ð<Ñ<Ô<¸TÀ4ÈÈÈ¸]ÔK€AÝŒ�Q˜uœ|°2´8Ð<Ñ<Ô<¸TÀ1À1À1Àd¸]ÔK€Að 
ˆa�2Šg˜!˜bš&Ñ!Ñ!€EØ	ˆa�2Šg˜!˜bš&Ñ!Ñ!€EØ€Lr   Úupsamplec                óF  — | j         \  }}}|j         d         dk    r0t          j        dg|r|n||f¢R t          j        |j        ¬¦  «        S ||                      ¦   «                              |d¦  «        z                       d||¦  «        }|r$t          j        |d         |d¬¦  «        d         }n;||d         z  }	||d         z  }
t          j	        |	|
|	|
gg|j        ¬¦  «        }||z  }t          |                     d	¦  «                             ¦   «         |¦  «        S )
aè  Apply masks to bounding boxes using mask head output.

    Args:
        protos (torch.Tensor): Mask prototypes with shape (mask_dim, mask_h, mask_w).
        masks_in (torch.Tensor): Mask coefficients with shape (N, mask_dim) where N is number of masks after NMS.
        bboxes (torch.Tensor): Bounding boxes with shape (N, 4) where N is number of masks after NMS.
        shape (tuple): Input image size as (height, width).
        upsample (bool): Whether to upsample masks to original image size.

    Returns:
        (torch.Tensor): A binary mask tensor of shape [n, h, w], where n is the number of masks after NMS. When
            upsample=True h and w match the input image size; otherwise they are the prototype mask resolution.
    r   ©r<   r   r>   NÚbilinear©Úmoder=   )r   r
   )r’   r…   rP   Úuint8r   r   ÚviewÚFÚinterpolaterÊ   r  Úgt_Úbyte)ÚprotosÚmasks_inÚbboxesr’   r  r   ÚmhÚmwrù   Úwidth_ratioÚheight_ratioÚratioss               r   Úprocess_maskr    s"  € ð ”�I€A€rˆ2Ø„~�aÔ˜AÒÐÝŒ{˜AÐB¨(Ð!@  ¸¸R¸ÐBÐBÍ%Ì+Ð^fÔ^mÐnÑnÔnÐnØ˜Ÿš™œ×+Ò+¨A¨rÑ2Ô2Ñ2×8Ò8¸¸RÀÑDÔD€Eàð !å”˜e Dœk¨5°zÐBÑBÔBÀ1ÔEˆˆà˜5 œ8‘mˆØ˜E !œH‘}ˆÝ” ¨\¸;ÈÐUÐVÐ_eÔ_lÐmÑmÔmˆØ˜&‘ˆå�U—Y’Y˜s‘^”^×(Ò(Ñ*Ô*¨FÑ3Ô3Ð3r   c                ó¾  ‡‡‡	‡
‡— | j         \  }Š	Š
‰\  }}|j         d         dk    r)t          j        d||ft          j        |j        ¬¦  «        S ||                      ¦   «                              |d¦  «        z  Št          dd||z  z  ¦  «        Šˆˆ	ˆ
ˆˆfd„t          d‰j         d         ‰¦  «        D ¦   «         }t          t          j
        |¦  «        |¦  «        S )a  Apply masks to bounding boxes using mask head output with native upsampling.

    Args:
        protos (torch.Tensor): Mask prototypes with shape (mask_dim, mask_h, mask_w).
        masks_in (torch.Tensor): Mask coefficients with shape (N, mask_dim) where N is number of masks after NMS.
        bboxes (torch.Tensor): Bounding boxes with shape (N, 4) where N is number of masks after NMS.
        shape (tuple): Input image size as (height, width).

    Returns:
        (torch.Tensor): Binary mask tensor with shape (N, H, W).
    r   r  r>   r=   i Hèc           	     óÒ   •— g | ]c}t          ‰||‰z   …                              d ‰‰¦  «        d         ‰¦  «        d                              d¦  «                             ¦   «         ‘ŒdS )r>   Nr   r
   )Úscale_masksr	  r  r  )rJ   rÕ   Úcoeffsr  r  r’   Ústeps     €€€€€r   rM   z'process_mask_native.<locals>.<listcomp>9  sv   ø€ ð ð ð àõ 	�F˜1˜q 4™x˜<Ô(×-Ò-¨b°"°bÑ9Ô9¸$Ô?ÀÑGÔGÈÔJ×NÒNÈsÑSÔS×XÒXÑZÔZðð ð r   )r’   r…   rP   r  r   r   r	  rR   rÜ   r  rÚ   )r  r  r  r’   r   r“   r”   rù   r  r  r  r  s      `    @@@@r   Úprocess_mask_nativer  $  sø   øøøøø€ ð ”�I€A€rˆ2Ø�D€A€qØ„~�aÔ˜AÒÐÝŒ{˜A˜q !˜9­E¬KÀÄÐPÑPÔPÐPØ˜Ÿš™œ×+Ò+¨A¨rÑ2Ô2Ñ2€Fõ ˆq�*  Q¡Ñ'Ñ(Ô(€Dðð ð ð ð ð ð ð å�q˜&œ, qœ/¨4Ñ0Ô0ðñ ô €Eõ •U”Y˜uÑ%Ô% vÑ.Ô.Ð.r   r  r’   ú.tuple[tuple[int, int], tuple[int, int]] | Noner  r   c                ó²  — | j         dd…         \  }}|dd…         \  }}||k    r||k    r| S | j         d         dk    r5|                      g | j         dd…         ¢|‘|‘R t          j        ¬¦  «        S |€Mt	          ||z  ||z  ¦  «        }	|t          ||	z  ¦  «        z
  |t          ||	z  ¦  «        z
  }}
|r
|
dz  }
|dz  }n|d         \  }
}|r$t          |dz
  ¦  «        t          |
dz
  ¦  «        fnd\  }}|t          |dz   ¦  «        z
  }|t          |
dz   ¦  «        z
  }t          j        | d||…||…f                              ¦   «         ||¬	¦  «        S )
a"  Rescale segment masks to target shape.

    Args:
        masks (torch.Tensor): Masks with shape (N, C, H, W).
        shape (tuple[int, int]): Target height and width as (height, width).
        ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_w, pad_h)).
        padding (bool): Whether masks are based on YOLO-style augmented images with padding.
        mode (str): Interpolation mode, e.g. 'bilinear' for logits or 'nearest' for integer class maps.

    Returns:
        (torch.Tensor): Rescaled masks.
    rt   Nr=   r   r;   ru   rD   .r  )	r’   Ú	new_zerosr…   rX   rQ   r{   r
  r  r   )rù   r’   rn   rp   r  Úim1_hÚim1_wÚim0_hÚim0_wr}   Úpad_wÚpad_hÚtopÚleftÚbottomÚrights                   r   r  r  @  sˆ  € ð& ”;˜q˜r˜r”?�L€Eˆ5Ø˜˜!˜”9�L€Eˆ5Ø�‚~€~˜% 5š.˜.ØˆØ„{�1„~˜ÒÐØ�ŠÐ? ¤¨R¨a¨R¤Ð?°%Ð?¸Ð?Ð?ÅuÄ}ˆÑUÔUÐUàÐÝ�5˜5‘= %¨%¡-Ñ0Ô0ˆØ¥ e¨d¡lÑ 3Ô 3Ñ3°u½uÀUÈTÁ\Ñ?RÔ?RÑ7RˆuˆØð 	Ø�Q‰JˆEØ�Q‰JˆEøà  ”|‰ˆˆuØ<CÐO•�u˜s‘{Ñ#Ô#¥U¨5°3©;Ñ%7Ô%7Ð8Ð8È�I€CˆØ•U˜5 3™;Ñ'Ô'Ñ'€FØ•E˜% #™+Ñ&Ô&Ñ&€EÝŒ=˜˜s C¨ J°°U°
Ð:Ô;×AÒAÑCÔCÀUÐQUÐVÑVÔVÐVr   Ú	normalizec                ó:  — |dd…         \  }}|€x| dd…         \  }}	t          ||z  |	|z  ¦  «        }
|
x}}t          |	t          ||
z  ¦  «        z
  dz  dz
  ¦  «        t          |t          ||
z  ¦  «        z
  dz  dz
  ¦  «        f}n|d         \  }}|d         }|r,|dxx         |d         z  cc<   |dxx         |d         z  cc<   |dxx         |z  cc<   |dxx         |z  cc<   t          ||¦  «        }|r |dxx         |z  cc<   |dxx         |z  cc<   |S )av  Rescale segment coordinates from img1_shape to img0_shape.

    Args:
        img1_shape (tuple): Source image shape as HWC or HW (supports both).
        coords (torch.Tensor): Coordinates to scale with shape (N, 2).
        img0_shape (tuple): Image 0 shape as HWC or HW (supports both).
        ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_w, pad_h)).
        normalize (bool): Whether to normalize coordinates to range [0, 1].
        padding (bool): Whether coordinates are based on YOLO-style augmented images with padding.

    Returns:
        (torch.Tensor): Scaled coordinates.
    Nrt   ru   r   r=   rv   rw   )rQ   r{   r—   )ri   r–   rm   rn   r*  rp   Úimg0_hÚimg0_wÚimg1_hÚimg1_wr}   r~   r   Úpads                 r   Úscale_coordsr1  h  sk  € ð     ”^�N€FˆFØÐØ# B Q Bœ‰ˆ�Ý�6˜F‘? F¨V¡OÑ4Ô4ˆØÐˆ�Ý�V�e F¨T¡MÑ2Ô2Ñ2°aÑ7¸#Ñ=Ñ>Ô>ÅÀvÕPUÐV\Ð_cÑVcÑPdÔPdÑGdÐhiÑFiÐloÑFoÑ@pÔ@pÐpˆˆà" 1œ‰ˆ�Ø˜Œlˆàð !ØˆvˆˆŒ˜#˜aœ&Ñ ˆˆ‰ØˆvˆˆŒ˜#˜aœ&Ñ ˆˆ‰Ø
ˆ6€N€N„N�fÑ€N€N�NØ
ˆ6€N€N„N�fÑ€N€N�NÝ˜ Ñ,Ô,€FØð !ØˆvˆˆŒ˜&Ñ ˆˆ‰ØˆvˆˆŒ˜&Ñ ˆˆ‰Ø€Mr   c                ó,  — |                       d¬¦  «        \  }}}}}|t          j        z  t          j        dz  k    }t          j        |||¦  «        }t          j        |||¦  «        }|t          j        dz  z  }t          j        |||||gd¬¦  «        S )zÜRegularize rotated bounding boxes to range [0, pi/2).

    Args:
        rboxes (torch.Tensor): Input rotated boxes with shape (N, 5) in xywhr format.

    Returns:
        (torch.Tensor): Regularized rotated boxes.
    r>   )Údimrt   )Úunbindr‡   rÈ   r…   ÚwhererÛ   )	rÌ   rZ   r[   r”   r“   r   ÚswapÚw_Úh_s	            r   Úregularize_rboxesr9  Œ  s�   € ð —M’M b�MÑ)Ô)�M€A€qˆ!ˆQ�à�tŒw‰;�$œ' A™+Ò%€DÝ	Œ�T˜1˜aÑ	 Ô	 €BÝ	Œ�T˜1˜aÑ	 Ô	 €BØ	�TŒW�q‰[Ñ€AÝŒ;˜˜1˜b " aÐ(¨bÐ1Ñ1Ô1Ð1r   Úallúnp.ndarray | torch.TensorÚstrategyúlist[np.ndarray]c                ór  — ddl m} t          | t          j        ¦  «        r|                      d¦  «        n7|                      ¦   «                              ¦   «                              ¦   «         } g }t          j	        | ¦  «        D �]1}t          j        |t          j        t          j        ¦  «        d         }|rÀ|dk    rWt          |¦  «        dk    r't          j         |d„ |D ¦   «         ¦  «        ¦  «        n|d                              dd¦  «        }nw|d	k    r\t          j        |t          j        d
„ |D ¦   «         ¦  «                             ¦   «                  ¦  «                             dd¦  «        }nt          j        d¦  «        }|                     |                     d¦  «        ¦  «         �Œ3|S )a!  Convert masks to segments using contour detection.

    Args:
        masks (np.ndarray | torch.Tensor): Binary masks with shape (N, H, W).
        strategy (str): Segmentation strategy, either 'all' or 'largest'.

    Returns:
        (list): List of segment masks as float32 arrays.
    r   )Úmerge_multi_segmentr  r:  r=   c                ó:   — g | ]}|                      d d¦  «        ‘ŒS )r>   rt   )rÇ   ©rJ   rZ   s     r   rM   z"masks2segments.<locals>.<listcomp>±  s&   € Ð7TÐ7TÐ7TÈQ¸¿	º	À"ÀaÑ8HÔ8HÐ7TÐ7TÐ7Tr   r>   rt   Úlargestc                ó,   — g | ]}t          |¦  «        ‘ŒS r1   )rN   rA  s     r   rM   z"masks2segments.<locals>.<listcomp>¶  s   € Ð(;Ð(;Ð(;°A­¨Q©¬Ð(;Ð(;Ð(;r   )r   rt   rX   )Úultralytics.data.converterr?  r„   rO   ÚndarrayrW   r  rÄ   rÅ   ÚascontiguousarrayrF   ÚfindContoursÚRETR_EXTERNALÚCHAIN_APPROX_SIMPLErN   rY   rÇ   rS   ÚargmaxrP   rÉ   )rù   r<  r?  rë   rZ   r   s         r   Úmasks2segmentsrK  ž  s—  € ð ?Ð>Ð>Ð>Ð>Ð>å%/°µr´zÑ%BÔ%BÐbˆE�LŠL˜Ñ!Ô!Ð!ÈÏ
Ê
ÉÌ×HXÒHXÑHZÔHZ×H`ÒH`ÑHbÔHb€EØ€HÝÔ! %Ñ(Ô(ð -ñ -ˆÝÔ˜Q¥Ô 1µ3Ô3JÑKÔKÈAÔNˆØð 
	!Ø˜5Ò Ð õ ˜1‘v”v ’z�zõ ”NÐ#6Ð#6Ð7TÐ7TÐRSÐ7TÑ7TÔ7TÑ#UÔ#UÑVÔVÐVà˜1œŸš b¨!Ñ,Ô,ð �ð
 ˜YÒ&Ð&Ý”H˜Q�rœxÐ(;Ð(;¸Ð(;Ñ(;Ô(;Ñ<Ô<×CÒCÑEÔEÔFÑGÔG×OÒOÐPRÐTUÑVÔV�øå”˜Ñ Ô ˆAØ�Š˜Ÿš Ñ+Ô+Ñ,Ô,Ð,Ñ,Ø€Or   Úbatchc                óð   — |                       dddd¦  «                             ¦   «         dz                       dd¦  «                             ¦   «                              ¦   «                              ¦   «         S )a_  Convert a batch of FP32 torch tensors to NumPy uint8 arrays, changing from BCHW to BHWC layout.

    Args:
        batch (torch.Tensor): Input tensor batch with shape (Batch, Channels, Height, Width) and dtype torch.float32.

    Returns:
        (np.ndarray): Output NumPy array batch with shape (Batch, Height, Width, Channels) and dtype uint8.
    r   rt   rz   r=   éÿ   )ÚpermuteÚ
contiguousr�   r  rÄ   rÅ   )rL  s    r   Úconvert_torch2numpy_batchrQ  ½  sa   € ð �MŠM˜!˜Q  1Ñ%Ô%×0Ò0Ñ2Ô2°SÑ8×?Ò?ÀÀ3ÑGÔG×LÒLÑNÔN×RÒRÑTÔT×ZÒZÑ\Ô\Ð\r   c                ó0   — t          j        dd| ¬¦  «        S )zìClean a string by replacing special characters with '_' character.

    Args:
        s (str): A string needing special characters replaced.

    Returns:
        (str): A string with special characters replaced by an underscore _.
    u!   [|@#!Â¡Â·$â‚¬%&()=?Â¿^*;:,Â¨`><+]rþ   )ÚpatternÚreplÚstring)ÚreÚsub)rì   s    r   Ú	clean_strrX  É  s   € õ Œ6Ð=ÀCÐPQÐRÑRÔRÐRr   c                ó¢   — t          | t          j        ¦  «        rt          j        | | j        ¬¦  «        nt          j        | | j        ¬¦  «        S )zKCreate empty torch.Tensor or np.ndarray with same shape and dtype as input.r;   )r„   r…   r†   r�   r<   rO   )rZ   s    r   r�   r�   Õ  sF   € å1;¸A½u¼|Ñ1LÔ1LÐq�5Ô˜A Q¤WÐ-Ñ-Ô-Ð-ÕRTÔR_Ð`aÐijÔipÐRqÑRqÔRqÐqr   c                ó¬   — t           €!	 ddlm} |a n# t          $ r
 t          a Y nw xY wt          t          j        | t
          j        ¬¦  «        ¦  «        S )a   Solve the rectangular linear sum assignment problem (minimum-cost one-to-one matching).

    Uses `scipy.optimize.linear_sum_assignment` when SciPy is installed (faster compiled C++ solver), and otherwise
    falls back to an equivalent pure-NumPy implementation of the same modified Jonker-Volgenant shortest augmenting path
    algorithm (Crouse 2016). This keeps SciPy out of Ultralytics' required dependencies while preserving its speed when
    present. SciPy is imported lazily so it never slows `import ultralytics`. For a rectangular matrix only min(rows,
    columns) entries are matched.

    The NumPy fallback supports `+inf` as a forbidden assignment and raises `ValueError("cost matrix is infeasible")`
    when no assignment exists; callers must sanitize `NaN` and `-inf`. The two backends may return a different
    equal-cost assignment under exact ties, but the total cost is identical.

    The NumPy fallback is validated against SciPy with exact optimal-cost parity across ~6.9k randomized cases (every
    shape including empty/tall/wide, ties, negatives, IoU- and RT-DETR-style matrices, `maximize` via negation,
    torch-tensor input) plus ~2k independent brute-force global-optimum checks. SciPy's compiled inner loop is faster,
    but at the call-site sizes (smaller dimension = object count) the fallback runs in well under a millisecond:

        cost matrix   NumPy   SciPy
        300 x 20      0.2ms   0.02ms
        300 x 80      0.6ms   0.1ms
        300 x 300     28ms    1.5ms

    Args:
        cost_matrix (np.ndarray | torch.Tensor): Cost matrix with shape (N, M); `+inf` forbids assignments.

    Returns:
        row_ind (np.ndarray): Row indices of the optimal assignment, sorted ascending, with length min(N, M).
        col_ind (np.ndarray): Column indices matched to each row in row_ind.

    Examples:
        >>> cost = np.array([[4, 1, 3], [2, 0, 5], [3, 2, 2]], dtype=float)
        >>> row_ind, col_ind = linear_sum_assignment(cost)
        >>> float(cost[row_ind, col_ind].sum())
        5.0
    Nr   )Úlinear_sum_assignmentr;   )Ú_assignment_solverÚscipy.optimizer[  ÚImportErrorÚ_linear_sum_assignment_numpyrO   rœ   Úfloat64)Úcost_matrixÚsolvers     r   r[  r[  Ý  sq   € õJ Ð!ð	>ØFÐFÐFÐFÐFÐFà!'ÐÐøÝð 	>ð 	>ð 	>Ý!=ÐÐÐð	>øøøå�bœj¨½B¼JÐGÑGÔGÑHÔHÐHs   ‰ ’&¥&c                óP  — | j         \  }}|dk    s|dk    r@t          j        dt          j        ¬¦  «        t          j        dt          j        ¬¦  «        fS ||k    }|r| j        ||}}} t          j        |dz   ¦  «        t          j        |dz   ¦  «        }}t          j        |dz   t          j        ¦  «        t          j        |dz   t          j        ¦  «        }}t          d|dz   ¦  «        D �]•}|dc|d<   }	t          j        |dz   t          j        ¦  «        t          j        |dz   t          ¦  «        }}
	 d||	<   ||	         }| |dz
           ||         z
  |dd…         z
  }|dd…          ||
dd…         k     z  }||         |	c|
dd…         |<   |dd…         |<   t          j
        |dd…         t          j        |
dd…         ¦  «        }t          t          j        |¦  «        ¦  «        dz   }||dz
           }|t          j        k    rt          d¦  «        ‚|||         xx         |z  cc<   ||xx         |z  cc<   |
| xx         |z  cc<   |}	||	         dk    rn�Œ-|	r|||	                  ||	<   ||	         }	|	°�Œ—t          j        |dd…         ¦  «        d         }|dd…         |         dz
  }|r||fn||f\  }}t          j        |d¬¦  «        }||                              t          j        ¦  «        ||                              t          j        ¦  «        fS )	a˜  Solve the rectangular linear sum assignment problem with NumPy (Jonker-Volgenant SciPy-free fallback).

    Args:
        a (np.ndarray): Float64 cost matrix of shape (N, M); `+inf` forbids assignments.

    Returns:
        row_ind (np.ndarray): Row indices of the optimal assignment, sorted ascending, with length min(N, M).
        col_ind (np.ndarray): Column indices matched to each row in row_ind.
    r   r;   r=   TNzcost matrix is infeasibleÚstable)Úkind)r’   rO   ÚemptyÚintprê   rP   rÜ   ÚfullÚinfrq   r5  r6   ÚargminÚ
ValueErrorÚnonzeroÚargsortrW   )Úarï   ÚmÚ
transposedÚuÚvrK   ÚwayrÕ   Új0ÚminvÚusedÚi0ÚcurÚimproveÚ
candidatesÚj1rc   ÚcolsÚrowsÚrow_indÚcol_indÚorders                          r   r_  r_    s#  € ð Œ7�D€A€qØˆA‚v€v��a’�ÝŒx˜¥¤Ð)Ñ)Ô)­2¬8°A½R¼WÐ+EÑ+EÔ+EÐEÐEØ�Q’€JØð Ø”#�q˜!ˆaˆ1ˆÝŒ8�A˜‘E‰?Œ?�BœH Q¨¡U™OœO€q€AÝŒX�a˜!‘e�RœWÑ%Ô%¥r¤x°°A±µr´wÑ'?Ô'?€s€AÝ�1�a˜!‘e‰_Œ_ð ñ ˆØ�aˆˆˆ!‰ˆbÝ”W˜Q ™U¥B¤FÑ+Ô+­R¬X°a¸!±e½TÑ-BÔ-Bˆdˆð	ØˆD�‰HØ�2”ˆBØ�B˜‘F”)˜a œeÑ# a¨¨¨¤eÑ+ˆCØ˜Q˜R˜Rœ�y S¨4°°°¬8¢^Ñ4ˆGØ25°g´,ÀÐ/ˆD���ŒH�WÑ˜s 1 2 2œw wÑ/Ýœ $ q r r¤(­B¬F°D¸¸¸´HÑ=Ô=ˆJÝ•R”Y˜zÑ*Ô*Ñ+Ô+¨aÑ/ˆBØ˜r A™vÔ&ˆEØ�œŠˆÝ Ð!<Ñ=Ô=Ð=Øˆa�ŒgˆJˆJŒJ˜%ÑˆJˆJ‰JØˆdˆGˆGŒG�uÑˆGˆG‰GØ�$�ˆKˆKŒK˜5Ñ ˆKˆK‰KØˆBØ�Œu˜ŠzˆzØñ!	ð" ð 	Ø�c˜"”g”JˆAˆb‰EØ�R”ˆBð ð 	ùõ Œ:�a˜˜˜”eÑÔ˜QÔ€DØˆQˆRˆRŒ5�Œ;˜‰?€DØ'1ÐC˜˜d�|�|¸¸d°|Ñ€GˆWÝŒJ�w XÐ.Ñ.Ô.€EØ�5Œ>× Ò ¥¤Ñ)Ô)¨7°5¬>×+@Ò+@ÅÄÑ+IÔ+IÐIÐIr   )r2   r2   )r3   r4   r5   r6   r7   r6   r8   r4   )NTF)ri   rj   rk   rl   rm   rj   rn   ro   rp   rq   rr   rq   r8   rl   )rZ   r6   )r2   r2   r   r   )r”   r6   r“   r6   r§   r6   r¨   r6   )r2   r2   Fr
   )r”   r6   r“   r6   r‘   rq   r±   r   )rî   )rï   r6   )rù   rú   rk   rú   r8   rú   )F)r  rq   )NTr  )rù   rú   r’   rj   rn   r  rp   rq   r  r   r8   rú   )NFT)r*  rq   rp   rq   )r:  )rù   r;  r<  r   r8   r=  )rL  rú   r8   r4   )5Ú
__future__r   Ú
contextlibr‡   rV  r   rF   rÅ   rO   r…   Útorch.nn.functionalÚnnÚ
functionalr
  Úultralytics.utilsr   r   Úultralytics.utils.checksr   Úultralytics.utils.torch_utilsr   ÚContextDecoratorr	   rh   r‚   rŠ   r|   r—   r¢   r¦   r°   r³   r¹   r¼   r¿   rÒ   ræ   rè   rí   rø   r  r  r  r  r1  r9  rK  rQ  rX  r�   r\  r[  r_  r1   r   r   ú<module>rŠ     sJ  ðð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø €€€Ø 	€	€	€	Ø €€€à 
€
€
€
Ø Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð à 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ø 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø BÐ BÐ BÐ BÐ BÐ Bð6#ð 6#ð 6#ð 6#ð 6#ˆjÔ)ñ 6#ô 6#ð 6#ðr*ð *ð *ð *ð *ðb #ØØð+<ð +<ð +<ð +<ð +<ð\,ð ,ð ,ð ,ðð ð ð8ð ð ð0ð ð ð,ð ð ð*ð ð ð ð ð0ð ð ð ð ð4ð ð ðð ð ðð ð ð Xð  Xð  XðF+ð +ð +ð@ð ð ð5ð 5ð 5ð ð ð ð ð ð.ð ð ð ð.4ð 4ð 4ð 4ð 4ð>/ð /ð /ð> AEØØð%Wð %Wð %Wð %Wð %WðP!ð !ð !ð !ð !ðH2ð 2ð 2ð$ð ð ð ð ð>	]ð 	]ð 	]ð 	]ð	Sð 	Sð 	Sðrð rð rð
 Ð ð,Ið ,Ið ,Ið^-Jð -Jð -Jð -Jð -Jr   