U
    a+dB                     @   s   d Z ddlmZ ddlmZmZmZmZmZm	Z	m
Z
mZmZ ddlZddlmZmZmZmZ ddlmZmZmZmZ ddlmZmZ ddlZdd	lmZ eeed
ddZ G dd deZ!dS )a   Read/Write images using Pillow/PIL.

Backend Library: `Pillow <https://pillow.readthedocs.io/en/stable/>`_

Plugin that wraps the the Pillow library. Pillow is a friendly fork of PIL
(Python Image Library) and supports reading and writing of common formats (jpg,
png, gif, tiff, ...). For, the complete list of features and supported formats
please refer to pillows official docs (see the Backend Library link).

Parameters
----------
request : Request
    A request object representing the resource to be operated on.

Methods
-------

.. autosummary::
    :toctree: _plugins/pillow

    PillowPlugin.read
    PillowPlugin.write
    PillowPlugin.iter
    PillowPlugin.get_meta

    )BytesIO)	CallableOptionalDictAnyTuplecastIteratorUnionListN)ImageUnidentifiedImageErrorImageSequenceExifTags   )RequestIOModeInitializationError	URI_BYTES)PluginV3ImageProperties)	ArrayLike)orientationmodereturnc              	      sd   t |dkrdnd dd  fdddd  fdd fd	dd
d  fdddd d}||  S )N   c                 S   s   | S N xr   r   :/tmp/pip-unpacked-wheel-xbmu82vq/imageio/plugins/pillow.py<lambda>1       z-_exif_orientation_transform.<locals>.<lambda>c                    s   t j|  dS )NZaxisnpflipr    r%   r   r"   r#   2   r$   c                 S   s   t j| ddS )Nr   kr'   rot90r    r   r   r"   r#   3   r$   c                    s   t j|  d dS )Nr   r%   r&   r    r%   r   r"   r#   4   r$   c                    s   t jt j| dd dS )N   r)   r%   r'   r(   r,   r    r%   r   r"   r#   5   r$   c                 S   s   t j| ddS )Nr   r)   r+   r    r   r   r"   r#   6   r$   c                    s   t jt j| dd dS )Nr   r)   r%   r.   r    r%   r   r"   r#   7   r$   c                 S   s   t j| ddS )Nr-   r)   r+   r    r   r   r"   r#   8   r$   )r   r   r-                  )r   getmodebands)r   r   ZEXIF_ORIENTATIONr   r%   r"   _exif_orientation_transform)   s    



r5   c                       s   e Zd Zedd fddZddddZdddddd	ejdd
dZdddde	e
e
eej dddZejdddZddddeeee f e	e	e
ee dddZddee	ef dddZd!ee
ee	ef dddZd"eeddd Z  ZS )#PillowPluginN)requestr   c              	      s  t  | d| _|jjtjkrzt|	  W 5 Q R X W n> t
k
r|   |jtkrdtddntd|j ddY nX t| j	 | _nl| jjp| jj}|dkrtdt dS tjtjg}|D ] }|  |t  kr dS qtd| dddS )zInstantiate a new Pillow Plugin Object

        Parameters
        ----------
        request : {Request}
            A request object representing the resource to be operated on.

        Nz'Pillow can not read the provided bytes.zPillow can not read .zCan't determine file format to write as. You _must_ set `format` during write or the call will fail. Use `extension` to supress this warning. zPillow can not write `z` files.)super__init___imager   Zio_moder   readr   openget_filer   	_uri_typer   r   Zraw_uri_requestr7   	extensionformat_hintwarningswarnUserWarningZpreinitinitregistered_extensionskeys)selfr7   rA   ZtirageZformat_loader	__class__r   r"   r:   ?   sH    


