o
    #i                    @  s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
mZ d dlmZmZmZmZ d dlmZ d dlmZ d dlmZmZ d dlZd dlmZ d d	lmZmZ d d
lm Z m!Z!m"Z"m#Z#m$Z$ d dl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ erd dl,Z,d dl-Z.d dl/Z/d dl0Z0d dl1m2Z2 d dl3m4Z5 d Z6 Z7 Z8 Z9Z:n*e*ddd\Z,Z7e*d\Z.Z8e*ddd\Z2Z;e*d\Z5Z9e*d\Z0Z:e*ddd\Z/Z6e*d\Z<Z=e*d\Z>Z?g dZ@G dd de
ZAd:d d!ZBd;d<d(d)ZCe+dd*G d+d, d,eAZDe+dd*G d-d. d.eAZEe+dd*G d/d0 d0eAZFG d1d2 d2eAZGe+d3d*G d4d5 d5eAZHeG d6d7 d7ZIe+dd*G d8d9 d9eAZJdS )=    )annotationsN)ABCabstractmethod)CallableIterableIteratorSequence)	dataclass)Path)TYPE_CHECKINGAny)np_str_obj_array_pattern)KeysCollectionPathLike)affine_to_spacing!correct_nifti_header_if_necessaryis_no_channelis_supported_formatorientation_ras_lps)MetaKeys	SpaceKeys	TraceKeysensure_tupleoptional_importrequire_pkg)Nifti1Image)ImageTitk)allow_namespace_pkgnibabelznibabel.nifti1r   )namez	PIL.Imagepydicomnrrdcupykvikio)ImageReader	ITKReaderNibabelReaderNumpyReader	PILReaderPydicomReader
NrrdReaderc                   @  s:   e Zd ZdZedddZedd
dZedddZdS )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.

    filenameSequence[PathLike] | PathLikereturnboolc                 C     t d| jj d)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.NotImplementedError	__class____name__selfr,    r9   Y/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/data/image_reader.pyverify_suffixR   s   zImageReader.verify_suffixdataSequence[Any] | Anyc                 K  r0   )#  
        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.

        r1   r2   r3   )r8   r<   kwargsr9   r9   r:   read`      zImageReader.readtuple[np.ndarray, dict]c                 C  r0   )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.

        r1   r2   r3   r8   imgr9   r9   r:   get_datam   rA   zImageReader.get_dataNr,   r-   r.   r/   r<   r-   r.   r=   r.   rB   )r6   
__module____qualname____doc__r   r;   r@   rE   r9   r9   r9   r:   r%   ?   s    r%   	from_dictdictto_dictc                 C  s   t |tstdt| d|s9| D ]#}| | }t |tjr)t|jj	d ur)q|d u r2t	t
jn|||< qd S tjtj}}|| v r]t| | || s]td| |  d||  d|| v rzt| | || s|td| |  d||  dd S d S )Nzto_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 )
isinstancerM   
ValueErrortypenpndarrayr   searchdtypestrr   NONEr   AFFINESPATIAL_SHAPEallcloseRuntimeError)rL   rN   keyZdatumZ
affine_key	shape_keyr9   r9   r:   _copy_compatible_dict{   s6   
r`   F
image_listlist	meta_dictto_cupyr/   c                 C  s   t | dkr
| d S t|tjd s,t|tj }|r%tr%tj| |dS t	j| |dS d|tj< |r<tr<tj
| ddS t	j
| ddS )N   r   axis)lenr   getr   ORIGINAL_CHANNEL_DIMinthas_cpcpconcatenaterT   stack)ra   rc   rd   channel_dimr9   r9   r:   _stack_images   s   
rq   )pkg_namec                      sr   e Zd ZdZ					d%d& fddZd'ddZd(ddZd)ddZd*ddZd+d,dd Z	d!d" Z
d#d$ 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

    N FTrp   str | int | Noneseries_namerX   reverse_indexingr/   series_metaaffine_lps_to_rasc                   sB   t    || _|dkrtdn|| _|| _|| _|| _|| _d S N
