o
    #i                     @  s  U d dl mZ d dlmZmZ d dlmZmZmZ d dl	Z
d dlmZ d dlmZmZmZ d dlmZ d dlmZmZmZmZmZ d d	lmZmZ d d
lmZmZ d dlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ dZ,dZ-ee.e,dZ/erd dl0Z0d dl1Z2d dl3m4Z5 ne*ddd\Z0Z6e*d\Z2Z6e*d\Z5Z6g dZ7i Z8de9d< dd Z:d*d+ddZ;G dd dZ<e+dd G d!d" d"e<Z=e+dd G d#d$ d$e<Z>e+d%d G d&d' d'e<Z?d(d) Z@dS ),    )annotations)MappingSequence)TYPE_CHECKINGAnycastN)
get_logger)	DtypeLikeNdarrayOrTensorPathLike)
MetaTensor)affine_to_spacingensure_tupleensure_tuple_reporientation_ras_lpsto_affine_nd)ResizeSpatialResample)ascontiguousarraymoveaxis)GridSampleModeGridSamplePadModeInterpolateModeMetaKeysOptionalImportError	SpaceKeysconvert_data_typeconvert_to_tensorget_equivalent_dtypelook_up_optionoptional_importrequire_pkgz?%(asctime)s %(levelname)s %(filename)s:%(lineno)d - %(message)s*)module_namefmt)ImageitkT)allow_namespace_pkgnibabelz	PIL.Image)ImageWriter	ITKWriterNibabelWriter	PILWriterSUPPORTED_WRITERSregister_writerresolve_writerloggerdictr-   c                 G  sB   |    }|dr|dd }t|tdd}|| }|t|< dS )av  
    Register ``ImageWriter``, so that writing a file with filename extension ``ext_name``
    could be resolved to a tuple of potentially appropriate ``ImageWriter``.
    The customised writers could be registered by:

    .. code-block:: python

        from monai.data import register_writer
        # `MyWriter` must implement `ImageWriter` interface
        register_writer("nii", MyWriter)

    Args:
        ext_name: the filename extension of the image.
            As an indexing key, it will be converted to a lower case string.
        im_writers: one or multiple ImageWriter classes with high priority ones first.
    .   N default)lower
startswithr   r-   )ext_nameZ
im_writersr$   existingall_writersr4   r4   Y/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/data/image_writer.pyr.   C   s   

r.   returnr   c              	   C  s   t st  |   }|dr|dd }g }t td}t|t |dD ]"}z
|  || W q$ ty9   Y q$ t	yF   || Y q$w |sS|rStd| dt
|}|t |< |S )a  
    Resolves to a tuple of available ``ImageWriter`` in ``SUPPORTED_WRITERS``
    according to the filename extension key ``ext_name``.

    Args:
        ext_name: the filename extension of the image.
            As an indexing key it will be converted to a lower case string.
        error_if_not_found: whether to raise an error if no suitable image writer is found.
            if True , raise an ``OptionalImportError``, otherwise return an empty tuple. Default is ``True``.
    r2   r3   Nr4   r5   z!No ImageWriter backend found for )r-   initr7   r8   getEXT_WILDCARDr   appendr   	Exceptionr   )r9   Zerror_if_not_foundr$   Zavail_writersZdefault_writers_writerZwriter_tupler4   r4   r<   r/   \   s*   

