a
    PSic<                     @   s  d dl mZ d dlZd dlZd dlmZ d dlmZ ddlmZ ddl	m
Z
mZmZmZ dd	lmZ eeeed
ddZeeeeedddZejjeeeeedddZejjeeeeedddZeeedddZeeeef edddZeeeedddZeedddZeeeeef d d!d"Zeeed d#d$Zeeed d%d&Zd2eeeed(d)d*Z d3eeeed(d+d,Z!d4eeeeeef d(d-d.Z"ejejd/d0d1Z#dS )5    )TupleN)Tensor)_assert_has_ops   )_log_api_usage_once   )_box_cxcywh_to_xyxy_box_xyxy_to_cxcywh_box_xywh_to_xyxy_box_xyxy_to_xywh)_upcast)boxesscoresiou_thresholdreturnc                 C   s4   t j st j stt t  t jj| ||S )a  
    Performs non-maximum suppression (NMS) on the boxes according
    to their intersection-over-union (IoU).

    NMS iteratively removes lower scoring boxes which have an
    IoU greater than iou_threshold with another (higher scoring)
    box.

    If multiple boxes have the exact same score and satisfy the IoU
    criterion with respect to a reference box, the selected box is
    not guaranteed to be the same between CPU and GPU. This is similar
    to the behavior of argsort in PyTorch when repeated values are present.

    Args:
        boxes (Tensor[N, 4])): boxes to perform NMS on. They
            are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and
            ``0 <= y1 < y2``.
        scores (Tensor[N]): scores for each one of the boxes
        iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold

    Returns:
        Tensor: int64 tensor with the indices of the elements that have been kept
        by NMS, sorted in decreasing order of scores
    )	torchjitis_scripting
