
    |h                     X   d dl Z d dlZd dlZd dlZd dlm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 d dlmZ  G d de j$                        ZdEdedefd	ZdFd
edefdZdefdZdGdedefdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dHdededededededededededededefdZd  Zd! ZdId"Zd# Zd$ Z dJd%ed&ed'ed(efd)Z!dKd%ed&ed*ed+efd,Z"d- Z#d. Z$d/ Z%d0 Z&d1 Z'd2 Z(d3 Z)dLd4efd5Z*d6 Z+dMd7efd8Z,d9 Z-dNd
efd:Z.dOd;ed
efd<Z/d= Z0dPd>e1fd?Z2d@e	jf                  dAejh                  fdBZ5dC Z6dD Z7y)Q    N)Optional)LOGGER)batch_probiouc                   T    e Zd ZdZd
dedeej                     fdZd Z	d Z
d Zd	 Zy)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 CUDA synchronization support for GPU operations.

    Attributes:
        t (float): Accumulated time in seconds.
        device (torch.device): Device used for model inference.
        cuda (bool): Whether CUDA is being used for timing synchronization.

    Examples:
        Use as a context manager to time code execution
        >>> with Profile(device=device) as dt:
        ...     pass  # slow operation here
        >>> print(dt)  # prints "Elapsed time is 9.5367431640625e-07 s"

        Use as a decorator to time function execution
        >>> @Profile()
        ... def slow_function():
        ...     time.sleep(0.1)
    Ntdevicec                 x    || _         || _        t        |xr t        |      j	                  d            | _        y)z
        Initialize the Profile class.

        Args:
            t (float): Initial accumulated time in seconds.
            device (torch.device, optional): Device used for model inference to enable CUDA synchronization.
        cudaN)r   r	   boolstr
startswithr   )selfr   r	   s      T/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/ops.py__init__zProfile.__init__*   s2     BCK$:$:6$BC	    c                 0    | j                         | _        | S )zStart timing.)timestartr   s    r   	__enter__zProfile.__enter__6   s    YY[
r   c                     | j                         | j                  z
  | _        | xj                  | j                  z  c_        y)zStop timing.N)r   r   dtr   )r   type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__@   s    !$&&,,r   c                     | j                   r)t        j                   j                  | j                         t	        j
                         S )z9Get current time with CUDA synchronization if applicable.)r   torchsynchronizer	   r   perf_counterr   s    r   r   zProfile.timeD   s.    99JJ""4;;/  ""r   )        N)__name__
__module____qualname____doc__floatr   r!   r	   r   r   r   r   r    r   r   r   r      s:    .
D% 
Dx/E 
D

-#r   r   widthheightc                    | j                   \  }}t        j                  |j                         dk  |j                         dk  |j	                         |kD  |j	                         |kD  g      j                         dk\  r$|j                  d|      }|j                  d|      }|dk\  |dk\  z  ||k  z  ||k  z  }||   }||   }t        |      r]t        j                  |j                         |j                         |j	                         |j	                         g| j                        S 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.
    Applies inside-image constraint and clips coordinates when necessary.

    Args:
        segment (torch.Tensor): 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].
    r      dtype   )
Tnparrayminmaxsumclipanyr0   zeros)segmentr+   r,   xyinsides         r   segment2boxr?   K   s    99DAq	xx1aeegk1557U?AEEGf<LMNRRTXYYFF1eFF1f1fa AJ/1;?F	&	A	&	A q6 	!%%'1557AEEGQUUW5W]]K XXaw}}-r   paddingxywhc                    |Yt        | d   |d   z  | d   |d   z        }t        | d   |d   |z  z
  dz  dz
        t        | d   |d   |z  z
  dz  dz
        f}n|d   d   }|d   }|rB|dxx   |d   z  cc<   |dxx   |d   z  cc<   |s |dxx   |d   z  cc<   |d	xx   |d   z  cc<   |d
ddfxx   |z  cc<   t        ||      S )a-  
    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): Shape of the source image (height, width).
        boxes (torch.Tensor): Bounding boxes to rescale in format (N, 4).
        img0_shape (tuple): Shape of the target image (height, width).
        ratio_pad (tuple, optional): Tuple of (ratio, pad) for scaling. If None, calculated from image shapes.
        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): Rescaled bounding boxes in the same format as input.
    Nr         皙?.r   .rC   .rD   .r.   .r1   )r5   round