r/   c                   @  s   e Zd ZdZdd Zdd Zd4dd	Zd5d6ddZed7ddZ	eddde
jejdejfd8d$d%Ze	&	
	'	d9d:d/d0Zed;d<d2d3ZdS )=r)   a	  
    The class is a collection of utilities to write images to disk.

    Main aspects to be considered are:

        - dimensionality of the data array, arrangements of spatial dimensions and channel/time dimensions
            - ``convert_to_channel_last()``
        - metadata of the current affine and output affine, the data array should be converted accordingly
            - ``get_meta_info()``
            - ``resample_if_needed()``
        - data type handling of the output image (as part of ``resample_if_needed()``)

    Subclasses of this class should implement the backend-specific functions:

        - ``set_data_array()`` to set the data array (input must be numpy array or torch tensor)
            - this method sets the backend object's data part
        - ``set_metadata()`` to set the metadata and output affine
            - this method sets the metadata including affine handling and image resampling
        - backend-specific data object ``create_backend_obj()``
        - backend-specific writing function ``write()``

    The primary usage of subclasses of ``ImageWriter`` is:

    .. code-block:: python

        writer = MyWriter()  # subclass of ImageWriter
        writer.set_data_array(data_array)
        writer.set_metadata(meta_dict)
        writer.write(filename)

    This creates an image writer object based on ``data_array`` and ``meta_dict`` and write to ``filename``.

    It supports up to three spatial dimensions (with the resampling step supports for both 2D and 3D).
    When saving multiple time steps or multiple channels `data_array`, time
    and/or modality axes should be the at the `channel_dim`. For example,
    the shape of a 2D eight-class and ``channel_dim=0``, the segmentation
    probabilities to be saved could be `(8, 64, 64)`; in this case
    ``data_array`` will be converted to `(64, 64, 1, 8)` (the third
    dimension is reserved as a spatial dimension).

    The ``metadata`` could optionally have the following keys:

        - ``'original_affine'``: for data original affine, it will be the
            affine of the output object, defaulting to an identity matrix.
        - ``'affine'``: it should specify the current data affine, defaulting to an identity matrix.
        - ``'spatial_shape'``: for data output spatial shape.

    When ``metadata`` is specified, the saver will may resample data from the space defined by
    `"affine"` to the space defined by `"original_affine"`, for more details, please refer to the
    ``resample_if_needed`` method.
    c                 K  s(   d| _ | D ]
\}}t| || qdS )a  
        The constructor supports adding new instance members.
        The current member in the base class is ``self.data_obj``, the subclasses can add more members,
        so that necessary meta information can be stored in the object and shared among the class methods.
        N)data_objitemssetattr)selfkwargskvr4   r4   r<   __init__   s   zImageWriter.__init__c                 K     t d| jj dNzSubclasses of z must implement this method.NotImplementedError	__class____name__)rG   
data_arrayrH   r4   r4   r<   set_data_array      zImageWriter.set_data_array	meta_dictMapping | Nonec                 K  rL   rM   rN   )rG   rU   optionsr4   r4   r<   set_metadata   rT   zImageWriter.set_metadataTfilenamer   verboseboolc                 K  s   |rt d|  dS dS )zPsubclass should implement this method to call the backend-specific writing APIs.z	writing: N)r0   inforG   rY   rZ   rH   r4   r4   r<   write   s   zImageWriter.writerR   r
   r=   
np.ndarrayc                 K  s   t |tjd S )z
        Subclass should implement this method to return a backend-specific data representation object.
        This method is used by ``cls.write`` and the input ``data_array`` is assumed 'channel-last'.
        r   )r   npndarray)clsrR   rH   r4   r4   r<   create_backend_obj   s   zImageWriter.create_backend_objNFaffineNdarrayOrTensor | Nonetarget_affineoutput_spatial_shapeSequence[int] | int | Nonemodestrpadding_modealign_cornersdtyper	   c	                 C  s   t |}	t|dd}|durt|dd|_t||||d}
