o
    i&                     @   s  d Z ddlmZ ddlZddlmZ ddlmZmZ er"ddl	m
Z
 zddlZdZW n ey5   dZY nw zddlZdd	lmZ dZeed
ZW n eyV   dZdZY nw ddlmZ ddlmZmZ ddlZddlmZmZmZ ddlmZmZmZm Z  dZ!dddZ"ej#j$ej#j%ej#j&ej#j'ej#j(ej#j)ej#jej#jgZ*ej#j$gZ+de,fddZ-ddde,fddZ.ddde,fddZ/dede,fddZ0d+d d!Z1d,d$d%Z2ddde3fd&d'Z4d-d)d*Z5dS ).zkUse the `GDCM <https://sourceforge.net/projects/gdcm/>`_ Python package to
decode pixel transfer syntaxes.
    )deepcopyN)NamedTemporaryFile)TYPE_CHECKINGcast)DatasetTF)DataElementSetByteStringValue)config)generate_framesgenerate_fragmented_frames)UIDJPEG2000JPEG2000Lossless)get_expected_lengthpixel_dtypeget_j2k_parametersget_nr_framesGDCM)zhttps://numpy.org/NumPy)z&https://sourceforge.net/projects/gdcm/r   )numpygdcmreturnc                   C   s   t otS )z8Return ``True`` if the handler has its dependencies met.)HAVE_NP	HAVE_GDCM r   r   ^/mnt/sdb/aimis/docanh/lib/python3.10/site-packages/pydicom/pixel_data_handlers/gdcm_handler.pyis_availableA   s   r   dsr   c                 C      dS )zReturn ``True`` if the *Pixel Data* should to be converted from YCbCr to
    RGB.

    This affects JPEG transfer syntaxes.
    Fr   r   r   r   r   needs_to_convert_to_RGBF      r    c                 C   r   )zReturn ``True`` if the *Photometric Interpretation* should be changed
    to RGB.

    This affects JPEG transfer syntaxes.
    Fr   r   r   r   r   .should_change_PhotometricInterpretation_to_RGBO   r!   r"   transfer_syntaxc                 C   s   | t v S )zReturn ``True`` if the handler supports the `transfer_syntax`.

    Parameters
    ----------
    transfer_syntax : uid.UID
        The Transfer Syntax UID of the *Pixel Data* that is to be used with
        the handler.
    )SUPPORTED_TRANSFER_SYNTAXES)r#   r   r   r   supports_transfer_syntaxX   s   	r%   r   c           	      C   s   | j j}ttdd}|jrCtj }t| dd}t	| j
|d}|D ]}|D ]}t }|| || q(q$||  |S || j
 |S )a  Return a ``gdcm.DataElement`` for the *Pixel Data*.

    Parameters
    ----------
    ds : dataset.Dataset
        The :class:`~pydicom.dataset.Dataset` containing the *Pixel
        Data*.

    Returns
    -------
    gdcm.DataElement
        The converted *Pixel Data* element.
    i     Fwarnnumber_of_frames)	file_metaTransferSyntaxUIDr   r   Tagis_compressedSequenceOfFragmentsNewr   r   	PixelDataFragmentr   AddFragmentSetValue__ref__)	r   tsyntaxdata_element	fragments	nr_framesfragment_genframe_fragmentsfragment_datafragmentr   r   r   create_data_elementd   s$   

r>   r7   
gdcm.Imagec                 C   s   t  }t| dd}||dkrdnd || j| j|f || t j	| j}|
t | | jj}t jt|}|t | t | j| j| j| j| j}|| d| v re|| j |S )a1  Return a ``gdcm.Image``.

    Parameters
    ----------
    ds : dataset.Dataset
        The :class:`~pydicom.dataset.Dataset` containing the Image
        Pixel module.
    data_element : gdcm.DataElement
        The ``gdcm.DataElement`` *Pixel Data* element.

    Returns
    -------
    gdcm.Image
    Fr'            PlanarConfiguration)r   Imager   SetNumberOfDimensionsSetDimensionsColumnsRowsSetDataElementPhotometricInterpretation	GetPITypeSetPhotometricInterpretationr+   r,   TransferSyntax	GetTSTypestr__str__SetTransferSyntaxPixelFormatSamplesPerPixelBitsAllocated