no_channelnan)	super__init__r?   floatrp   ru   rv   rw   rx   )r8   rp   ru   rv   rw   rx   r?   r5   r9   r:   r}      s   
	
zITKReader.__init__r,   r-   r.   c                 C     t S )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_itkr7   r9   r9   r:   r;         	zITKReader.verify_suffixr<   c                 K  sh  g }t |}| j }|| |D ]}| }t| rtj }|	d |
d || | }t|dk rCtd| dt|dkrRtd| d | jsY|d n| j}	||	}t|dkrk|d n|}tj|fi |}
| jrtjj|d	}|  | }t|dkr|
|d  ||
 q|tj|fi | qt|dkr|S |d 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.
        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|0021re   zno DICOMs in: rO   zthe directory: z% contains more than one DICOM series.r   )Z	FileNames)r   r?   copyupdater
   is_dirr   ZGDCMSeriesFileNamesZNewZSetUseSeriesDetailsZAddSeriesRestrictionZSetDirectoryZGetSeriesUIDsrh   FileNotFoundErrorwarningswarnru   ZGetFileNamesimreadrw   ZImageSeriesReaderZUpdateZGetMetaDataDictionaryArrayZSetMetaDataDictionaryappend)r8   r<   r?   img_	filenameskwargs_r    Znames_generator
series_uidZseries_identifier_obj_reader_metar9   r9   r:   r@      s:   