|
|d ||d}t|tr.g |_t||	d^}}t|j|	d^}}|d |fS )	a  
        Convert the ``data_array`` into the coordinate system specified by
        ``target_affine``, from the current coordinate definition of ``affine``.

        If the transform between ``affine`` and ``target_affine`` could be
        achieved by simply transposing and flipping ``data_array``, no resampling
        will happen.  Otherwise, this function resamples ``data_array`` using the
        transformation computed from ``affine`` and ``target_affine``.

        This function assumes the NIfTI dimension notations. Spatially it
        supports up to three dimensions, that is, H, HW, HWD for 1D, 2D, 3D
        respectively. When saving multiple time steps or multiple channels,
        time and/or modality axes should be appended after the first three
        dimensions. For example, shape of 2D eight-class segmentation
        probabilities to be saved could be `(64, 64, 1, 8)`. Also, data in
        shape `(64, 64, 8)` or `(64, 64, 8, 1)` will be considered as a
        single-channel 3D image. The ``convert_to_channel_last`` method can be
        used to convert the data to the format described here.

        Note that the shape of the resampled ``data_array`` may subject to some
        rounding errors. For example, resampling a 20x20 pixel image from pixel
        size (1.5, 1.5)-mm to (3.0, 3.0)-mm space will return a 10x10-pixel
        image. However, resampling a 20x20-pixel image from pixel size (2.0,
        2.0)-mm to (3.0, 3.0)-mm space will output a 14x14-pixel image, where
        the image shape is rounded from 13.333x13.333 pixels. In this case
        ``output_spatial_shape`` could be specified so that this function
        writes image data to a designated shape.

        Args:
            data_array: input data array to be converted.
            affine: the current affine of ``data_array``. Defaults to identity
            target_affine: the designated affine of ``data_array``.
                The actual output affine might be different from this value due to precision changes.
            output_spatial_shape: spatial shape of the output image.
                This option is used when resampling is needed.
            mode: available options are {``"bilinear"``, ``"nearest"``, ``"bicubic"``}.
                This option is used when resampling is needed.
                Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
            padding_mode: available options are {``"zeros"``, ``"border"``, ``"reflection"``}.
                This option is used when resampling is needed.
                Padding mode for outside grid values. Defaults to ``"border"``.
                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
            align_corners: boolean option of ``grid_sample`` to handle the corner convention.
                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
            dtype: data type for resampling computation. Defaults to
                ``np.float64`` for best precision. If ``None``, use the data type of input data.
                The output data type of this method is always ``np.float32``.
        T)
track_metaNF)ri   rk   rl   rm   )
dst_affinespatial_size)output_typer   )typer   rd   r   
isinstancer   applied_operationsr   )rb   rR   rd   rf   rg   ri   rk   rl   rm   	orig_type	resamplerZoutput_array_r4   r4   r<   resample_if_needed   s   =

zImageWriter.resample_if_neededr      datachannel_dimNone | int | Sequence[int]squeeze_end_dimsspatial_ndim
int | None
contiguousc                 C  s   |durt |}t||ttt| d}n|d }|rSt|j|d k r8|ddddf }t|j|d k s&t|j|d krS|ddddf }t|j|d ksA|rk|jd dkrkt|d}|rk|jd dks\|rqt|}|S )aF  
        Rearrange the data array axes to make the `channel_dim`-th dim the last
        dimension and ensure there are ``spatial_ndim`` number of spatial
        dimensions.

        When ``squeeze_end_dims`` is ``True``, a postprocessing step will be
        applied to remove any trailing singleton dimensions.

        Args:
            data: input data to be converted to "channel-last" format.
            channel_dim: specifies the channel axes of the data array to move to the last.
                ``None`` indicates no channel dimension, a new axis will be appended as the channel dimension.
                a sequence of integers indicates multiple non-spatial dimensions.
            squeeze_end_dims: if ``True``, any trailing singleton dimensions will be removed (after the channel
                has been moved to the end). So if input is `(H,W,D,C)` and C==1, then it will be saved as `(H,W,D)`.
                If D is also 1, it will be saved as `(H,W)`. If ``False``, image will always be saved as `(H,W,D,C)`.
            spatial_ndim: modifying the spatial dims if needed, so that output to have at least
                this number of spatial dims. If ``None``, the output will have the same number of
                spatial dimensions as the input.
            contiguous: if ``True``, the output will be contiguous.
        Nr   ).Nr3   .)	r   r   tuplerangelenshaper`   squeezer   )rb   rz   r{   r}   r~   r   Z_chnsr4   r4   r<   convert_to_channel_last  s"   z#ImageWriter.convert_to_channel_lastmetadatac                 C  sD   |sddt jdt jdi}|d}|t j}|t j}|||fS )z
        Extracts relevant meta information from the metadata object (using ``.get``).
        Optional keys are ``"spatial_shape"``, ``MetaKeys.AFFINE``, ``"original_affine"``.
        original_affineN)r   AFFINESPATIAL_SHAPEr?   )rb   r   r   rd   spatial_shaper4   r4   r<   get_meta_infoL  s   

zImageWriter.get_meta_info)rU   rV   TrY   r   rZ   r[   )rR   r
   r=   r_   )rR   r
   rd   re   rf   re   rg   rh   ri   rj   rk   rj   rl   r[   rm   r	   )r   Try   F)
rz   r
   r{   r|   r}   r[   r~   r   r   r[   Nr   rV   )rQ   
__module____qualname____doc__rK   rS   rX   r^   classmethodrc   r   BILINEARr   BORDERr`   float64rx   r   r   r4   r4   r4   r<   r)   }   s2    4