clip_boxes)
img1_shapeboxes
img0_shape	ratio_padr@   rA   gainpads           r   scale_boxesrR   i   s   $ :a=:a=0*Q-*Q-2OP:a=:a=4#771<sBC:a=:a=4#771<sBC

 |AlfQfQ&MSV#M&MSV#M	#rr'NdNeZ((r   r<   c                     t        |t        j                        rt        |j	                               }t        j                  | |z        |z  S )a  
    Return the nearest number that is divisible by the given divisor.

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

    Returns:
        (int): The nearest number divisible by the divisor.
    )
isinstancer!   Tensorintr6   mathceil)r<   divisors     r   make_divisiblerZ      s:     '5<<(gkkm$99Q[!G++r   	thresholduse_triuc                    t        j                  |d      }| |   } t        | |       }|rP|j                  d      }t        j                  ||k\  j                  d      dk        j                  d      }||   S | j                  d   }t        j                  || j                        j                  dd      j                  d|      }t        j                  || j                        j                  dd      j                  |d      }	||	k  }
||
z  }d|||k\  j                  d      dk   <   t        j                  ||j                  d         j                  }||   S )a  
    Perform NMS on oriented bounding boxes using probiou and fast-nms.

    Args:
        boxes (torch.Tensor): Rotated bounding boxes with shape (N, 5) in xywhr format.
        scores (torch.Tensor): Confidence scores with shape (N,).
        threshold (float): IoU threshold for NMS.
        use_triu (bool): Whether to use torch.triu operator for upper triangular matrix operations.

    Returns:
        (torch.Tensor): Indices of boxes to keep after NMS.
    T
descendingrC   )diagonalr   r	   )r!   argsortr   triu_nonzeror7   squeeze_shapearanger	   viewexpandtopkindices)rM   scoresr[   r\   
sorted_idxiouspicknrow_idxcol_idx
upper_masks              r   nms_rotatedru      sB    v$7J*E&Dzz1z%}}di/44Q71<=FFrJ d KKN,,q6;;BBII"aP,,q6;;ArBII!RPw&
j 56$)#((+q012zz&&,,q/2::dr   
conf_thres	iou_thresagnosticmulti_labelmax_detncmax_time_imgmax_nmsmax_whin_placerotatedend2endreturn_idxsc           
      
   ddl }d|cxk  rdk  sn J d| d       d|cxk  rdk  sn J d| d       t        | t        t        f      r| d   } |!t	        j
                  || j                        }| j                  d   d	k(  s|rP| D cg c]  }||ddd
f   |kD     d|  }}|-|D cg c]"  }||dddd	f   |k(  j                  d         $ }}|S | j                  d   }|xs | j                  d   d
z
  }| j                  d   |z
  d
z
  }d
