
    ^j{                        d 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 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 d	dlmZmZ d	dlmZmZ d	dlmZm Z m!Z!m"Z"m#Z#m$Z$ d	dl%m&Z&m'Z' d	dl(m)Z)m*Z*m+Z+  e+       rddl,Z, G d de&d      Z-e* G d de             Z.ddde/de0fdZ1d3dZ2d4dZ3de4e0   de0de0fd Z5	 	 	 	 d5d!e0d"e0d#e/d$e0dz  d%e4e0   dz  d&e6e4e4e0      e4e0   f   fd'Z7d( Z8d)e0d&ejr                  fd*Z:	 d6d+Z;	 d7d!e0d,ejr                  d-e6e0e0f   d&ejr                  fd.Z<d/e=e>e	f   d&ejr                  fd0Z?d8d1Z@d9d2ZAdgZBy):zImage processor class for SAM.    N)Iterable)deepcopy)product)AnyOptionalUnion)
functional)batched_nms   )TorchvisionBackend)BatchFeatureget_size_dict)group_images_by_shapereorder_images)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STDChannelDimension
ImageInputPILImageResamplingSizeDict)ImagesKwargsUnpack)
TensorTypeauto_docstringis_vision_availablec                   :    e Zd ZU dZeeef   ed<   eeef   ed<   y)SamImageProcessorKwargsaV  
    mask_size (`dict[str, int]`, *optional*):
        The size `{"longest_edge": int}` to resize the segmentation maps to.
    mask_pad_size (`dict[str, int]`, *optional*):
        The size `{"height": int, "width": int}` to pad the segmentation maps to. Must be larger than any segmentation
        map size provided for preprocessing.
    	mask_sizemask_pad_sizeN)__name__
__module____qualname____doc__dictstrint__annotations__     w/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/sam/image_processing_sam.pyr   r   /   s%     CH~S>!r)   r   F)totalc            #           e Zd ZeZej                  ZeZ	e
ZddiZddiZdZdZdZdZdZdddZdddZdee   f fdZe	 d3d	ed
edz  dee   def fd       Z	 	 d4deee   z  eeef   z  ez  dz  deee   z  eeef   z  ez  dz  def fdZ de!eef   defdZ"	 d3dddeddddf fdZ#	 d3d	ed
edz  de$de%dee&z  dz  de'edf   dz  defdZ(d	e)d   de$deddde$d ed!e$d"e*d#e$d$e*e)e*   z  dz  d%e*e)e*   z  dz  d&e$dz  d'edz  d(e$dz  de!e)d   e)e!eef      f   fd)Z+	 	 	 	 	 d5dd*d+ed,e*d-edz  d.e)e   dz  de,d   fd/Z-	 	 	 	 d6d0Z.	 	 	 d7d1Z/d2 Z0 xZ1S )8SamImageProcessorlongest_edgei      Theightwidthkwargsc                 $    t        |   di | y )Nr(   )super__init__)selfr3   	__class__s     r*   r6   zSamImageProcessor.__init__L   s    "6"r)   Nimagessegmentation_mapsreturnc                 &    t        |   ||fi |S )zp
        segmentation_maps (`ImageInput`, *optional*):
            The segmentation maps to preprocess.
        )r5   
preprocess)r7   r9   r:   r3   r8   s       r*   r=   zSamImageProcessor.preprocessO   s     w!&*;FvFFr)   r   r   c                     t        |   di |}|&t        |t              st        di t	        |d      }|&t        |t              st        di t	        |d      }||d<   ||d<   |S )z
        Update kwargs that need further processing before being validated
        Can be overridden by subclasses to customize the processing of kwargs.
        r   )
param_namer   r(   )r5   _standardize_kwargs
isinstancer   r   )r7   r   r   r3   r8   s       r*   r@   z%SamImageProcessor._standardize_kwargs\   sv     ,6v6 Ix)H T={#STI$Zx-P$`}]'_`M'{"/r)   	old_shapec                     |\  }}|dz  t        ||      z  }||z  ||z  }}t        |dz         }t        |dz         }||fS )zW
        Compute the output size given input size and target long side length.
              ?      ?)maxr&   )r7   rB   r.   oldholdwscalenewhnewws           r*   _get_preprocess_shapez'SamImageProcessor._get_preprocess_shapeq   sW     
