U
    Ph&                     @  s  d dl mZ d dlmZmZ d dlZd dlZd dlm	Z	m
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 erd d
lmZ neddd\ZZddgZdddddddddddejdejfdddddddddddddddddd d!dZd(ddd%ddddd&d'dZdS ))    )annotations)TYPE_CHECKINGAnyN)	DtypeLikeNdarrayOrTensor)
SpatialPad)rescale_array)repeat)optional_import)convert_data_typeconvert_to_dst_type)pyplot
matplotlibr   )name	matshow3dblend_images)
   r      noneFr   r   z
str | Noneztuple[int, int]z
int | Noneintzfloat | Nonestrboolr   ztuple[Any, np.ndarray])volumefigtitlefigsizeframes_per_row	frame_dimchannel_dimvminvmaxevery_ninterpolationshow
fill_valuemargindtypekwargsreturnc                   s   t | tjdd |dk	r8|dks0j| dkr8tdtttfrtd tjs^tdtjt	dd	 D dd
}t
|dd tjfdd	D dd
ntjdk rtdq|dk	rt|ddjd jd jd fn*t|ddjd jd f|dkrBtn|}|dkrZtn|}ddt|	d |stttt}ttt|d ttt  }d | t gg}|dk	r|ddgg7 }|||ggd 7 }tjj|dd|d|dt fdd	t|D }|dk	rLt|dd}t|tjr`|}n2|dkrvtjdd}|js|d |jd }|j|f|||
d| | d |dk	r|!| |dk	rt"|dr|#| |rt$  ||fS )a8
  
    Create a 3D volume figure as a grid of images.

    Args:
        volume: 3D volume to display. data shape can be `BCHWD`, `CHWD` or `HWD`.
            Higher dimensional arrays will be reshaped into (-1, H, W, [C]), `C` depends on `channel_dim` arg.
            A list of channel-first (C, H[, W, D]) arrays can also be passed in,
            in which case they will be displayed as a padded and stacked volume.
        fig: matplotlib figure or Axes to use. If None, a new figure will be created.
        title: title of the figure.
        figsize: size of the figure.
        frames_per_row: number of frames to display in each row. If None, sqrt(firstdim) will be used.
        frame_dim: for higher dimensional arrays, which dimension from (`-1`, `-2`, `-3`) is moved to
            the `-3` dimension. dim and reshape to (-1, H, W) shape to construct frames, default to `-3`.
        channel_dim: if not None, explicitly specify the channel dimension to be transposed to the
            last dimensionas shape (-1, H, W, C). this can be used to plot RGB color image.
            if None, the channel dimension will be flattened with `frame_dim` and `batch_dim` as shape (-1, H, W).
            note that it can only support 3D input image. default is None.
        vmin: `vmin` for the matplotlib `imshow`.
        vmax: `vmax` for the matplotlib `imshow`.
        every_n: factor to subsample the frames so that only every n-th frame is displayed.
        interpolation: interpolation to use for the matplotlib `matshow`.
        show: if True, show the figure.
        fill_value: value to use for the empty part of the grid.
        margin: margin to use for the grid.
        dtype: data type of the output stacked frames.
        kwargs: additional keyword arguments to matplotlib `matshow` and `imshow`.

    See Also:
        - https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html
        - https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.matshow.html

    Example:

        >>> import numpy as np
        >>> import matplotlib.pyplot as plt
        >>> from monai.visualize import matshow3d
        # create a figure of a 3D volume
        >>> volume = np.random.rand(10, 10, 10)
        >>> fig = plt.figure()
        >>> matshow3d(volume, fig=fig, title="3D Volume")
        >>> plt.show()
        # create a figure of a list of channel-first 3D volumes
        >>> volumes = [np.random.rand(1, 10, 10, 10), np.random.rand(1, 10, 10, 10)]
        >>> fig = plt.figure()
        >>> matshow3d(volumes, fig=fig, title="List of Volumes")
        >>> plt.show()

    )dataoutput_typer   N)r   r   )r         zKchannel_dim must be: None, 0 or 1, and channels of image must be 1, 3 or 4.z volume must be a list of arrays.c                 S  s   g | ]
}|j qS  )shape.0vr.   r.   J/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/visualize/utils.py
<listcomp>n   s     zmatshow3d.<locals>.<listcomp>axisr   c                   s   g | ]} |qS r.   r.   r0   )padr.   r3   r4   p   s     r,   r      F)copyconstant)modeconstant_valuesc                   s&   g | ]  fd dt D qS )c                   s   g | ]}  |  qS r.   r.   )r1   j)colsivolr.   r3   r4      s     z(matshow3d.<locals>.<listcomp>.<listcomp>)range)r1   )rA   rC   )rB   r3   r4      s     T)tight_layouto   )r    r!   r#   offset_size_inches)%r   npndarrayr/   
ValueError
isinstancelisttuplemaxasarrayr   concatenatelenexpand_dimsmoveaxisreshapenanminnanmaxr   ceilsqrtminr7   astypeblockrD   pltAxesfigureaxesadd_subplotmatshowr6   	set_titlehasattrrH   r$   )r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   pad_sizerowswidthimaxr.   )rA   r7   rC   r3   r   "   s`    C
&








      ?hsvTzfloat | NdarrayOrTensor)imagelabelalphacmaprescale_arraystransparent_backgroundr)   c           
      C  s<  |j d dkrtd| j d dkr,td| j dd |j dd krPtdt|tjtjfr| j dd |j dd krtd|rt| } t|}| j d dkrt| d	dd
} dddddd}|||}t|tjtjfr|}n(t|tjrt	||}nt	||}|r$d||dk< d| }	|	|  ||  S )a  
    Blend an image and a label. Both should have the shape CHW[D].
    The image may have C==1 or 3 channels (greyscale or RGB).
    The label is expected to have C==1.

    Args:
        image: the input image to blend with label data.
        label: the input label to blend with image data.
        alpha: this specifies the weighting given to the label, where 0 is completely
            transparent and 1 is completely opaque. This can be given as either a
            single value or an array/tensor that is the same size as the input image.
        cmap: specify colormap in the matplotlib, default to `hsv`, for more details, please refer to:
            https://matplotlib.org/2.0.2/users/colormaps.html.
        rescale_arrays: whether to rescale the array to [0, 1] first, default to `True`.
        transparent_background: if true, any zeros in the label field will not be colored.

    .. image:: ../../docs/images/blend_images.png

    r   r   zLabel should have 1 channel.)r   r,   z"Image should have 1 or 3 channels.Nz3image and label should have matching spatial sizes.z;if alpha is image, size should match input image and label.r,   r5   r   r   )ro   rm   r)   c                 S  sP   t j| }t|tj^}}||d }t|ddd d }t||^}}|S )Nr   r9   r,   )r]   	colormapsget_cmapr   rI   rJ   rT   r   )ro   rm   _cmapZlabel_np_Zlabel_rgb_np	label_rgbr.   r.   r3   get_label_rgb   s    z#blend_images.<locals>.get_label_rgb)
r/   rK   rL   rI   rJ   torchTensorr   r	   	full_like)
rl   rm   rn   ro   rp   rq   rw   rv   Zw_labelZw_imager.   r.   r3   r      s2    
)rj   rk   TT)
__future__r   typingr   r   numpyrI   rx   monai.config.type_definitionsr   r   Zmonai.transforms.croppad.arrayr   monai.transforms.utilsr   0monai.transforms.utils_pytorch_numpy_unificationr	   monai.utils.moduler
   monai.utils.type_conversionr   r   r   r   r]   ru   __all__nanfloat32r   r   r.   r.   r.   r3   <module>   sD   0     