BitsStoredHighBitPixelRepresentationSetPixelFormatSetPlanarConfigurationrC   )r   r7   imager*   pi_typer6   ts_typepixel_formatr   r   r   create_image   s*   

r^   c                 C   s   t  }t| dd}|r't|tr'|| | stdtt|	 
 S | d}| d |d< | j|_tddd}|| W d   n1 sLw   Y  ||j | s_td|	 
 }d}t|j |S )	zReturn the pixel data from `ds` as a str.

    Used for GDCM < 2.8.8.

    Parameters
    ----------
    ds : pydicom.dataset.Dataset
        The dataset to create the str from.

    Returns
    -------
    str
        The UTF-8 encoded pixel data.
    filenameNzGDCM could not read DICOM image(   r1   wbF)delete)r   ImageReadergetattr
isinstancerO   SetFileNameRead	TypeErrorr   GetImage	GetBuffergroup_datasetr+   r   save_asnameosremove)r   readerfnamenewt	pixel_strr   r   r   _get_pixel_str_fileio   s(   

ru   numpy.ndarrayc                 C   s  t stdtrt| }t| |}| }nt| }|dd}t| }| j	dkr/|d d }t
||krM||d }tt|tjrL|d| }n	 t| }tj||d}t| d	}	|j|	krmtd
|j d|	 | jj}
tjr|
ttfv rt| }tt| j|d}t|}tt|d| j }|dd}|s| j!dkrtt| j"| }t#| $d}d|_!t|}|%||> %||? }t&| rd| _	td|' S )a  Use the GDCM package to decode *Pixel Data*.

    Returns
    -------
    numpy.ndarray
        A correctly sized (but not shaped) array of the entire data volume

    Raises
    ------
    ImportError
        If the required packages are not available.
    TypeError
        If the image could not be read by GDCM or if the *Pixel Data* type is
        unsupported.
    AttributeError
        If the decoded amount of data does not match the expected amount.
    z-The GDCM handler requires both gdcm and numpyzutf-8surrogateescapeYBR_FULL_422rA   rB   N)dtypepixelszAmount of pixel data z" does not match the expected data r)   	precision	is_signedr@   r`   r   RGBrv   )(r   ImportErrorHAVE_GDCM_IN_MEMORY_SUPPORTr>   r^   rj   ru   encoder   rJ   lenr   any
frombufferbyter   sizeAttributeErrorr+   r,   r	   APPLY_J2K_CORRECTIONSr   r   r   nextr
   r1   r   r   int
setdefaultrU   rW   rT   r   rk   astyper"   copy)r   gdcm_data_element
gdcm_imagert   pixel_bytearrayexpected_length_bytespaddingnumpy_dtypearrexpected_length_pixelsr6   r9   
codestreamparamsj2k_precisionj2k_signshiftpixel_modulery   r   r   r   get_pixeldata   sR   

	



r   )r   r   r   r   )r   r   r7   r   r   r?   )r   r   r   rv   )6__doc__r   r   rn   tempfiler   typingr   r   pydicom.datasetr   r   r   r~   r   r   r   hasattrr   pydicomr	   pydicom.encapsr
   r   pydicom.uidr   r   r   pydicom.pixels.utilsr   r   r   r   HANDLER_NAMEDEPENDENCIESuidJPEGBaseline8BitJPEGExtended12BitJPEGLosslessJPEGLosslessSV1JPEGLSLosslessJPEGLSNearLosslessr$   $should_convert_these_syntaxes_to_RGBboolr   r    r"   r%   r>   r^   rO   ru   r   r   r   r   r   <module>   sb   
		

#).