
    FPh\                         d Z ddlZddlZddlmc m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 ddlmZ dd	lmZmZmZmZmZmZmZmZmZ dd
lmZ  G d de      Z y)a  
Generate predictions using the Segment Anything Model (SAM).

SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
segmentation tasks.
    N)	LetterBox)BasePredictor)Results)DEFAULT_CFGops)select_device   )	batch_iteratorbatched_mask_to_boxbuild_all_layer_point_gridscalculate_stability_scoregenerate_crop_boxesis_box_near_crop_edgeremove_small_regionsuncrop_boxes_xyxyuncrop_masks)	build_samc                        e Zd ZdZeddf fd	Zd Zd ZddZddZ		 	 	 	 	 	 	 	 	 	 ddZ
dd	Zd
 Z fdZd Zd Zd Zedd       Z xZS )	Predictora  
    Predictor class for the Segment Anything Model (SAM), extending BasePredictor.

    The class provides an interface for model inference tailored to image segmentation tasks.
    With advanced architecture and promptable segmentation capabilities, it facilitates flexible and real-time
    mask generation. The class is capable of working with various types of prompts such as bounding boxes,
    points, and low-resolution masks.

    Attributes:
        cfg (dict): Configuration dictionary specifying model and task-related parameters.
        overrides (dict): Dictionary containing values that override the default configuration.
        _callbacks (dict): Dictionary of user-defined callback functions to augment behavior.
        args (namespace): Namespace to hold command-line arguments or other operational variables.
        im (torch.Tensor): Preprocessed input image tensor.
        features (torch.Tensor): Extracted image features used for inference.
        prompts (dict): Collection of various prompt types, such as bounding boxes and points.
        segment_all (bool): Flag to control whether to segment all objects in the image or only specified ones.
    Nc                     |i }|j                  t        ddd             t        |   |||       d| j                  _        d| _        d| _        i | _        d| _	        y)a=  
        Initialize the Predictor with configuration, overrides, and callbacks.

        The method sets up the Predictor object and applies any configuration overrides or callbacks provided. It
        initializes task-specific settings for SAM, such as retina_masks being set to True for optimal results.

        Args:
            cfg (dict): Configuration dictionary.
            overrides (dict, optional): Dictionary of values to override default configuration.
            _callbacks (dict, optional): Dictionary of callback functions to customize behavior.
        Nsegmentpredicti   )taskmodeimgszTF)
updatedictsuper__init__argsretina_masksimfeaturespromptssegment_all)selfcfg	overrides
_callbacks	__class__s       iC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/models/sam/predict.pyr   zPredictor.__init__/   sa     I99DIJi4!%		     c                    | j                   | j                   S t        |t        j                         }|rgt	        j
                  | j                  |            }|ddddf   j                  d      }t	        j                  |      }t        j                  |      }|j                  | j                        }| j                  j                  r|j                         n|j                         }|r|| j                   z
  | j"                  z  }|S )a  
        Preprocess the input image for model inference.

        The method prepares the input image by applying transformations and normalization.
        It supports both torch.Tensor and list of np.ndarray as input formats.

        Args:
            im (torch.Tensor | List[np.ndarray]): BCHW tensor format or list of HWC numpy arrays.

        Returns:
            (torch.Tensor): The preprocessed image tensor.
        N.)r      r	      )r"   
