§
    l¬¸j
.  ã                  óª   — d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	Z
d dlZ	 d1d2d„Zd3d„Zd4d„Zd5d„Zd6d„Zd7d#„Zd8d$„Zd9d&„Zd:d)„Zd;d/„Zd<d0„ZdS )=é    )ÚannotationsN)Ú	Generator)Úproduct)ÚAnyç      4@Úboxesútorch.TensorÚcrop_boxú	list[int]Úorig_boxÚatolÚfloatÚreturnc                ó¾  — t          j        |t           j        | j        ¬¦  «        }t          j        |t           j        | j        ¬¦  «        }t	          | |¦  «                             ¦   «         } t          j        | |ddd…f         |d¬¦  «        }t          j        | |ddd…f         |d¬¦  «        }t          j        || ¦  «        }t          j        |d¬¦  «        S )a	  Determine if bounding boxes are near the edge of a cropped image region using a specified tolerance.

    Args:
        boxes (torch.Tensor): Bounding boxes in XYXY format.
        crop_box (list[int]): Crop box coordinates in [x0, y0, x1, y1] format.
        orig_box (list[int]): Original image box coordinates in [x0, y0, x1, y1] format.
        atol (float, optional): Absolute tolerance for edge proximity detection.

    Returns:
        (torch.Tensor): Boolean tensor indicating which boxes are near crop edges.

    Examples:
        >>> boxes = torch.tensor([[10, 10, 50, 50], [100, 100, 150, 150]])
        >>> crop_box = [0, 0, 200, 200]
        >>> orig_box = [0, 0, 300, 300]
        >>> near_edge = is_box_near_crop_edge(boxes, crop_box, orig_box, atol=20.0)
    )ÚdtypeÚdeviceNr   )r   Úrtolé   ©Údim)ÚtorchÚ	as_tensorr   r   Úuncrop_boxes_xyxyÚiscloseÚlogical_andÚany)r   r
   r   r   Úcrop_box_torchÚorig_box_torchÚnear_crop_edgeÚnear_image_edges           új/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/sam/amg.pyÚis_box_near_crop_edger"      sÉ   € õ( ”_ XµU´[ÈÌÐVÑVÔV€NÝ”_ XµU´[ÈÌÐVÑVÔV€NÝ˜e XÑ.Ô.×4Ò4Ñ6Ô6€EÝ”] 5¨.¸¸q¸q¸q¸Ô*AÈÐSTÐUÑUÔU€NÝ”m E¨>¸$ÀÀÀ¸'Ô+BÈÐTUÐVÑVÔV€OÝÔ& ~¸Ð7GÑHÔH€NÝŒ9�^¨Ð+Ñ+Ô+Ð+ó    Ú
batch_sizeÚintúGenerator[list[Any]]c              '  ó(  ‡ ‡‡K  — ‰rt          ˆfd„‰D ¦   «         ¦  «        s
J d¦   «         ‚t          ‰d         ¦  «        ‰ z  t          t          ‰d         ¦  «        ‰ z  dk    ¦  «        z   }t          |¦  «        D ]Šˆˆ fd„‰D ¦   «         V — ŒdS )a  Yield batches of data from input arguments with specified batch size for efficient processing.

    This function takes a batch size and any number of iterables, then yields batches of elements from those
    iterables. All input iterables must have the same length.

    Args:
        batch_size (int): Size of each batch to yield.
        *args (Any): Variable length input iterables to batch. All iterables must have the same length.

    Yields:
        (list[Any]): A list of batched elements from each input iterable.

    Examples:
        >>> data = [1, 2, 3, 4, 5]
        >>> labels = ["a", "b", "c", "d", "e"]
        >>> for batch in batch_iterator(2, data, labels):
        ...     print(batch)
        [[1, 2], ['a', 'b']]
        [[3, 4], ['c', 'd']]
        [[5], ['e']]
    c              3  ód   •K  — | ]*}t          |¦  «        t          ‰d          ¦  «        k    V — Œ+dS )r   N)Úlen)Ú.0ÚaÚargss     €r!   ú	<genexpr>z!batch_iterator.<locals>.<genexpr>A   s8   øè è € Ð=Ð=°1�˜A™œ¥# d¨1¤g¡,¤,Ò.Ð=Ð=Ð=Ð=Ð=Ð=r#   z-Batched iteration must have same-size inputs.r   c                ó6   •— g | ]}|‰‰z  ‰d z   ‰z  …         ‘ŒS ©r   © )r*   ÚargÚbr$   s     €€r!   ú
