U
    ee*                     @   s   d Z ddlmZ ddlZddlZddlT zddlm	Z	m
Z
 W n4 ek
rp   ed ed ddlm	Z	m
Z
 Y nX G dd	 d	e	ZdS )
ztSegmenting remote sensing images with the Fast Segment Anything Model (FastSAM.
https://github.com/opengeos/FastSAM
    N   )*)FastSAMFastSAMPromptz$FastSAM not installed. Installing...zsegment-anything-fastc                       s   e Zd ZdZd fdd	ZdddZddd	Zd d
dZd!ddZd"ddZ	d#e
jdddZd$ddZd%ddZd&ddZ  ZS )'SamGeozPSegmenting remote sensing images with the Fast Segment Anything Model (FastSAM).FastSAM-x.ptc                    s   d|kr|d }| d ntjdtjd}ddd}||krbtdt|  d| d	tj	||}tj
|std
| d| d t|| | t j|f| dS )z!Initialize the FastSAM algorithm.checkpoint_dirZ
TORCH_HOMEz~/.cache/torch/hub/checkpointszRhttps://drive.google.com/file/d/1m1sjY4ihXBU1fZXdQ-Xdj-mDltW-2Rqv/view?usp=sharingzRhttps://drive.google.com/file/d/10XmSj6mmpmRb8NhXbtiuO9cTTBwR_9SV/view?usp=sharing)r   zFastSAM-s.ptzModel must be one of z
, but got z	 instead.zDownloading z to z...N)poposenvirongetpath
expanduser
ValueErrorlistkeysjoinexistsprintdownload_filesuper__init__)selfmodelkwargsr   modelsZ
model_path	__class__ R/home/ankuromar296_gmail_com/.local/lib/python3.8/site-packages/samgeo/fast_sam.pyr      s&     
zSamGeo.__init__Nc                 K   s   t |tr@|drt|}tj|s8td| d|| _nd| _|dkrrt	j
 r\dnd}|dkrrt	j
  | |fd|i|}t|||d| _dS )	a'  Set the input image.

        Args:
            image (str): The path to the image file or a HTTP URL.
            device (str, optional): The device to use. Defaults to "cuda" if available, otherwise "cpu".
            kwargs: Additional keyword arguments to pass to the FastSAM model.
        httpzInput path z does not exist.Ncudacpudevice)r#   )
isinstancestr
startswithr   r
   r   r   r   sourcetorchr!   Zis_availableZempty_cacher   prompt_process)r   imager#   r   Zeverything_resultsr   r   r   	set_image2   s    	


zSamGeo.set_imagec                 K   s4   | j }| }|| _|dk	r,| j|f| n|S dS )zSegment the image with the everything prompt. Adapted from
        https://github.com/CASIA-IVA-Lab/FastSAM/blob/main/fastsam/prompt.py#L451

        Args:
            output (str, optional): The path to save the output image. Defaults to None.
        N)r)   everything_promptannotations
save_masks)r   outputr   r)   annr   r   r   r,   P   s    zSamGeo.everything_promptc                 K   s8   | j }|||}|| _|dk	r0| j|f| n|S dS )ae  Segment the image with the point prompt. Adapted from
        https://github.com/CASIA-IVA-Lab/FastSAM/blob/main/fastsam/prompt.py#L414

        Args:
            points (list): A list of points.
            pointlabel (list): A list of labels for each point.
            output (str, optional): The path to save the output image. Defaults to None.
        N)r)   point_promptr-   r.   )r   ZpointsZ
pointlabelr/   r   r)   r0   r   r   r   r1   a   s    
zSamGeo.point_promptc                 K   s8   | j }|||}|| _|dk	r0| j|f| n|S dS )a  Segment the image with the box prompt. Adapted from
        https://github.com/CASIA-IVA-Lab/FastSAM/blob/main/fastsam/prompt.py#L377

        Args:
            bbox (list, optional): The bounding box. Defaults to None.
            bboxes (list, optional): A list of bounding boxes. Defaults to None.
            output (str, optional): The path to save the output image. Defaults to None.
        N)r)   
box_promptr-   r.   )r   ZbboxZbboxesr/   r   r)   r0   r   r   r   r2   t   s    
zSamGeo.box_promptc                 K   s6   | j }||}|| _|dk	r.| j|f| n|S dS )a$  Segment the image with the text prompt. Adapted from
        https://github.com/CASIA-IVA-Lab/FastSAM/blob/main/fastsam/prompt.py#L439

        Args:
            text (str): The text to segment.
            output (str, optional): The path to save the output image. Defaults to None.
        N)r)   text_promptr-   r.   )r   textr/   r   r)   r0   r   r   r   r3      s    	