zITKReader.readrB   c                 C  s   g }i }t |D ]_}| |}|| | |}| || j|tj< | jr)tj	ntj
|tj< |tj  |tj< | ||tj< | jdu r\t|jt|tj krVtdnd|tj< n| j|tj< t|| qt|||fS )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.

        Nr{   )r   _get_array_datar   _get_meta_dict_get_affinerx   r   ORIGINAL_AFFINEr   RASLPSSPACEr   rZ   _get_spatial_shaper[   rp   rh   shaper~   rj   r`   rq   )r8   rD   	img_arraycompatible_metair<   headerr9   r9   r:   rE     s    



"
zITKReader.get_datarM   c                 C  sf   |  }i }| D ]}|drq
|| }t|jdr#t|n|||< q
t| |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.

        ZITK_r   spacing)ZGetMetaDataDictionaryZGetKeys
startswithrS   r6   rT   asarray
GetSpacing)r8   rD   Zimg_meta_dictrc   r^   valr9   r9   r:   r   1  s   
$zITKReader._get_meta_dict
lps_to_rasc                 C  s   t | }t| }t| }t|}tt|j	d dd}t
|d }|d|d|f t|d|  |d|d|f< |d| |d|df< |rYt|}|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.

        r   re      Nr   )r   array_from_matrixGetDirectionrT   r   r   Z	GetOriginminmaxr   eyediagr   )r8   rD   r   	directionr   originsraffiner9   r9   r:   r   D  s   

6zITKReader._get_affinec                 C  s\   t | jd }tt|dd}tt |}t| j	t
r%|| j	 t|d| S )z
        Get the spatial shape of `img`.

        Args:
            img: an ITK image object loaded from an image file.

        r   r   re   N)r   r   r   r   r   r   rb   sizerQ   rp   rk   poprT   r   )r8   rD   r   _sizer9   r9   r:   r   [  s   zITKReader._get_spatial_shapec                 C  sD   t j|dd}| dkr| jr|S |jS | jr|S t|jddS )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_axesre   r   r   )r   Zarray_view_from_imageZGetNumberOfComponentsPerPixelrv   TrT   moveaxis)r8   rD   Znp_imgr9   r9   r:   r   j  s   zITKReader._get_array_data)Nrs   FFT)
rp   rt   ru   rX   rv   r/   rw   r/   rx   r/   rF   r<   r-   rH   r.   rM   T)r   r/   )r6   rI   rJ   rK   r}   r;   r@   rE   r   r   r   r   __classcell__r9   r9   r   r:   r&      s     


3
!r&   c                      s   e Zd ZdZ							d5d6 fddZdd Zd7ddZd8ddZd9d d!Zd:d#d$Z	d;d&d'Z
d<d=d*d+Zd>d-d.Zd/d0 Zd1d2 Zd3d4 Z  ZS )?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.
    NTrs   Frp   rt   rx   r/   swap_ijprune_metadata
label_dictdict | Nonefname_regexrX   to_gpuc           	        st   t    || _|dkrtdn|| _|| _|| _|| _|| _|| _	|r/t
r(ts/td d}|r5|   || _d S )Nrz   r{   z]PydicomReader: CuPy and/or Kvikio not installed for GPU loading, falling back to CPU loading.F)r|   r}   r?   r~   rp   rx   r   r   r   r   rl   
has_kvikior   r   warmup_kvikior   )	r8   rp   rx   r   r   r   r   r   r?   r   r9   r:   r}     s    

zPydicomReader.__init__c                 C     t rBtrDtd}t +}|j}t|d}|	| |
  t|}t|d}|| W d   dS 1 s;w   Y  dS dS dS z
        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.
        d   wrNrl   r   rm   arangetempfileNamedTemporaryFiler    r$   CuFilewriteclose
empty_liker@   r8   aZtmp_fileZtmp_file_namefbr9   r9   r:   r        



"zPydicomReader.warmup_kvikior,   r-   r.   c                 C  r   )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_pydicomr7   r9   r9   r:   r;     r   zPydicomReader.verify_suffixr<   c                   s  g }t |}t| _ j } jrd|d< || d _t|D ]\}}| }t	|
 r jdurG fddttj|dD }ndd ttj|dD }g }	g }
|D ]8}z|	tjdd	|i| |
| W q\ tjjy } ztjd
| d| ddd W Y d}~q\d}~ww t|	dkrd _||	 |
 j|< q#||	d  |
d  j|< q#tjdd	|i|}|| q#t|dkr|d S |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.

        z100 KBZ
defer_sizeFNc                   s   g | ]}t  j|r|qS r9   )rematchr   .0slcr8   r9   r:   
<listcomp>  s    z&PydicomReader.read.<locals>.<listcomp>*c                 S  s   g | ]
}t j|r|qS r9   )r!   miscZis_dicomr   r9   r9   r:   r     s    fpzFailed to read z with exception: 
rO      )
stacklevelre   Tr   r9   )r   rb   r   r?   r   r   r   
has_series	enumerater
   r   r   globospathjoinr   r!   ZdcmreaderrorsZInvalidDicomErrorr   r   rh   )r8   r<   r?   r   r   r   r   r    Zseries_slcsslicesZloaded_slc_namesr   edsr9   r   r:   r@     sF   



$(
zPydicomReader.readr   r   Sequence[PathLike]c                 C  sv  g }t ||D ]\}}t|dr|||f qtd| d qt|dd d}t|dkr4td|d \}}d	}| ||}	|	j	}
t
|d
dgt|
 }t
|ddd }|	g}tdt|D ]d}| || d || d }|j	}t
|| d d
dgt|
 }t
|| d dd	d	t|fd }t||std| d| d |
|krtd|
 d| d |t|| 7 }|}|| qbt|dkr"|t|d  }|| | jrtj|dd}ntj|dd}|dd= | |}t||d< t|d d drt|d d j|d< |
t|f |tj< ||fS |d }| |}t||d< |
|tj< ||fS )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.
        InstanceNumberzslice: z+ does not have InstanceNumber tag, skip it.c                 S  s
   | d j S )Nr   )r   )sr9   r9   r:   <lambda>=  s   
 z5PydicomReader._combine_dicom_series.<locals>.<lambda>)r^   r   z%the input does not have valid slices.        ZPixelSpacing      ?ImagePositionPatient)r   r   r   r   re   z6the list contains slices that have different spacings rP   rO   z4the list contains slices that have different shapes r   rf   Nr   lastImagePositionPatient)ziphasattrr   r   r   sortedrh   rR   r   r   getattrranger~   rT   r\   absr   rm   ro   r   r   r   r   r[   )r8   r<   r   r   Zslc_dsr,   Zfirst_sliceZfirst_filenameZaverage_distanceZfirst_arrayr   r   Zprev_posZstack_array_listidxZ	slc_arrayZ	slc_shapeZslc_spacingZslc_posZstack_arrayZstack_metadatar9   r9   r:   _combine_dicom_series$  sZ   
"




z#PydicomReader._combine_dicom_seriesrB   c              	   C  sb  g }| j du r1t|d ts|| || jd  nSt|D ]\}}|| || j|  qn=t|ts9|g}t|D ]0\}}t|drR| || j| \}}n| 	|| j| }| 
|}|j|tj< |||f q=g }i }	t|D ]\}}| jr| jrt|ddnt|dd}|| jrt|nt| | || j}
| jrtjntj|tj< | jr|
tg dg dg dg dg }
t|tj }|d |d |d< |d< t||tj< |
|tj< |
 |tj< | jd	u rt |jt |tj krt!d
nd|tj"< n| j|tj"< t#|tj t |tj d|d< t$||	 qvt%||	| jd|	fS )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.

        Tr   SegmentSequencere   )r   re   r   r   )re   r   r   r   )r   r   re   r   )r   r   r   re   Nr{   r   )r   r   rd   )&r   rQ   rb   r   r   r   r   r   _get_seg_datar   r   r   r   r[   r   r   r   rm   swapaxesrT   ascontiguousarrayr   rx   r   r   r   r   arrayr   r   rZ   rp   rh   r~   rj   r   r`   rq   )r8   r<   Z