is_tracingr   nmsr   opstorchvision)r   r   r    r   Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/torchvision/ops/boxes.pyr      s    r   )r   r   idxsr   r   c                 C   s`   t j st j stt |  | jjdkr2dndkrNt	
 sNt| |||S t| |||S dS )a  
    Performs non-maximum suppression in a batched fashion.

    Each index value correspond to a category, and NMS
    will not be applied between elements of different categories.

    Args:
        boxes (Tensor[N, 4]): boxes where NMS will be performed. They
            are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and
            ``0 <= y1 < y2``.
        scores (Tensor[N]): scores for each one of the boxes
        idxs (Tensor[N]): indices of the categories for each one of the boxes.
        iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold

    Returns:
        Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted
        in decreasing order of scores
    cpui  i N  N)r   r   r   r   r   batched_nmsnumeldevicetyper   _is_tracing_batched_nms_vanilla_batched_nms_coordinate_trick)r   r   r   r   r   r   r   r   ,   s
    $r   c                 C   sj   |   dkr tjdtj| jdS |  }|| |td|   }| |d d d f  }t|||}|S )Nr   )r   dtyper   r   )	r   r   emptyint64r   maxtotensorr   )r   r   r   r   Zmax_coordinateoffsetsZboxes_for_nmskeepr   r   r   r"   N   s    r"   c           	      C   sx   t j|t jd}t |D ]6}t ||kd }t| | || |}d||| < qt |d }||| jddd  S )N)r$   r   T)
descendingr   )r   
zeros_likebooluniquewherer   sort)	r   r   r   r   	keep_maskclass_idcurr_indicesZcurr_keep_indiceskeep_indicesr   r   r   r!   b   s    r!   )r   min_sizer   c                 C   s   t j st j stt | dddf | dddf  | dddf | dddf   }}||k||k@ }t |d }|S )ac  
    Remove boxes which contains at least one side smaller than min_size.

    Args:
        boxes (Tensor[N, 4]): boxes in ``(x1, y1, x2, y2)`` format
            with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
        min_size (float): minimum size

    Returns:
        Tensor[K]: indices of the boxes that have both sides
        larger than min_size
    Nr   r      r   )r   r   r   r   r   remove_small_boxesr0   )r   r6   wshsr+   r   r   r   r8   s   s    Br8   )r   sizer   c                 C   s  t j st j stt |  }| ddddf }| ddddf }|\}}t rt 	|t j
d| j| jd}t |t j
|| j| jd}t 	|t j
d| j| jd}t |t j
|| j| jd}n|jd|d}|jd|d}t j||f|d}|| jS )	a4  
    Clip boxes so that they lie inside an image of size `size`.

    Args:
        boxes (Tensor[N, 4]): boxes in ``(x1, y1, x2, y2)`` format
            with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
        size (Tuple[height, width]): size of the image

    Returns:
        Tensor[N, 4]: clipped boxes
    .r   Nr   r   r#   )minr'   )dim)r   r   r   r   r   clip_boxes_to_imager=   r   r    r'   r)   r$   r   r<   clampstackreshapeshape)r   r;   r=   Zboxes_xZboxes_yheightwidthZclipped_boxesr   r   r   r>      s    r>   )r   in_fmtout_fmtr   c                 C   s   t j st j stt d}||vs0||vr8td||krH|  S |dkr~|dkr~|dkrjt| } n|dkrzt	| } d}|dkr|dkrt
| } q|dkrt| } n*|dkr|dkrt| } n|dkrt	| } | S )aF  
    Converts boxes from given in_fmt to out_fmt.
    Supported in_fmt and out_fmt are:

    'xyxy': boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right.
    This is the format that torchvision utilities expect.

    'xywh' : boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height.

    'cxcywh' : boxes are represented via centre, width and height, cx, cy being center of box, w, h
    being width and height.

    Args:
        boxes (Tensor[N, 4]): boxes which will be converted.
        in_fmt (str): Input format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh'].
        out_fmt (str): Output format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh']

    Returns:
        Tensor[N, 4]: Boxes into converted format.
    )xyxyxywhcxcywhzAUnsupported Bounding Box Conversions for given in_fmt and out_fmtrG   rH   rI   )r   r   r   r   r   box_convert
ValueErrorcloner
   r   r   r	   )r   rE   rF   Zallowed_fmtsr   r   r   rJ      s0    



rJ   )r   r   c                 C   sd   t j st j stt t| } | dddf | dddf  | dddf | dddf   S )ax  
    Computes the area of a set of bounding boxes, which are specified by their
    (x1, y1, x2, y2) coordinates.

    Args:
        boxes (Tensor[N, 4]): boxes for which the area will be computed. They
            are expected to be in (x1, y1, x2, y2) format with
            ``0 <= x1 < x2`` and ``0 <= y1 < y2``.

    Returns:
        Tensor[N]: the area for each box
    Nr   r   r7   r   )r   r   r   r   r   box_arear   )r   r   r   r   rM      s    rM   )boxes1boxes2r   c           	      C   s   t | }t |}t| d d d d df |d d d df }t| d d d dd f |d d dd f }t|| jdd}|d d d d df |d d d d df  }|d d d f | | }||fS )Nr   r   r<   r   )rM   r   r'   r<   r   r?   )	rN   rO   Zarea1Zarea2ltrbwhinterunionr   r   r   _box_inter_union   s    ..,rV   c                 C   s6   t j st j stt t| |\}}|| }|S )a  
    Return intersection-over-union (Jaccard index) between two sets of boxes.

    Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.

    Args:
        boxes1 (Tensor[N, 4]): first set of boxes
        boxes2 (Tensor[M, 4]): second set of boxes

    Returns:
        Tensor[N, M]: the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2
    )r   r   r   r   r   box_iourV   )rN   rO   rT   rU   iour   r   r   rW      s
    rW   c           	      C   s   t j st j stt t| |\}}|| }t | dddddf |ddddf }t | dddddf |ddddf }t	|| j
dd}|dddddf |dddddf  }||| |  S )a  
    Return generalized intersection-over-union (Jaccard index) between two sets of boxes.

    Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.

    Args:
        boxes1 (Tensor[N, 4]): first set of boxes
        boxes2 (Tensor[M, 4]): second set of boxes

    Returns:
        Tensor[N, M]: the NxM matrix containing the pairwise generalized IoU values
        for every element in boxes1 and boxes2
    Nr   r   rP   r   )r   r   r   r   r   generalized_box_iourV   r<   r'   r   r?   )	rN   rO   rT   rU   rX   ltirbiwhiZareair   r   r   rY     s    ..,rY   Hz>)rN   rO   epsr   c                 C   s@  t j st j stt t| } t|}t| ||\}}| ddddf | ddddf  }| ddddf | ddddf  }|dddf |dddf  }|dddf |dddf  }dt jd  t 	t 
|| t 
||  d }	t  $ |	d| |	 |  }
W d   n1 s*0    Y  ||
|	  S )a(  
    Return complete intersection-over-union (Jaccard index) between two sets of boxes.
    Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
    Args:
        boxes1 (Tensor[N, 4]): first set of boxes
        boxes2 (Tensor[M, 4]): second set of boxes
        eps (float, optional): small number to prevent division by zero. Default: 1e-7
    Returns:
        Tensor[N, M]: the NxM matrix containing the pairwise complete IoU values
        for every element in boxes1 and boxes2
    Nr   r   r7   r      )r   r   r   r   r   complete_box_iour   _box_diou_ioupipowatanno_grad)rN   rO   r^   diourX   Zw_predZh_predZw_gtZh_gtvalphar   r   r   r`   3  s    $$  2