|z   }| ddd
|f   j                  d      |kD  }t	        j                  |D cg c],  }t	        j                  t        |      | j                        . c}      d   }d|	|z  z   }||dkD  z  }| j                  dd      } |sL|rt        | ddd
f         | ddd
f<   n0t	        j                  t        | ddd
f         | dd
df   fd      } t!        j                          }t	        j"                  dd	|z   f| j                        g|z  }t	        j"                  d| j                        g|z  }t%        t'        | |            D ]  \  }\  }}||   }||   ||   }}|rt        ||         r|s||   } t	        j"                  t        |       ||z   d
z   f|j                        }!t        | ddddf         |!dddd
f<   d|!t)        t        |             | dddf   j+                         d
z   f<   t	        j                  ||!fd      }|j                  d   s|j-                  d
||fd      \  }"}#}$|r_t	        j.                  |#|kD        \  }}%t	        j                  |"|   ||d
|%z   df   |%dddf   j1                         |$|   fd      }||   }nZ|#j3                  dd      \  }&}%|&j5                  d      |kD  }t	        j                  |"|&|%j1                         |$fd      |   }||   }|'|dddd	f   |k(  j                  d      }||   ||   }}|j                  d   }'|'s|'|
kD  r&|ddd
f   j7                  d      d|
 }||   ||   }}|dddd	f   |rdn|z  }(|ddd
f   })|rFt	        j                  |ddddf   |(z   |dddd
f   |ddddf   fd      }*t9        |*|)|      }n+|dddd
f   |(z   }*|j:                  j=                  |*|)|      }|d| }||   ||   j?                  d      c||<   ||<   t!        j                          |z
  |kD  stA        jB                  d|dd        n |r||fS |S c c}w c c}w c c}w )a  
    Perform non-maximum suppression (NMS) on prediction results.

    Applies NMS to filter overlapping bounding boxes based on confidence and IoU thresholds. Supports multiple
    detection formats including standard boxes, rotated boxes, and masks.

    Args:
        prediction (torch.Tensor): Predictions with shape (batch_size, num_classes + 4 + num_masks, num_boxes)
            containing boxes, classes, and optional masks.
        conf_thres (float): Confidence threshold for filtering detections. Valid values are between 0.0 and 1.0.
        iou_thres (float): IoU threshold for NMS filtering. Valid values are between 0.0 and 1.0.
        classes (List[int], optional): List of class indices to consider. If None, all classes are considered.
        agnostic (bool): Whether to perform class-agnostic NMS.
        multi_label (bool): Whether each box can have multiple labels.
        labels (List[List[Union[int, float, torch.Tensor]]]): A priori labels for each image.
        max_det (int): Maximum number of detections to keep per image.
        nc (int): Number of classes. Indices after this are considered masks.
        max_time_img (float): Maximum time in seconds for processing one image.
        max_nms (int): Maximum number of boxes for torchvision.ops.nms().
        max_wh (int): Maximum box width and height in pixels.
        in_place (bool): Whether to modify the input prediction tensor in place.
        rotated (bool): Whether to handle Oriented Bounding Boxes (OBB).
        end2end (bool): Whether the model is end-to-end and doesn't require NMS.
        return_idxs (bool): Whether to return the indices of kept detections.

    Returns:
        output (List[torch.Tensor]): List of detections per image with shape (num_boxes, 6 + num_masks)
            containing (x1, y1, x2, y2, confidence, class, mask1, mask2, ...).
        keepi (List[torch.Tensor]): Indices of kept detections if return_idxs=True.
    r   NrC   zInvalid Confidence threshold z&, valid values are between 0.0 and 1.0zInvalid IoU rb   ra      r1      ).Ng       @.dim)r   rC   g      ?T)keepdimr^   rD   zNMS time limit z.3fz