isinstancetorchTensornpstackpre_transform	transposeascontiguousarray
from_numpytodevicemodelfp16halffloatmeanstd)r&   r"   
not_tensors      r+   
preprocesszPredictor.preprocessE   s     7777N#B55
$,,R01BC2I((6B%%b)B!!"%BUU4;;**//RWWYrxxztyy.DHH,B	r,   c                     t        |      dk(  sJ d       t        | j                  j                  dd      }|D cg c]  } ||       c}S c c}w )a  
        Perform initial transformations on the input image for preprocessing.

        The method applies transformations such as resizing to prepare the image for further preprocessing.
        Currently, batched inference is not supported; hence the list length should be 1.

        Args:
            im (List[np.ndarray]): List containing images in HWC numpy array format.

        Returns:
            (List[np.ndarray]): List of transformed images.
        r	   z6SAM model does not currently support batched inferenceF)autocenter)image)lenr   r    r   )r&   r"   	letterboxxs       r+   r6   zPredictor.pre_transforma   sM     2w!|UUU|diiooE%H	,./Bq	"B///s   Ac                 ,   | j                   j                  d|      }| j                   j                  d|      }| j                   j                  d|      }t        d |||fD              r | j                  |g|i |S | j	                  ||||||      S )a  
        Perform image segmentation inference based on the given input cues, using the currently loaded image. This
        method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
        mask decoder for real-time and promptable segmentation tasks.

        Args:
            im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
            bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixel coordinates.
            labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 for foreground and 0 for background.
            masks (np.ndarray, optional): Low-resolution masks from previous predictions. Shape should be (N, H, W). For SAM, H=W=256.
            multimask_output (bool, optional): Flag to return multiple masks. Helpful for ambiguous prompts. Defaults to False.

        Returns:
            (tuple): Contains the following three elements.
                - np.ndarray: The output masks in shape CxHxW, where C is the number of generated masks.
                - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
                - np.ndarray: Low-resolution logits of shape CxHxW for subsequent inference, where H=W=256.
        bboxespointsmasksc              3   $   K   | ]  }|d u  
 y wN .0is     r+   	<genexpr>z&Predictor.inference.<locals>.<genexpr>   s     :"9QqDy"9s   )r$   popallgenerateprompt_inference)	r&   r"   rL   rM   labelsrN   multimask_outputr    kwargss	            r+   	inferencezPredictor.inferencer   s    * !!(F3!!(F3  %0:665"9:: 4==5d5f55$$RHXYYr,   c                    | j                   | j                  j                  |      n| j                   }| j                  d   d   j                  dd |j                  dd }	}| j
                  rdnt        |	d   |d   z  |	d   |d   z        }
|t        j                  |t        j                  | j                        }|j                  dk(  r|d   n|}|"t        j                  |j                  d         }t        j                  |t        j                  | j                        }||
z  }|dddddf   |dddf   }}|Kt        j                  |t        j                  | j                        }|j                  dk(  r|d   n|}||
z  }|?t        j                  |t        j                  | j                        j                  d      }|||fnd}| j                  j!                  |||      \  }}| j                  j#                  || j                  j                   j%                         |||      \  }}|j'                  dd      |j'                  dd      fS )	aJ  
        Internal function for image segmentation inference based on cues like bounding boxes, points, and masks.
        Leverages SAM's specialized architecture for prompt-based, real-time segmentation.

        Args:
            im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
            bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixel coordinates.
            labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 for foreground and 0 for background.
            masks (np.ndarray, optional): Low-resolution masks from previous predictions. Shape should be (N, H, W). For SAM, H=W=256.
            multimask_output (bool, optional): Flag to return multiple masks. Helpful for ambiguous prompts. Defaults to False.

        Returns:
            (tuple): Contains the following three elements.
                - np.ndarray: The output masks in shape CxHxW, where C is the number of generated masks.
                - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
                - np.ndarray: Low-resolution logits of shape CxHxW for subsequent inference, where H=W=256.
        Nr	   r   r0   g      ?dtyper;   )rM   boxesrN   )image_embeddingsimage_pesparse_prompt_embeddingsdense_prompt_embeddingsr[   )r#   r<   image_encoderbatchshaper%   minr2   	as_tensorfloat32r;   ndimr4   onesint32	unsqueezeprompt_encodermask_decoderget_dense_peflatten)r&   r"   rL   rM   rZ   rN   r[   r#   	src_shape	dst_shapersparse_embeddingsdense_embeddings
pred_maskspred_scoress                  r+   rY   zPredictor.prompt_inference   s!   & 48==3H4::++B/dmm#zz!}Q/55bq9288AB<9	##CYq\IaL-H)TU,YbcdYeJe)f__V5==UF%+[[A%5VD\6F~a1__V5;;t{{SFaKF#AtQJ/4FF__V5==UF%+[[A%5VD\6FaKFOOEt{{S]]^_`E%+%7&&!T.2jj.G.Gv]ckp.G.q++ #'**"9"9%ZZ..;;=%6$4- #: #