ds"St_4E\4%<d4#:4#:d|r)   imagetorch.Tensorsizeresamplez7PILImageResampling | tvF.InterpolationMode | int | Nonec                     |j                   st        d|j                                |j                  dd }| j	                  ||j                         \  }}t        |   |ft        ||      |d|S )a  
        Resize an image to `(size["height"], size["width"])`.

        Args:
            image (`torch.Tensor`):
                Image to resize.
            size (`SizeDict`):
                Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest
                edge of the image will be resized to the specified size, while the other edge will be resized to
                maintain the aspect ratio.
            resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
                Resampling filter to use when resizing the image.

        Returns:
            `torch.Tensor`: The resized image.
        z?The `size` dictionary must contain the key `longest_edge`. Got Nr0   )rO   rP   )r.   
ValueErrorkeysshaperL   r5   resizer   )	r7   rM   rO   rP   r3   
input_sizeoutput_heightoutput_widthr8   s	           r*   rV   zSamImageProcessor.resize|   s    .   ^_c_h_h_j^klmm[[%
&*&@&@TM^M^&_#|w~
 \JU]
ag
 	
r)   do_convert_rgbinput_data_formatreturn_tensorsdeviceztorch.devicec           	         | j                  ||||      }|D cg c]  }|j                  dd  }	}|j                         }
 | j                  |fi |
\  }}||	|d}|| j                  |ddt        j
                        }|j                         }|j                  ddt        j                  |j                  d      |j                  d	      d
        | j                  dd|i|\  }}|D cg c]0  }|j                  d      j                  t        j                        2 c}|d<   t        ||      S c c}w c c}w )z/
        Preprocess image-like inputs.
        )r9   rZ   r[   r]   rR   N)pixel_valuesoriginal_sizesreshaped_input_sizes   F)r9   expected_ndimsrZ   r[   r   r   )do_normalize
do_rescalerP   rO   pad_sizer9   r   labels)datatensor_typer(   )_prepare_image_like_inputsrU   copy_preprocessr   FIRSTupdater   NEARESTpopsqueezetotorchint64r   )r7   r9   r:   rZ   r[   r\   r]   r3   rM   r`   images_kwargsr_   ra   rh   processed_segmentation_mapssegmentation_maps_kwargs_ms                     r*   _preprocess_image_like_inputsz/SamImageProcessor._preprocess_image_like_inputs   sj    00.L]fl 1 
 9??u%++bc*??-=T-=-=f-V-V**(,$8
 (*.*I*I( $"2"8"8	 +J +' (.{{}$$++$)"' 2 : :488E 8 < <_ M .>T-=-= .2.6N.*' E``qaiilooekk:`DN>BBA @< as   D915D>	do_resizedo_center_crop	crop_sizere   rescale_factorrd   
image_mean	image_stddo_padrf   disable_groupingc           	         t        ||      \  }}i }|j                         D ]   \  }}|r| j                  |||      }|||<   " t        ||      }|D cg c]  }|j                  dd   }}t        ||      \  }}i }|j                         D ]4  \  }}|r| j                  ||      }| j                  ||||	|
|      }|||<   6 t        ||      }|r| j                  |||      }||fS c c}w )N)r   )rM   rO   rP   rR   )rf   r   )r   itemsrV   r   rU   center_croprescale_and_normalizepad)r7   r9   r{   rO   rP   r|   r}   re   r~   rd   r   r   r   rf   r   r3   grouped_imagesgrouped_images_indexresized_images_groupedrU   stacked_imagesresized_imagesrM   ra   processed_images_groupedprocessed_imagess                             r*   rl   zSamImageProcessor._preprocess   sC   & 0EV^n/o,,!#%3%9%9%; 	;!E>!%>W_!`,:"5)	; ((>@TU>LMUBC 0MM 0E^fv/w,,#% %3%9%9%; 	=!E>!%!1!1.)!L!77
NL*V_N /=$U+	= **BDXY#xx(88^nxo!555'  Ns   C-z+np.ndarray | PIL.Image.Image | torch.Tensorcrop_n_layersoverlap_ratiopoints_per_cropcrop_n_points_downscale_factorc                     | j                  |      }t        ||||||      \  }}}	}
|t        j                  d      }|j	                  |      }|j	                  |      }|
j	                  |      }
|||	|
fS )a  
        Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

        Args:
            image (`torch.Tensor`):
                Input original image
            target_size (`int`):
                Target size of the resized image
            crop_n_layers (`int`, *optional*, defaults to 0):
                If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where
                each layer has 2**i_layer number of image crops.
            overlap_ratio (`float`, *optional*, defaults to 512/1500):
                Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
                the image length. Later layers with more crops scale down this overlap.
            points_per_crop (`int`, *optional*, defaults to 32):
                Number of points to sample from each crop.
            crop_n_points_downscale_factor (`list[int]`, *optional*, defaults to 1):
                The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
            device (`torch.device`, *optional*, defaults to None):
                Device to use for the computation. If None, cpu will be used.
        cpu)process_image_generate_crop_boxesrs   r]   rr   )r7   rM   target_sizer   r   r   r   r]   