s exceeded)"torchvisionrT   listtupler!   tensorr	   rg   r9   amaxstackrh   len	transpose	xywh2xyxycatr   r:   	enumerateziprangelongsplitwherer)   r6   ri   rc   ru   opsnmsreshaper   warning)+
predictionrv   rw   classesrx   ry   labelsrz   r{   r|   r}   r~   r   r   r   r   r   predoutputbsextramixcixinds
time_limitr   keepixir<   xkfiltlbvboxclsmaskjconfrq   crm   rM   s+                                              r   non_max_suppressionr      s   `  
as#@Lr!ss	Q`,yk9_ ``*tUm,]
,,wz/@/@Aq GFPQd$tAqDzJ./9QQIOPdDAaCLG388;<PFP			!	B		(
  #a'BQ"$q(E	
RB	AqtG		!	!!	$z	1BKKQSTAc!fZ5F5FGTUV_`E |b((J26K%%b"-J"+JsBQBw,?"@JsBQBwIjbqb.A$BJsTUTVwDW#X^`aJ		Akk1a%i.1B1BCDrIF[[
(9(9:;b@E Z!78 :GQ "v$D2 c&*ogBSWb5j1n5ahhGA AqsF,Aa!eH58AeCGnbAhmmo112		1a&!$A wwqz !R3S$;;sZ/0DAq		3q61QAt^#4a4j6F6F6H$q'RTUVAABggag.GD!99R=:-D		3aggi6:4@ADB a1fI(--a0DdGRXrA GGAJw;QT7??d?3HW=DdGRXrA a1fIhF31a4IIqBQBx!|Qq!A#vY!RS&	BKEE695Aa!eHqLE##E69=AhwK !!bemmB&7r
E"IIIK!Oz)NN_Z,<JGHu:x *FE?5v5o RP Us   U0,'U51U:c                    t        | t        j                        rn| d   j                  d|d         | d<   | d   j                  d|d         | d<   | d   j                  d|d         | d<   | d   j                  d|d         | d<   | S | dddgf   j	                  d|d         | dddgf<   | ddd	gf   j	                  d|d         | ddd	gf<   | S )
a  
    Clip bounding boxes to image boundaries.

    Args:
        boxes (torch.Tensor | numpy.ndarray): Bounding boxes to clip.
        shape (tuple): Image shape as (height, width).

    Returns:
        (torch.Tensor | numpy.ndarray): Clipped bounding boxes.
    rF   r   rC   rG   rH   rI   .rD   r.   rT   r!   rU   clampr8   )rM   rg   s     r   rK   rK   U  s     %&f++AuQx8ff++AuQx8ff++AuQx8ff++AuQx8f L #3A;/44QaAcAq6k"3A;/44QaAcAq6kLr   c                    t        | t        j                        r8| d   j                  d|d         | d<   | d   j                  d|d         | d<   | S | d   j	                  d|d         | d<   | d   j	                  d|d         | d<   | S )a
  
    Clip line coordinates to image boundaries.

    Args:
        coords (torch.Tensor | numpy.ndarray): Line coordinates to clip.
        shape (tuple): Image shape as (height, width).

    Returns:
        (torch.Tensor | numpy.ndarray): Clipped coordinates.
    rF   r   rC   rG   r   )coordsrg   s     r   clip_coordsr   k  s     &%,,'--aq:v--aq:v M  ,,Qa9v,,Qa9vMr   c                    | j                   }|dd |dd k(  r| S |At        |d   |d   z  |d   |d   z        }|d   |d   |z  z
  dz  |d   |d   |z  z
  dz  f}n|d   }t        t        |d   dz
              t        t        |d   dz
              }}|d   t        t        |d   dz               z
  |d   t        t        |d   dz               z
  }	}t	        | j                         dk  r!t        dt	        | j                                | ||||	f   } t        j                  | |d   |d   f      } t	        | j                         dk(  r| dddddf   } | S )aF  
    Rescale masks to original image size.

    Takes resized and padded masks and rescales them back to the original image dimensions, removing any padding
    that was applied during preprocessing.

    Args:
        masks (np.ndarray): Resized and padded masks with shape [H, W, N] or [H, W, 3].
        im0_shape (tuple): Original image shape as (height, width).
        ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_h, pad_w)).

    Returns:
        (np.ndarray): Rescaled masks with shape [H, W, N] matching original image dimensions.
    NrD   r   rC   rE   z/"len of masks shape" should be 2 or 3, but got )rg   r5   rV   rJ   r   
ValueErrorcv2resize)
masks	im0_shaperO   	im1_shaperP   rQ   topleftbottomrights
             r   scale_imager     s     I!}	"1%9Q<)A,.	!y|0KL|ilT11Q61	RSW[H[9[_`8``lU3q6C<()3uSVc\/B+CC!s5Q#.//!s5Q#.// F
 5;;!J3u{{K[J\]^^#f*d5j()EJJuy|Yq\:;E
5;;1aDj!Lr   c                     | j                   d   dk(  sJ d| j                           t        |       }| d   | d   z   dz  |d<   | d   | d   z   dz  |d<   | d   | d   z
  |d<   | d   | 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): Input bounding box coordinates in (x1, y1, x2, y2) format.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in (x, y, width, height) format.
    ra   r1   9input shape last dimension expected 4 but input shape is rF   rH   rD   rG   rI   rg   
empty_liker<   r=   s     r   	xyxy2xywhr     s     772;!bXYZY`Y`Xabb1A6QvY&!+AfI6QvY&!+AfI&	AfI%AfI&	AfI%AfIHr   c                     | 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): Input bounding box coordinates in (x, y, width, height) format.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format.
    ra   r1   r   .NrD   r   )r<   r=   xywhs       r   r   r     s     772;!bXYZY`Y`Xabb1A	
37B	
37aBbAc2A2gJbAc12gJHr   whpadwpadhc                     | j                   d   dk(  sJ d| j                           t        |       }|| d   | d   dz  z
  z  |z   |d<   || d   | d   dz  z
  z  |z   |d<   || d   | d   dz  z   z  |z   |d<   || d   | d   dz  z   z  |z   |d<   |S )	aC  
    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:
        y (np.ndarray | torch.Tensor): The coordinates of the bounding box in the format [x1, y1, x2, y2] where
            x1,y1 is the top-left corner, x2,y2 is the bottom-right corner of the bounding box.
    ra   r1   r   rF   rH   rD   rG   rI   r   )r<   r   r   r   r   r=   s         r   