K !!!Q')<)<Q)BBBr,   c           
      (   d| _         |j                  dd \  }}t        ||f||      \  }}|t        |||      }g g g g f\  }}}}t	        ||      D ]  \  }}|\  }}}}||z
  ||z
  }}t        j                  ||z  |j                        }t        j                  ||gg      }t        j                  |d||||f   ||fdd      }||   |z  }g g g }"}!} t        ||      D ]  \  }#| j                  ||#d	      \  }$}%t        j                  |$d   ||fdd      d
   }$|%|kD  }&|$|&   |%|&   }%}$t        |$| j                  j                   |
      }'|'|	kD  }&|$|&   |%|&   }%}$|$| j                  j                   kD  }$t#        |$      j%                         }(t'        |(|d
d
||g       })t        j(                  |)      s|(|)   |$|)   |%|)   }%}$}(| j+                  |$       |"j+                  |(       |!j+                  |%        t        j,                  |       } t        j,                  |"      }"t        j,                  |!      }!t.        j0                  j3                  |"|!| j4                  j6                        }*t9        |"|*   |      }"t;        | |*   |||      } |!|*   }!|j+                  |        |j+                  |"       |j+                  |!       |j+                  |j=                  t?        |                     t        j,                  |      }t        j,                  |      }t        j,                  |      }t        j,                  |      }t?        |      dkD  r5d|z  }+t.        j0                  j3                  ||+|      }*||*   ||*   ||*   }}}|||fS )a_  
        Perform image segmentation using the Segment Anything Model (SAM).

        This function segments an entire image into constituent parts by leveraging SAM's advanced architecture
        and real-time performance capabilities. It can optionally work on image crops for finer segmentation.

        Args:
            im (torch.Tensor): Input tensor representing the preprocessed image with dimensions (N, C, H, W).
            crop_n_layers (int): Specifies the number of layers for additional mask predictions on image crops.
                                 Each layer produces 2**i_layer number of image crops.
            crop_overlap_ratio (float): Determines the extent of overlap between crops. Scaled down in subsequent layers.
            crop_downscale_factor (int): Scaling factor for the number of sampled points-per-side in each layer.
            point_grids (list[np.ndarray], optional): Custom grids for point sampling normalized to [0,1].
                                                      Used in the nth crop layer.
            points_stride (int, optional): Number of points to sample along each side of the image.
                                           Exclusive with 'point_grids'.
            points_batch_size (int): Batch size for the number of points processed simultaneously.
            conf_thres (float): Confidence threshold [0,1] for filtering based on the model's mask quality prediction.
            stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on mask stability.
            stability_score_offset (float): Offset value for calculating stability score.
            crop_nms_thresh (float): IoU cutoff for Non-Maximum Suppression (NMS) to remove duplicate masks between crops.

        Returns:
            (tuple): A tuple containing segmented masks, confidence scores, and bounding boxes.
        Tr0   N)r;   .bilinearF)r   align_corners)rM   r[   r   r	   ) r%   rh   r   r   zipr2   tensorr;   r4   arrayFinterpolater
   rY   r   r<   mask_thresholdr   r?   r   rW   appendcattorchvisionr   nmsr    iour   r   expandrH   ),r&   r"   crop_n_layerscrop_overlap_ratiocrop_downscale_factorpoint_gridspoints_stridepoints_batch_size