K0r)   )pkg_namec                      s   e Zd ZU dZdZded< ded< ejdfd# fd
dZ	d$d%ddZ	d&d'ddZ
d(d) fddZeddejdfd* fd!d"Z  ZS )+r*   a  
    Write data and metadata into files on disk using ITK-python.

    .. code-block:: python

        import numpy as np
        from monai.data import ITKWriter

        np_data = np.arange(48).reshape(3, 4, 4)

        # write as 3d spatial image no channel
        writer = ITKWriter(output_dtype=np.float32)
        writer.set_data_array(np_data, channel_dim=None)
        # optionally set metadata affine
        writer.set_metadata({"affine": np.eye(4), "original_affine": -1 * np.eye(4)})
        writer.write("test1.nii.gz")

        # write as 2d image, channel-first
        writer = ITKWriter(output_dtype=np.uint8)
        writer.set_data_array(np_data, channel_dim=0)
        writer.set_metadata({"spatial_shape": (5, 5)})
        writer.write("test1.png")

    Nr	   output_dtyper   r{   Taffine_lps_to_rasbool | Nonec                   s    t  jd||ddd| dS )a?  
        Args:
            output_dtype: output data type.
            affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``.
                Set to ``True`` to be consistent with ``NibabelWriter``,
                otherwise the affine matrix is assumed already in the ITK convention.
                Set to ``None`` to use ``data_array.meta[MetaKeys.SPACE]`` to determine the flag.
            kwargs: keyword arguments passed to ``ImageWriter``.

        The constructor will create ``self.output_dtype`` internally.
        ``affine`` and ``channel_dim`` are initialized as instance members (default ``None``, ``0``):

            - user-specified ``affine`` should be set in ``set_metadata``,
            - user-specified ``channel_dim`` should be set in ``set_data_array``.
        Nr   )r   r   rd   r{   r4   superrK   )rG   r   r   rH   rP   r4   r<   rK   x  s
   
zITKWriter.__init__r   rR   r
   r}   r[   c              	   K  s~   |dur	|j | nd}| j||||dd|ddd| _d| _|r*|d	kr*d| _|s;|d	k r=d| _| jd
 | _dS dS dS )av  
        Convert ``data_array`` into 'channel-last' numpy ndarray.

        Args:
            data_array: input data array with the channel dimension specified by ``channel_dim``.
            channel_dim: channel dimension of the data array. Defaults to 0.
                ``None`` indicates data without any channel dimension.
            squeeze_end_dims: if ``True``, any trailing singleton dimensions will be removed.
            kwargs: keyword arguments passed to ``self.convert_to_channel_last``,
                currently support ``spatial_ndim`` and ``contiguous``, defauting to ``3`` and ``False`` respectively.
        Nr   r~   ry   r   Trz   r{   r}   r~   r   r   r3   ).r   )r   r   poprD   r{   )rG   rR   r{   r}   rH   Zn_chnsr4   r4   r<   rS     s   