xywhn2xyxyr     s     772;!bXYZY`Y`Xabb1AQvY6Q./$6AfIQvY6Q./$6AfIQvY6Q./$6AfIQvY6Q./$6AfIHr   r8   epsc                 (   |rt        | ||z
  ||z
  f      } | j                  d   dk(  sJ d| j                          t        |       }| d   | d   z   dz  |z  |d<   | d   | d   z   dz  |z  |d<   | d   | d   z
  |z  |d<   | d   | d   z
  |z  |d<   |S )	af  
    Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height, normalized) 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.
    ra   r1   r   rF   rH   rD   rG   rI   )rK   rg   r   )r<   r   r   r8   r   r=   s         r   
xyxy2xywhnr     s     q1s7AG,-772;!bXYZY`Y`Xabb1AF)ai'1,1AfIF)ai'1,1AfI6QvY&!+AfI6QvY&!+AfIHr   c                     t        | t        j                        r| j                         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 xyltwh format.
    rF   rH   rD   rG   rI   rT   r!   rU   cloner3   copyr   s     r   	xywh2ltwhr     _      5<<0	bggajA&	AfIM)AfI&	AfIM)AfIHr   c                     t        | t        j                        r| j                         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 xyltwh format.
    rH   rF   rI   rG   r   r   s     r   	xyxy2ltwhr     W      5<<0	bggajA&	AfI%AfI&	AfI%AfIHr   c                     t        | t        j                        r| j                         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 (torch.Tensor): Input bounding box coordinates.

    Returns:
        (np.ndarray | torch.Tensor): Bounding box coordinates in xywh format.
    rF   rH   rD   rG   rI   r   r   s     r   	ltwh2xywhr   "  r   r   c           	         t        | t        j                        }|r| j                         j	                         n| }|j                  t        |       dd      }g }|D ]K  }t        j                  |      \  \  }}\  }}}	|j                  |||||	dz  t        j                  z  g       M |r,t        j                  || j                  | j                        S t        j                  |      S )a  
    Convert batched Oriented Bounding Boxes (OBB) from [xy1, xy2, xy3, xy4] to [xywh, rotation] format.

    Args:
        x (numpy.ndarray | torch.Tensor): Input box corners with shape (N, 8) in [xy1, xy2, xy3, xy4] format.

    Returns:
        (numpy.ndarray | torch.Tensor): Converted data in [cx, cy, w, h, rotation] format with shape (N, 5).
            Rotation values are in radians from 0 to pi/2.
    ra   rD      r	   r0   )rT   r!   rU   cpunumpyr   r   r   minAreaRectappendr3   pir   r	   r0   asarray)
