U Ph$d@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlZddlZddlmZmZmZdd lmZdd lmZmZmZdd lmZmZm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&dd l'm(Z(ddl)m*Z*ddl+m,Z,ddl-m.Z.ddl-m/Z0ddl-m1Z1m2Z2m3Z3m4Z4m5Z5e5d\Z6Z7e5d\Z8Z7e5d\Z9Z7dddgZ:e$ee!e"e#e dZ;dddZdS) z8 A collection of "vanilla" transforms for IO functions. ) annotationsN)Sequence)Path)locate)Callable) DtypeLikeNdarrayOrTensorPathLike) image_writer) FolderLayoutFolderLayoutBasedefault_name_formatter) ImageReader ITKReader NibabelReader NrrdReader NumpyReader PILReader PydicomReader) MetaTensor) is_no_channel) Transform)EnsureChannelFirst)GridSamplePadMode) ImageMetaKey)OptionalImportErrorconvert_to_dst_type ensure_tuplelook_up_optionoptional_importnibabelz PIL.Imagenrrd LoadImage SaveImageSUPPORTED_READERS)Z pydicomreaderZ itkreaderZ nrrdreaderZ numpyreaderZ pilreaderZ nibabelreader". ) requires_gradlittler%>)r%r(zNot implemented option new=.c3s|]}t|VqdSNswitch_endianness.0xnewN/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/io/array.py [sz$switch_endianness..csg|]}t|qSr2r+r-r0r2r3 ]sz%switch_endianness..csi|]\}}|t|qSr2r+)r.kvr0r2r3 _sz%switch_endianness..NzUnknown type: ) isinstancetorchTensordevicer& from_numpyr,cpudetachnumpytorequires_grad_npndarraysys byteorderdtypeNotImplementedErrorbyteswap newbyteordertuplelistdictitemsboolstrfloatinttype RuntimeError__name__)datar1r<r&Z sys_nativeZcurrent_r2r0r3r,Bs2     r,c @s`eZdZdZddejdddddfdddddd dd d d d ZddddZddddddZdS)r"a Load image file or files from provided path based on reader. If reader is not specified, this class automatically chooses readers based on the supported suffixes and in the following order: - User-specified reader at runtime when calling this loader. - User-specified reader in the constructor of `LoadImage`. - Readers from the last to the first in the registered list. - Current default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader), (npz, npy -> NumpyReader), (nrrd -> NrrdReader), (DICOM file -> ITKReader). Please note that for png, jpg, bmp, and other 2D formats, readers by default swap axis 0 and 1 after loading the array with ``reverse_indexing`` set to ``True`` because the spatial axes definition for non-medical specific file formats is different from other common medical packages. See also: - tutorial: https://github.com/Project-MONAI/tutorials/blob/master/modules/load_medical_images.ipynb NTFr)rODtypeLike | Nonez str | NonerPNone) image_onlyrGensure_channel_first simple_keysprune_meta_patternprune_meta_sep expanduserreturnc  Os|dk|_||_||_||_||_||_||_||_g|_t D]} z| t | | | Wq>t k rt |jjd| dYq>tk rt |jj| d| d| d| t | Yq>Xq>|dkrdSt|D]} t| trtd| d\} }|st| } | dkr4t| t } z| | | | Wndt k rptd| dYn>tk rt| d| d| d| | YnXqt| r| | | | q| | qdS) a Args: reader: reader to load image file and metadata - if `reader` is None, a default set of `SUPPORTED_READERS` will be used. - if `reader` is a string, it's treated as a class name or dotted path (such as ``"monai.data.ITKReader"``), the supported built-in reader classes are ``"ITKReader"``, ``"NibabelReader"``, ``"NumpyReader"``, ``"PydicomReader"``. a reader instance will be constructed with the `*args` and `**kwargs` parameters. - if `reader` is a reader class/instance, it will be registered to this loader accordingly. image_only: if True return only the image MetaTensor, otherwise return image and header dict. dtype: if not None convert the loaded image to this data type. ensure_channel_first: if `True` and loaded both image array and metadata, automatically convert the image array shape to `channel first`. default to `False`. simple_keys: whether to remove redundant metadata keys, default to False for backward compatibility. prune_meta_pattern: combined with `prune_meta_sep`, a regular expression used to match and prune keys in the metadata (nested dictionary), default to None, no key deletion. prune_meta_sep: combined with `prune_meta_pattern`, used to match and prune keys in the metadata (nested dictionary). default is ".", see also :py:class:`monai.transforms.DeleteItemsd`. e.g. ``prune_meta_pattern=".*_code$", prune_meta_sep=" "`` removes meta keys that ends with ``"_code"``. expanduser: if True cast filename to Path and call .expanduser on it, otherwise keep filename as is. args: additional parameters for reader if providing a reader name. kwargs: additional parameters for reader if providing a reader name. Note: - The transform returns a MetaTensor, unless `set_track_meta(False)` has been used, in which case, a `torch.Tensor` will be returned. - If `reader` is specified, the loader will attempt to use the specified readers and the default supported readers. This might introduce overheads when handling the exceptions of trying the incompatible loaders. In this case, it is therefore recommended setting the most appropriate reader as the last item of the `reader` parameter. Nzrequired package for reader z< is not installed, or the version doesn't match requirement.z, is not supported with the given parameters  r) monai.dataname) auto_selectrYrGrZr[patternsepr^readersr$registerrlogging getLogger __class__rUdebug TypeErrorrr9rPrrrlowerwarningswarninspectisclass)selfreaderrYrGrZr[r\r]r^argskwargsr_rZ the_reader has_built_inr2r2r3__init__{sV/         zLoadImage.__init__r)rtcCs0t|ts tdt|d|j|dS)z Register image reader to load image file and metadata. Args: reader: reader instance to be registered with this loader. z:Preferably the reader should inherit ImageReader, but got r)N)r9rrorprSrgappend)rsrtr2r2r3rhs zLoadImage.registerzSequence[PathLike] | PathLikezImageReader | None)filenamertc stfddt|D}dg}}|dk r8||}njdddD]}jrl||r||}qqHz||}Wnltk r}zN|t t j j j|ddt j j |j j d|dW5d}~XYqHXg}qqH|dks|dkr`t|tr(t|d kr(|d }d d d |D}tj j d|djd|||\}}t||jdd }t|tstdt|dt|d}t|d |tj<tj||j j!j"d}j#rt$|}j%r|S|t|tr |j&n|fS)a Load image file and metadata from the given filename(s). If `reader` is not specified, this class automatically chooses readers based on the reversed order of registered readers `self.readers`. Args: filename: path file or file-like object or a list of files. will save the filename to meta_data with key `filename_or_obj`. if provided a list of files, use the filename of first file to save, and will stack them together as multi-channels data. if provided directory path instead of file path, will treat it as DICOM images series and read. reader: runtime reader to load image file and metadata. c3s&|]}jrt|n|VqdSr*)r^r)r.srsr2r3r4sz%LoadImage.__call__..NTexc_infoz: unable to load . r cSsg|] }|qSr2r2r.er2r2r3r5sz&LoadImage.__call__..z) cannot find a suitable reader for file: z. Please install the reader libraries, see also the installation instructions: https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies. The current registered: )dstrGz%`meta_data` must be a dict, got type r)r%)rerf)'rKrreadrgrdZ verify_suffix Exceptionr{ traceback format_excrirjrkrUrlinfor9rlenjoinrTget_datarrGrM ValueErrorrSr,KeyFILENAME_OR_OBJrensure_torch_and_prune_metar[rerfrZrrYmeta) rsr|rtimgerrrmsgZ img_array meta_datar2r~r3__call__s\        zLoadImage.__call__)N) rU __module__ __qualname____doc__rCfloat32rzrhrr2r2r2r3r"es^ c@seZdZdZdddejddejdejdd ddd dd dddfd d d d dd d dddd ddd dddddddddZ d ddZ d!ddddddZ dS)"r#a Save the image (in the form of torch tensor or numpy ndarray) and metadata dictionary into files. The name of saved file will be `{input_image_name}_{output_postfix}{output_ext}`, where the `input_image_name` is extracted from the provided metadata dictionary. If no metadata provided, a running index starting from 0 will be used as the filename prefix. Args: output_dir: output image directory. Handled by ``folder_layout`` instead, if ``folder_layout`` is not ``None``. output_postfix: a string appended to all output file names, default to `trans`. Handled by ``folder_layout`` instead, if ``folder_layout`` is not ``None``. output_ext: output file extension name. Handled by ``folder_layout`` instead, if ``folder_layout`` is not ``None``. output_dtype: data type (if not None) for saving data. Defaults to ``np.float32``. resample: whether to resample image (if needed) before saving the data array, based on the ``"spatial_shape"`` (and ``"original_affine"``) from metadata. mode: This option is used when ``resample=True``. Defaults to ``"nearest"``. Depending on the writers, the possible options are - {``"bilinear"``, ``"nearest"``, ``"bicubic"``}. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample - {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}. See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate padding_mode: This option is used when ``resample = True``. Defaults to ``"border"``. Possible options are {``"zeros"``, ``"border"``, ``"reflection"``} See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling [0, 255] (``uint8``) or [0, 65535] (``uint16``). Default is ``None`` (no scaling). dtype: data type during resampling computation. Defaults to ``np.float64`` for best precision. if ``None``, use the data type of input data. To set the output data type, use ``output_dtype``. 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 (C,H,W,D), this will be altered to (H,W,D,C), and then if C==1, 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). data_root_dir: if not empty, it specifies the beginning parts of the input file's absolute path. It's used to compute ``input_file_rel_path``, the relative path to the file from ``data_root_dir`` to preserve folder structure when saving in case there are files in different folders with the same file names. For example, with the following inputs: - input_file_name: ``/foo/bar/test1/image.nii`` - output_postfix: ``seg`` - output_ext: ``.nii.gz`` - output_dir: ``/output`` - data_root_dir: ``/foo/bar`` The output will be: ``/output/test1/image/image_seg.nii.gz`` Handled by ``folder_layout`` instead, if ``folder_layout`` is not ``None``. separate_folder: whether to save every file in a separate folder. For example: for the input filename ``image.nii``, postfix ``seg`` and ``folder_path`` ``output``, if ``separate_folder=True``, it will be saved as: ``output/image/image_seg.nii``, if ``False``, saving as ``output/image_seg.nii``. Default to ``True``. Handled by ``folder_layout`` instead, if ``folder_layout`` is not ``None``. print_log: whether to print logs when saving. Default to ``True``. output_format: an optional string of filename extension to specify the output image writer. see also: ``monai.data.image_writer.SUPPORTED_WRITERS``. writer: a customised ``monai.data.ImageWriter`` subclass to save data arrays. if ``None``, use the default writer from ``monai.data.image_writer`` according to ``output_ext``. if it's a string, it's treated as a class name or dotted path (such as ``"monai.data.ITKWriter"``); the supported built-in writer classes are ``"NibabelWriter"``, ``"ITKWriter"``, ``"PILWriter"``. channel_dim: the index of the channel dimension. Default to ``0``. ``None`` to indicate no channel dimension. output_name_formatter: a callable function (returning a kwargs dict) to format the output file name. If using a custom ``monai.data.FolderLayoutBase`` class in ``folder_layout``, consider providing your own formatter. see also: :py:func:`monai.data.folder_layout.default_name_formatter`. folder_layout: A customized ``monai.data.FolderLayoutBase`` subclass to define file naming schemes. if ``None``, uses the default ``FolderLayout``. savepath_in_metadict: if ``True``, adds a key ``"saved_to"`` to the metadata, which contains the path to where the input image has been saved. z./transz.nii.gzFnearestNTrr rPrWrOz int | Nonerz+type[image_writer.ImageWriter] | str | Nonez(Callable[[dict, Transform], dict] | NonezFolderLayoutBase | NonerX) output_diroutput_postfix output_ext output_dtyperesamplemode padding_modescalerGsqueeze_end_dims data_root_dirseparate_folder print_log output_formatwriter channel_dimoutput_name_formatter folder_layoutsavepath_in_metadictr_cCsv||dkr$t|||| d| d|_n||_||dkr>t|_n||_|pR||_|jrt|jdstd|jn|j|_t|trt d|d\}}|st |}|dkrt d|d|}|dkrt |jn|f|_d|_|}|jdkr|tjtjdfkrtj}|jd kr4|tjtjdfkr4tj}||d |_| |d |_|||| d |_d | i|_d|_||_dS)NT)rpostfix extensionparentmakedirsrr)rarbzwriter z not foundz.pngz.dcm)rr)rr)rrrrGverboser)r rr fname_formatterrnr startswithr9rPrrrr resolve_writerwriters writer_objrCuint8uint16 init_kwargs data_kwargs meta_kwargs write_kwargs _data_indexr)rsrrrrrrrrrGrrrrrrrrrrZwriter_ry _output_dtyper2r2r3rzwsL "       zSaveImage.__init__cCsT|dk r|j||dk r(|j||dk r<|j||dk rP|j||S)a Set the options for the underlying writer by updating the `self.*_kwargs` dictionaries. The arguments correspond to the following usage: - `writer = ImageWriter(**init_kwargs)` - `writer.set_data_array(array, **data_kwargs)` - `writer.set_metadata(meta_data, **meta_kwargs)` - `writer.write(filename, **write_kwargs)` N)rupdaterrr)rsrrrrr2r2r3 set_optionss     zSaveImage.set_optionsztorch.Tensor | np.ndarrayz dict | Nonezstr | PathLike | None)rrr|c Cst|tr|jn|}|dk r,||j}n|||}|jjf|}|rt|dd}t |t |j krxd|j d<n8t |j drt d|j d|d|j ddg}|jD]}zR|f|j}|jfd |i|j |jfd |i|j|j|f|j||_Wnntk r~} zN|tt|jjj| d d t|jj |jjd |dW5d} ~ XYqX|j!d7_!|j"r|dk r||d<|Sqd#dd|D} t$|jjd|d|jd|jd| dS)az Args: img: target data content that save into file. The image should be channel-first, shape: `[C,H,W,[D]]`. meta_data: key-value pairs of metadata corresponding to the data. filename: str or file-like object which to save img. If specified, will ignore `self.output_name_formatter` and `self.folder_layout`. N spatial_shaper2rz data shape z (with spatial shape z() but SaveImage `channel_dim` is set to z no channel. data_array meta_dictTrz: unable to write rrZsaved_torcSsg|] }|qSr2r2rr2r2r3r5sz&SaveImage.__call__..z# cannot find a suitable writer for z. Please install the writer libraries, see also the installation instructions: https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies. The current registered writers for z: )%r9rrrrrr|rgetrshaperrrorprrZset_data_arrayZ set_metadatarwriterrrr{rrrirjrkrUrlrrrrrT) rsrrr|kwZmeta_spatial_shaperZ writer_clsrrrr2r2r3rsF        &zSaveImage.__call__)NNNN)NN) rUrrrrCrrBORDERfloat64rzrrr2r2r2r3r#,s2L6C )r%)?r __future__rrqrirErrocollections.abcrpathlibrpydocrtypingrr@rCr: monai.configrrr monai.datar Zmonai.data.folder_layoutr r r Zmonai.data.image_readerrrrrrrrmonai.data.meta_tensorrmonai.data.utilsrmonai.transforms.transformrZmonai.transforms.utility.arrayr monai.utilsrrrrrrrrnib_Imager!__all__r$r,r"r#r2r2r2r3 sL      $           #H