zITKWriter.set_data_arrayrU   rV   resamplec                 K  s   |  |\}}}| jdu rt| jdr| jj| _| jtt| j||r$|nd|r)|nd|dt	j
|dtj|dd|dtjd\| _| _dS a  
        Resample ``self.dataobj`` if needed.  This method assumes ``self.data_obj`` is a 'channel-last' ndarray.

        Args:
            meta_dict: a metadata dictionary for affine, original affine and spatial shape information.
                Optional keys are ``"spatial_shape"``, ``"affine"``, ``"original_affine"``.
            resample: if ``True``, the data will be resampled to the original affine (specified in ``meta_dict``).
            options: keyword arguments passed to ``self.resample_if_needed``,
                currently support ``mode``, ``padding_mode``, ``align_corners``, and ``dtype``,
                defaulting to ``bilinear``, ``border``, ``False``, and ``np.float64`` respectively.
        Nrm   ri   rk   rl   F)rR   rd   rf   rg   ri   rk   rl   rm   )r   r   hasattrrD   rm   rx   r   r
   r   r   r   r   r   r`   r   rd   rG   rU   r   rW   r   rd   r   r4   r4   r<   rX     s   




zITKWriter.set_metadataFrY   r   rZ   c                   sf   t  j||d | jtt| jf| j| j| j| j	d|| _t
j| j||dd|ddd dS )a  
        Create an ITK object from ``self.create_backend_obj(self.obj, ...)`` and call ``itk.imwrite``.

        Args:
            filename: filename or PathLike object.
            verbose: if ``True``, log the progress.
            kwargs: keyword arguments passed to ``itk.imwrite``,
                currently support ``compression`` and ``imageio``.

        See also:

            - https://github.com/InsightSoftwareConsortium/ITK/blob/v5.2.1/Wrapping/Generators/Python/itk/support/extras.py#L809
        rZ   )r{   rd   rm   r   compressionFimageioN)r   r   )r   r^   rc   r   r
   rD   r{   rd   r   r   r&   imwriter   r]   r   r4   r<   r^     s   

zITKWriter.writerd   re   rm   c                   s<  t |tr|du r|jtjtjtjk}t 	|}|du}|r(t
|dd}|jjt|t
jddd}tj|||ddd}tt|}	|du rVt
j|	d	 t
jd
}t|t
jd }
|rgtt|	|
}
t|
|	d}t
d	| }|
d|	d|	f | }||  ||
d|	df   |t | |S )a2  
        Create an ITK object from ``data_array``. This method assumes a 'channel-last' ``data_array``.

        Args:
            data_array: input data array.
            channel_dim: channel dimension of the data array. This is used to create a Vector Image if it is not ``None``.
            affine: affine matrix of the data array. This is used to compute `spacing`, `direction` and `origin`.
            dtype: output data type.
            affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``.
                Set to ``True`` to be consistent with ``NibabelWriter``,
                otherwise the affine matrix is assumed already in the ITK convention.
                Set to ``None`` to use ``data_array.meta[MetaKeys.SPACE]`` to determine the flag.
            kwargs: keyword arguments. Current `itk.GetImageFromArray` will read ``ttype`` from this dictionary.

        see also:

            - https://github.com/InsightSoftwareConsortium/ITK/blob/v5.2.1/Wrapping/Generators/Python/itk/support/extras.py#L389

        Nr   r   TC)copyorderttype)Z	is_vectorr   r3   )rm   )r)!rs   r   metar?   r   SPACEr   LPSr   rc   r`   r   Tastyper   ra   r&   ZGetImageFromArrayr   r   sizeeyer   r   r   r   r   diagZ