r<   is_torchpointsrboxesptscxcyr   r   angles
             r   xyxyxyxy2xywhrr   2  s     !U\\*H (QUUW]]_aF^^CFB*FF ; #&//#"6R&1a%r2q!US[255%89:	;
 DL5<<qxxqww?cQSQ[Q[\bQccr   c                 ^    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 )a  
    Convert batched Oriented Bounding Boxes (OBB) from [xywh, rotation] to [xy1, xy2, xy3, xy4] format.

    Args:
        x (numpy.ndarray | torch.Tensor): Boxes in [cx, cy, w, h, rotation] format with shape (N, 5) or (B, N, 5).
            Rotation values should be in radians from 0 to pi/2.

    Returns:
        (numpy.ndarray | torch.Tensor): Converted corner points with shape (N, 4, 2) or (B, N, 4, 2).
    .NrD   c              3   6   K   | ]  }d ||dz   f     yw).rC   Nr*   ).0r   r<   s     r   	<genexpr>z!xywhr2xyxyxyxy.<locals>.<genexpr>[  s"     :1S!a!e)^$:s   r   ra   r   )
rT   r!   rU   cossinr   r   r3   concatenater   )r<   r   r   r   r   ctrr   r   r   	cos_value	sin_valuevec1vec2pt1pt2pt3pt4s   `                r   xywhr2xyxyxyxyr  I  s2    a& 
EIIuyy%++6ffbffbnnbhh7 Cc5 C!G*C:eAqk:KAq%u:s5zyIEIq1uy01DBFYA	 12DtR=DtR=D
*t
C
*t
C
*t
C
*t
C#sC%r**r   c                     t        | t        j                        r| j                         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.
    rH   rF   rI   rG   r   r   s     r   	ltwh2xyxyr	  h  r   r   c                    g }| D ]^  }|j                   \  }}|j                  |j                         |j                         |j                         |j                         g       ` t	        t        j                  |            S )a%  
    Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh).

    Args:
        segments (list): List of segments where each segment is a list of points, each point is [x, y] coordinates.

    Returns:
        (np.ndarray): Bounding box coordinates in xywh format.
    )r2   r   r5   r6   r   r3   r4   )segmentsrM   sr<   r=   s        r   segments2boxesr  x  sg     E ;ss1aeegquuw9:; RXXe_%%r   rq   c                    t        |       D ]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                  t        d      D cg c]   }t        j                  |||dd|f         " c}t        j                        j                  dd      j                  | <   G | S c c}w )a7  
    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   rC   N)axisrD   r/   ra   )r   r   r3   r   linspacerh   insertsearchsortedr   interpfloat32r   r2   )r  rq   r   r  r<   xps         r   resample_segmentsr    s    (# 	
1q6Q;NNAq1ay>2KK3q6A:SVaZq3q6zQGYYs1v8;A
BIIaB/4NNuQxH!BIIaQq!tW5HPRPZPZ[ccdegijll 		
 O Is   8%E
c                 r   | 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  |
|k\  z  |
|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 relative point form.

    Returns:
        (torch.Tensor): Cropped masks.
    Nr1   rC   r   )rg   r!   chunkrh   r	   r0   )r   rM   _r   r   x1y1x2y2rr   s              r   	crop_maskr    s     kkGAq![[q!Tz!2Aq9NBBQu||288<T4]KAQu||288<T1d]KAQ"WR(AG4B?@@r   upsamplec                    | j                   \  }}}|\  }}	|| j                         j                  |d      z  j                  d||      }
||	z  }||z  }|j                         }|dddfxx   |z  cc<   |dddfxx   |z  cc<   |dddfxx   |z  cc<   |dddfxx   |z  cc<   t	        |
|      }
|rt        j                  |
d   |dd	      d   }
|
j                  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, and h and w
            are the height and width of the input image. The mask is applied to the bounding boxes.
    ra   Nr   rD   r.   rC   bilinearFmodealign_cornersr$   )rg   r)   ri   r   r  Finterpolategt_)protosmasks_inbboxesrg   r   r   mhmwihiwr   width_ratioheight_ratiodownsampled_bboxess                 r   process_maskr3    s     IAr2FB++Ar2288RDEr'K7Lq!t+q!t+q!t,q!t,e/0EeDk5zQVWXYZ99S>r   c                     | j                   \  }}}|| j                         j                  |d      z  j                  d||      }t        |d   |      d   }t	        ||      }|j                  d      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 (H, W, N).
    ra   Nr   r$   )rg   r)   ri   scale_masksr  r(  )r)  r*  r+  rg   r   r,  r-  r   s           r   process_mask_nativer6    sn     IAr2++Ar2288RDEdU+A.EeV$E99S>r   c                    | j                   dd \  }}t        ||d   z  ||d   z        }||d   |z  z
  ||d   |z  z
  g}|r|dxx   dz  cc<   |dxx   dz  cc<   |r4t        t        |d   dz
              t        t        |d   dz
              fnd\  }}|t        t        |d   dz               z
  |t        t        |d   dz               z
  }
}	| d||	||
f   } t	        j
                  | |dd	
      } | S )aN  
    Rescale segment masks to target shape.

    Args:
        masks (torch.Tensor): Masks with shape (N, C, H, W).
        shape (tuple): Target height and width as (height, width).
        padding (bool): Whether masks are based on YOLO-style augmented images with padding.

    Returns:
        (torch.Tensor): Rescaled masks.
    rD   Nr   rC   rE   )r   r   .r"  Fr#  )rg   r5   rV   rJ   r&  r'  )r   rg   r@   r,  r-  rP   rQ   r   r   r   r   s              r   r5  r5    s    [[_FBrE!H}b58m,Da4eAho!5