zSamGeo.text_promptT   )returnc              	   K   s  | j }t|d tr"dd |D }| jj}t|tj}|jd }|jd }	|rt|d t	j
rnt| }t|D ]P\}
}t|tjtjtdtj}t|tjtjtdtj||
< qv| jdkrt|}nt|d tjrt	|}t|t	j
r|  }|dkrNt|d	k r2tj}nt|d
k rHtj}ntj}tj|dd}tj||	|ftjd}d||dk< ||| }|| _|dk	rt | j|| j!f| n|S dS )zSave the mask of the image. Adapted from
        https://github.com/CASIA-IVA-Lab/FastSAM/blob/main/fastsam/prompt.py#L222

        Returns:
            np.ndarray: The mask of the image.
        r   c                 S   s   g | ]}|d  qS )Zsegmentationr   ).0
annotationr   r   r   
<listcomp>   s     z%SamGeo.save_masks.<locals>.<listcomp>r   )   r:   )   r;   r"   Nr5   i  Zaxisinterpolation)"r-   r$   dictr)   Zimgcv2ZcvtColorZCOLOR_BGR2RGBshaper(   ZTensornparrayr"   	enumerateZmorphologyExZastypeZuint8ZMORPH_CLOSEonesZ
MORPH_OPENr#   ndarrayZ
from_numpynumpylenZuint16Zuint32sumresizeINTER_NEARESTobjectsZarray_to_imager'   )r   r/   Zbetter_qualityZdtypeZmask_multiplierr   r-   r*   heightwidthimaskmasksr   r   r   r.      sR    


  
  




zSamGeo.save_masksFc                 C   sf  | j jd }| j jd }| j}t| }|jd }|jd }|jd }tj|dd}	t|	}
||
 }|dkjdd}|rtj		|dddf}n"t
|dddftddd	g }t
|dddfd
 }tj||gdd}t|d| }t||df}tjt|t|dd\}}|||f ||tdf}|| |||ddf< tj|||ftjd}|S )a?  Show the mask of the image. Adapted from
        https://github.com/CASIA-IVA-Lab/FastSAM/blob/main/fastsam/prompt.py#L222

        Args:
            random_color (bool, optional): Whether to use random colors for each object. Defaults to False.

        Returns:
            np.ndarray: The mask of the image.
        r   r      )r   rR   r<   r:   g?g?g      ?g333333?   Zij)ZindexingNr=   )r*   rA   r-   rB   rC   r"   rI   ZargsortZargmaxrandomrE   ZconcatenateZexpand_dimsZzerosZmeshgridZarangeslicer@   rJ   rK   )r   Zrandom_colorZtarget_heightZtarget_widthr-   r8   Zmask_sumrM   weightZareasZsorted_indicesindexcolorZtransparencyZvisualZ
mask_imageshowZ	h_indicesZ	w_indicesindicesr   r   r   fast_show_mask   sB    



  
  zSamGeo.fast_show_mask	EPSG:4326c                 K   s   t ||f||d| dS )ag  Save the result to a vector file.

        Args:
            image (str): The path to the image file.
            output (str): The path to the vector file.
            simplify_tolerance (float, optional): The maximum allowed geometry displacement.
                The higher this value, the smaller the number of vertices in the resulting geometry.
        )simplify_tolerancedst_crsN)raster_to_vector)r   r*   r/   r^   r_   r   r   r   r   r`     s    zSamGeo.raster_to_vectorc                 K   s8   | j }| j}|dkrtd}|j||f| t| dS )a   Show the annotations (objects with random color) on the input image.

        Args:
            figsize (tuple, optional): The figure size. Defaults to (12, 10).
            axis (str, optional): Whether to show the axis. Defaults to "off".
            alpha (float, optional): The alpha value for the annotations. Defaults to 0.35.
            output (str, optional): The path to the output image. Defaults to None.
            blend (bool, optional): Whether to show the input image. Defaults to True.
        Nz.png)r-   r)   Ztemp_file_pathZplotZ
show_image)r   r/   r   r-   r)   r   r   r   	show_anns!  s    zSamGeo.show_anns)r   )N)N)N)NNN)N)NTNr5   )F)Nr]   )N)__name__
__module____qualname____doc__r   r+   r,   r1   r2   r3   rB   rF   r.   r\   r`   ra   __classcell__r   r   r   r   r      s*   




    B 
5   
 r   )re   Zmatplotlib.pyplotZpyplotZpltrG   rB   r(   commonZfastsamr   r   ImportErrorr   Zinstall_packager   r   r   r   r   <module>   s   