4r`   c                 C   sB   t j st j stt t| } t|}t| ||d\}}|S )a+  
    Return distance intersection-over-union (Jaccard index) between two sets of boxes.

    Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.

    Args:
        boxes1 (Tensor[N, 4]): first set of boxes
        boxes2 (Tensor[M, 4]): second set of boxes
        eps (float, optional): small number to prevent division by zero. Default: 1e-7

    Returns:
        Tensor[N, M]: the NxM matrix containing the pairwise distance IoU values
        for every element in boxes1 and boxes2
    )r^   )r   r   r   r   r   distance_box_iour   ra   )rN   rO   r^   rf   _r   r   r   ri   T  s    ri   c                 C   s  t | |}t| d d d d df |d d d df }t| d d d dd f |d d dd f }t|| jdd}|d d d d df d |d d d d df d  | }| d d df | d d df  d }| d d df | d d df  d }	|d d df |d d df  d }
|d d df |d d df  d }t|d d d f |
d d d f  d t|	d d d f |d d d f  d  }|||  |fS )Nr   r   rP   r   r7   )rW   r   r<   r'   r   r?   )rN   rO   r^   rX   rZ   r[   r\   Zdiagonal_distance_squaredx_py_pZx_gZy_gZcenters_distance_squaredr   r   r   ra   m  s    
..8$$$$&&ra   )masksr   c                 C   s   t j st j stt |  dkr<t jd| jt j	dS | j
d }t j|df| jt j	d}t| D ]b\}}t |dk\}}t |||df< t |||df< t |||df< t |||df< qf|S )a  
    Compute the bounding boxes around the provided masks.

    Returns a [N, 4] tensor containing bounding boxes. The boxes are in ``(x1, y1, x2, y2)`` format with
    ``0 <= x1 < x2`` and ``0 <= y1 < y2``.

    Args:
        masks (Tensor[N, H, W]): masks to transform where N is the number of masks
            and (H, W) are the spatial dimensions.

    Returns:
        Tensor[N, 4]: bounding boxes
    r   )r   r_   )r   r$   r_   r   r   r7   )r   r   r   r   r   masks_to_boxesr   zerosr   floatrB   	enumerater0   r<   r'   )rm   nbounding_boxesindexmaskyxr   r   r   rn     s    
rn   )r]   )r]   )r]   )$typingr   r   r   r   Ztorchvision.extensionr   utilsr   Z_box_convertr   r	   r
   r   _utilsr   rp   r   r   r   _script_if_tracingr"   r!   r8   intr>   strrJ   rM   rV   rW   rY   r`   ri   ra   rn   r   r   r   r   <module>   sN    " 3!