conf_thresstability_score_threshstability_score_offsetcrop_nms_threshihiwcrop_regions
layer_idxsry   rz   pred_bboxesregion_areascrop_region	layer_idxx1y1x2y2whareapoints_scalecrop_impoints_for_image
crop_maskscrop_scorescrop_bboxesrM   	pred_mask
pred_scoreidxstability_score	pred_bbox	keep_maskkeepscoress,                                               r+   rX   zPredictor.generate   s   J  !"B#6BxPb#c j5m]TijK=?R^:
Kl&),
&C"K(NBB7BGqA<<Abii8D88aVH-LmmBsBrE2b5'8$9B8*dijG*95D35r2[J,->@PQ
(,(=(=gfgk(=(l%	:MM)D/Aq6
bghijk	 :-(1#
3:	";ItzzG`G`<R#T%(>>(1#
3:	%

(A(AA	/	:@@B	29kAqRTVX>ZZ	yy+7@7KYW`Macmnwcx*yI!!),""9-"":.+ R0 :.J))K0K))K0K??&&{KOD+K,={KK%j&6RLJ%d+Kj){+{+C
O <=[ 'D^ YYz*
ii,ii,yy. |q %F??&&{FOLD3=d3C[QUEVXcdhXi[J;33r,   c                 h   t        | j                  j                  |      }|t        | j                  j                        }|j                          |j                  |      | _        || _        t        j                  g d      j                  ddd      j                  |      | _
        t        j                  g d      j                  ddd      j                  |      | _        d| j                  _        d| j                  _        d| j                  _        d| j                  _        d	| _        y)
a[  
        Initializes the Segment Anything Model (SAM) for inference.

        This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
        parameters for image normalization and other Ultralytics compatibility settings.

        Args:
            model (torch.nn.Module): A pre-trained SAM model. If None, a model will be built based on configuration.
            verbose (bool): If True, prints selected device information.

        Attributes:
            model (torch.nn.Module): The SAM model allocated to the chosen device for inference.
            device (torch.device): The device to which the model and tensors are allocated.
            mean (torch.Tensor): The mean values for image normalization.
            std (torch.Tensor): The standard deviation values for image normalization.
        )verboseN)g33333^@gR]@gRY@r.   r	   )g(\2M@g(\L@g     L@F    T)r   r    r;   r   r<   evalr:   r2   r   viewr@   rA   pttritonstrider=   done_warmup)r&   r<   r   r;   s       r+   setup_modelzPredictor.setup_model1  s    " tyy//A=diioo.E

XXf%
LL!:;@@QJMMfU	<< 78==b!QGJJ6R 

!





r,   c           
      p   |dd \  }}| j                   r|d   nd}t        t        d t        t	        |            D                    }t        |t              st        j                  |      }g }t        |g      D ]/  \  }	}
||	   }|t        j                  |j                  dd |j                         |j                  d      }t        j                  t	        |      t        j                  |j                        }t        j                   ||dddf   |dddf   gd      }t        j"                  |
d   j                         |j                  dd d      d	   }
|
| j$                  j&                  kD  }
| j(                  d	   |	   }|j+                  t-        ||||
|
             2 d| _         |S )a  
        Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.

        The method scales masks and boxes to the original image size and applies a threshold to the mask predictions. The
        SAM model uses advanced architecture and promptable segmentation tasks to achieve real-time performance.

        Args:
            preds (tuple): The output from SAM model inference, containing masks, scores, and optional bounding boxes.
            img (torch.Tensor): The processed input image tensor.
            orig_imgs (list | torch.Tensor): The original, unprocessed images.

        Returns:
            (list): List of Results objects containing detection masks, bounding boxes, and other metadata.
        Nr0   c              3   2   K   | ]  }t        |        y wrP   )strrR   s     r+   rU   z(Predictor.postprocess.<locals>.<genexpr>d  s     F/E!s1v/Es   F)paddingr_   r.   dimr   )pathnamesrN   ra   )r%   r   	enumeraterangerH   r1   listr   convert_torch2numpy_batchscale_boxesrh   r?   r2   arangern   r;   r   scale_masksr<   r   rg   r   r   )r&   predsimg	orig_imgsry   rz   r   r   resultsrT   rN   orig_imgclsimg_paths                 r+   postprocesszPredictor.postprocessR  s     #()
K"&"2"2eAhYFuS_/EFFG)T*55i@I!:,/HAu |H&!oociim[=N=N=PRZR`R`jopll3z?%++jN_N_`#iik!T'6JCPQSWPWL(Y_abOOE$K$5$5$79KUZ[\]^EDJJ555Ezz!}Q'HNN78(%u\ghi 0 !r,   c                 *    |t         |   |       yy)aW  
        Sets up the data source for inference.

        This method configures the data source from which images will be fetched for inference. The source could be a
        directory, a video file, or other types of image data sources.

        Args:
            source (str | Path): The path to the image data source for inference.
        N)r   setup_source)r&   sourcer*   s     r+   r   zPredictor.setup_sourcey  s     G ( r,   c                 v   | j                   0t        | j                  j                         }| j                  |       | j	                  |       t        | j                        dk(  sJ d       | j                  D ]>  }| j                  |d         }| j                   j                  |      | _	        || _
         y y)a  
        Preprocesses and sets a single image for inference.

        This function sets up the model if not already initialized, configures the data source to the specified image,
        and preprocesses the image for feature extraction. Only one image can be set at a time.

        Args:
            image (str | np.ndarray): Image file path as a string, or a np.ndarray image read by cv2.

        Raises:
            AssertionError: If more than one image is set.
        Nr	   z,`set_image` only supports setting one image!)r<   r   r    r   r   rH   datasetrC   rf   r#   r"   )r&   rG   r<   rg   r"   s        r+   	set_imagezPredictor.set_image  s     ::diioo.EU#% 4<< A%U'UU%\\Eq*B JJ44R8DMDG	 "r,   c                     || _         y)zSet prompts in advance.N)r$   )r&   r$   s     r+   set_promptszPredictor.set_prompts  s	    r,   c                      d| _         d| _        y)z*Resets the image and its features to None.N)r"   r#   )r&   s    r+   reset_imagezPredictor.reset_image  s    r,   c                    t        |       dk(  r| S g }g }| D ]  }|j                         j                         j                  t        j
                        }t        ||d      \  }}| }t        ||d      \  }}|xr | }|j                  t        j                  |      j                  d             |j                  t        |              t        j                  |d      }t        |      }t        j                  j!                  |j                         t        j                  |      |      }	||	   j#                  | j$                  | j&                        |	fS )a  
        Perform post-processing on segmentation masks generated by the Segment Anything Model (SAM). Specifically, this
        function removes small disconnected regions and holes from the input masks, and then performs Non-Maximum
        Suppression (NMS) to eliminate any newly created duplicate boxes.

        Args:
            masks (torch.Tensor): A tensor containing the masks to be processed. Shape should be (N, H, W), where N is
                                  the number of masks, H is height, and W is width.
            min_area (int): The minimum area below which disconnected regions and holes will be removed. Defaults to 0.
            nms_thresh (float): The IoU threshold for the NMS algorithm. Defaults to 0.7.

        Returns:
            (tuple([torch.Tensor, List[int]])):
                - new_masks (torch.Tensor): The processed masks with small regions removed. Shape is (N, H, W).
                - keep (List[int]): The indices of the remaining masks post-NMS, which can be used to filter the boxes.
        r   holes)r   islandsr   )r;   r`   )rH   cpunumpyastyper4   uint8r   r   r2   rj   ro   r?   r   r   r   r   r   r:   r;   r`   )
rN   min_area
nms_thresh	new_masksr   maskchanged	unchangedra   r   s
             r+   r   zPredictor.remove_small_regions  s!   $ u:?L 	D88:##%,,RXX6D0xgNMD'#I0xiPMD'!1'kIU__T2<<Q?@MM%	*+  IIiQ/	#I.""5;;=%//&2I:V!!U[[!I4OOr,   )NNNNF)
r   gg?r	   Nr   @   g)\(?ffffff?r   ffffff?)T)r   r   )__name__
__module____qualname____doc__r   r   rC   r6   r]   rY   rX   r   r   r   r   r   r   staticmethodr   __classcell__)r*   s   @r+   r   r      s    & '$4 !,80"Z<8Cx  !$.'(!!#% (,(,!$e4N B%N)0
 'P 'Pr,   r   )!r   r   r4   r2   torch.nn.functionalnn
functionalr   r   ultralytics.data.augmentr   ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   ultralytics.utils.torch_utilsr   amgr
   r   r   r   r   r   r   r   r   buildr   r   rQ   r,   r+   <module>r      sO         . 6 . . 7u u u tP tPr,   