dicom_datar   seriesd
data_arraymetadatar   r   r   sp_sizer9   r9   r:   rE   k  sP   



" &
$

zPydicomReader.get_datarM   c                 C  s`   |j dd}| jri }dD ]}|| v r|| ||< q|S dD ]}|| v r-|| q |S )z
        Get all the metadata of the image and convert to dict type.

        Args:
            img: a Pydicom dataset object.

        T)Zsuppress_invalid_tags)0020003700200032002800305200922952009230)Z7FE00008Z7FE00009Z7FE00010ZFFFCFFFC)Zto_json_dictr   keysr   )r8   rD   r  r   r^   r9   r9   r:   r     s   	
zPydicomReader._get_meta_dictr  r   c                 C  s`  t d}d|v rd|v s|S |d d \}}}}}}	|d d \}
}}d|v r.|d d nd}|d|dd	 \}}|| |d
< || |d< |
|d< || |d< || |d< ||d< |	| |d< || |d< d|d< ||d< d|v r|d \}}}|tj d }||
 |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.

           r  r  Valuer  )r   r   r   Nr   )r   r   )r   re   )r   r   )re   r   )re   re   )re   r   )r   r   )r   re   r   )r   r   )r   r   r   r   re   )r   r   )re   r   )rT   r   ri   r   r[   r   )r8   r  r   r   rxryZrzcxcyczsxsyszr   drdcZt1nZt2nZt3nnk1k2k3r9   r9   r:   r     s6   

4zPydicomReader._get_affiner   c           
      c  s    t |dstd| dg }|jD ]}t |ds"td| d|t|jd j q| jr6t	|nt
	|}dd |jD }| jsKt
|nt|D ]"}| js^t
||kd nt||kd }	||	d	f || fV  qPd
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".

         PerFrameFunctionalGroupsSequencezTo read dicom seg: z1, 'PerFrameFunctionalGroupsSequence' is required.SegmentIdentificationSequencez=, 'SegmentIdentificationSequence' is required for each frame.r   c                 S  s   i | ]}t |j|qS r9   )rk   ZSegmentNumber)r   r   r9   r9   r:   