crop_boxescropped_imagesinput_labelss              r*   generate_crop_boxesz%SamImageProcessor.generate_crop_boxes   s    > ""5)DX*E
A
O^\ >\\%(F]]6*
),,V4#v.?NLHHr)   c	                    |\  }	}
|j                  dd      }|j                  dd      }|j                  d   |j                  d   k7  rt        d      |j                  |j                  k7  r|j	                  |j                        }|j                  d   }t        j                  |t
        j                  |j                        }|dkD  r|||kD  z  }|dkD  rt        |||      }|||kD  z  }||   }||   }||kD  }t        |      }t        ||dd|
|	g       }||   }||   }||   }t        |||	|
      }t        |      }|||fS )a  
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`torch.Tensor`):
                Input masks.
            iou_scores (`torch.Tensor`):
                List of IoU scores.
            original_size (`tuple[int,int]`):
                Size of the original image.
            cropped_box_image (`torch.Tensor`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.
        r      z3masks and iou_scores must have the same batch size.dtyper]           )flattenrU   rS   r]   rr   rs   onesbool_compute_stability_score_batched_mask_to_box_is_box_near_crop_edge
_pad_masks_mask_to_rle)r7   masks
iou_scoresoriginal_sizecropped_box_imagepred_iou_threshstability_score_threshmask_thresholdstability_score_offsetoriginal_heightoriginal_width
batch_size	keep_maskstability_scoresscoresconverted_boxess                   r*   filter_maskszSamImageProcessor.filter_masks-  sw   F +8'''1-
a#;;q>Z--a00RSS<<:,,,#u||4J[[^
JJzELLQ	S !Z/%ABI "C'7~Oef!%58N%NOII&i  &.u5+.A~0W
 
	 	"i ))45"3_nUU#fo--r)   c                    || j                   n|}|d   |d   f}t        |t        j                  t        j
                  f      r|j                         }t        |t        j                  t        j
                  f      r|j                         }g }t        |      D ]  \  }	}
t        ||	   t        j
                        rt        j                  ||	         ||	<   n(t        ||	   t        j                        st        d      t        j                  ||	   |dd      }|dd||	   d	   d||	   d
   f   }t        j                  ||
dd      }|r||kD  }|j                  |        |S )aF  
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
                The original sizes of each image before it was resized to the model's expected input shape, in (height,
                width) format.
            reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
                The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.
        Returns:
            (`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
            is given by original_size.
        Nr1   r2   zIInput masks should be a list of `torch.tensors` or a list of `np.ndarray`bilinearF)modealign_corners.r   r   )rf   rA   rs   Tensornpndarraytolist	enumerate
from_numpy	TypeErrorFinterpolateappend)r7   r   r`   ra   r   binarizerf   target_image_sizeoutput_masksir   interpolated_masks               r*   post_process_masksz$SamImageProcessor.post_process_masks{  sk   > %-$44==(%h/'1BCnu||RZZ&@A+224N*U\\2::,FG#7#>#>#@  ). 9 
	3A}%(BJJ/ ++E!H5aa%,,7 kll !eAh8IPZjo p 1#7S9Ma9PQR9S7SUqWklmWnopWqUq2q r !.?U_ot u$5$F! 12
	3 r)   c                     t        ||||      S )a$  
        Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

        Args:
            all_masks (`torch.Tensor`):
                List of all predicted segmentation masks
            all_scores (`torch.Tensor`):
                List of all predicted iou scores
            all_boxes (`torch.Tensor`):
                List of all bounding boxes of the predicted masks
            crops_nms_thresh (`float`):
                Threshold for NMS (Non Maximum Suppression) algorithm.
        )!_post_process_for_mask_generation)r7   	all_masks
all_scores	all_boxescrops_nms_threshs        r*    post_process_for_mask_generationz2SamImageProcessor.post_process_for_mask_generation  s     1J	Scddr)   N)NN)r   g?    r   N)g)\(?gffffff?r   r   )r   TN)2r    r!   r"   r   valid_kwargsr   BILINEARrP   r   r   r   r   rO   r   r{   re   rd   rZ   r   rf   r   r   r6   r   r   r   r=   r&   r   r$   r%   r   r@   tuplerL   rV   r   r   r   r   rz   listfloatrl   r   r   r   r   r   __classcell__)r8   s   @r*   r-   r-   <   si   *L!**H&J$ID!D%IIJLNF.H"S1M#(?!@ #  04
G
G &,
G 01	
G
 

G 
G MQPT#&c3h7(BTI Xc]*T#s(^;hFM
 
*	uS#X 	c 	 OS	

 
 L	
 

L 590C0C &,0C 	0C
 ,0C j(4/0C c>)*T10C 
0Cd-6^$-6 -6 	-6
 L-6 -6 -6 -6 -6 -6 DK'$.-6 4;&--6 t-6 T/-6 +-6" 
tN#T%S/%::	;#-6f )&(;<+//I</I 	/I
 /I t/I )-S	D(8/I (/In # L.f 3jer)   r-   r   rN   r   r   c                 (   | ||z   kD  j                  dt        j                        j                  dt        j                        }| ||z
  kD  j                  dt        j                        j                  dt        j                        }||z  }|S )Nr   )sumrs   int16int32)r   r   r   intersectionsunionsr   s         r*   r   r     s     
.#99	:??%++?VZZ[]ejepepZq  ~(>>?DDRu{{D[__`bjojuju_vF$v-r)   c                 l   t        j                  |       dk(  r1t        j                  g | j                  dd dd| j                  iS | j                  }|dd \  }}t        j
                  | d      \  }}|t        j                  ||j                        dddf   z  }t        j
                  |d      \  }}||| z  z   }t        j                  |d      \  }}t        j
                  | d      \  }	}|	t        j                  ||	j                        dddf   z  }
t        j
                  |
d      \  }}|
||	 z  z   }
t        j                  |
d      \  }}||k  ||k  z  }t        j                  ||||gd      }|| j                  d      z  } |j                  g |dd d }|S )	aL  
    Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
    corresponds the following required indices:
        - LEFT: left hand side of the bounding box
        - TOP: top of the bounding box
        - RIGHT: right of the bounding box
        - BOTTOM: bottom of the bounding box

    Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
    is channel_1 x channel_2 x ... x 4.

    Args:
        - masks (`torch.Tensor` of shape `(batch, nb_mask, height, width)`)
    r   NrR      r]   r   dimr]   )rs   numelzerosrU   r]   rF   arangeminstack	unsqueezereshape)r   rU   r1   r2   	in_heightrx   in_height_coordsbottom_edges	top_edgesin_widthin_width_coordsright_edges
left_edgesempty_filterouts                  r*   r   r     s   " {{5Q{{EEKK,EaEEE KKE"#JMFE 99U+LIq 5<<y?O?O#PQUWXQX#YYii 0b9OL!'&YJ*??99-26LIq ))Er*KHaeHOO!LTSTW!UUOYYB7NK%((;;OIIo26MJ  *,	1IJL
++z9k<Hb
QC
,))"-
-C #++
%uSbz
%1
%CJr)   c                 p   t        j                  |t         j                  | j                        }t        j                  |t         j                  | j                        }|\  }}}}t        j                  ||||gg| j                        }	t        | j                        dk(  r|	j                  d      }	| |	z   j                         } t        j                  | |dddf   |d      }
t        j                  | |dddf   |d      }t        j                  |
|       }
t        j                  |
d      S )	zNFilter masks at the edge of a crop, but not at the edge of the original image.r   r   r   r   Nr   )atolrtolr   )rs   	as_tensorr   r]   tensorlenrU   r   iscloselogical_andany)boxescrop_boxorig_boxr   crop_box_torchorig_box_torchlefttoprx   offsetnear_crop_edgenear_image_edges               r*   r   r     s    __XU[[VN__XU[[VNOD#q!\\D#tS125<<HF
5;;1!!!$V^""$E]]5.q*ASTUNmmE>$'+BTUVO&&~7GHN99^++r)   r  orig_height
orig_widthc                     |\  }}}}|dk(  r|dk(  r||k(  r||k(  r| S |||z
  z
  |||z
  z
  }	}|||z
  ||	|z
  f}
t         j                  j                  j                  | |
d      S )Nr   )value)rs   nnr	   r   )r   r  r  r  r	  r
  rightbottompad_xpad_yr   s              r*   r   r     s    'D#ufqySAX%:"5&K:O.v|0L5EsECK
0C88""5#Q"77r)   r   r   r   r   r   r;   c                 p   t        | t              rt        d      | j                  dd }g }t	        |dz         D ]-  }t        |||z  z        }	|j                  t        |	             / t        |||      \  }
}t        |
| ||||      \  }}t        j                  |
      }
|
j                         }
t        j                  |      }|j                  d      j                  dddd      }t        j                  |      }t        j                   |dddddddf   t        j"                        }|
|||fS )	a  
    Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

    Args:
        image (`torch.Tensor`):
            Image to generate crops for.
        target_size (`int`):
            Size of the smallest crop.
        crop_n_layers (`int`, *optional*):
            If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers
            to run, where each layer has 2**i_layer number of image crops.
        overlap_ratio (`int`, *optional*):
            Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the
            image length. Later layers with more crops scale down this overlap.
        points_per_crop (`int`, *optional*):
            Number of points to sample per crop.
        crop_n_points_downscale_factor (`int`, *optional*):
            The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
    z.Only one image is allowed for crop generation.rR   Nr   r   rb   r   r   )rA   r   rS   rU   ranger&   r   _build_point_grid_generate_per_layer_crops_generate_crop_imagesrs   r   r   r   r   permute	ones_likert   )rM   r   r   r   r   r   r   points_gridr   n_pointsr   
layer_idxsr   point_grid_per_cropr   s                  r*   r   r     s0   8 %IJJKK$MK=1$% 8*H!*KLM,X678 7}mUbcJ
*?E;
K+'N' j)J!!#Jkk"56O%//2::1aAFO[[0N???1aA:#>ekkRLDDr)   c           	         g g }}|\  }}t        ||      }|j                  dd||g       |j                  d       t        |       D ]  }d|dz   z  }	t        ||z  d|	z  z        }
t        t	        j
                  |
|	dz
  z  |z   |	z              }t        t	        j
                  |
|	dz
  z  |z   |	z              }t        |	      D cg c]  }t        ||
z
  |z         }}t        |	      D cg c]  }t        ||
z
  |z         }}t        ||      D ]J  \  }}||t        ||z   |      t        ||z   |      g}|j                  |       |j                  |dz          L  ||fS c c}w c c}w )aq  
    Generates 2 ** (layers idx + 1) crops for each crop_n_layers. Crops are in the XYWH format : The XYWH format
    consists of the following required indices:
        - X: X coordinate of the top left of the bounding box
        - Y: Y coordinate of the top left of the bounding box
        - W: width of the bounding box
        - H: height of the bounding box
    r   rb   r   )r   r   r  r&   mathceilr   )r   r   r   r   r   	im_heightim_width
short_sidei_layern_crops_per_sideoverlap
crop_widthcrop_heightr   crop_box_x0crop_box_y0r	  r
  boxs                      r*   r  r  N  s     
J'IxY)J q!Xy12a' +1-mj0A8H4HIJG/?!/C$Dx$OSc#cde
$))W0@10D%E	%QUe$efg@EFV@WX1sJ0A56XXAFGWAXYAsK'1Q67YY k: 	+ID#c$"3X>C+DUW`@abCc"gk*	++ z!! YYs   E)/E.
n_per_sidec                    dd| z  z  }t        j                  |d|z
  |       }t        j                  |dddf   | df      }t        j                  |dddf   d| f      }t        j                  ||gd      j	                  dd      }|S )z;Generates a 2D grid of points evenly spaced in [0,1]x[0,1].r   rb   Nr   r   )rs   linspacetiler   r   )r0  r  points_one_sidepoints_xpoints_ypointss         r*   r  r  p  s    !j.!FnnVQZDOzz/$'2ZODHzz/!T'2Q
ODH[[(H-26>>r1EFMr)   c                 \   g }g }t        |       D ]  \  }	}
|
\  }}}}|dd||||f   }|j                  |       |j                  dd }t        j                  |      j                  d      j                  d      }|||	      |z  }t        |||      }|j                  |        ||fS )z
    Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are
    also passed.
    NrR   )r   )dimsr   )r   r   rU   rs   r   flipr   _normalize_coordinates)r   rM   r  r   r   r   r[   r   total_points_per_cropr   r  r	  r
  r  r  
cropped_imcropped_im_sizepoints_scaler7  normalized_pointss                       r*   r  r  z  s     N , 88#+ c5&1c&j$u*45
j)$**23/||O499t9DNNqQZ]+l:2;V$$%678 000r)   coordsr   c                 <   |\  }}| dz  t        ||      z  }||z  ||z  }}t        |dz         }t        |dz         }t        |      j                         }|r|j	                  ddd      }|d   ||z  z  |d<   |d   ||z  z  |d<   |r|j	                  dd      }|S )z
    Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
    format.
    rD   rE   r   rb   ).r   ).r   r   )rF   r&   r   r   r   )	r   rA  r   is_bounding_box
old_height	old_widthrI   
new_height	new_widths	            r*   r;  r;    s     *J	#J	 ::E&.	E0A	JIO$IZ#%&Jf##%FAq)F^y9'<=F6NF^zJ'>?F6NA&Mr)   rlec                     | d   \  }}t        j                  ||z  t              }d}d}| d   D ]  }|||||z    ||z  }| } |j                  ||      }|j	                  dd      S )z/Compute a binary mask from an uncompressed RLE.rO   r   r   Fcountsr   )rs   emptyr   r   	transpose)rH  r1   r2   maskidxparitycounts          r*   _rle_to_maskrQ    s    KMFE;;v~T2D
CFX "(S3;u <<v&D>>!Qr)   c                    t        |j                         |t        j                  |j                  d         |      }||   }|D cg c]  }| |   	 } }||   }| D cg c]  }t        |       }}||| |fS c c}w c c}w )a  
    Perform NMS (Non Maximum Suppression) on the outputs.

    Args:
            rle_masks (`torch.Tensor`):
                binary masks in the RLE format
            iou_scores (`torch.Tensor` of shape (nb_masks, 1)):
                iou_scores predicted by the model
            mask_boxes (`torch.Tensor`):
                The bounding boxes corresponding to segmentation masks
            amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
                NMS threshold.
    r   )r  r   idxsiou_threshold)r
   r   rs   r   rU   rQ  )	rle_masksr   
mask_boxesamg_crops_nms_threshkeep_by_nmsr   rH  r   s           r*   r   r     s      [[))!,-*	K K(J'23!13I3K(J*343\#4E4*i33	 44s   A8A=c                    | j                   \  }}}| j                  ddd      j                  d      } | ddddf   | ddddf   z  }|j                         }g }t	        |      D ]  }||dddf   |k(  df   dz   }t        |      dk(  rA| |df   dk(  r|j                  ||g||z  gd       n|j                  ||gd||z  gd       f|dd |dd z
  }	| |df   dk(  rg ndg}
|
|d   j                         g|	j                         z   ||z  |d   j                         z
  gz   z  }
|j                  ||g|
d        |S )z^
    Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
    r   rb   r   Nr   )rO   rJ  )	rU   r  r   nonzeror  r   r   itemr   )
input_maskr   r1   r2   diffchange_indicesr   r   cur_idxsbtw_idxsrJ  s              r*   r   r     s   
 !+ 0 0J##Aq!,44Q7J aez!SbS&11D\\^N C: @!.A"6!";Q">?!Cx=A !Q$1$

VUO?OPQ

VUO6E>?RSTAB<(3B-/!!Q$'1,1#8A;##%&)::funxXZ|O`O`Ob>b=ccc

VUOv>?@ Jr)   )r   rN   )g      4@)r   r   r   r   r   )F)gffffff?)r\  rN   )Cr#   r#  collections.abcr   rk   r   	itertoolsr   typingr   r   r   numpyr   rs   torch.nnr	   r   torchvision.ops.boxesr
   torchvision.transforms.v2tvFimage_processing_backendsr   image_processing_utilsr   r   image_transformsr   r   image_utilsr   r   r   r   r   r   processing_utilsr   r   utilsr   r   r   PILr   r-   r   r&   r   r   r   r   r   r   r   r  r   r  r  r;  r$   r%   rQ  r   r   __all__r(   r)   r*   <module>rq     s   %  $   ' '   $ - 7 ; A E  5 D D 
"l% 
" Ae* Ae AeHN E cf .b,$8S	 8 8 8 %"$782E2E 2E 	2E
 4Z2E %)I$42E 4S	?DI%&2Ej"D# %,,  _c14 ]b#ll;@c?
\\8 d38n    4:> 
r)   