o
    oi$                     @  sn   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gZG dd deZdS )	    )annotations)ClassVarOptionalUnionN)Tensor)PILImage)	ModelBaseSemanticSegmentationc                   @  s   e Zd ZU dZg dZded< g dZded< e d'd
dZ	d(d)ddZ
d*ddZ				d+d,d d!Z					d-d.d%d&ZdS )/r	   zSemantic Segmentation is a module that wraps a semantic segmentation model.

    This module uses SegmentationModel library for semantic segmentation.
    )   r
   r
   zClassVar[list[int]]ONNX_DEFAULT_INPUTSHAPE)r
   r
   r
   r
   ONNX_DEFAULT_OUTPUTSHAPEimagesUnion[Tensor, list[Tensor]]returnc                 C  sr   t |ttfr(g }|D ]}| |d }| |}| |}||d  q|S | |}| |}| |}|S )a  Forward pass of the semantic segmentation model.

        Args:
            images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
                If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.

        Returns:
            output tensor.

        Nr   )
isinstancelisttuplepre_processormodelpost_processorappend)selfr   outputsimageoutput r   S/home/ubuntu/.local/lib/python3.10/site-packages/kornia/models/segmentation/base.pyforward)   s"   




zSemanticSegmentation.forwardrandomc  num_classesintcolormapstrmanual_seedr   c                 C  s<   |dkrt  }|| t j|d|d}|S td| )an  Get a color map of size num_classes.

        Args:
            num_classes: The number of colors in the color map.
            colormap: The colormap to use, can be "random" or a custom color map.
            manual_seed: The manual seed to use for the colormap.

        Returns:
            A tensor of shape (num_classes, 3) representing the color map.

        r   r   )	generatorzUnsupported colormap: )torch	Generatorr%   rand
ValueError)r   r!   r#   r%   g_cpucolorsr   r   r   get_colormapK   s   
z!SemanticSegmentation.get_colormapsemantic_maskr,   c                 C  s   |  dkr	d}n|  dkrd}n	td|j dt|j|dtjd|j|jdrc|j	|d	d
}||
| }|  dkrJ|ddd}|S |  dkrZ|dddd}|S td|j dtd)a  Visualize the output of the segmentation model.

        Args:
            semantic_mask: The output of the segmentation model. Shape should be (C, H, W) or (B, C, H, W).
            colors: The color map to use for visualizing the output of the segmentation model.
                Shape should be (num_classes, 3).

        Returns:
            A tensor of shape (3, H, W) or (B, 3, H, W) representing the visualized output of the segmentation model.

        Raises:
            ValueError: If the shape of the semantic mask is not of shape (C, H, W) or (B, C, H, W).
            ValueError: If the shape of the colors is not of shape (num_classes, 3).
            ValueError: If only muliclass segmentation is supported. Please ensure a softmax is used, or submit a PR.

        r   r         z>Semantic mask must be of shape (C, H, W) or (B, C, H, W), got .)dim)dtypedeviceT)r2   keepdim   zZOnly muliclass segmentation is supported. Please ensure a softmax is used, or submit a PR.)r2   r*   shaper'   allclosesumtensorr3   r4   argmaxsqueezepermute)r   r.   r,   channel_dimr   r   r   r   visualize_outputa   s,   
z%SemanticSegmentation.visualize_outputNr'   semantic_masks%Optional[Union[Tensor, list[Tensor]]]output_type.Union[Tensor, list[Tensor], list[Image.Image]]c           	      C  s   |du r	|  |}t|ttfr:g }|D ]$}|jdkr$td|j d| j|d||d}|	| 
|| qn| j|d||d}| 
||}| j||t|trXdd
S d	d
S )am  Visualize the segmentation masks.

        Args:
            images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
                If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.
            semantic_masks: If list of segmentation masks. Each mask is a Tensor with shape :math:`(C, H, W)`.
                If Tensor, a Tensor with shape :math:`(B, C, H, W)`.
            output_type: The type of output, can be "torch" or "PIL".
            colormap: The colormap to use, can be "random" or a custom color map.
            manual_seed: The manual seed to use for the colormap.

        Nr   z.Semantic mask must be of shape (C, H, W), got r1   r   )r%   r0   TF)is_batch)r   r   r   r   ndimr*   r7   r-   sizer   r?   _tensor_to_typer   )	r   r   r@   rB   r#   r%   r   r.   r,   r   r   r   	visualize   s$   

	"zSemanticSegmentation.visualize	directoryOptional[str]Nonec           
   
   C  s   | j |||||d}t|trt|trtj|d|dd}n:t|ttfrPt|ttfrPg }tt	|D ]}	|
tj||	 d d||	 d ddd  q5n	tdt| | j||dd | j||d	d | j||d
d dS )a  Save the segmentation results.

        Args:
            images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
                If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.
            semantic_masks: If list of segmentation masks. Each mask is a Tensor with shape :math:`(C, H, W)`.
                If Tensor, a Tensor with shape :math:`(B, C, H, W)`.
            directory: The directory to save the results.
            output_type: The type of output, can be "torch" or "PIL".
            colormap: The colormap to use, can be "random" or a custom color map.
            manual_seed: The manual seed to use for the colormap.

        )r#   r%   g      ?g      ?Nr   z6`images` should be a Tensor or a list of Tensors. Got _src)suffix_mask_overlay)rH   r   r   korniaenhanceadd_weightedr   r   rangelenr   r*   type_save_outputs)
r   r   r@   rI   rB   r#   r%   colored_masksoverlaidir   r   r   save   s0   0zSemanticSegmentation.save)r   r   r   r   )r   r    )r!   r"   r#   r$   r%   r"   r   r   )r.   r   r,   r   r   r   )Nr'   r   r    )r   r   r@   rA   rB   r$   r#   r$   r%   r"   r   rC   )NNr'   r   r    )r   r   r@   rA   rI   rJ   rB   r$   r#   r$   r%   r"   r   rK   )__name__
__module____qualname____doc__r   __annotations__r   r'   inference_moder   r-   r?   rH   rZ   r   r   r   r   r	       s&   
 !
11)
__future__r   typingr   r   r   r'   rP   kornia.corer   kornia.core.externalr   Imagekornia.models.baser   __all__r	   r   r   r   r   <module>   s   