SetSpacingtolistZ	SetOriginZSetDirectionZGetMatrixFromArray)rb   rR   r{   rd   rm   r   rH   Z_is_vecZitk_objd_affinespacing
_directionr   r4   r<   rc     s,   zITKWriter.create_backend_obj)r   r	   r   r   r   TrR   r
   r{   r   r}   r[   NTrU   rV   r   r[   Fr   )
rR   r
   r{   r   rd   re   rm   r	   r   r   )rQ   r   r   r   r   __annotations__r`   float32rK   rS   rX   r^   r   rc   __classcell__r4   r4   r   r<   r*   Z  s   
 r*   c                      sz   e Zd ZU dZded< ded< ejfd" fddZ		d#d$ddZd%d&ddZ	d'd( fddZ
e	d)d* fd d!Z  ZS )+r+   a  
    Write data and metadata into files on disk using Nibabel.

    .. code-block:: python

        import numpy as np
        from monai.data import NibabelWriter

        np_data = np.arange(48).reshape(3, 4, 4)
        writer = NibabelWriter()
        writer.set_data_array(np_data, channel_dim=None)
        writer.set_metadata({"affine": np.eye(4), "original_affine": np.eye(4)})
        writer.write("test1.nii.gz", verbose=True)

    r	   r   r   rd   c                   s   t  jd|dd| dS )aZ  
        Args:
            output_dtype: output data type.
            kwargs: keyword arguments passed to ``ImageWriter``.

        The constructor will create ``self.output_dtype`` internally.
        ``affine`` is initialized as instance members (default ``None``),
        user-specified ``affine`` should be set in ``set_metadata``.
        N)r   rd   r4   r   )rG   r   rH   r   r4   r<   rK   *  s   
zNibabelWriter.__init__r   TrR   r
   r{   r   r}   r[   c                 K  s    | j ||||ddd| _dS )aH  
        Convert ``data_array`` into 'channel-last' numpy ndarray.

        Args:
            data_array: input data array with the channel dimension specified by ``channel_dim``.
            channel_dim: channel dimension of the data array. Defaults to 0.
                ``None`` indicates data without any channel dimension.
            squeeze_end_dims: if ``True``, any trailing singleton dimensions will be removed.
            kwargs: keyword arguments passed to ``self.convert_to_channel_last``,
                currently support ``spatial_ndim``, defauting to ``3``.
        r~   ry   )rz   r{   r}   r~   Nr   r   rD   )rG   rR   r{   r}   rH   r4   r4   r<   rS   6  s   
zNibabelWriter.set_data_arrayrU   rV   r   c                 K  s   |  |\}}}| jdu r| jdurt| jdr| jj| _| jtt| j||r)|nd|r.|nd|dt	j
|dtj|dd|dtjd\| _| _dS r   )r   r   rD   r   rm   rx   r   r
   r   r   r   r   r   r`   r   rd   r   r4   r4   r<   rX   K  s    




zNibabelWriter.set_metadataFrY   r   rZ   c                   s   t  j||d | jtt| jf| j| jd|| _| jdu r&t	d| _t
dt| jtjd d}| jj|dd	 | jj|dd	 t| j| dS )
a  
        Create a Nibabel object from ``self.create_backend_obj(self.obj, ...)`` and call ``nib.save``.

        Args:
            filename: filename or PathLike object.
            verbose: if ``True``, log the progress.
            obj_kwargs: keyword arguments passed to ``self.create_backend_obj``,

        See also:

            - https://nipy.org/nibabel/reference/nibabel.nifti1.html#nibabel.nifti1.save
        r   )rd   rm   N   ry   r   r   rd   r3   )code)r   r^   rc   r   r
   rD   rd   r   r`   r   r   r   ra   	set_sform	set_qformnibsave)rG   rY   rZ   Z
obj_kwargsr   r   r4   r<   r^   g  s   

zNibabelWriter.writeNre   rm   c              	     s   t  |}|dur|jt|tjdd}t|tjd }|du r&td}td|d}t	j
j|||dd|d	d|d
ddS )a  
        Create an Nifti1Image object from ``data_array``. This method assumes a 'channel-last' ``data_array``.

        Args:
            data_array: input data array.
            affine: affine matrix of the data array.
            dtype: output data type.
            kwargs: keyword arguments. Current ``nib.nifti1.Nifti1Image`` will read
                ``header``, ``extra``, ``file_map`` from this dictionary.

        See also:

            - https://nipy.org/nibabel/reference/nibabel.nifti1.html#nibabel.nifti1.Nifti1Image
        NFr   r   r   ry   r   headerextrafile_map)r   r   r   )r   rc   r   r   r`   ra   r   r   r   r   Znifti1ZNifti1Imager   )rb   rR   rd   rm   rH   r   r4   r<   rc     s   



