U Ph@sUddlmZddlmZmZddlmZmZmZddl Z ddl m Z ddl mZmZmZddlmZddlmZmZmZmZmZdd lmZmZdd lmZmZdd lm 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,dZ/erddl0Z0ddl1Z2ddl3m4Z5n(e*ddd\Z0Z6e*d\Z2Z6e*d\Z5Z6ddddddddgZ7iZ8de9d<ddZ:d*dd d!dZ;Gd"ddZe+d&d#Gd'dde<Z?d(d)Z@dS)+) annotations)MappingSequence) TYPE_CHECKINGAnycastN) get_logger) DtypeLikeNdarrayOrTensorPathLike) MetaTensor)affine_to_spacing ensure_tupleensure_tuple_reporientation_ras_lps to_affine_nd)ResizeSpatialResample)ascontiguousarraymoveaxis) GridSampleModeGridSamplePadModeInterpolateModeMetaKeysOptionalImportError SpaceKeysconvert_data_typeconvert_to_tensorget_equivalent_dtypelook_up_optionoptional_import require_pkgz?%(asctime)s %(levelname)s %(filename)s:%(lineno)d - %(message)s*) module_namefmt)ImageitkT)allow_namespace_pkgnibabelz PIL.Image ImageWriter ITKWriter NibabelWriter PILWriterSUPPORTED_WRITERSregister_writerresolve_writerloggerdictcGsB|}|dr |dd}t|tdd}||}|t|<dS)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. .Ndefault)lower startswithrr-)ext_nameZ im_writersr$existing all_writersr4r4L/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/data/image_writer.pyr.Cs    r)returnc Csts t|}|dr*|dd}g}ttd}t|t|dD]N}z|||WqHtk rxYqHYqHt k r||YqHXqH|s|rtd|dt |}|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``. r2r3Nr4r5z!No ImageWriter backend found for ) r-initr7r8get EXT_WILDCARDrappendr Exceptionr)r9Zerror_if_not_foundr$Z avail_writersZdefault_writers_writerZ writer_tupler4r4r<r/\s(     c @seZdZdZddZddZdddd Zd(d d d ddZedddddZ eddde j e j dejfddddddd ddddZed)dd d d!d d"d#d$Zed*dd%d&d'ZdS)+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. cKs(d|_|D]\}}t|||qdS)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_objitemssetattr)selfkwargskvr4r4r<__init__szImageWriter.__init__cKstd|jjddSNzSubclasses of z must implement this method.NotImplementedError __class____name__)rG data_arrayrHr4r4r<set_data_arrayszImageWriter.set_data_arrayMapping | None) meta_dictcKstd|jjddSrLrM)rGrToptionsr4r4r< set_metadataszImageWriter.set_metadataTr boolfilenameverbosecKs|rtd|dS)zPsubclass should implement this method to call the backend-specific writing APIs.z writing: N)r0inforGrYrZrHr4r4r<writeszImageWriter.writer np.ndarray)rQr=cKst|tjdS)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)rnpndarray)clsrQrHr4r4r<create_backend_objszImageWriter.create_backend_objNFNdarrayOrTensor | NonezSequence[int] | int | Nonestrr rQaffine target_affineoutput_spatial_shapemode padding_mode align_cornersdtypec Cst|} t|dd}|dk r*t|dd|_t||||d} | |d||d} t| tr\g| _t| | d^}} t| j| d^}} |d|fS) 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)rirjrkrl) dst_affine spatial_size) output_typer)typerrfr isinstancer applied_operationsr) rarQrfrgrhrirjrkrl orig_type resamplerZ output_array_r4r4r<resample_if_neededs=  zImageWriter.resample_if_neededrzNone | int | Sequence[int] int | Nonedata channel_dimsqueeze_end_dims spatial_ndim contiguouscCs|dk r.t|}t||ttt| d}n|d}|rt|j|dkr`|ddddf}q:t|j|dkr|ddddf}q`|r|jddkrt|d}q|rt|}|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.) rrtuplerangelenshaper_squeezer)rar{r|r}r~rZ_chnsr4r4r<convert_to_channel_lastsz#ImageWriter.convert_to_channel_lastmetadatacCsD|sddtjdtjdi}|d}|tj}|tj}|||fS)z Extracts relevant meta information from the metadata object (using ``.get``). Optional keys are ``"spatial_shape"``, ``MetaKeys.AFFINE``, ``"original_affine"``. original_affineN)rAFFINE SPATIAL_SHAPEr?)rarrrf spatial_shaper4r4r< get_meta_infoLs    zImageWriter.get_meta_info)T)rTrxF)N)rP __module__ __qualname____doc__rKrRrVr] classmethodrbrBILINEARrBORDERr_float64rwrrr4r4r4r<r)}s04  K0)pkg_namecseZdZUdZdZded<ded<ejdfddd fd d Zdd dddddZ d dddddZ d!dddfdd Z e d dejdfd dddddfdd Z ZS)"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_dtyperyr|Tz bool | None)raffine_lps_to_rasc s tjf||ddd|dS)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)rrrfr|superrK)rGrrrHrOr4r<rKxszITKWriter.__init__rr rWrQr|r}c Ksv|dk r|j|nd}|j||||dd|ddd|_d|_|rT|d krTd|_|sr|d krrd|_|jd |_dS) 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. Nrr~rxrTrzrr3).r)rrpoprDr|)rGrQr|r}rHZn_chnsr4r4r<rRs    zITKWriter.set_data_arrayrSrTresamplec Ks||\}}}|jdkr0t|jdr0|jj|_|jtt|j||rH|nd|rR|nd|dt j |dt j |dd|dt jd\|_|_dSa 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. NrlrirjrkFre)rrhasattrrDrlrwrr rrrrrr_rrfrGrTrrUrrfrr4r4r<rVs         zITKWriter.set_metadataFr rXc sftj||d|jtt|jf|j|j|j|j d||_t j |j|| dd| ddddS)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|rfrlr compressionFimageioN)rr) rr]rbrr rDr|rfrrr&imwriterr\rr4r<r]s"  zITKWriter.writerc)rQr|rfrlrc  s<t|tr*|dkr*|jtjtjtjk}t |}|dk }|rPt |dd}|j j t|t jddd}tj|||ddd}tt|} |dkrt j| d t jd }t|t jd} |rtt| | } t| | d } t d | } | d| d| f| } || || d| df|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 NrrTC)copyorderttype) is_vectorrr3)rl)r)!rrr metar?rSPACErLPSrrbr_rTastyperr`r&ZGetImageFromArrayrrsizeeyerrrrr diagZ SetSpacingtolistZ SetOriginZ SetDirectionZGetMatrixFromArray) rarQr|rfrlrrHZ_is_vecZitk_objd_affinespacing _directionrr4r<rbs,  zITKWriter.create_backend_obj)rT)NT)F)rPrrrr__annotations__r_float32rKrRrVr]rrb __classcell__r4r4rr<r*Zs  cseZdZUdZded<ded<ejfddfdd Zdd d d dddZd dd dddZ d!dd dfdd Z e d"d dddfdd 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 rrrf)rc stjf|dd|dS)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)rrfr)rGrrHrr4r<rK*s zNibabelWriter.__init__rTr ryrWrcKs |j||||ddd|_dS)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~rx)r{r|r}r~NrrrD)rGrQr|r}rHr4r4r<rR6s  zNibabelWriter.set_data_arrayrSrc Ks||\}}}|jdkr:|jdk r:t|jdr:|jj|_|jtt|j||rR|nd|r\|nd|dt j |dt j |dd|dt jd\|_|_dSr)rrrDrrlrwrr rrrrrr_rrfrr4r4r<rVKs$          zNibabelWriter.set_metadataFr rXc stj||d|jtt|jf|j|jd||_|jdkrLt d|_t dt |jtj dd}|jj |dd |jj|dd t|j|dS) 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)rfrlNrxrrrfr3)code)rr]rbrr rDrfrr_rrrr` set_sform set_qformnibsave)rGrYrZZ obj_kwargsrrr4r<r]gs    zNibabelWriter.writeNrc)rQrfrlc st|}|dk r*|jt|tjdd}t|tjd}|dkrLtd}td|d}t j j ||| dd| d d| d dd 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 NFrrrrxrheaderextrafile_map)rrr) rrbrrr_r`rrrrnifti1 Nifti1Imager)rarQrfrlrHrr4r<rbs      z NibabelWriter.create_backend_obj)rT)T)F)NN)rPrrrrr_rrKrRrVr]rrbrr4r4rr<r+s  PILcseZdZUdZded<ded<ded<ejddfdddd fd d Zd(dddddddZd)dddddZ d*dddfdd Z e d+ddddZ e de jfddd d!d"d#d$Ze d,ddddd%fd&d' ZZS)-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 rryr|scalerrr|rc stjf|||d|dS)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``. rNr)rGrr|rrHrr4r<rKs zPILWriter.__init__TFr rW)rQr|r}rcKs"|j||||dd|d|_dS)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~rzNr)rGrQr|r}rrHr4r4r<rRs zPILWriter.set_data_arrayNrSrcKsT||}|jdkr*t|jdr*|jj|_|j|j|r:|nd|dtjd|_dS)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``. Nrlri)rQrhri) rrrrDrlresample_and_cliprrBICUBIC)rGrTrrUrr4r4r<rVs    zPILWriter.set_metadatar rXc sXtj||d|jf|j|j|dd|dd|jd||_|jj|f|dS)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 rreverse_indexingT image_modeN)rQrlrrr)rr]rbrDrrrrr\rr4r<r]s  zPILWriter.writercCs|sdS|tjS)N)r?rr)rarr4r4r<rszPILWriter.get_meta_infozSequence[int] | Nonerdr^)rQrhrir=c Cst|tjd}|dk rt|d}t|t}|tjtjfkr@dnd}t|||d}t |t |}} t |j dkrt |dd}t||tjd}t |dd}n$t|d}t||tjdd}|tjkrt||| }|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``. rNrF)rorirkrxr)rr_r`rrrNEARESTAREArminmaxrrr expand_dimsclip) rarQrhrir{Zoutput_spatial_shape_rkxform_min_maxr4r4r<rs     zPILWriter.resample_and_clip)rQrlrrc st|}|r~t|dd}|ttjjkrF||jtjdd}n8|ttjjkrn||jtjdd}nt d|d|dk r|jt |tj dd}|rt |dd }t j||d dd 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 gg?FrzUnsupported scale: z%, available options are [255, 65535].Nrr3r)ri)rrbr_riinfouint8rruint16 ValueErrorrr`rPILImage fromarrayr)rarQrlrrrHr{rr4r<rb5s zPILWriter.create_backend_obj)rTF)NT)F)N)NrT)rPrrrrr_rrKrRrVr]rrrrrrbrr4r4rr<r,s2  cCsHdD]}t|tqdD]}t|ttqtdtttttttdS)zR Initialize the image writer modules according to the filename extension. )pngjpgjpegbmptifftif)znii.gzZniinrrdN)r.r,r+r*r@)extr4r4r<r>as   r>)T)A __future__rcollections.abcrrtypingrrrnumpyr_monai.apps.utilsr monai.configr r r monai.data.meta_tensorr monai.data.utilsr rrrrZmonai.transforms.spatial.arrayrr0monai.transforms.utils_pytorch_numpy_unificationrr monai.utilsrrrrrrrrrrr r! DEFAULT_FMTr@rPr0r&r(rrr%rrv__all__r-rr.r/r)r*r+r,r>r4r4r4r< sZ   8    !^; ?