U PhG@snddlmZddlZddlZddlZddlZddlmZmZddl m Z m Z m Z m Z ddlmZddlmZddlmZmZddlZddlmZdd lmZmZdd lmZmZmZm Z m!Z!dd l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(er0ddl)Z)ddl*Z+ddl,Z,ddl-Z-dd l.m/Z/dd l0m1Z2dZ3Z4Z5Z6Z7nTe'ddd\Z)Z4e'd\Z+Z5e'ddd\Z/Z8e'd\Z2Z6e'd\Z-Z7e'ddd\Z,Z3dddddddgZ9GdddeZ:d d d!d"d#Z;d$d d%d&d'Ze(dd(Gd+dde:Z?Gd,dde:Z@e(d-d(Gd.dde:ZAeGd/d0d0ZBe(dd(Gd1dde:ZCdS)2) annotationsN)ABCabstractmethod)CallableIterableIteratorSequence) dataclass)Path) TYPE_CHECKINGAny)np_str_obj_array_pattern)KeysCollectionPathLike)affine_to_spacing!correct_nifti_header_if_necessary is_no_channelis_supported_formatorientation_ras_lps)MetaKeys SpaceKeys TraceKeys ensure_tupleoptional_import require_pkg) Nifti1Image)ImageTitk)allow_namespace_pkgnibabelznibabel.nifti1r)namez PIL.Imagepydicomnrrd ImageReader ITKReader NibabelReader NumpyReader PILReader PydicomReader NrrdReaderc@sJeZdZdZedddddZedddd d Zed d d dZdS)r#a7 An abstract class defines APIs to load image files. Typical usage of an implementation of this class is: .. code-block:: python image_reader = MyImageReader() img_obj = image_reader.read(path_to_image) img_data, meta_data = image_reader.get_data(img_obj) - The `read` call converts image filenames into image objects, - The `get_data` call fetches the image data, as well as metadata. - A reader should implement `verify_suffix` with the logic of checking the input filename by the filename extensions. Sequence[PathLike] | PathLikeboolfilenamereturncCstd|jjddS)a` Verify whether the specified `filename` is supported by the current reader. This method should return True if the reader is able to read the format suggested by the `filename`. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. Subclass  must implement this method.NNotImplementedError __class____name__selfr-r7L/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/data/image_reader.py verify_suffixLs zImageReader.verify_suffixSequence[Any] | Anydatar.cKstd|jjddS)# Read image data from specified file or files. Note that it returns a data object or a sequence of data objects. Args: data: file name or a list of file names to read. kwargs: additional args for actual `read` API of 3rd party libs. r/r0Nr1)r6r<kwargsr7r7r8readZs zImageReader.readtuple[np.ndarray, dict]r.cCstd|jjddS)aD Extract data array and metadata from loaded image and return them. This function must return two objects, the first is a numpy array of image data, the second is a dictionary of metadata. Args: img: an image object loaded from an image file or a list of image objects. r/r0Nr1r6imgr7r7r8get_datags zImageReader.get_dataN)r4 __module__ __qualname____doc__rr9r?rDr7r7r7r8r#9s  dict) from_dictto_dictcCst|tstdt|d|sp|D]F}||}t|tjrRt|jj dk rRq&|dkrdt t j n|||<q&nt j t j}}||krt||||std||d||d||krt||||std||d||ddS)Nzto_dict must be a Dict, got .zSaffine matrix of all images should be the same for channel-wise concatenation. Got  and zSspatial_shape of all images should be the same for channel-wise concatenation. Got ) isinstancerH ValueErrortypenpndarrayr searchdtypestrrNONErAFFINE SPATIAL_SHAPEallclose RuntimeError)rIrJkeyZdatumZ affine_key shape_keyr7r7r8_copy_compatible_dictus" r\list) image_list meta_dictcCsZt|dkr|dSt|tjdsBt|tj}tj||dSd|tj<tj|ddS)Nraxis) lenrgetrORIGINAL_CHANNEL_DIMintrP concatenatestack)r^r_ channel_dimr7r7r8 _stack_imagess  rj)pkg_namecseZdZdZd!dddddd fd d Zd dd ddZd dddZddddZddddZd"ddddZ ddZ dd Z Z S)#r$a Load medical images based on ITK library. All the supported image formats can be found at: https://github.com/InsightSoftwareConsortium/ITK/tree/master/Modules/IO The loaded data array will be in C order, for example, a 3D image NumPy array index order will be `CDWH`. Args: channel_dim: the channel dimension of the input image, default is None. This is used to set original_channel_dim in the metadata, EnsureChannelFirstD reads this field. If None, `original_channel_dim` will be either `no_channel` or `-1`. - Nifti file is usually "channel last", so there is no need to specify this argument. - PNG file usually has `GetNumberOfComponentsPerPixel()==3`, so there is no need to specify this argument. series_name: the name of the DICOM series if there are multiple ones. used when loading DICOM series. reverse_indexing: whether to use a reversed spatial indexing convention for the returned data array. If ``False``, the spatial indexing convention is reversed to be compatible with ITK; otherwise, the spatial indexing follows the numpy convention. Default is ``False``. This option does not affect the metadata. series_meta: whether to load the metadata of the DICOM series (using the metadata from the first slice). This flag is checked only when loading DICOM series. Default is ``False``. affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``. Set to ``True`` to be consistent with ``NibabelReader``, otherwise the affine matrix remains in the ITK convention. kwargs: additional args for `itk.imread` API. more details about available args: https://github.com/InsightSoftwareConsortium/ITK/blob/master/Wrapping/Generators/Python/itk/support/extras.py NFTstr | int | NonerTr+)ri series_namereverse_indexing series_metaaffine_lps_to_rasc sBt||_|dkr tdn||_||_||_||_||_dSN no_channelnan) super__init__r>floatrirnrorprq)r6rirnrorprqr>r3r7r8rvs zITKReader.__init__r*r,cCstS)z Verify whether the specified file or files format is supported by ITK reader. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. )has_itkr5r7r7r8r9s zITKReader.verify_suffixr<c Ksjg}t|}|j}|||D](}|}t|r:tj}| d| d| || }t |dkrtd|dt |dkrtd|d|js|dn|j} || }t |dkr|dn|}tj|f|} |jr.tjj|d } | | } t | dkr.| | d|| q$|tj|f|q$t |dkrb|S|dS) a Read image data from specified file or files, it can read a list of images and stack them together as multi-channel data in `get_data()`. If passing directory path instead of file path, will treat it as DICOM images series and read. Note that the returned object is ITK image object or list of ITK image objects. Args: data: file name or a list of file names to read, kwargs: additional args for `itk.imread` API, will override `self.kwargs` for existing keys. More details about available args: https://github.com/InsightSoftwareConsortium/ITK/blob/master/Wrapping/Generators/Python/itk/support/extras.py Tz 0008|0021r`zno DICOMs in: rKzthe directory: z% contains more than one DICOM series.r)Z FileNames)rr>copyupdater is_dirrZGDCMSeriesFileNamesZNewZSetUseSeriesDetailsZAddSeriesRestrictionZ SetDirectoryZ GetSeriesUIDsrcFileNotFoundErrorwarningswarnrnZ GetFileNamesimreadrpZImageSeriesReaderZUpdateZGetMetaDataDictionaryArrayZSetMetaDataDictionaryappend) r6r<r>img_ filenameskwargs_r Znames_generator series_uidZseries_identifier_obj_reader_metar7r7r8r?s:           zITKReader.readr@rAcCsg}i}t|D]}||}||||}|||j|tj<|jrRtj ntj |tj <|tj |tj <|||tj<|jdkrt|jt|tjkrtdnd|tj<n |j|tj<t||qt|||fS)aT Extract data array and metadata from loaded image and return them. This function returns two objects, first is numpy array of image data, second is dict of metadata. It constructs `affine`, `original_affine`, and `spatial_shape` and stores them in meta dict. When loading a list of files, they are stacked together at a new dimension as the first dimension, and the metadata of the first image is used to represent the output metadata. Args: img: an ITK image object loaded from an image file or a list of ITK image objects. Nrt)r_get_array_datar_get_meta_dict _get_affinerqrORIGINAL_AFFINErRASLPSSPACEr{rV_get_spatial_shaperWrircshaperwrer\rj)r6rC img_arraycompatible_metair<headerr7r7r8rDs      "   zITKReader.get_datarHcCsf|}i}|D]:}|dr$q||}t|jdrFt|n|||<qt||d<|S)z Get all the metadata of the image and convert to dict type. Args: img: an ITK image object loaded from an image file. ZITK_rspacing)ZGetMetaDataDictionaryZGetKeys startswithrOr4rPasarray GetSpacing)r6rCZ img_meta_dictr_rZvalr7r7r8r's  $zITKReader._get_meta_dict) lps_to_rascCst|}t|}t|}t|}tt|j ddd}t |d}|d|d|ft |d||d|d|f<|d||d|df<|rt |}|S)aL Get or construct the affine matrix of the image, it can be used to correct spacing, orientation or execute spatial transforms. Args: img: an ITK image object loaded from an image file. lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to True. rr`Nr) rarray_from_matrix GetDirectionrPrrZ GetOriginminmaxreyediagr)r6rCr directionroriginsraffiner7r7r8r:s  6zITKReader._get_affinecCs\t|jd}tt|dd}tt|}t|j t rJ| |j t |d|S)z Get the spatial shape of `img`. Args: img: an ITK image object loaded from an image file. rrr`N)rrrrrrr]sizerMrirfpoprPr)r6rCr_sizer7r7r8rQs   zITKReader._get_spatial_shapecCsDtj|dd}|dkr*|jr$|S|jS|jr4|St|jddS)a Get the raw array data of the image, converted to Numpy array. Following PyTorch conventions, the returned array data has contiguous channels, e.g. for an RGB image, all red channel image pixels are contiguous in memory. The last axis of the returned array is the channel axis. See also: - https://github.com/InsightSoftwareConsortium/ITK/blob/v5.2.1/Modules/Bridge/NumPy/wrapping/PyBuffer.i.in Args: img: an ITK image object loaded from an image file. F)Z keep_axesr`rr)rZarray_view_from_imageZGetNumberOfComponentsPerPixelroTrPmoveaxis)r6rCZnp_imgr7r7r8r`s zITKReader._get_array_data)NrlFFT)T r4rErFrGrvr9r?rDrrrr __classcell__r7r7rxr8r$s  3!cseZdZdZd'ddddddd fd d Zd dd ddZd dddZddddZddddZddddZ d(dddddZ d dd!d"Z d#d$Z d%d&Z ZS))r(a Load medical images based on Pydicom library. All the supported image formats can be found at: https://dicom.nema.org/medical/dicom/current/output/chtml/part10/chapter_7.html PydicomReader is also able to load segmentations, if a dicom file contains tag: `SegmentSequence`, the reader will consider it as segmentation data, and to load it successfully, `PerFrameFunctionalGroupsSequence` is required for dicom file, and for each frame of dicom file, `SegmentIdentificationSequence` is required. This method refers to the Highdicom library. This class refers to: https://nipy.org/nibabel/dicom/dicom_orientation.html#dicom-affine-formula https://github.com/pydicom/contrib-pydicom/blob/master/input-output/pydicom_series.py https://highdicom.readthedocs.io/en/latest/usage.html#parsing-segmentation-seg-images Args: channel_dim: the channel dimension of the input image, default is None. This is used to set original_channel_dim in the metadata, EnsureChannelFirstD reads this field. If None, `original_channel_dim` will be either `no_channel` or `-1`. affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``. Set to ``True`` to be consistent with ``NibabelReader``, otherwise the affine matrix remains in the Dicom convention. swap_ij: whether to swap the first two spatial axes. Default to ``True``, so that the outputs are consistent with the other readers. prune_metadata: whether to prune the saved information in metadata. This argument is used for `get_data` function. If True, only items that are related to the affine matrix will be saved. Default to ``True``. label_dict: label of the dicom data. If provided, it will be used when loading segmentation data. Keys of the dict are the classes, and values are the corresponding class number. For example: for TCIA collection "C4KC-KiTS", it can be: {"Kidney": 0, "Renal Tumor": 1}. fname_regex: a regular expression to match the file names when the input is a folder. If provided, only the matched files will be included. For example, to include the file name "image_0001.dcm", the regular expression could be `".*image_(\d+).dcm"`. Default to `""`. Set it to `None` to use `pydicom.misc.is_dicom` to match valid files. kwargs: additional args for `pydicom.dcmread` API. more details about available args: https://pydicom.github.io/pydicom/stable/reference/generated/pydicom.filereader.dcmread.html If the `get_data` function will be called (for example, when using this reader with `monai.transforms.LoadImage`), please ensure that the argument `stop_before_pixels` is `True`, and `specific_tags` covers all necessary tags, such as `PixelSpacing`, `ImagePositionPatient`, `ImageOrientationPatient` and all `pixel_array` related tags. NTrlrmr+z dict | NonerT)rirqswap_ijprune_metadata label_dict fname_regexc sHt||_|dkr tdn||_||_||_||_||_||_ dSrr) rurvr>rwrirqrrrr)r6rirqrrrrr>rxr7r8rvs zPydicomReader.__init__r*r,cCstS)z Verify whether the specified file or files format is supported by Pydicom reader. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. ) has_pydicomr5r7r7r8r9s zPydicomReader.verify_suffixrzc spg}t|}j}||d_|D](}|}t|r6jdk rrfddtt j |dD}nddtt j |dD}g}|D]f} z| t jfd| i|Wqt jjk r} z tjd| d | d d d W5d} ~ XYqXq| t|d kr|n|dt|d krTd_q*t jfd|i|} | | q*t|d krh|S|dS)a Read image data from specified file or files, it can read a list of images and stack them together as multi-channel data in `get_data()`. If passing directory path instead of file path, will treat it as DICOM images series and read. Args: data: file name or a list of file names to read, kwargs: additional args for `pydicom.dcmread` API, will override `self.kwargs` for existing keys. Returns: If `data` represents a filename: return a pydicom dataset object. If `data` represents a list of filenames or a directory: return a list of pydicom dataset object. If `data` represents a list of directories: return a list of list of pydicom dataset object. FNcsg|]}tj|r|qSr7)rematchr.0slcr6r7r8 sz&PydicomReader.read..*cSsg|]}tj|r|qSr7)r!miscZis_dicomrr7r7r8rs fpzFailed to read z with exception: rK) stacklevelr`rT)rr>r{r| has_seriesr r}rglobospathjoinrr!ZdcmreaderrorsZInvalidDicomErrorrrrc) r6r<r>rrrr Z series_slcsslicesredsr7rr8r?s.    $0  zPydicomReader.readrcCsg}|D].}t|dr"||qtd|jdqt|ddd}t|dkr\td|d}d }||}|j }t |d d d d g}t |d d d} |g} t dt|D]} ||| } | j } t || d d}t || d d d t | fd}t ||std|d|d|| krz5PydicomReader._combine_dicom_series..)rZrz%the input does not have valid slices.Z PixelSpacing?ImagePositionPatient)rrrrr`)rrrz6the list contains slices that have different spacings rLrKz4the list contains slices that have different shapes rrarlastImagePositionPatient)hasattrrrrr-sortedrcrNrrgetattrrangerwrPrXabsrhrrrrrW)r6r<rZslc_dsZ first_sliceZaverage_distanceZ first_arrayrrZprev_posZ stack_arrayidxZ slc_arrayZ slc_shapeZ slc_spacingZslc_posZstack_metadatar7r7r8_combine_dicom_seriessR          z#PydicomReader._combine_dicom_seriesr@rAc Csg}|jdkrJt|dts.|||q|D]}|||q2nbt|tsZ|g}|D]L}t|dr|||\}}n ||}||}|j |t j <|||fq^g}i}t |D]P\}}|t |jrt |ddn||||j} |jrtjntj|t j<|jr| t ddddgddddgddddgddddgg} t|t j } | d| d| d<| d<t | |t j <| |t j<| |t j<|jdkrt|j t|t j krtdnd|t j<n |j|t j<t|t jt|t j d|d <t ||qt!|||fS) a Extract data array and metadata from loaded image and return them. This function returns two objects, first is numpy array of image data, second is dict of metadata. It constructs `affine`, `original_affine`, and `spatial_shape` and stores them in meta dict. For dicom series within the input, all slices will be stacked first, When loading a list of files (dicom file, or stacked dicom series), they are stacked together at a new dimension as the first dimension, and the metadata of the first image is used to represent the output metadata. To use this function, all pydicom dataset objects (if not segmentation data) should contain: `pixel_array`, `PixelSpacing`, `ImagePositionPatient` and `ImageOrientationPatient`. For segmentation data, we assume that the input is not a dicom series, and the object should contain `SegmentSequence` in order to identify it. In addition, tags (5200, 9229) and (5200, 9230) are required to achieve `PixelSpacing`, `ImageOrientationPatient` and `ImagePositionPatient`. Args: data: a pydicom dataset object, or a list of pydicom dataset objects, or a list of list of pydicom dataset objects. TrSegmentSequencer`Nrtr)rr)"rrMr]rrr _get_seg_datarrrrrWrrPascontiguousarrayrswapaxesrrqrrrrarrayrr{rVrircrwrerr\rj) r6r<Z dicom_dataseriesd data_arraymetadatarrrsp_sizer7r7r8rD2sL      $6  $    zPydicomReader.get_datarHcCs`|jdd}|jrsz1PydicomReader._get_frame_data...N)rr2r-rrrfrZReferencedSegmentNumberrPrruniquewhere pixel_array)r6rCZframe_seg_numsrZframe_seg_nums_arrZseg_descriptionsrindicesr7r7r8_get_frame_datas %      zPydicomReader._get_frame_datacCsn||}t|j}t|jj}|d||d<|jdk r\|j|d<t|t|jf}ni|d<t||f}t | |D]^\}\}}t |dd|} t |d| } | |d kr||d| <|d| } ||d| f<q| dd dd g}|jdd |tj<d | kr|d d d} d| kr^| dd d} d| kr^| d|d<d| kr| dd d}d| kr|dd }||d<d| kr|d|dd 7<|jr|d d| krf|dd d}d| krT|dd d}d| krT|d|d<|dd d dd ddd |d<|jrf|d||fS)z Get the array data and metadata of the segmentation image. Aegs: img: a Pydicom dataset object that has attribute "SegmentSequence". rNlabelsZ SegmentLabelZlabel_ZSegmentDescription.r`rrrrrZ00209116rZ00289110rrZ00180050rZ00209113rr)rrcrr]rrrrPzeros enumeraterrr transposerrWrr)r6rCr n_classes spatial_shapeZall_segsrframes descriptionZ segment_label class_nameZ class_numZshared_func_group_seqZplane_orient_seqZpixel_measure_seqZ pixel_spacingZfirst_frame_func_group_seqZplane_position_seqr7r7r8rs^             zPydicomReader._get_seg_datacCsrt|dstd|jd|j}d\}}d}t|drB|j}d}t|drV|j}d}|rn|tj||}|S) a Get the array data of the image. If `RescaleSlope` and `RescaleIntercept` are available, the raw array data will be rescaled. The output data has the dtype np.float32 if the rescaling is applied. Args: img: a Pydicom dataset object. rz dicom data: z does not have pixel_array.)rrF RescaleSlopeTRescaleIntercept) rrNr-rrrastyperPfloat32)r6rCr<slopeoffsetZ rescale_flagr7r7r8rAs   zPydicomReader._get_array_data)NTTTNrl)T)r4rErFrGrvr9r?rrDrrrrrrr7r7rxr8r(ws", .CJ,:Ecs~eZdZdZdddddfdd Zd dd d d Zd d ddZddddZddddZddZ ddZ ddZ Z S)r%a1 Load NIfTI format images based on Nibabel library. Args: as_closest_canonical: if True, load the image as closest to canonical axis format. squeeze_non_spatial_dims: if True, non-spatial singletons will be squeezed, e.g. (256,256,1,3) -> (256,256,3) channel_dim: the channel dimension of the input image, default is None. this is used to set original_channel_dim in the metadata, EnsureChannelFirstD reads this field. if None, `original_channel_dim` will be either `no_channel` or `-1`. most Nifti files are usually "channel last", no need to specify this argument for them. kwargs: additional args for `nibabel.load` API. more details about available args: https://github.com/nipy/nibabel/blob/master/nibabel/loadsave.py NFrmr+)rias_closest_canonicalsqueeze_non_spatial_dimsc s6t|dkrtdn||_||_||_||_dSrr)rurvrwrirrr>)r6rirrr>rxr7r8rvns  zNibabelReader.__init__r*r,cCsddg}tot||S)z Verify whether the specified file or files format is supported by Nibabel reader. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. niiznii.gz)has_nibrr6r-suffixesr7r7r8r9{s zNibabelReader.verify_suffixrzcKsbg}t|}|j}|||D]$}tj|f|}t|}||q$t|dkrZ|S|dS)a> Read image data from specified file or files, it can read a list of images and stack them together as multi-channel data in `get_data()`. Note that the returned object is Nibabel image object or list of Nibabel image objects. Args: data: file name or a list of file names to read. kwargs: additional args for `nibabel.load` API, will override `self.kwargs` for existing keys. More details about available args: https://github.com/nipy/nibabel/blob/master/nibabel/loadsave.py r`r) rr>r{r|nibloadrrrcr6r<r>rrrr rCr7r7r8r?s    zNibabelReader.readr@rAcCsDg}i}t|D]"}||}|||tj<|||tj<|j|d<|jrjt|}|||tj<|||tj <t j |tj <| |}|jrtt|jt|tj dD]&}|j|ddkr|j|dd}q|||jdkrt|jt|tj krtdnd|tj<n |j|tj<t||qt|||fS)aY Extract data array and metadata from loaded image and return them. This function returns two objects, first is numpy array of image data, second is dict of metadata. It constructs `affine`, `original_affine`, and `spatial_shape` and stores them in meta dict. When loading a list of files, they are stacked together at a new dimension as the first dimension, and the metadata of the first image is used to present the output metadata. Args: img: a Nibabel image object loaded from an image file or a list of Nibabel image objects. rrr`raNrt)rrrrrVrrrrrWrrrrrrrcrsqueezerrirwrer\rj)r6rCrrrrr<rr7r7r8rDs0         $   zNibabelReader.get_datarHcCs4z|jd}Wntk r*|j}YnXt|S)z Get the all the metadata of the image and convert to dict type. Args: img: a Nibabel image object loaded from an image file. <)ras_byteswappedrNrH)r6rCrr7r7r8rs  zNibabelReader._get_meta_dictcCstj|jddS)z Get the affine matrix of the image, it can be used to correct spacing, orientation or execute spatial transforms. Args: img: a Nibabel image object loaded from an image file. T)r{)rPrrrBr7r7r8rs zNibabelReader._get_affinecCsz|jd}Wntk r*|j}YnX|dd}|dkrX|d}t|dd}|d}t|dd}t|js| t |jt t |dd}t |d|S)z Get the spatial shape of image data, it doesn't contain the channel dim. Args: img: a Nibabel image object loaded from an image file. rdimNdimsrrr`)rrrNrdrPinsertr]rrirrfrrr)r6rCrr ndimr spatial_rankr7r7r8rs     z NibabelReader._get_spatial_shapecCstj|jddS)z Get the raw array data of the image, converted to Numpy array. Args: img: a Nibabel image object loaded from an image file. C)order)rP asanyarraydataobjrBr7r7r8rszNibabelReader._get_array_data)NFFrr7r7rxr8r%]s  ) csVeZdZdZddddfdd Zdd d d d Zdd ddZddddZZS)r&a Load NPY or NPZ format data based on Numpy library, they can be arrays or pickled objects. A typical usage is to load the `mask` data for classification task. It can load part of the npz file with specified `npz_keys`. Args: npz_keys: if loading npz file, only load the specified keys, if None, load all the items. stack the loaded items together to construct a new first dimension. channel_dim: if not None, explicitly specify the channel dim, otherwise, treat the array as no channel. kwargs: additional args for `numpy.load` API except `allow_pickle`. more details about available args: https://numpy.org/doc/stable/reference/generated/numpy.load.html NzKeysCollection | Nonerm)npz_keysric s@t|dk rt|}||_|dkr0tdn||_||_dSrr)rurvrr)rwrir>)r6r)rir>rxr7r8rvs  zNumpyReader.__init__r*r+r,cCsddg}t||S)z Verify whether the specified file or files format is supported by Numpy reader. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. npznpy)rrr7r7r8r9szNumpyReader.verify_suffixrzc Ksg}t|}|j}|||D]j}tj|fddi|}t|jdr|j dkrdt | n|j }|D]} | || qnq$| |q$t |dkr|S|dS)aE Read image data from specified file or files, it can read a list of data files and stack them together as multi-channel data in `get_data()`. Note that the returned object is Numpy array or list of Numpy arrays. Args: data: file name or a list of file names to read. kwargs: additional args for `numpy.load` API except `allow_pickle`, will override `self.kwargs` for existing keys. More details about available args: https://numpy.org/doc/stable/reference/generated/numpy.load.html allow_pickleTz.npzNr`r)rr>r{r|rPrr r endswithr)r]rrrc) r6r<r>rrrr rCr)kr7r7r8r?'s    zNumpyReader.readr@rAcCsg}i}t|tjr|f}t|D]}i}t|tjrrt|j}t|jtr\t||j}||t j <t j |t j <||t|jtr|jntd|t j<t||q"t|||fS)aB Extract data array and metadata from loaded image and return them. This function returns two objects, first is numpy array of image data, second is dict of metadata. It constructs `affine`, `original_affine`, and `spatial_shape` and stores them in meta dict. When loading a list of files, they are stacked together at a new dimension as the first dimension, and the metadata of the first image is used to represent the output metadata. Args: img: a Numpy array loaded from a file or a list of Numpy arrays. rt)rMrPrQrrrrirfdeleterrWrrrrrwrer\rj)r6rCrrrrr r7r7r8rDEs"          zNumpyReader.get_data)NN) r4rErFrGrvr9r?rDrr7r7rxr8r&s  PILcsleZdZdZddddfdd Zd dd d d Zd dddZddddZddddZddZ Z S)r'a Load common 2D image format (supports PNG, JPG, BMP) file or files from provided path. Args: converter: additional function to convert the image data after `read()`. for example, use `converter=lambda image: image.convert("LA")` to convert image format. reverse_indexing: whether to swap axis 0 and 1 after loading the array, this is enabled by default, so that output of the reader is consistent with the other readers. Set this option to ``False`` to use the PIL backend's original spatial axes convention. kwargs: additional args for `Image.open` API in `read()`, mode details about available args: https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open NTzCallable | Noner+) converterroc s t||_||_||_dSr)rurvr1ror>)r6r1ror>rxr7r8rvws zPILReader.__init__r*r,cCsddddg}tot||S)z Verify whether the specified file or files format is supported by PIL reader. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. pngjpgjpegbmp)has_pilrrr7r7r8r9}s zPILReader.verify_suffixz*Sequence[PathLike] | PathLike | np.ndarrayrzcKsng}t|}|j}|||D]0}tj|f|}t|jrJ||}||q$t |dkrf|S|dS)a= Read image data from specified file or files, it can read a list of images and stack them together as multi-channel data in `get_data()`. Note that the returned object is PIL image or list of PIL image. Args: data: file name or a list of file names to read. kwargs: additional args for `Image.open` API in `read()`, will override `self.kwargs` for existing keys. Mode details about available args: https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open r`r) rr>r{r|PILImageopencallabler1rrcrr7r7r8r?s      zPILReader.readr@rAcCsg}i}t|D]}||}|||tj<|jrHtt|ddnt|}| |t |j t |tjkr|t dnd|tj <t||qt|||fS)a Extract data array and metadata from loaded image and return them. This function returns two objects, first is numpy array of image data, second is dict of metadata. It computes `spatial_shape` and stores it in meta dict. When loading a list of files, they are stacked together at a new dimension as the first dimension, and the metadata of the first image is used to represent the output metadata. Note that by default `self.reverse_indexing` is set to ``True``, which swaps axis 0 and 1 after loading the array because the spatial axes definition in PIL is different from other common medical packages. Args: img: a PIL Image object loaded from a file or a list of PIL Image objects. rr`rtr)rrrrrWrorPrrrrcrrwrer\rj)r6rCrrrrr<r7r7r8rDs  $ " zPILReader.get_datarHcCs|j|j|j|jdS)z Get the all the metadata of the image and convert to dict type. Args: img: a PIL Image object loaded from an image file. formatmodewidthheightr:rBr7r7r8rszPILReader._get_meta_dictcCst|j|jfS)z Get the spatial shape of image data, it doesn't contain the channel dim. Args: img: a PIL Image object loaded from an image file. )rPrr=r>rBr7r7r8rszPILReader._get_spatial_shape)NT) r4rErFrGrvr9r?rDrrrr7r7rxr8r'hs   c@s"eZdZUdZded<ded<dS) NrrdImagez2Class to wrap nrrd image array and metadata header np.ndarrayrrHrN)r4rErFrG__annotations__r7r7r7r8r?s r?c@seZdZdZdejddfddddd d d Zd dd ddZd ddddZdddddZ dddddZ dddddZ dddd d!Z dS)"r)u Load NRRD format images based on pynrrd library. Args: channel_dim: the channel dimension of the input image, default is None. This is used to set original_channel_dim in the metadata, EnsureChannelFirstD reads this field. If None, `original_channel_dim` will be either `no_channel` or `0`. NRRD files are usually "channel first". dtype: dtype of the data array when loading image. index_order: Specify whether the returned data array should be in C-order (‘C’) or Fortran-order (‘F’). Numpy is usually in C-order, but default on the NRRD header is F affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``. Set to ``True`` to be consistent with ``NibabelReader``, otherwise the affine matrix is unmodified. kwargs: additional args for `nrrd.read` API. more details about available args: https://github.com/mhe/pynrrd/blob/master/nrrd/reader.py NFTrmznp.dtype | type | str | NonerTr+)rirS index_orderrqcKs2|dkrtdn||_||_||_||_||_dSrr)rwrirSrCrqr>)r6rirSrCrqr>r7r7r8rvs zNrrdReader.__init__r*r,cCsddg}tot||S)z Verify whether the specified `filename` is supported by pynrrd reader. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. r"zseg.nrrd)has_nrrdrrr7r7r8r9s zNrrdReader.verify_suffixr:r;cKshg}t|}|j}|||D]*}ttj|fd|ji|}||q$t |dkr`|S|dS)r=rCr`r) rr>r{r|r?r"r?rCrrc)r6r<r>rrrr Z nrrd_imager7r7r8r?s    zNrrdReader.readzNrrdImage | list[NrrdImage]r@)rCr.csg}i}t|D]}|j|j}||t|j|jdkrJ|| t j <|j rj| t jddkrtjt j<t j t j<dt j<fdddD|jdkrt|jtt jkrtdnd t j<n |jt j<t|qt|||fS) aB Extract data array and metadata from loaded image and return them. This function must return two objects, the first is a numpy array of image data, the second is a dictionary of metadata. Args: img: a `NrrdImage` loaded from an image file or a list of image objects. r%left-posterior-superiorsizescsg|]}|qSr7)r)rr.rr7r8r7sz'NrrdReader.get_data..)rF space originspace directionsNrtr)rrrrSrrHrrC_convert_f_to_c_orderrrrrq_switch_lps_rasrdrrrr{rVrWrircrrwrer\rj)r6rCrrrr<r7rGr8rDs,         "   zNrrdReader.get_datarHr@)rr.cCs^|d}|d}|j\}}t||d}t|}||d|d|f<||d|ddf<|S)z Get the affine matrix of the image, it can be used to correct spacing, orientation or execute spatial transforms. Args: img: A `NrrdImage` loaded from image file rIrHr`Nr)rrrPr)r6rrrxyZ affine_diamrr7r7r8rCs   zNrrdReader._get_affinecCs8d|ks|ddkr4t|tj|tj<tj|tj<|S)a For compatibility with nibabel, switch from LPS to RAS. Adapt affine matrix and `space` argument in header accordingly. If no information of space is given in the header, LPS is assumed and thus converted to RAS. If information about space is given, but is not LPS, the unchanged header is returned. Args: header: The image metadata as dict spacerE)rrrrrrr6rr7r7r8rKVs  zNrrdReader._switch_lps_rascCsJtt|dd|d<|dddd|d<|dddd|d<|S)a All header fields of a NRRD are specified in `F` (Fortran) order, even if the image was read as C-ordered array. 1D arrays of header['space origin'] and header['sizes'] become inverted, e.g, [1,2,3] -> [3,2,1] The 2D Array for header['space directions'] is transposed: [[1,0,0],[0,2,0],[0,0,3]] -> [[3,0,0],[0,2,0],[0,0,1]] For more details refer to: https://pynrrd.readthedocs.io/en/latest/user-guide.html#index-ordering Args: header: The image metadata as dict rIrrHNrrF)rProt90fliprOr7r7r8rJfs z NrrdReader._convert_f_to_c_order) r4rErFrGrPrrvr9r?rDrrKrJr7r7r7r8r)s ()D __future__rrrrrabcrrcollections.abcrrrr dataclassesr pathlibr typingr r numpyrPZtorch.utils.data._utils.collater monai.configrrmonai.data.utilsrrrrr monai.utilsrrrrrrrrrr"r!Znibabel.nifti1rr0rr7rDryrr6r___all__r#r\rjr$r(r%r&r'r?r)r7r7r7r8 sd          < `h(ch