z NibabelWriter.create_backend_obj)r   r	   r   r   r   r   r   r   )NN)rR   r
   rd   re   rm   r	   )rQ   r   r   r   r   r`   r   rK   rS   rX   r^   r   rc   r   r4   r4   r   r<   r+     s   
 r+   PILc                      s   e Zd ZU dZded< ded< ded< ejddfd. fd	d
Z			d/d0ddZd1d2ddZ	d3d4 fddZ
ed5d6d d!Zedejfd7d(d)Ze			d8d9 fd,d-Z  ZS ):r,   a  
    Write image data into files on disk using pillow.

    It's based on the Image module in PIL library:
    https://pillow.readthedocs.io/en/stable/reference/Image.html

    .. code-block:: python

        import numpy as np
        from monai.data import PILWriter

        np_data = np.arange(48).reshape(3, 4, 4)
        writer = PILWriter(np.uint8)
        writer.set_data_array(np_data, channel_dim=0)
        writer.write("test1.png", verbose=True)
    r	   r   r   r{   scaler      c                   s   t  jd|||d| dS )a  
        Args:
            output_dtype: output data type.
            channel_dim: channel dimension of the data array. Defaults to 0.
                ``None`` indicates data without any channel dimension.
            scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling
                [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling.
            kwargs: keyword arguments passed to ``ImageWriter``.
        )r   r{   r   Nr4   r   )rG   r   r{   r   rH   r   r4   r<   rK     s   zPILWriter.__init__TFrR   r
   r}   r[   r   c                 K  s"   | j ||||dd|d| _dS )a  
        Convert ``data_array`` into 'channel-last' numpy ndarray.

        Args:
            data_array: input data array with the channel dimension specified by ``channel_dim``.
            channel_dim: channel dimension of the data array. Defaults to 0.
                ``None`` indicates data without any channel dimension.
            squeeze_end_dims: if ``True``, any trailing singleton dimensions will be removed.
            contiguous: if ``True``, the data array will be converted to a contiguous array. Default is ``False``.
            kwargs: keyword arguments passed to ``self.convert_to_channel_last``,
                currently support ``spatial_ndim``, defauting to ``2``.
        r~      r   Nr   )rG   rR   r{   r}   r   rH   r4   r4   r<   rS     s   
zPILWriter.set_data_arrayNrU   rV   r   c                 K  sT   |  |}| jdu rt| jdr| jj| _| j| j|r|nd|dtjd| _dS )a*  
        Resample ``self.dataobj`` if needed.  This method assumes ``self.data_obj`` is a 'channel-last' ndarray.

        Args:
            meta_dict: a metadata dictionary for affine, original affine and spatial shape information.
                Optional key is ``"spatial_shape"``.
            resample: if ``True``, the data will be resampled to the spatial shape specified in ``meta_dict``.
            options: keyword arguments passed to ``self.resample_if_needed``,
                currently support ``mode``, defaulting to ``bicubic``.
        Nrm   ri   )rR   rg   ri   )	r   r   r   rD   rm   resample_and_clipr   r   BICUBIC)rG   rU   r   rW   r   r4   r4   r<   rX     s   


zPILWriter.set_metadatarY   r   rZ   c              	     s\   t  j||d | jd| j| j|dd|dd| jd|| _| jj|fi | dS )a$  
        Create a PIL image object from ``self.create_backend_obj(self.obj, ...)`` and call ``save``.

        Args:
            filename: filename or PathLike object.
            verbose: if ``True``, log the progress.
            kwargs: optional keyword arguments passed to ``self.create_backend_obj``
                currently support ``reverse_indexing``, ``image_mode``, defaulting to ``True``, ``None`` respectively.

        See also:

            - https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save
        r   reverse_indexingT
image_modeN)rR   rm   r   r   r   r4   )r   r^   rc   rD   r   r   r   r   r]   r   r4   r<   r^     s   

zPILWriter.writer   c                 C  s   |sd S | tjS r   )r?   r   r   )rb   r   r4   r4   r<   r     s   zPILWriter.get_meta_inforg   Sequence[int] | Noneri   rj   r=   r_   c           
      C  s   t |tjd }|durrt|d}t|t}|tjtjfv r dnd}t|||d}t	|t
|}}	t|jdkrTt|dd}t ||tjd }t|dd}nt|d}t ||tjd d }|tjkrrt|||	}|S )a=  
        Resample ``data_array`` to ``output_spatial_shape`` if needed.
        Args:
            data_array: input data array. This method assumes the 'channel-last' format.
            output_spatial_shape: output spatial shape.
            mode: interpolation mode, default is ``InterpolateMode.BICUBIC``.
        r   Nr   F)rp   ri   rl   ry   r   )r   r`   ra   r   r   r   NEARESTAREAr   minmaxr   r   r   expand_dimsclip)