<listcomp>z"batch_iterator.<locals>.<listcomp>D   s0   ø€ ÐJÐJÐJ¸cˆs�1�z‘> Q¨¡U¨jÑ$8Ð8Ô9ÐJÐJÐJr#   N)Úallr)   r%   Úrange)r$   r,   Ú	n_batchesr2   s   `` @r!   Úbatch_iteratorr7   +   sÂ   øøøè è € ð, Ðn•CÐ=Ð=Ð=Ð=¸Ð=Ñ=Ô=Ñ=Ô=ÐnÐnÐ?nÑnÔnÐ=Ý�D˜”G‘” 
Ñ*­Sµ°T¸!´W±´À
Ñ1JÈaÒ1OÑ-PÔ-PÑP€IÝ�9ÑÔð Kð KˆØJÐJÐJÐJÐJÀTÐJÑJÔJÐJÐJÐJÐJðKð Kr#   ÚmasksÚmask_thresholdÚthreshold_offsetc                ó(  — | ||z   k                          dt          j        ¬¦  «                              dt          j        ¬¦  «        }| ||z
  k                          dt          j        ¬¦  «                              dt          j        ¬¦  «        }||z  S )a”  Compute the stability score for a batch of masks.

    The stability score is the IoU between binary masks obtained by thresholding the predicted mask logits at high and
    low values.

    Args:
        masks (torch.Tensor): Batch of predicted mask logits.
        mask_threshold (float): Threshold value for creating binary masks.
        threshold_offset (float): Offset applied to the threshold for creating high and low binary masks.

    Returns:
        (torch.Tensor): Stability scores for each mask in the batch.

    Examples:
        >>> masks = torch.rand(10, 256, 256)  # Batch of 10 masks
        >>> mask_threshold = 0.5
        >>> threshold_offset = 0.1
        >>> stability_scores = calculate_stability_score(masks, mask_threshold, threshold_offset)

    Notes:
        - One mask is always contained inside the other.
        - Memory is saved by preventing unnecessary cast to torch.int64.
    éÿÿÿÿ)r   )Úsumr   Úint16Úint32)r8   r9   r:   ÚintersectionsÚunionss        r!   Úcalculate_stability_scorerB   G   s‹   € ð0 ˜nÐ/?Ñ?Ò@×EÒEÀbÕPUÔP[ÐEÑ\Ô\×`Ò`ÐacÕkpÔkvÐ`ÑwÔw€MØ�~Ð(8Ñ8Ò9×>Ò>¸rÍÌÐ>ÑUÔU×YÒYÐZ\ÕdiÔdoÐYÑpÔp€FØ˜6Ñ!Ð!r#   Ú
n_per_sideú
np.ndarrayc                ó   — 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¬¦  «                             dd¦  «        S )zaGenerate a 2D grid of evenly spaced points in the range [0,1]x[0,1] for image segmentation tasks.r   é   Nr<   )Úaxis)ÚnpÚlinspaceÚtileÚstackÚreshape)rC   ÚoffsetÚpoints_one_sideÚpoints_xÚpoints_ys        r!   Úbuild_point_gridrQ   d   s•   € à�!�j‘.Ñ!€FÝ”k &¨!¨f©*°jÑAÔA€OÝŒw� t¨Q¨Q¨Q wÔ/°*¸a°ÑAÔA€HÝŒw� q q q¨$ wÔ/°!°Z°ÑAÔA€HÝŒ8�X˜xÐ(¨rÐ2Ñ2Ô2×:Ò:¸2¸qÑAÔAÐAr#   Ún_layersÚscale_per_layerúlist[np.ndarray]c                óD   ‡ ‡— ˆ ˆfd„t          |dz   ¦  «        D ¦   «         S )zPGenerate point grids for multiple crop layers with varying scales and densities.c           	     óT   •— g | ]$}t          t          ‰‰|z  z  ¦  «        ¦  «        ‘Œ%S r0   )rQ   r%   )r*   ÚirC   rS   s     €€r!   r3   z/build_all_layer_point_grids.<locals>.<listcomp>o   s4   ø€ ÐbÐbÐbÈÕ�S ¨ÀÑ/AÑ!BÑCÔCÑDÔDÐbÐbÐbr#   r   )r5   )rC   rR   rS   s   ` `r!   Úbuild_all_layer_point_gridsrX   m   s0   øø€ àbÐbÐbÐbÐbÍeÐT\Ð_`ÑT`ÑNaÔNaÐbÑbÔbÐbr#   Úim_sizeútuple[int, ...]Úoverlap_ratioú!tuple[list[list[int]], list[int]]c           	     ó‚  ‡‡‡— g g }}| \  }}t          ||¦  «        }|                     dd||g¦  «         |                     d¦  «         d„ }t          |¦  «        D ]ß}	d|	dz   z  }
t          ||z  d|
z  z  ¦  «        Š |||
‰¦  «        Š |||
‰¦  «        Šˆˆfd„t          |
¦  «        D ¦   «         }ˆˆfd„t          |
¦  «        D ¦   «         }t	          ||¦  «        D ]Z\  }}||t          |‰z   |¦  «        t          |‰z   |¦  «        g}|                     |¦  «         |                     |	dz   ¦  «         Œ[Œà||fS )aá  Generate crop boxes of varying sizes for multiscale image processing, with layered overlapping regions.

    Args:
        im_size (tuple[int, ...]): Height and width of the input image.
        n_layers (int): Number of layers to generate crop boxes for.
        overlap_ratio (float): Ratio of overlap between adjacent crop boxes.

    Returns:
        crop_boxes (list[list[int]]): List of crop boxes in [x0, y0, x1, y1] format.
        layer_idxs (list[int]): List of layer indices corresponding to each crop box.

    Examples:
        >>> im_size = (800, 1200)  # Height, width
        >>> n_layers = 3
        >>> overlap_ratio = 0.25
        >>> crop_boxes, layer_idxs = generate_crop_boxes(im_size, n_layers, overlap_ratio)
    r   c                óB   — t          j        ||dz
  z  | z   |z  ¦  «        S )zZCalculate the length of each crop given the original length, number of crops, and overlap.r   )ÚmathÚceil)Úorig_lenÚn_cropsÚoverlaps      r!   Úcrop_lenz%generate_crop_boxes.<locals>.crop_lenŽ   s%   € åŒy˜' W¨q¡[Ñ1°HÑ<ÀÑGÑHÔHÐHr#   rF   r   c                ó:   •— g | ]}t          ‰‰z
  |z  ¦  «        ‘ŒS r0   ©r%   )r*   rW   Úcrop_wrc   s     €€r!   r3   z'generate_crop_boxes.<locals>.<listcomp>™   ó+   ø€ ÐTÐTÐT°q•s˜F WÑ,°Ñ1Ñ2Ô2ÐTÐTÐTr#   c                ó:   •— g | ]}t          ‰‰z
  |z  ¦  «        ‘ŒS r0   rf   )r*   rW   Úcrop_hrc   s     €€r!   r3   z'generate_crop_boxes.<locals>.<listcomp>š   rh   r#   )ÚminÚappendr5   r%   r   )rY   rR   r[   Ú
crop_boxesÚ
layer_idxsÚim_hÚim_wÚ
short_siderd   Úi_layerÚn_crops_per_sideÚcrop_box_x0Úcrop_box_y0Úx0Úy0Úboxrj   rg   rc   s                   @@@r!   Úgenerate_crop_boxesry   r   sª  øøø€ ð(   �
€JØ�J€Dˆ$Ý�T˜4‘”€Jð ×Ò�q˜!˜T 4Ð(Ñ)Ô)Ð)Ø×Ò�aÑÔÐðIð Ið Iõ ˜‘?”?ð +ð +ˆØ ¨1¡Ñ-ÐÝ�m jÑ0°AÐ8HÑ4HÑIÑJÔJˆà�˜$Ð 0°'Ñ:Ô:ˆØ�˜$Ð 0°'Ñ:Ô:ˆàTÐTÐTÐTÐT½EÐBRÑ<SÔ<SÐTÑTÔTˆØTÐTÐTÐTÐT½EÐBRÑ<SÔ<SÐTÑTÔTˆõ ˜k¨;Ñ7Ô7ð 	+ð 	+‰FˆB�Ø�r�3˜r F™{¨DÑ1Ô1µ3°r¸F±{ÀDÑ3IÔ3IÐJˆCØ×Ò˜cÑ"Ô"Ð"Ø×Ò˜g¨™kÑ*Ô*Ð*Ð*ð	+ð
 �zÐ!Ð!r#   c                ó´   — |\  }}}}t          j        ||||gg| j        ¬¦  «        }t          | j        ¦  «        dk    r|                     d¦  «        }| |z   S )zIUncrop bounding boxes by adding the crop box offset to their coordinates.©r   é   r   ©r   Útensorr   r)   ÚshapeÚ	unsqueeze)r   r
   rv   rw   Ú_rM   s         r!   r   r   ¥   sc   € à�L€BˆˆAˆqÝŒ\˜B  B¨Ð+Ð,°U´\ÐBÑBÔB€Få
ˆ5Œ;ÑÔ˜1ÒÐØ×!Ò! !Ñ$Ô$ˆØ�6‰>Ðr#   Úpointsc                ó°   — |\  }}}}t          j        ||gg| j        ¬¦  «        }t          | j        ¦  «        dk    r|                     d¦  «        }| |z   S )zAUncrop points by adding the crop box offset to their coordinates.r{   r|   r   r}   )r‚   r
   rv   rw   r�   rM   s         r!   Úuncrop_pointsr„   ¯   s]   € à�L€BˆˆAˆqÝŒ\˜B ˜8˜*¨V¬]Ð;Ñ;Ô;€Få
ˆ6Œ<ÑÔ˜AÒÐØ×!Ò! !Ñ$Ô$ˆØ�F‰?Ðr#   Úorig_hÚorig_wc                óÊ   — |\  }}}}|dk    r|dk    r||k    r||k    r| S |||z
  z
  |||z
  z
  }	}|||z
  ||	|z
  f}
t           j        j                             | |
d¬¦  «        S )z]Uncrop masks by padding them to the original image size, handling coordinate transformations.r   )Úvalue)r   ÚnnÚ
functionalÚpad)r8   r
   r…   r†   rv   rw   Úx1Úy1Úpad_xÚpad_yr‹   s              r!   Úuncrop_masksr�   ¹   s†   € à�N€BˆˆB�Ø	ˆQ‚w€w�2˜’7�7˜r Vš|˜|°°f²°Øˆà˜R "™WÑ% v°°b±Ñ'9ˆ5€EØˆu�r‰z˜2˜u r™zÐ
*€CÝŒ8Ô×"Ò" 5¨#°QÐ"Ñ7Ô7Ð7r#   ÚmaskÚarea_threshÚmodeÚstrútuple[np.ndarray, bool]c                óâ  ‡‡— ddl }|dv sJ d|› d�¦   «         ‚|dk    }|| z                       t          j        ¦  «        }|                     |d¦  «        \  }}}}	|dd…df         d	d…         }
ˆfd
„t          |
¦  «        D ¦   «         }|s| dfS dg|¢Š|s@ˆfd„t          |¦  «        D ¦   «         p$t          t          j        |
¦  «        ¦  «        d	z   gŠt          j	        |‰¦  «        } | dfS )a  Remove small disconnected regions or holes in a mask based on area threshold and mode.

    Args:
        mask (np.ndarray): Binary mask to process.
        area_thresh (float): Area threshold below which regions will be removed.
        mode (str): Processing mode, either 'holes' to fill small holes or 'islands' to remove small disconnected
            regions.

    Returns:
        processed_mask (np.ndarray): Processed binary mask with small regions removed.
        modified (bool): Whether any regions were modified.

    Examples:
        >>> mask = np.zeros((100, 100), dtype=np.bool_)
        >>> mask[40:60, 40:60] = True  # Create a square
        >>> mask[45:55, 45:55] = False  # Create a hole
        >>> processed_mask, modified = remove_small_regions(mask, 50, "holes")
    r   N>   ÚholesÚislandszProvided mode z is invalidr—   é   r<   r   c                ó,   •— g | ]\  }}|‰k     ¯|d z   ‘ŒS r/   r0   )r*   rW   Úsr’   s      €r!   r3   z(remove_small_regions.<locals>.<listcomp>Þ   s&   ø€ ÐKÐKÐK™t˜q !¸1¸{º?¸?�Q˜‘U¸?¸?¸?r#   Fc                ó   •— g | ]}|‰v¯|‘Œ	S r0   r0   )r*   rW   Úfill_labelss     €r!   r3   z(remove_small_regions.<locals>.<listcomp>ä   s#   ø€ ÐJÐJÐJ˜Q°Q¸kÐ5IÐ5I�qÐ5IÐ5IÐ5Ir#   T)
Úcv2ÚastyperH   Úuint8ÚconnectedComponentsWithStatsÚ	enumerater5   r%   ÚargmaxÚisin)r‘   r’   r“   rž   Úcorrect_holesÚworking_maskÚn_labelsÚregionsÚstatsr�   ÚsizesÚsmall_regionsr�   s    `          @r!   Úremove_small_regionsr¬   Ä   s7  øø€ ð& €J€J€JàÐ'Ð'Ð'Ð'Ð)K¸$Ð)KÐ)KÐ)KÑ'Ô'Ð'Ø˜G’O€MØ! DÑ(×0Ò0µ´Ñ:Ô:€LØ"%×"BÒ"BÀ<ÐQRÑ"SÔ"SÑ€Hˆg�u˜aØ�!�!�!�R�%ŒL˜˜˜Ô€EØKÐKÐKÐK¥y°Ñ'7Ô'7ÐKÑKÔK€MØð Ø�Uˆ{ÐØÐ%�}Ð%€KØð jàJÐJÐJÐJ¥%¨¡/¤/ÐJÑJÔJÐiÍsÕSUÔS\Ð]bÑScÔScÑOdÔOdÐghÑOhÐNiˆÝŒ7�7˜KÑ(Ô(€DØ�ˆ:Ðr#   c                óú  — t          j        | ¦  «        dk    r(t          j        g | j        dd…         ¢d‘R d| j        iŽS | j        }|dd…         \  }}t          |¦  «        dk    r|                      dd¦  «        n|                      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¬	¦  «        }||                      d¦  «        z  }t          |¦  «        dk    r |j        g |dd…         ¢d‘R Ž n|d         S )a  Calculate bounding boxes in XYXY format around binary masks.

    Args:
        masks (torch.Tensor): Binary masks with shape (B, H, W) or (B, C, H, W).

    Returns:
        (torch.Tensor): Bounding boxes in XYXY format with shape (B, 4) or (B, C, 4).

    Notes:
        - Handles empty masks by returning zero boxes.
        - Preserves input tensor dimensions in the output.
    r   Néþÿÿÿé   r   rF   éýÿÿÿr<   r   r{   )r   ÚnumelÚzerosr   r   r)   Úflattenr€   ÚmaxÚarangerk   rK   rL   )r8   r   ÚhÚwÚ	in_heightr�   Úin_height_coordsÚbottom_edgesÚ	top_edgesÚin_widthÚin_width_coordsÚright_edgesÚ