zPillowPlugin.__init__)r   c                 C   s   | j r| j   | j  d S r   )r;   closer@   finish)rI   r   r   r"   rL   t   s    
zPillowPlugin.closeF)indexr   rotateapply_gammaas_grayc                C   s   |dk	rt d|dkr@| jjdkr*t}n| jjdkr<t}nd}t|trl| j| | | j|||}|S | j	|||d}t
jdd |D dd	}|S dS )
a  
        Parses the given URI and creates a ndarray from it.

        Parameters
        ----------
        index : int
            If the ImageResource contains multiple ndimages, and index is an
            integer, select the index-th ndimage from among them and return it.
            If index is an ellipsis (...), read all ndimages in the file and
            stack them along a new batch dimension and return them. If index is
            None, this plugin reads the first image of the file (index=0) unless
            the image is a GIF or APNG, in which case all images are read
            (index=...).
        mode : str
            Convert the image to the given mode before returning it. If None,
            the mode will be left unchanged. Possible modes can be found at:
            https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
        rotate : bool
            If set to ``True`` and the image contains an EXIF orientation tag,
            apply the orientation before returning the ndimage.
        apply_gamma : bool
            If ``True`` and the image contains metadata about gamma, apply gamma
            correction to the image.
        as_gray : bool
            Deprecated. Exists to raise a constructive error message.

        Returns
        -------
        ndimage : ndarray
            A numpy array containing the loaded image data

        Notes
        -----
        If you open a GIF - or any other format using color pallets - you may
        wish to manually set the `mode` parameter. Otherwise, the numbers in
        the returned image will refer to the entries in the color pallet, which
        is discarded during conversion to ndarray.

        NzDThe keyword `as_gray` is no longer supported.Use `mode='L'` instead.GIF
image/apngr   r   rO   rP   c                 S   s   g | ]}|qS r   r   ).0imr   r   r"   
<listcomp>   s     z%PillowPlugin.read.<locals>.<listcomp>r%   )	TypeErrorr;   formatEllipsiscustom_mimetype
isinstanceintseek_apply_transformsiterr'   stack)rI   rN   r   rO   rP   rQ   imageiteratorr   r   r"   r<   z   s"    +
zPillowPlugin.readrT   )r   rO   rP   r   c                c   s(   t | jD ]}| ||||V  qdS )a  
        Iterate over all ndimages/frames in the URI

        Parameters
        ----------
        mode : {str, None}
            Convert the image to the given mode before returning it. If None,
            the mode will be left unchanged. Possible modes can be found at:
            https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
        rotate : {bool}
            If set to ``True`` and the image contains an EXIF orientation tag,
            apply the orientation before returning the ndimage.
        apply_gamma : {bool}
            If ``True`` and the image contains metadata about gamma, apply gamma
            correction to the image.
        N)r   r	   r;   r_   )rI   r   rO   rP   rV   r   r   r"   r`      s    zPillowPlugin.iterc           
      C   s   |d k	r| |}n|jdkr,| |jj}t|}| j| j dd}|rpd|krpt	|d | jj}||}|rd|krt
|d }t
|jtjkrdnd}d}	|| | | |	 d	 }t|tj}|S )
NrR   FrN   exclude_appliedOrientationgammai      g      ?g<Nё\?)convertrY   paletter   r'   asarraymetadatar;   tellr5   floatdtypeZuint16roundZastypeZuint8)
rI   rb   r   rO   rP   metaZtransformationrg   ZscaleZgainr   r   r"   r_      s&    

 zPillowPlugin._apply_transforms)r   rY   is_batch)ndimager   rY   rr   r   c                K   s  d|krt d| jjp| jj}d|p0t | i}t|trRtj	|dd}d}n