<dictcomp>3  s    z1PydicomReader._get_frame_data.<locals>.<dictcomp>.N)r   r4   r  r   rk   r  ZReferencedSegmentNumberr   rm   r   rT   r   uniquewhere)
r8   rD   r,   
array_dataZframe_seg_numsr   Zframe_seg_nums_arrZseg_descriptionsr   indicesr9   r9   r:   _get_frame_data  s    
%


*zPydicomReader._get_frame_datac                 C  s  |  |}t|j}| ||}t|j}|d | |d< | jdurJ| j|d< | jr:tj	g |t| j|j
d}n0tj	g |t| j|j
d}n i |d< | jr^tj	g |||j
d}ntj	g |||j
d}t| |||D ]/\}\}	}
t|
dd| }t|
d|}||d  vr||d |< |d | }|	|d|f< qs|g d	}|jdd
 |tj< d| v r|d d d }d| v r|d d d }d| v r|d |d< d| v r|d d d }d| v r|d d }||d< d| v r|d  |d d 7  < | jr|d d| v ra|d d d }d| v rX|d d d }d| v rX|d |d< |d d d
 d d d d d |d< | jra|d ||fS )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.

        r   NlabelsrW   ZSegmentLabelZlabel_ZSegmentDescription.)re   r   r   r   r   r	  r  Z00209116r  Z00289110r  r   Z00180050r
  Z00209113r  r   )r   rh   r   r   rb   r   r   r   rm   zerosrW   rT   r   r#  r   r  	transposer   r[   r   r   )r8   rD   r,   r  	n_classesr!  spatial_shapeZall_segsr   framesdescriptionZsegment_label
class_nameZ	class_numZshared_func_group_seqZplane_orient_seqZpixel_measure_seqZpixel_spacingZfirst_frame_func_group_seqZplane_position_seqr9   r9   r:   r   9  sh   





  

zPydicomReader._get_seg_datac                 C  s  t |dd}t |dd}t |dd}t |dd}t |dd}t |dd}|du s0|du s0|du rKtd	| d
 t|dsFtd	| d|j}	|	S |dkrZ|dkrVtjntj}
n"|dkri|dkretj	ntj
}
n|dkrx|dkrttjntj}
ntd|d }|| | | }|| }tjdd}||vrtd	| d|j|ddj}t|d}tj|tjd}|||| W d   n1 sw   Y  |dkr|||fn||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.

        ZRowsNColumnsZBitsAllocatedSamplesPerPixelre   ZNumberOfFramesZPixelRepresentationdicom data: zK does not have Rows, Columns or BitsAllocated, falling back to CPU loading.pixel_array does not have pixel_array.          zUnsupported BitsAllocated valuei  z does not have pixel data.T)Zkeep_deferredr   r%  )r   r   r   r   rR   r0  rm   int8uint8int16uint16int32uint32r!   tagTagget_itemZ
value_tellr$   r   emptyr@   viewreshape)r8   rD   r,   rowscolumnsZbits_allocatedZsamples_per_pixelZnumber_of_framesZpixel_representationr<   rW   Zbytes_per_pixelZtotal_pixelsZexpected_pixel_data_lengthZpixel_data_tagoffsetr   buffer	new_shaper9   r9   r:   _get_array_data_from_gpu  sF   	

z&PydicomReader._get_array_data_from_gpuc                 C  s   | j r
| ||}nt|dstd| d|j}d\}}d}t|dr*|j}d}t|dr4|j}d}|r_| j rUtj|tj	d	}tj|tj	d	}|
tj	| | }|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.

        r0  r/  r1  )r   r   FRescaleSlopeTRescaleInterceptr%  )r   rF  r   rR   r0  rG  rH  rm   r   float32astyperT   )r8   rD   r,   r<   sloperC  Zrescale_flagr9   r9   r:   r     s*   