rb   rR   rg   ri   rz   Zoutput_spatial_shape_rl   xform_min_maxr4   r4   r<   r     s    


zPILWriter.resample_and_cliprm   r   c                   s   t  |}|r?t|dd}|ttjjkr#|| jtjdd}n|ttjjkr7|| jtjdd}nt	d| d|durN|jt
|tjdd}|rWt|dd	}tj||d
ddS )a  
        Create a PIL object from ``data_array``.

        Args:
            data_array: input data array.
            dtype: output data type.
            scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling
                [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling.
            reverse_indexing: if ``True``, the data array's first two dimensions will be swapped.
            kwargs: keyword arguments. Currently ``PILImage.fromarray`` will read
                ``image_mode`` from this dictionary, defaults to ``None``.

        See also:

            - https://pillow.readthedocs.io/en/stable/reference/Image.html
        g        g      ?Fr   zUnsupported scale: z%, available options are [255, 65535].Nr   r3   r   )ri   )r   rc   r`   r   iinfouint8r   r   uint16
ValueErrorr   ra   r   PILImage	fromarrayr   )rb   rR   rm   r   r   rH   rz   r   r4   r<   rc   5  s   zPILWriter.create_backend_obj)r   r	   r{   r   r   r   )r   TF)rR   r
   r{   r   r}   r[   r   r[   r   r   r   r   r   r   )rR   r
   rg   r   ri   rj   r=   r_   )Nr   T)rR   r
   rm   r	   r   r   r   r[   )rQ   r   r   r   r   r`   r   rK   rS   rX   r^   r   r   r   r   r   rc   r   r4   r4   r   r<   r,     s0   
  r,   c                  C  sH   dD ]} t | t qdD ]} t | tt qt dtt t tttt dS )zR
    Initialize the image writer modules according to the filename extension.
    )pngjpgjpegbmptifftif)znii.gzZniinrrdN)r.   r,   r+   r*   r@   )extr4   r4   r<   r>   a  s   r>   r   )r=   r   )A
__future__r   collections.abcr   r   typingr   r   r   numpyr`   monai.apps.utilsr   monai.configr	   r
   r   monai.data.meta_tensorr   monai.data.utilsr   r   r   r   r   Zmonai.transforms.spatial.arrayr   r   0monai.transforms.utils_pytorch_numpy_unificationr   r   monai.utilsr   r   r   r   r   r   r   r   r   r   r    r!   DEFAULT_FMTr@   rQ   r0   r&   r(   r   r   r%   r   rw   __all__r-   r   r.   r/   r)   r*   r+   r,   r>   r4   r4   r4   r<   <module>   sJ   8! ^ ;  ?