6CA!A!HOU3q6C<()3uSVc\/B+CDU[IC
Ss1v|$%%
Ss1v|$%% F #s6z4:-.EMM%ZuMELr   	normalizec                 z   |At        | d   |d   z  | d   |d   z        }| d   |d   |z  z
  dz  | d   |d   |z  z
  dz  f}n|d   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   |d   z  cc<   |dxx   |d   z  cc<   |S )aT  
    Rescale segment coordinates from img1_shape to img0_shape.

    Args:
        img1_shape (tuple): Shape of the source image.
        coords (torch.Tensor): Coordinates to scale with shape (N, 2).
        img0_shape (tuple): Shape of the target image.
        ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_h, pad_w)).
        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.
    r   rC   rD   rF   rG   )r5   r   )rL   r   rN   rO   r8  r@   rP   rQ   s           r   scale_coordsr:    s     :a=:a=0*Q-*Q-2OP!}z!}t33q8:a=:VW=[_K_;_cd:dd|Alv#a& v#a& 
6NdN
6NdN,Fv*Q-'v*Q-'Mr   c                 @   | j                  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.
    ra   r   rD   )unbindrW   r   r!   r   r   )	r   r<   r=   r   r   r   swapw_h_s	            r   regularize_rboxesr@  (  s     MMbM)MAq!Qtww;$''A+%D	T1a	 B	T1a	 B	TWWq[A;;1b"a(b11r   strategyc                    ddl m} g }| j                         j                         j	                         j                  d      D ]8  }t        j                  |t        j                  t        j                        d   }|r|dk(  r]t        |      dkD  r9t        j                   ||D cg c]  }|j                  dd       c}            n|d   j                  dd      }n{|dk(  rvt        j                  |t        j                  |D cg c]  }t        |       c}      j                                  j                  dd      }nt        j                   d	      }|j#                  |j                  d
             ; |S c c}w c c}w )a&  
    Convert masks to segments using contour detection.

    Args:
        masks (torch.Tensor): Binary masks with shape (batch_size, 160, 160).
        strategy (str): Segmentation strategy, either 'all' or 'largest'.

    Returns:
        (list): List of segment masks as float32 arrays.
    r   )merge_multi_segmentuint8allrC   ra   rD   largest)r   rD   r  )ultralytics.data.converterrC  rV   r   r   astyper   findContoursRETR_EXTERNALCHAIN_APPROX_SIMPLEr   r3   r   r   r4   argmaxr:   r   )r   rA  rC  r  r<   r   s         r   masks2segmentsrM  ;  s=    ?HYY[__$$&--g6 -Q 1 133J3JKAN5  1vz NN#6RS7TQ		"a8H7T#UV1b!, 
 Y&HHQrxx(;AQ(;<CCEFGOOPRTUV A+,- O 8U
 )<s   (F
Fbatchreturnc                     | j                  dddd      j                         dz  j                  dd      j                  t        j
                        j                         j                         S )ad  
    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   rD   r.   rC      )permute
contiguousr   tor!   rD  r   r   )rN  s    r   convert_torch2numpy_batchrU  Z  sU     MM!Q1%002S8??3GJJ5;;W[[]cceer   c                 2    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_strr\  g  s     66>SQRSSr   c                     t        | t        j                        r%t        j                  | t        j                        S t        j                  | t
        j                        S )zSCreate empty torch.Tensor or np.ndarray with same shape as input and float32 dtype.r/   )rT   r!   rU   r   r  r3   )r<   s    r   r   r   t  sG     5?q%,,4O%--0UWUbUbcdlnlvlvUwr   )  r^  )NTF)?T)g      ?r_  NFFr*   i,  r   g?i0u  i   TFFF)N)r^  r^  r   r   )r^  r^  Fr$   )i  )F)T)NFT)rE  )8
contextlibrW   rZ  r   typingr   r   r   r3   r!   torch.nn.functionalnn
functionalr&  ultralytics.utilsr   ultralytics.utils.metricsr   ContextDecoratorr   rV   r?   r   rR   rZ   r)   ru   r   rK   r   r   r   r   r   r   r   r   r   r   r  r	  r  r  r  r3  r6  r5  r:  r@  r   rM  rU   ndarrayrU  r\  r   r*   r   r   <module>ri     sH     	   
     $ 36#j)) 6#r 3 <#) #)[_ #)L,c , % $ F !R6R6 R6
 R6 R6 R6 	R6 R6 R6 R6 R6 R6 R6  !R6j,(&R((S 3 C 3 0S 3 D u 4   d.+> &"3 0A&D B(t :D cg D2&C >
fU\\ 
fbjj 
f
Tr   