zPydicomReader._get_array_data)NTTTNrs   F)rp   rt   rx   r/   r   r/   r   r/   r   r   r   rX   r   r/   rF   r   )r<   r   r   r   rH   r   r   )r  rM   r   r/   )r.   r   )r6   rI   rJ   rK   r}   r   r;   r@   r   rE   r   r   r#  r   rF  r   r   r9   r9   r   r:   r*     s*    0


9
G
P
,8M7r*   c                      st   e Zd ZdZ				d"d# fd
dZdd Zd$ddZd%ddZd&ddZd'ddZ	dd Z
dd Z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

    NFrp   rt   as_closest_canonicalr/   squeeze_non_spatial_dimsr   c                   sb   t    |dkrtdn|| _|| _|| _|r#trts#t	d d}|r)| 
  || _|| _d S )Nrz   r{   z]NibabelReader: CuPy and/or Kvikio not installed for GPU loading, falling back to CPU loading.F)r|   r}   r~   rp   rL  rM  rl   r   r   r   r   r   r?   )r8   rp   rL  rM  r   r?   r   r9   r:   r}     s   

zNibabelReader.__init__c                 C  r   r   r   r   r9   r9   r:   r     r   zNibabelReader.warmup_kvikior,   r-   r.   c                 C     ddg}t o
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.

        niiznii.gz)has_nibr   r8   r,   suffixesr9   r9   r:   r;   "     	zNibabelReader.verify_suffixr<   c                 K  sl   g }t |}|| _| j }|| |D ]}tj|fi |}t|}|| qt	|dkr2|S |d 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()`.
        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

        re   r   )
r   r   r?   r   r   nibloadr   r   rh   r8   r<   r?   r   r   r   r    rD   r9   r9   r:   r@   .  s   

zNibabelReader.readrB   c           	      C  sR  g }i }t t|| jD ]\}}| |}| ||tj< | ||tj< | j|d< | jr:t	|}| ||tj< | 
||tj< tj|tj< | ||}| jrstt|jt|tj dD ]}|j|d  dkrr|j|d d}q_|| | jdu rt|jt|tj krtdnd|tj< n| j|tj< t|| qt||| jd|fS )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.

        rL  r   re   rf   Nr{   r   )r   r   r   r   r   r   rZ   r   rL  rT  r   r[   r   r   r   r   rM  r   rh   r   squeezer   rp   r~   rj   r`   rq   r   )	r8   rD   r   r   r   r,   r   r<   r  r9   r9   r:   rE   G  s2   


 

"
zNibabelReader.get_datarM   c                 C  s6   z|j d}W t|S  ty   |j }Y t|S w )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.

        <)r   as_byteswappedrR   rM   )r8   rD   r   r9   r9   r:   r   s  s   	zNibabelReader._get_meta_dictc                 C  s   t j|jddS )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   )rT   r   r   rC   r9   r9   r:   r     s   	zNibabelReader._get_affinec                 C  s   z|j d}W n ty   |j }Y nw |dd}|du r+|d}t|dd}|d }t|dd }t| jsD|	t
| j tt|dd}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.

        rX  dimNdimsr   r   re   )r   rY  rR   ri   rT   insertrb   r   rp   r   rk   r   r   r   )r8   rD   r   rZ  ndimr   spatial_rankr9   r9   r:   r     s   	


z NibabelReader._get_spatial_shapec                 C  s  | j rytj|}tj|tjd}t|d}|	| W d   n1 s'w   Y  |
dr`td t|}tjt|d}|	 }W d   n1 sSw   Y  tj|tjd}|j}	|jj}
|jj}||
d |j|	ddS tj|jd	dS )
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%  r   Nz.nii.gzz<Loading compressed NIfTI file into GPU may not be efficient.)fileobjF)orderC)r   r   r   getsizerm   r>  r6  r$   r   r@   endswithr   r   asnumpygzipGzipFileioBytesIO
frombufferr   ZdataobjrC  rW   r?  r@  rT   
asanyarray)r8   rD   r,   	file_sizeimager   compressed_dataZgz_fileZdecompressed_data
data_shapedata_offset
data_dtyper9   r9   r:   r     s$   	