t
|}|dk	rfn|dk	rt|dkr|jd	kn|jd
k}nT|jd
krd}nD|jd	kr|jd dkrtdn"|jd	kr|jd dkrd}nd}|s|d }t }|D ]:}	tj|	|d}
d|kr,|
jd
|d  d}
||
 q|d |dd  }}|rdd|d< ||d< || |j| j f| | jjtkrtt| j }| S dS )aH  
        Write an ndimage to the URI specified in path.

        If the URI points to a file on the current host and the file does not
        yet exist it will be created. If the file exists already, it will be
        appended if possible; otherwise, it will be replaced.

        If necessary, the image is broken down along the leading dimension to
        fit into individual frames of the chosen format. If the format doesn't
        support multiple frames, and IOError is raised.

        Parameters
        ----------
        image : ndarray or list
            The ndimage to write. If a list is given each element is expected to
            be an ndimage.
        mode : str
            Specify the image's color format. If None (default), the mode is
            inferred from the array's shape and dtype. Possible modes can be
            found at:
            https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
        format : str
            Optional format override. If omitted, the format to use is
            determined from the filename extension. If a file object was used
            instead of a filename, this parameter must always be used.
        is_batch : bool
            Explicitly tell the writer that ``image`` is a batch of images
            (True) or not (False). If None, the writer will guess this from the
            provided ``mode`` or ``image.shape``. While the latter often works,
            it may cause problems for small images due to aliasing of spatial
            and color-channel axes.
        kwargs : ...
            Extra arguments to pass to pillow. If a writer doesn't recognise an
            option, it is silently ignored. The available options are described
            in pillow's `image format documentation
            <https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html>`_
            for each writer.

        Notes
        -----
        When writing batches of very narrow (2-4 pixels wide) gray images set
        the ``mode`` explicitly to avoid the batch being identified as a colored
        image.

        ZfpszvThe keyword `fps` is no longer supported. Use `duration`(in ms) instead, e.g. `fps=50` == `duration=20` (1000 * 1/50).rY   r   r%   TNr   r-   r   Fr   z*Can't write images with one color channel.)r   r-   r/   )N.)r   bits)colorsZsave_allZappend_images)rX   r7   rA   rB   r   rG   r\   listr'   ra   rk   r4   ndimshape
ValueErrorZ	fromarrayquantizeappendupdatesaver@   r>   r?   r   r   r   getvalue)rI   rs   r   rY   rr   kwargsrA   Z	save_argsZ
pil_framesframeZ	pil_frameZprimary_imageZother_imagesfiler   r   r"   write   sT    6 

 



zPillowPlugin.writer   )rN   c                C   s   | j |ddS )NFrd   )rl   )rI   rN   r   r   r"   get_meta_  s    zPillowPlugin.get_metaT)rN   re   r   c                 C   s   |dkr0| j jdkrt}n| j jdkr,t}nd}t|trT| j  |krT| j | | j j	 }| j j
|d< | j j|d< | j j
dkr| j j|d< | j  rd	d
 t| j   D }|dd || |r|dd |S )a  Read ndimage metadata.

        Parameters
        ----------
        index : {integer, None}
            If the ImageResource contains multiple ndimages, and index is an
            integer, select the index-th ndimage from among them and return its
            metadata. If index is an ellipsis (...), read and return global
            metadata. If index is None, this plugin reads metadata from the
            first image of the file (index=0) unless the image is a GIF or APNG,
            in which case global metadata is read (index=...).

        Returns
        -------
        metadata : dict
            A dictionary of format-specific metadata.

        NrR   rS   r   r   rx   Prj   c                 S   s    i | ]\}}t j|d |qS )unknown)r   ZTAGSget)rU   keyvaluer   r   r"   
<dictcomp>  s    z)PillowPlugin.metadata.<locals>.<dictcomp>r   rf   )r;   rY   rZ   r[   r\   r]   rm   r^   infocopyr   sizerj   Zgetexifdictitemspopr|   )rI   rN   re   rl   Z	exif_datar   r   r"   rl   b  s,    

zPillowPlugin.metadata)rN   r   c           	      C   s   |dkr0| j jdkrt}n| j jdkr,t}nd}|tkrF| j d n| j | | j jdkrj| j jj}n| j j}| j j}| j j}||f}| j j	}|dkr|f|}t
t|d}|j}t|dkr||dd }t||j|tkrdnd	d
S )a  Standardized ndimage metadata
        Parameters
        ----------
        index : int
            If the ImageResource contains multiple ndimages, and index is an
            integer, select the index-th ndimage from among them and return its
            properties. If index is an ellipsis (...), read and return the
            properties of all ndimages in the file stacked along a new batch
            dimension. If index is None, this plugin reads and returns the
            properties of the first image (index=0) unless the image is a GIF or
            APNG, in which case it reads and returns the properties all images
            (index=...).

        Returns
        -------
        properties : ImageProperties
            A dataclass filled with standardized image metadata.

        Notes
        -----
        This does not decode pixel data and is 394fast for large images.

        NrR   rS   r   .)r   r   r   TF)rx   ro   rr   )r;   rY   rZ   r[   r^   rj   r   widthheightn_framesr'   rk   r   newrx   lenr   ro   )	rI   rN   r   r   r   rx   r   dummyZ	pil_shaper   r   r"   
properties  s6    
zPillowPlugin.properties)NT)N)__name__
__module____qualname__r   r:   rL   r'   Zndarrayr<   strboolr	   r`   r_   r
   r   r   r   bytesr   r   r   r   r]   rl   r   r   __classcell__r   r   rJ   r"   r6   >   sN   5    D    r    
5r6   )"__doc__ior   typingr   r   r   r   r   r   r	   r
   r   Znumpyr'   ZPILr   r   r   r   Zcore.requestr   r   r   r   Zcore.v3_plugin_apir   r   rC   r   r]   r   r5   r6   r   r   r   r"   <module>   s   ,