left_edgesÚempty_filterÚouts                  r!   Úbatched_mask_to_boxrÂ   é   s+  € õ „{�5ÑÔ˜QÒÐÝŒ{ÐE˜EœK¨¨¨Ô,ÐE¨aÐEÐEÐE¸¼ÐEÐEÐEð ŒK€EØ���Œ:�D€A€qÝ$'¨¡J¤J°¢N NˆE�MŠM˜!˜RÑ Ô Ð ¸¿ºÈÑ8JÔ8J€Eå”9˜U¨Ð+Ñ+Ô+�L€IˆqØ ¥5¤<°¸)Ô:JÐ#KÑ#KÔ#KÈDÐRSÐRSÐRSÈGÔ#TÑTÐÝ”iÐ 0°bÐ9Ñ9Ô9�O€L�!Ø'¨!°	¨zÑ*:Ñ:ÐÝ”9Ð-°2Ð6Ñ6Ô6�L€Iˆqõ ”)˜E rÐ*Ñ*Ô*�K€HˆaØ¥¤¨a¸¼Ð!HÑ!HÔ!HÈÈqÈqÈqÈÔ!QÑQ€OÝ”Y˜°BÐ7Ñ7Ô7�N€K�Ø%¨¨h¨Y©Ñ7€OÝ”I˜o°2Ð6Ñ6Ô6�M€J�ð   *Ò,°À	Ò1IÑJ€LÝ
Œ+�z 9¨k¸<ÐHÈbÐ
QÑ
QÔ
Q€CØ
�,�×)Ò)¨"Ñ-Ô-Ñ
-€Cõ +.¨e©*¬*°qª.¨.ˆ;ˆ3Œ;Ð&˜˜c˜r˜cœ
Ð& AÐ&Ð&Ð&Ð&¸cÀ!¼fÐDr#   )r   )
r   r	   r
   r   r   r   r   r   r   r	   )r$   r%   r   r&   )r8   r	   r9   r   r:   r   r   r	   )rC   r%   r   rD   )rC   r%   rR   r%   rS   r%   r   rT   )rY   rZ   rR   r%   r[   r   r   r\   )r   r	   r
   r   r   r	   )r‚   r	   r
   r   r   r	   )
r8   r	   r
   r   r…   r%   r†   r%   r   r	   )r‘   rD   r’   r   r“   r”   r   r•   )r8   r	   r   r	   )Ú
__future__r   r_   Úcollections.abcr   Ú	itertoolsr   Útypingr   ÚnumpyrH   r   r"   r7   rB   rQ   rX   ry   r   r„   r�   r¬   rÂ   r0   r#   r!   ú<module>rÈ      ss  ðð #Ð "Ð "Ð "Ð "Ð "à €€€Ø %Ð %Ð %Ð %Ð %Ð %Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø €€€ð RVð,ð ,ð ,ð ,ð ,ð:Kð Kð Kð Kð8"ð "ð "ð "ð:Bð Bð Bð Bðcð cð cð cð
0"ð 0"ð 0"ð 0"ðfð ð ð ðð ð ð ð8ð 8ð 8ð 8ð"ð "ð "ð "ðJ*Eð *Eð *Eð *Eð *Eð *Er#   