zNibabelReader._get_array_data)NFFF)rp   rt   rL  r/   rM  r/   r   r/   rF   r   rH   r   )r6   rI   rJ   rK   r}   r   r;   r@   rE   r   r   r   r   r   r9   r9   r   r:   r'     s    



,r'   c                      sB   e Zd ZdZdd fddZdddZdddZdddZ  ZS )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

    Nnpz_keysKeysCollection | Nonerp   rt   c                   s@   t    |d urt|}|| _|dkrtdn|| _|| _d S ry   )r|   r}   r   rr  r~   rp   r?   )r8   rr  rp   r?   r   r9   r:   r}     s   

zNumpyReader.__init__r,   r-   r.   r/   c                 C  s   ddg}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.
        npznpy)r   rQ  r9   r9   r:   r;     s   
zNumpyReader.verify_suffixr<   c           
      K  s   g }t |}| j }|| |D ]5}tj|fddi|}t|jdrB| j	du r2t
| n| j	}|D ]	}	|||	  q7q|| qt|dkrP|S |d S )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.npzNre   r   )r   r?   r   r   rT   rU  r
   r    rd  rr  rb   r  r   rh   )
r8   r<   r?   r   r   r   r    rD   rr  kr9   r9   r:   r@     s   

zNumpyReader.readrB   c                 C  s   g }i }t |tjr|f}t|D ]B}i }t |tjr9t|j}t | jtr.t|| j}||t	j
< tj|t	j< || t | jtrG| jntd|t	j< t|| qt|||fS )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{   )rQ   rT   rU   r   r   r   rp   rk   deleter   r[   r   r   r   r   r~   rj   r`   rq   )r8   rD   r   r   r   r   r)  r9   r9   r:   rE     s"   

zNumpyReader.get_data)NN)rr  rs  rp   rt   rF   r   rH   )	r6   rI   rJ   rK   r}   r;   r@   rE   r   r9   r9   r   r:   r(     s    

r(   PILc                      sT   e Zd ZdZdd fdd	ZdddZdddZdddZd ddZdd Z	  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	converterCallable | Nonerv   r/   c                   s    t    || _|| _|| _d S )N)r|   r}   rz  rv   r?   )r8   rz  rv   r?   r   r9   r:   r}   6  s   

zPILReader.__init__r,   r-   r.   c                 C  s   g d}t o
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.
        )pngjpgjpegbmp)has_pilr   rQ  r9   r9   r:   r;   <  s   zPILReader.verify_suffixr<   *Sequence[PathLike] | PathLike | np.ndarrayc                 K  sr   g }t |}| j }|| |D ]}tj|fi |}t| jr'| |}|| qt	|dkr5|S |d 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()`.
        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

        re   r   )
r   r?   r   r   PILImageopencallablerz  r   rh   rV  r9   r9   r:   r@   G  s   



zPILReader.readrB   c                 C  s   g }i }t |D ]@}| |}| ||tj< | jr$tt|ddnt|}|	| t
|jt
|tj kr>tdnd|tj< t|| qt|||fS )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.

        r   re   r{   r   )r   r   r   r   r[   rv   rT   r   r   r   rh   r   r~   rj   r`   rq   )r8   rD   r   r   r   r   r<   r9   r9   r:   rE   a  s   
$
"zPILReader.get_datarM   c                 C  s   |j |j|j|jdS )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.

        formatmodewidthheightr  rC   r9   r9   r:   r   ~  s   zPILReader._get_meta_dictc                 C  s   t |j|jfS )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.
        )rT   r   r  r  rC   r9   r9   r:   r     s   zPILReader._get_spatial_shape)NT)rz  r{  rv   r/   rF   )r<   r  rH   r   )r6   rI   rJ   rK   r}   r;   r@   rE   r   r   r   r9   r9   r   r:   r)   '  s    



	r)   c                   @  s"   e Zd ZU dZded< ded< dS )	NrrdImagez2Class to wrap nrrd image array and metadata header
np.ndarrayr   rM   r   N)r6   rI   rJ   rK   __annotations__r9   r9   r9   r:   r    s   
 r  c                   @  sb   e Zd ZdZdejddfd&ddZd'ddZd(ddZd)ddZ	d*d d!Z
d+d"d#Zd+d$d%ZdS ),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`  Trp   rt   rW   np.dtype | type | str | Noneindex_orderrX   rx   r/   c                 K  s2   |dkrt dn|| _|| _|| _|| _|| _d S ry   )r~   rp   rW   r  rx   r?   )r8   rp   rW   r  rx   r?   r9   r9   r:   r}     s
   
