o # i@sddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z ddl m Z mZmZmZddlmZddlmZddlmZmZddlZddlmZdd lmZmZdd lm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+erddl,Z,ddl-Z.ddl/Z/ddl0Z0dd l1m2Z2dd l3m4Z5dZ6Z7Z8Z9Z:n*e*ddd\Z,Z7e*d\Z.Z8e*ddd\Z2Z;e*d\Z5Z9e*d\Z0Z:e*ddd\Z/Z6e*d\ZZ?gdZ@Gddde ZAd:d d!ZBd;dd-d.Z d/d0Z d1d2Zd3d4ZZS)?r*as 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. to_gpu: If True, load the image into GPU memory using CuPy and Kvikio. This can accelerate data loading. Default is False. CuPy and Kvikio are required for this option. In practical use, it's recommended to add a warm up call before the actual loading. A related tutorial will be prepared in the future, and the document will be updated accordingly. 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. NTrsFrprtrxr/swap_ijprune_metadata label_dict dict | None fname_regexrXto_gpuc  stt||_|dkrtdn||_||_||_||_||_||_ |r/t r(t s/t dd}|r5|||_dS)Nrzr{z]PydicomReader: CuPy and/or Kvikio not installed for GPU loading, falling back to CPU loading.F)r|r}r?r~rprxrrrrrl has_kvikiorr warmup_kvikior) r8rprxrrrrrr?rr9r:r}s   zPydicomReader.__init__cCtrBtrDtd}t+}|j}t|d}| || t |}t|d}| |WddS1s;wYdSdSdSz Warm up the Kvikio library to initialize the internal buffers, cuFile, GDS, etc. This can accelerate the data loading process when `to_gpu` is set to True. dwrN rlrrmarangetempfileNamedTemporaryFiler r$CuFilewriteclose empty_liker@r8aZtmp_fileZ tmp_file_namefbr9r9r:r       "zPydicomReader.warmup_kvikior,r-r.cCr)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_pydicomr7r9r9r:r;rzPydicomReader.verify_suffixr<c sg}t|}t|_j}jrd|d<||d_t|D]\}}|}t | rj durGfddt t j|dD}nddt t j|dD}g} g} |D]8} z| tjdd | i|| | Wq\tjjy} ztjd | d | d d dWYd} ~ q\d} ~ wwt| dkrd_|| | j|<q#|| d| dj|<q#tjdd |i|} || q#t|dkr|dS|S)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. z100 KBZ defer_sizeFNcsg|] }tj|r|qSr9)rematchr.0slcr8r9r: sz&PydicomReader.read..*cSsg|] }tj|r|qSr9)r!miscZis_dicomrr9r9r:r sfpzFailed to read z with exception: rO) stacklevelreTrr9)rrbrr?rrr has_series enumerater rrglobospathjoinrr!ZdcmreaderrorsZInvalidDicomErrorrrrh)r8r<r?rrrrr Z series_slcsslicesZloaded_slc_namesredsr9rr:r@sF     $(     zPydicomReader.readrrSequence[PathLike]cCsvg}t||D]\}}t|dr|||fqtd|dqt|ddd}t|dkr4td|d\}}d }|||} | j } t |d d gt| } t |d d d} | g} t dt|D]d}|||d||d}|j }t ||dd d gt| }t ||dd d d t |fd}t || std| d|d| |krtd| d|d|t| |7}|} | |qbt|dkr"|t|d}| ||jrtj| dd}nt j| dd}| dd=||}t | |d<t|ddd rt |ddj|d<| t|f|tj<||fS| d}||}t | |d<| |tj<||fS)a Combine dicom series (a list of pydicom dataset objects). Their data arrays will be stacked together at a new dimension as the last dimension. The stack order depends on Instance Number. The metadata will be based on the first slice's metadata, and some new items will be added: "spacing": the new spacing of the stacked slices. "lastImagePositionPatient": `ImagePositionPatient` for the last slice, it will be used to achieve the affine matrix. "spatial_shape": the spatial shape of the stacked slices. Args: data: a list of pydicom dataset objects. Returns: a tuple that consisted with data array and metadata. InstanceNumberzslice: z+ does not have InstanceNumber tag, skip it.cSs |djS)Nr)r)sr9r9r:=s z5PydicomReader._combine_dicom_series..)r^rz%the input does not have valid slices.Z PixelSpacing?ImagePositionPatient)rrrrrez6the list contains slices that have different spacings rPrOz4the list contains slices that have different shapes rrfNrlastImagePositionPatient)ziphasattrrrrsortedrhrRrrgetattrranger~rTr\absrrmrorrrrr[)r8r<rrZslc_dsr,Z first_sliceZfirst_filenameZaverage_distanceZ first_arrayrrZprev_posZstack_array_listidxZ slc_arrayZ slc_shapeZ slc_spacingZslc_posZ stack_arrayZstack_metadatar9r9r:_combine_dicom_series$sZ    "       z#PydicomReader._combine_dicom_seriesrBc Csbg}|jdur1t|dts||||jdnSt|D]\}}||||j|qn=t|ts9|g}t|D]0\}}t|drR|||j|\}}n| ||j|}| |}|j |t j <|||fq=g}i} t|D]\}}|jr|jrt|ddnt|dd}||jrt|nt||||j} |jrtjntj|t j<|jr| tgdgdgdgdg} t|t j } | d| d| d<| d<t| |t j <| |t j<| |t j<|jd ur t |j t |t j krt!d nd |t j"<n|j|t j"<t#|t jt |t j d |d <t$|| qvt%|| |jd| 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. TrSegmentSequencere)rrerr)rerrr)rrrer)rrrreNr{r)rrrd)&rrQrbrrrrr _get_seg_datarrrrr[rrrrmswapaxesrTascontiguousarrayrrxrrrrarrayrrrZrprhr~rjrr`rq) r8r<Z dicom_datarseriesd data_arraymetadatarrrsp_sizer9r9r:rEksP     " &  $  zPydicomReader.get_datarMcCs`|jdd}|jri}dD]}||vr||||<q |SdD] }||vr-||q |S)z Get all the metadata of the image and convert to dict type. Args: img: a Pydicom dataset object. T)Zsuppress_invalid_tags)0020003700200032002800305200922952009230)Z7FE00008Z7FE00009Z7FE00010ZFFFCFFFC)Z to_json_dictrkeysr)r8rDrrr^r9r9r:rs     zPydicomReader._get_meta_dictrrcCs`td}d|vr d|vs|S|dd\}}}}}} |dd\} } } d|vr.|ddnd} |d| dd \}}|||d <|||d <| |d <|||d <|||d<| |d<| ||d<|||d<d|d<| |d<d|vr|d\}}}|tjd}|| |d|| |d|| |d}}}||d<||d<||d<|rt|}|S)a; Get or construct the affine matrix of the image, it can be used to correct spacing, orientation or execute spatial transforms. Args: metadata: metadata with dict type. lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to True. rrValuer)rrrNr)rr)rre)rr)rer)rere)rer)rr)rrer)rr)rrrrre)rr)rer)rTrrirr[r)r8rrrrxryZrzcxcyczsxsyszrdrdcZt1nZt2nZt3nnk1k2k3r9r9r:rs6       4zPydicomReader._get_affinerc cst|dstd|dg}|jD]}t|ds"td|d|t|jdjq|jr6t |nt |}dd|j D}|jsKt |nt |D]"}|js^t ||kdnt ||kd} || d f||fVqPd S) am yield frames and description from the segmentation image. This function is adapted from Highdicom: https://github.com/herrmannlab/highdicom/blob/v0.18.2/src/highdicom/seg/utils.py which has the following license... # ========================================================================= # https://github.com/herrmannlab/highdicom/blob/v0.18.2/LICENSE # # Copyright 2020 MGH Computational Pathology # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ========================================================================= (https://github.com/herrmannlab/highdicom/issues/188) Args: img: a Pydicom dataset object that has attribute "SegmentSequence". PerFrameFunctionalGroupsSequencezTo read dicom seg: z1, 'PerFrameFunctionalGroupsSequence' is required.SegmentIdentificationSequencez=, 'SegmentIdentificationSequence' is required for each frame.rcSsi|]}t|j|qSr9)rkZ SegmentNumber)rrr9r9r: 3sz1PydicomReader._get_frame_data...N)rr4rrrkrZReferencedSegmentNumberrrmrrTruniquewhere) r8rDr, array_dataZframe_seg_numsrZframe_seg_nums_arrZseg_descriptionsrindicesr9r9r:_get_frame_datas  %   *zPydicomReader._get_frame_datacCs||}t|j}|||}t|j}|d||d<|jdurJ|j|d<|jr:tj g|t|j|j d}n0t j g|t|j|j d}n i|d<|jr^tj g|||j d}n t j g|||j d}t | |||D]/\}\} } t| dd|} t| d| } | |dvr||d| <|d| } | |d| f<qs|gd }|jdd |tj<d |vr|d d d}d |vr|d d d}d|vr|d|d<d|vr|dd d}d|vr|dd }||d<d|vr|d|dd 7<|jr|d d|vra|dd d}d|vrX|dd d}d|vrX|d|d<|dd d dd ddd |d<|jra|d||fS)z Get the array data and metadata of the segmentation image. Aegs: img: a Pydicom dataset object that has attribute "SegmentSequence". filename: the file path of the image. rNlabelsrWZ SegmentLabelZlabel_ZSegmentDescription.)rerrrrr r Z00209116rZ00289110rrZ00180050r Z00209113rr)rrhrrrbrrrrmzerosrWrTrr#rr  transposerr[rr)r8rDr,r n_classesr! spatial_shapeZall_segsrframes descriptionZ segment_label class_nameZ class_numZshared_func_group_seqZplane_orient_seqZpixel_measure_seqZ pixel_spacingZfirst_frame_func_group_seqZplane_position_seqr9r9r:r9sh                 zPydicomReader._get_seg_datacCst|dd}t|dd}t|dd}t|dd}t|dd}t|dd}|dus0|dus0|durKtd |d t|d sFtd |d |j} | S|d krZ|dkrVtjntj} n"|dkri|dkretj ntj } n|dkrx|dkrttj ntj } ntd|d } ||||} | | } t jdd}||vrtd |d|j|ddj}t|d}tj| tjd}||| |Wdn1swY|dkr|||fn||f}|| |} | S)z Get the raw array data of the image. This function is used when `to_gpu` is set to True. Args: img: a Pydicom dataset object. filename: the file path of the image. ZRowsNColumnsZ BitsAllocatedSamplesPerPixelreZNumberOfFramesZPixelRepresentation dicom data: zK does not have Rows, Columns or BitsAllocated, falling back to CPU loading. pixel_array does not have pixel_array. zUnsupported BitsAllocated valueiz does not have pixel data.T)Z keep_deferredrr%)rrrrrRr0rmint8uint8int16uint16int32uint32r!tagTagget_itemZ value_tellr$remptyr@viewreshape)r8rDr,rowscolumnsZbits_allocatedZsamples_per_pixelZnumber_of_framesZpixel_representationr<rWZbytes_per_pixelZ total_pixelsZexpected_pixel_data_lengthZpixel_data_tagoffsetrbuffer new_shaper9r9r:_get_array_data_from_gpusF       z&PydicomReader._get_array_data_from_gpucCs|jr |||}nt|dstd|d|j}d\}}d}t|dr*|j}d}t|dr4|j}d}|r_|jrUtj|tj d }tj|tj d }| tj ||}|S| t j ||}|S) aG 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 float32 if the rescaling is applied. Args: img: a Pydicom dataset object. filename: the file path of the image. r0r/r1)rrF RescaleSlopeTRescaleInterceptr%) rrFrrRr0rGrHrmrfloat32astyperT)r8rDr,r<sloperCZ rescale_flagr9r9r:rs*    zPydicomReader._get_array_data)NTTTNrsF)rprtrxr/rr/rr/rrrrXrr/rFr)r<rrrrHrr)rrMrr/)r.r)r6rIrJrKr}rr;r@rrErrr#rrFrrr9r9rr:r*s*0  9 G P  ,8M7r*csteZdZdZ    d"d#fd d Zd d Zd$ddZd%ddZd&ddZd'ddZ ddZ ddZ d d!Z Z S)(r'a Load NIfTI format images based on Nibabel 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 `-1`. most Nifti files are usually "channel last", no need to specify this argument for them. 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) to_gpu: If True, load the image into GPU memory using CuPy and Kvikio. This can accelerate data loading. Default is False. CuPy and Kvikio are required for this option. Note: For compressed NIfTI files, some operations may still be performed on CPU memory, and the acceleration may not be significant. In some cases, it may be slower than loading on CPU. kwargs: additional args for `nibabel.load` API. more details about available args: https://github.com/nipy/nibabel/blob/master/nibabel/loadsave.py NFrprtas_closest_canonicalr/squeeze_non_spatial_dimsrc sbt|dkr tdn||_||_||_|r#trts#t dd}|r)| ||_ ||_ dS)Nrzr{z]NibabelReader: CuPy and/or Kvikio not installed for GPU loading, falling back to CPU loading.F) r|r}r~rprLrMrlrrrrrr?)r8rprLrMrr?rr9r:r}s   zNibabelReader.__init__cCrrrrr9r9r:rrzNibabelReader.warmup_kvikior,r-r.cCddg}to t||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_nibrr8r,suffixesr9r9r:r;" zNibabelReader.verify_suffixr<cKslg}t|}||_|j}|||D]}tj|fi|}t|}||qt |dkr2|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 rer) rrr?rrnibloadrrrhr8r<r?rrrr rDr9r9r:r@.s    zNibabelReader.readrBc CsRg}i}tt||jD]\}}||}|||tj<|||tj<|j|d<|jr:t |}|||tj<| ||tj <t j |tj<|||}|jrstt|jt|tj dD]}|j|ddkrr|j|dd}q_|||jdurt|jt|tj krtdnd|tj<n|j|tj<t||q t|||jd|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. rLrrerfNr{r)rrrrrrrZrrLrTrr[rrrrrMrrhrsqueezerrpr~rjr`rqr) r8rDrrrr,rr<rr9r9r:rEGs2        "  zNibabelReader.get_datarMcCs6z |jd}Wt|Sty|j}Yt|Sw)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_byteswappedrRrM)r8rDrr9r9r:rss  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)rTrrrCr9r9r:rs zNibabelReader._get_affinecCsz|jd}Wn ty|j}Ynw|dd}|dur+|d}t|dd}|d}t|dd}t|jsD| 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. rXdimNdimsrrre)rrYrRrirTinsertrbrrprrkrrr)r8rDrrZndimr spatial_rankr9r9r:rs      z NibabelReader._get_spatial_shapec Cs|jrytj|}tj|tjd}t|d }| |Wdn1s'wY| dr`t dt |}tjt|d }| }Wdn1sSwYtj|tjd}|j} |jj} |jj} || d| j| ddStj|jd dS) z Get the raw array data of the image, converted to Numpy array. Args: img: a Nibabel image object loaded from an image file. filename: file name of the image. r%rNz.nii.gzzr6r$rr@endswithrrasnumpygzipGzipFileioBytesIO frombufferrZdataobjrCrWr?r@rT asanyarray) r8rDr, file_sizeimagercompressed_dataZgz_fileZdecompressed_data data_shape data_offset data_dtyper9r9r:rs$      zNibabelReader._get_array_data)NFFF)rprtrLr/rMr/rr/rFrrHr)r6rIrJrKr}rr;r@rErrrrrr9r9rr:r's   , r'csBeZdZdZddfdd Zdd dZdddZdddZZS)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 Nnpz_keysKeysCollection | Nonerprtc s@t|dur t|}||_|dkrtdn||_||_dSry)r|r}rrrr~rpr?)r8rrrpr?rr9r:r}s  zNumpyReader.__init__r,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)rrQr9r9r:r;s zNumpyReader.verify_suffixr<c Ksg}t|}|j}|||D]5}tj|fddi|}t|jdrB|j dur2t | n|j }|D] } | || q7q| |qt |dkrP|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.npzNrer)rr?rrrTrUr r rdrrrbr rrh) r8r<r?rrrr rDrrkr9r9r:r@s    zNumpyReader.readrBcCsg}i}t|tjr |f}t|D]B}i}t|tjr9t|j}t|jtr.t||j}||t j <t j |t j <||t|jtrG|jntd|t j<t||qt|||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. r{)rQrTrUrrrrprkdeleterr[rrrrr~rjr`rq)r8rDrrrrr)r9r9r:rEs"          zNumpyReader.get_data)NN)rrrsrprtrFrrH) r6rIrJrKr}r;r@rErr9r9rr:r(s   r(PILcsTeZdZdZddfdd Zdd dZdddZdddZd ddZddZ 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 NT converterCallable | Nonervr/c s t||_||_||_dS)N)r|r}rzrvr?)r8rzrvr?rr9r:r}6s  zPILReader.__init__r,r-r.cCsgd}to t||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_pilrrQr9r9r:r;<szPILReader.verify_suffixr<*Sequence[PathLike] | PathLike | np.ndarraycKsrg}t|}|j}|||D]}tj|fi|}t|jr'||}||qt |dkr5|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 rer) rr?rrPILImageopencallablerzrrhrVr9r9r:r@Gs      zPILReader.readrBcCsg}i}t|D]@}||}|||tj<|jr$tt|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. rrer{r)rrrrr[rvrTrrrrhrr~rjr`rq)r8rDrrrrr<r9r9r:rEas  $ " zPILReader.get_datarMcCs|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. formatmodewidthheightrrCr9r9r:r~szPILReader._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. )rTrrrrCr9r9r:rszPILReader._get_spatial_shape)NT)rzr{rvr/rF)r<rrHr) r6rIrJrKr}r;r@rErrrr9r9rr:r)'s    r)c@s"eZdZUdZded<ded<dS) NrrdImagez2Class to wrap nrrd image array and metadata header np.ndarrayrrMrN)r6rIrJrK__annotations__r9r9r9r:rs  rc@sbeZdZdZdejddfd&d dZd'ddZd(ddZd)ddZ d*d d!Z d+d"d#Z d+d$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 Nr`TrprtrWnp.dtype | type | str | None index_orderrXrxr/cKs2|dkrtdn||_||_||_||_||_dSry)r~rprWrrxr?)r8rprWrrxr?r9r9r:r}s  zNrrdReader.__init__r,r-r.cCrN)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_nrrdrrQr9r9r:r;rSzNrrdReader.verify_suffixr<r=cKshg}t|}|j}|||D]}ttj|fd|ji|}||qt |dkr0|S|dS)r>rrer) rr?rrrr"r@rrrh)r8r<r?rrrr Z nrrd_imager9r9r:r@s    zNrrdReader.readrDNrrdImage | list[NrrdImage]rBcsg}i}t|D]~}|j|j}||t|j|jdkr%|| t j <|j r5| t jddkrDtjt j<t j t j<dt j<fdddD|jdur{t|jtt jkrutdnd 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. rbleft-posterior-superiorsizescsg|]}|qSr9)r)rrwrr9r:rsz'NrrdReader.get_data..)r space originspace directionsNr{r)rrrJrWrrMrr_convert_f_to_c_orderrrrrx_switch_lps_rasrirrrrrZr[rprhrr~rjr`rq)r8rDrrrr<r9rr:rEs,         "  zNrrdReader.get_datarrMrcCs`|d}|d}|j\}}t||d}t|}|j|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 rrreNr)rrrTrr)r8rrrxyZ affine_diamrr9r9r:rs   zNrrdReader._get_affinecCs8d|vs |ddkrt|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 spacer)rrrrrrr8rr9r9r:rs  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 rrrNrr)rTrot90fliprr9r9r:r%s z NrrdReader._convert_f_to_c_order)rprtrWrrrXrxr/rFrG)rDrr.rB)rrMr.r)rrMr.rM) r6rIrJrKrTrIr}r;r@rErrrr9r9r9r:r+s   ( r+)rLrMrNrM)F)rarbrcrMrdr/)K __future__rrrfrhrrrrabcrrcollections.abcrrrr dataclassesr pathlibr typingr r numpyrTtorch.utils.data._utils.collater monai.configrrmonai.data.utilsrrrrr monai.utilsrrrrrrrrrTr"r!Znibabel.nifti1rryrrrrrPrr_rmrlr$r__all__r%r`rqr&r*r'r(r)rr+r9r9r9r:sr             < `f`ch