o  iDk@sdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl mZddlmZddlZddlZddlmZmZmZdd lmZdd lmZmZmZdd lmZm Z m!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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6e6d\Z7Z8e6d\Z9Z8e6d\Z:Z8e6ddd\Z;Zd"ddZ?Gddde+Z@Gddde+ZAGd d!d!e+ZBdS)#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 ImageMetaKeyMetaKeysOptionalImportErrorconvert_to_dst_type ensure_tuplelook_up_optionoptional_importnibabelz PIL.ImagenrrdZfilelockFileLockname) LoadImage SaveImageSUPPORTED_READERS)Z pydicomreaderZ itkreaderZ nrrdreaderZ numpyreaderZ pilreaderZ nibabelreader". ) requires_gradlittler)>)r)r,zNot implemented option new=.c3s|]}t|VqdSNswitch_endianness.0xnew[/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/io/array.py csz$switch_endianness..csg|]}t|qSr6r/r1r4r6r7 esz%switch_endianness..csi|] \}}|t|qSr6r/)r2kvr4r6r7 gsz%switch_endianness..NzUnknown type: ) isinstancetorchTensordevicer* from_numpyr0cpudetachnumpytorequires_grad_npndarraysys byteorderdtypeNotImplementedErrorbyteswapview newbyteordertuplelistdictitemsboolstrfloatinttype RuntimeError__name__)datar5r@r*Z sys_nativeZcurrent_r6r4r7r0Js:     r0c@sDeZdZdZddejdddddfdddZdddZd d!ddZdS)"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- image_onlyrTrKDtypeLike | Noneensure_channel_first simple_keysprune_meta_pattern str | Noneprune_meta_seprU expanduserreturnNonec  Os|du|_||_||_||_||_||_||_||_g|_t D]J} z| t | | i| Wqt yFt |jjd| dYqtyit |jj| d| d| d| t | Yqw|durpdSt|D]r} t| trtd| d\} }|st| } | durt| t } z | | | i| Wqtt ytd| dYqttyt| d| d| d| | Yqtwt| r| | | i| qt| | qtdS) 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.datar$) auto_selectr\rKr^r_patternseprcreadersr(registerrlogging getLogger __class__rZdebug TypeErrorrr=rUr rrlowerwarningswarninspectisclass)selfreaderr\rKr^r_r`rbrcargskwargsr_rZ the_reader has_built_inr6r6r7__init__sZ /           zLoadImage.__init__rxrcCs0t|tstdt|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)r=rrsrtrXrkappend)rwrxr6r6r7rls zLoadImage.registerfilenameSequence[PathLike] | PathLikeImageReader | Nonec stfddt|D}dg}}|dur||}n\jdddD]S}jr6||r5||}nCq$z||}Wn7tyt}z+|t t j j j|ddt j j |j j d|dWYd}~q$d}~wwg}|dus|durt|trt|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&fS|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.)rcr)r2srwr6r7r8s z%LoadImage.__call__..NTexc_infoz: unable to load . r cSg|]}|qSr6r6r2er6r6r7r9z&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: )dstrKz%`meta_data` must be a dict, got type r-r))rirj)'rPrreadrkrhZ verify_suffix Exceptionr traceback format_excrmrnrorZrpinfor=rlenjoinrYget_datarrKrR ValueErrorrXr0rFILENAME_OR_OBJrensure_torch_and_prune_metar_rirjr^rr\meta) rwrrximgerrrmsgZ img_array meta_datar6rr7__call__sb        zLoadImage.__call__)r\rTrKr]r^rTr_rTr`rarbrUrcrTrdre)rxrr.)rrrxr) rZ __module__ __qualname____doc__rGfloat32r~rlrr6r6r6r7r&ms ^ r&c@s`eZdZdZdddejddejdejdd ddd dd dddfd5d)d*Z d6d+d,Z d7d8d3d4Z dS)9r'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.gzFnearestNTr output_dirr output_postfixrU output_ext output_dtyper]resamplerTmode padding_modescale int | NonerKrsqueeze_end_dims data_root_dirseparate_folder print_log output_formatwriter+type[image_writer.ImageWriter] | str | None channel_dimoutput_name_formatter(Callable[[dict, Transform], dict] | None folder_layoutFolderLayoutBase | Nonesavepath_in_metadictrdrecCsn||durt|||| d| d|_n||_||durt|_n||_|p)||_|jr:|jds:d|jn|j|_t|trat d|d\}}|sSt |}|dur_t d|d|}|durkt |jn|f|_d|_|}|jdkr|tjtjdfvrtj}|jd kr|tjtjdfvrtj}||d |_| |d |_|||| d |_d | i|_d|_||_dS)NT)rpostfix extensionparentmakedirsrr-rgr$zwriter z not foundz.pngz.dcm)rr)rr)rrrrKverboser)r rr fname_formatterrrr startswithr=rUr rrr resolve_writerwriters writer_objrGuint8uint16 init_kwargs data_kwargs meta_kwargs write_kwargs _data_indexr)rwrrrrrrrrrKrrrrrrrrrrZwriter_r} _output_dtyper6r6r7r~sL  "      zSaveImage.__init__cCsT|dur |j||dur|j||dur|j||dur(|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)rwrrrrr6r6r7 set_optionss    zSaveImage.set_optionsrtorch.Tensor | np.ndarrayr dict | Nonerstr | PathLike | Nonec Cst|tr|jn|}|dur||j}n|||}|jjdi|}|rZt|dd}t |t |j kr>d|j d<nt |j drZt d|j d|d|j ddg}|jD]}}z-|di|j}|jdd |i|j |jdd |i|j|j|fi|j||_Wn7ty} z+|tt|jjj| d d t|jj |jjd |dWYd} ~ q_d} ~ ww|j!d7_!|j"r|dur||t#j$<|Sd%dd|D} t&|jjd|d|jd|jd| )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_shaper6rz data shape z (with spatial shape z() but SaveImage `channel_dim` is set to z no channel.Z data_array meta_dictTrz: unable to write rrrcSrr6r6rr6r6r7r9rz&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: )'r=rrrrrrrgetrshaperrrsrtrrZset_data_arrayZ set_metadatarwriterrrrrrrmrnrorZrprrrrSAVED_TOrrY) rwrrrkwZmeta_spatial_shaperZ writer_clsrrrr6r6r7rsZ       zSaveImage.__call__)(rr rrUrrUrr]rrTrrUrrUrrrKrrrTrr rrTrrTrrUrrrrrrrrrrTrdre)NNNN)NN)rrrrrr) rZrrrrGrrBORDERfloat64r~rrr6r6r6r7r'4s2L Cr'c@s.eZdZdZddddZdd d Zd d Zd S)WriteFileMappingaB Writes a JSON file that logs the mapping between input image paths and their corresponding output paths. This class uses FileLock to ensure safe writing to the JSON file in a multiprocess environment. Args: mapping_file_path (Path or str): Path to the JSON file where the mappings will be saved. mapping.jsonmapping_file_path Path | strcCst||_dSr.)rr)rwrr6r6r7r~szWriteFileMapping.__init__rrcCst|tr|j}tj|vrtd|tj}|tj}||d}trCt t |j d| |Wd|S1s 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.utilsrrrrrrrr nib_Imager"r#r__all__r(r0r&r'rr6r6r6r7sR      $   (   #H\