zNrrdReader.__init__r,   r-   r.   c                 C  rN  )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"   zseg.nrrd)has_nrrdr   rQ  r9   r9   r:   r;     rS  zNrrdReader.verify_suffixr<   r=   c                 K  sh   g }t |}| j }|| |D ]}ttj|fd| ji| }|| qt	|dkr0|S |d S )r>   r  re   r   )
r   r?   r   r   r  r"   r@   r  r   rh   )r8   r<   r?   r   r   r   r    Z
nrrd_imager9   r9   r:   r@     s   


zNrrdReader.readrD   NrrdImage | list[NrrdImage]rB   c                   s  g }i }t |D ]~}|j| j}|| t|j | jdkr%|   | 	  t
j< | jr5|    t
jddkrDtj t
j<  t
j   t
j<  d   t
j<  fdddD  | jdu r{t|jt t
j krutdnd	 t
j< n| j t
j< t | qt|||fS )
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.

        rb  left-posterior-superiorsizesc                   s   g | ]}  |qS r9   )r   )r   rw  r   r9   r:   r     s    z'NrrdReader.get_data.<locals>.<listcomp>)r  space originspace directionsNr{   r   )r   r   rJ  rW   r   rM   r   r  _convert_f_to_c_orderr   r   r   rx   _switch_lps_rasri   r   r   r   r   rZ   r[   rp   rh   r   r~   rj   r`   rq   )r8   rD   r   r   r   r<   r9   r  r:   rE     s,   






"
zNrrdReader.get_datar   rM   r  c                 C  s`   |d }|d }|j \}}t||d }t|}|j|d|d|f< ||d|d df< |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

        r  r  re   Nr   )r   r   rT   r   r   )r8   r   r   r   xyZaffine_diamr   r9   r9   r:   r     s   	

zNrrdReader._get_affinec                 C  s8   d|vs
|d dkrt |tj |tj< tj|tj< |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  )r   r   r   r   r   r   r8   r   r9   r9   r:   r    s   zNrrdReader._switch_lps_rasc                 C  sJ   t t |d d|d< |d ddd |d< |d ddd |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

        r  r   r  Nr   r  )rT   rot90flipr  r9   r9   r:   r  %  s   z NrrdReader._convert_f_to_c_order)rp   rt   rW   r  r  rX   rx   r/   rF   rG   )rD   r  r.   rB   )r   rM   r.   r  )r   rM   r.   rM   )r6   rI   rJ   rK   rT   rI  r}   r;   r@   rE   r   r  r  r9   r9   r9   r:   r+     s    



(
r+   )rL   rM   rN   rM   )F)ra   rb   rc   rM   rd   r/   )K
__future__r   r   rf  rh  r   r   r   r   abcr   r   collections.abcr   r   r   r   dataclassesr	   pathlibr
   typingr   r   numpyrT   torch.utils.data._utils.collater   monai.configr   r   monai.data.utilsr   r   r   r   r   monai.utilsr   r   r   r   r   r   r   r   rT  r"   r!   Znibabel.nifti1r   ry  r   r  r  r   rP  r  r   _rm   rl   r$   r   __all__r%   r`   rq   r&   r*   r'   r(   r)   r  r+   r9   r9   r9   r:   <module>   sr    
< `    f `ch