U
    7c                     @   s  d Z ddlZddlZddlZddlmZ ddlZddlZddl	Z
ddlZddlmZmZmZ ddlmZ ddlT ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZm Z m!Z! e"e#Z$ej%ej%ej%ej&ej'ej(ej)ej*ej+ej,ej-ej.ej/ej0ej1ej2ej3ej4ej5d	Z6e7e6Z8d0ddZ9d1ddZ:dddddZ;dd Z<G dd dej=ej>Z?G dd de?Z@G dd de@ZAG dd de@ZBG dd de?ZCG dd  d e?ZDd2d!d"ZEd3ddd$d%d&ZFd'd( ZGd)d* ZHd4d.d/ZIdS )5zR
The image module supports basic image loading, rescaling and display
operations.
    N)Path)_apicbookcm)_image)*)FigureCanvasBase)Affine2DBboxBaseBboxBboxTransformBboxTransformToIdentityTransformTransformedBbox)antialiasednonenearestbilinearZbicubicZspline16Zspline36hanningZhammingZhermiteZkaiserZquadricZcatromZgaussianZbesselZmitchellZsincZlanczosZblackman      ?c              	   C   sL  t | dkr"tjdtjdddfS g }g }| D ]t}|||\}}}}	|dk	r.||9 }||9 }||||| f |t||g||jd  ||jd  gg q.t |dkrtjdtjdddfS t	|}
tj
t|
jt|
jdftjd}|D ]>\}}}}t ||
j ||
j }	tj|||	tjd|d q||
j| |
j| fS )	a-  
    Composite a number of RGBA images into one.  The images are
    composited in the order in which they appear in the *images* list.

    Parameters
    ----------
    images : list of Images
        Each must have a `make_image` method.  For each image,
        `can_composite` should return `True`, though this is not
        enforced by this function.  Each image must have a purely
        affine transformation with no shear.

    renderer : `.RendererBase`

    magnification : float, default: 1
        The additional magnification to apply for the renderer in use.

    Returns
    -------
    image : uint8 array (M, N, 4)
        The composited RGBA image.
    offset_x, offset_y : float
        The (left, bottom) offset where the composited image should be placed
        in the output figure.
    r   )r   r      dtypeN   r   Fresamplealpha)lennpemptyuint8
make_imageappend_get_scalar_alphar   shapeunionzerosintheightwidthr	   	translatex0y0r   r   NEAREST)ZimagesrenderermagnificationpartsZbboxesimagedataxytransbboxoutputr    r8   4/tmp/pip-unpacked-wheel-bcsgmve3/matplotlib/image.pycomposite_images9   s6    &
  r:   c                    s   t dd |D }|dk	r|n }|s.|sD|D ]}| q2nlg    fdd}|D ]B}t|tr| r| r| s 	| qf|  | qf|  dS )a  
    Draw a sorted list of artists, compositing images into a single
    image where possible.

    For internal Matplotlib use only: It is here to reduce duplication
    between `Figure.draw` and `Axes.draw`, but otherwise should not be
    generally useful.
    c                 s   s   | ]}t |tV  qd S N)
isinstance
_ImageBase.0r3   r8   r8   r9   	<genexpr>{   s     z0_draw_list_compositing_images.<locals>.<genexpr>Nc                     s   t  dkr d  njt  dkrt \} }}| jdkr }|j |  	|t
|t
||  |   d d = d S )Nr   r   )r   drawr:   sizenew_gcZset_clip_rectangler6   Zset_clip_pathget_clip_path
draw_imageroundrestore)r2   lbgcZimage_groupZmagparentr.   r8   r9   flush_images   s    
z3_draw_list_compositing_images.<locals>.flush_images)
anyZoption_image_nocompositerA   get_image_magnificationr<   r=   can_compositeget_clip_onrD   r"   )r.   rL   ZartistsZsuppress_compositeZ
has_imagesZnot_compositearM   r8   rK   r9   _draw_list_compositing_imagesq   s(    
rS   r   r   c                C   s
  d}|j d dkrdt|jdd tt|j d d }|dddd|f }t |d| }|j d dkrt|jd	d tt|j d d }|dd|ddf }t d|| }| 	 }|d
krt
ddg|j d |j d gg}	||	}
tt|
dddf }tt|
dddf }|d|j d  ksr||j d ksr|d|j d  kr|d|j d  ks||j d ks|d|j d  krd}nd}t||j dd  |j}|dkr|  }t|||t| |||  |   |S )a  
    Convenience wrapper around `._image.resample` to resample *data* to
    *out_shape* (with a third dimension if *data* is RGBA) that takes care of
    allocating the output array and fetching the relevant properties from the
    Image object *image_obj*.
    zData with more than {n} cannot be accurately displayed. Downsampling to less than {n} before displaying. To remove this warning, manually downsample your data.r   i   z2**23 columns)nNr   i   z
2**24 rowsr         r   r   )r$   warningswarnformatr'   r   ceilr	   scaleget_interpolationarray	transformabsdiffr&   r   get_resampler   r   	_interpd_get_filternormget_filterrad)Z	image_objr2   	out_shaper^   r   r   msgstepinterpolationposZdispZdispxZdispyoutr8   r8   r9   	_resample   sR    
"


rk   c                 C   sz   t j| jd | jd df| jd}| |ddddddf< |jt jkr`d|dddddf< nd|dddddf< |S )	z\
    Convert an RGB image to RGBA, as required by the image resample C++
    extension.
    r   r   r   r   NrU      r   )r   r&   r$   r   r    )Argbar8   r8   r9   _rgb_to_rgba   s    "ro   c                       s   e Zd ZdZdZd;dddd	Zd
d Z fddZdd Zdd Z	dd Z
dd Zd<ddZd=ddZdd Zejdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Z  Z S )>r=   a  
    Base class for images.

    interpolation and cmap default to their rc settings

    cmap is a colors.Colormap instance
    norm is a colors.Normalize instance to map luminance to 0-1

    extent is data axes (left, right, bottom, top) for making image plots
    registered with data plots.  Default is to label the pixel
    centers with the zero-based row and column indices.

    Additional kwargs are matplotlib.artist properties
    r   NT      @Finterpolation_stagec	                K   s   t j|  tj| || |d kr.tjd }tjddg|d || _	| 
| | | | | | |	 | | || _d | _| |
 d S )Nimage.originupperlower)origin)martistArtist__init__r   ScalarMappablemplrcParamsr   check_in_listrv   set_filternormset_filterradset_interpolationset_interpolation_stageset_resampleaxes_imcache_internal_update)selfaxcmapnormrh   rv   
filternorm	filterradr   rr   kwargsr8   r8   r9   ry      s    





z_ImageBase.__init__c                 C   sD   z |   }t| j d|dW S  tk
r>   t| j Y S X d S )Nz(size=))get_sizetype__name__RuntimeError)r   rB   r8   r8   r9   __str__  s
    z_ImageBase.__str__c                    s   t   dd iS )Nr   )super__getstate__r   	__class__r8   r9   r     s    z_ImageBase.__getstate__c                 C   s"   | j dkrtd| j jdd S )z9Return the size of the image as tuple (numrows, numcols).N"You must first set the image arrayrV   )_Ar   r$   r   r8   r8   r9   r     s    
z_ImageBase.get_sizec                 C   s.   t j| | t|dkr$tdd| _dS )z
        Set the alpha value used for blending - not supported on all backends.

        Parameters
        ----------
        alpha : float or 2D array-like or None
        )r   rV   z5alpha must be a float, two-dimensional array, or NoneN)rw   rx   Z_set_alpha_for_arrayr   ndim	TypeErrorr   )r   r   r8   r8   r9   	set_alpha&  s    z_ImageBase.set_alphac                 C   s$   | j dkst| j dkrdS | j S )a  
        Get a scalar alpha value to be applied to the artist as a whole.

        If the alpha value is a matrix, the method returns 1.0 because pixels
        have individual alpha values (see `~._ImageBase._make_image` for
        details). If the alpha value is a scalar, the method returns said value
        to be applied to the artist as a whole because pixels do not have
        individual alpha values.
        Nr   r   )Z_alphar   r   r   r8   r8   r9   r#   4  s    
z_ImageBase._get_scalar_alphac                 C   s   d| _ tj|  dS )zU
        Call this whenever the mappable is changed so observers can update.
        N)r   r   rz   changedr   r8   r8   r9   r   A  s    z_ImageBase.changedr   c           -   
   C   s@  |dkrt d|jdkr"t dt||}|dkr:dS |j| }	|j| }
|	dks^|
dkrbdS | jdkrt d|j	d  
dd}nt }|t 
|j|j	d  |j|j	d  |j|j|   7 }|t |j |j 
| }|jrb|rb|	d	 d
ks|
d	 d
krbt|	}t|
}||	 |	 }||
 |
 }|t 
d	| d	| 7 }nt|	}t|
}||f}|sr|jdks|jdkr|j	d dkstd|j	 d|jdkr| jdkr| }| }|tjjkrtdtd }}|jjdkr`t|jjdkr,tjntj }|j|jjk rt!"d|j d| d n.|#tj|#tj }|dkrtjntj }tj$||d}| j%&| t| j%j't| j%j( }t| j%j(|d  }|tjkrdnd}|||  }||k r
d}n
t|}|||  }||kr0d}n
t|}|dk	sN|dk	r`tj)||||d d}d}| j%j(| j%j' }}|tjjkr|| }}tj$||g|d} ||8 }| |8 } |#|* }|#|* }||kr||| |  }| || |  } ||7 }| |7 } t+| |||}!~|!|8 }!| |8 } ||krT|!|| | 9 }!| || | 9 } |!|7 }!| |7 } t,| j%t-j.r|!#|j}!|j/j	|j	krt0|j/t tj1t dnt2|tj }"t+| |"||dd}#~"t3|#}$d|#|$< | 4 }%|%dk	rt|%dkr|#t+| |%||dd9 }#tj5|!|$}&| \}'}(t,| j%t-j6rV|'dkrVt7|j8}'| j%j9: . t;j<| j%|'|(d | %|&})W 5 Q R X W 5 Q R X n|jdkr| j%&| | =|}|j	d dkrt>|}| ? }%t+| |d  |||%d!}*t+| t>|d"ddf |||%d!})|*|)d < | j=|)dd#d$})|jdkr0| ? }%|)dddddf }+|+#tj |# |% |+dd< n| j@dkr| j=|d|jdkd$| _@| j@})tA||B C },|)tt|,jDdtt|,jEd |)j	d tt|,jFdtt|,jGd |)j	d f })t tt|,jFdtt|,jDd| }|)|j|j|fS )%a  
        Normalize, rescale, and colormap the image *A* from the given *in_bbox*
        (in data space), to the given *out_bbox* (in pixel space) clipped to
        the given *clip_bbox* (also in pixel space), and magnified by the
        *magnification* factor.

        *A* may be a greyscale image (M, N) with a dtype of float32, float64,
        float128, uint16 or uint8, or an (M, N, 4) RGBA image with a dtype of
        float32, float64, float128, or uint8.

        If *unsampled* is True, the image will not be scaled, but an
        appropriate affine transformation will be returned instead.

        If *round_to_pixel_border* is True, the output image size will be
        rounded to the nearest pixel boundary.  This makes the images align
        correctly with the axes.  It should not be used if exact scaling is
        needed, such as for `FigureImage`.

        Returns
        -------
        image : (M, N, 4) uint8 array
            The RGBA image, resampled unless *unsampled* is True.
        x, y : float
            The upper left corner where the image should be drawn, in pixel
            space.
        trans : Affine2D
            The affine transformation from image to pixel space.
        Nz9You must first set the image array or the image attributer   zk_make_image must get a non-empty image. Your Artist's draw method must filter before this method is called.)Nr   r   Nrt   r   r   g        rV   rU   rU   r   zInvalid shape z for image datarn   fr   zCasting input data from z to z for imshow.g    חAr   g    cAg     @)rj   皙?g?T)r   )vminvmax).rU   )r   .Fbytesr   )Hr   rB   r   intersectionr)   r(   rv   r	   r*   r$   r[   r   r+   r,   get_transform	is_affinemathrZ   r'   r   
ValueError_interpolation_stageminmaxr   maZmaskedZint32r   kinditemsizefloat64float32r   warn_externalastyper]   r   Zautoscale_Noner   r   clipitemrk   r<   mcolorsZNoNormmaskwherenanZ	ones_likeisnanZ	get_alphaZmasked_arrayZLogNormZfinfoeps	callbacksZblockedr   Z_setattr_cmto_rgbaro   r#   r   r   invertedfrozenyminymaxxminxmax)-r   rm   Zin_bboxZout_bboxZ	clip_bboxr/   	unsampledround_to_pixel_borderZclipped_bboxZout_width_baseZout_height_baset0tZ	out_widthZ
out_heightZextra_widthZextra_heightre   Za_minZa_maxZscaled_dtypedaZA_scaledZdvZvmidZfactZnewminZnewmaxoffsetfracr   r   ZvrangeZA_resampledr   Z	out_alphaZout_maskr   Zresampled_maskedZs_vminZs_vmaxr7   Zoutput_alphaZalpha_channelZsubsetr8   r8   r9   _make_imageH  sT   



   



(	






"

  
         z_ImageBase._make_imagec                 C   s   t ddS )am  
        Normalize, rescale, and colormap this image's data for rendering using
        *renderer*, with the given *magnification*.

        If *unsampled* is True, the image will not be scaled, but an
        appropriate affine transformation will be returned instead.

        Returns
        -------
        image : (M, N, 4) uint8 array
            The RGBA image, resampled unless *unsampled* is True.
        x, y : float
            The upper left corner where the image should be drawn, in pixel
            space.
        trans : Affine2D
            The affine transformation from image to pixel space.
        z(The make_image method must be overriddenNNotImplementedError)r   r.   r/   r   r8   r8   r9   r!   M  s    z_ImageBase.make_imagec                 C   s   dS )z|
        Return whether the image is better to be drawn unsampled.

        The derived class needs to override it.
        Fr8   r   r8   r8   r9   _check_unsampled_imagea  s    z!_ImageBase._check_unsampled_imagec           	      O   s  |   sd| _d S |  jdkr*d| _d S | }| | ||   || 	  |
|   | r|  r|  jr| j|dd\}}}}|d k	rt |jd |jd | }|||||| n2| || \}}}}|d k	r||||| |  d| _d S )NFr   Tr   r   )get_visiblestale	get_arrayrB   rC   Z_set_gc_clipr   r#   Zset_urlget_urlZset_gidZget_gidZoption_scale_imager   r   r   r!   r	   r[   r$   rE   rO   rG   )	r   r.   argsr   rJ   imrH   rI   r5   r8   r8   r9   rA   i  s8    
 
z_ImageBase.drawc                 C   s   |  |\}}|dk	r||fS | j|jk	r2di fS |   }||j|jg\}}|  \}}}	}
||krv|| }}|	|
kr|
|	 }	}
|dk	r|dk	r||  ko|kn  o|	|  ko|
kn  }nd}|i fS z7Test whether the mouse event occurred within the image.NF)	_default_containsr   Zinaxesr   r   r^   r3   r4   
get_extent)r   
mouseeventinsideinfor5   r3   r4   r   r   r   r   r8   r8   r9   contains  s     

2z_ImageBase.containsc                 C   sF   | j | jdkr| jddd n| jddd}tj|j|dd dS )z$Write the image to png file *fname*.ru   Nr   Tr   png)rY   )r   rv   r   PILImageZ	fromarraysave)r   fnamer   r8   r8   r9   	write_png  s
    " z_ImageBase.write_pngc                 C   sp  t |tjjrt|}tj|dd| _| jjtj	krXt
| jjtdsXtd| jj| jjdkr| jjd dkr| jddddd	f | _| jjd
ks| jjdkr| jjd dkstd| jj| jjdkr`t| jjtjrdnd}| j d	k s|| j k r,td t| jd	|| _| jjtj	kr`t| jjtjr`| jtj	| _d| _d| _dS )z
        Set the image array.

        Note that this function does *not* update the normalization used.

        Parameters
        ----------
        A : array-like or `PIL.Image.Image`
        TcopyZ	same_kindz3Image data of dtype {} cannot be converted to floatrU   r   r   Nr   rV   r   zInvalid shape {} for image datarl   zmClipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).)r<   r   r   pil_to_arrayr   safe_masked_invalidr   r   r   r    Zcan_castfloatr   rY   r   r$   Z
issubdtypeintegerr   r   _logwarningr   r   r   r   )r   rm   highr8   r8   r9   set_data  s@    

 z_ImageBase.set_datac                 C   s   |  | dS )z
        Retained for backwards compatibility - use set_data instead.

        Parameters
        ----------
        A : array-like
        N)r   r   rm   r8   r8   r9   	set_array  s    
z_ImageBase.set_arrayc                 C   s   | j S )a@  
        Return the interpolation method the image uses when resizing.

        One of 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16',
        'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
        'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos',
        or 'none'.
        )_interpolationr   r8   r8   r9   r\     s    	z_ImageBase.get_interpolationc                 C   s8   |dkrt jd }| }tjt|d || _d| _dS )a@  
        Set the interpolation method the image uses when resizing.

        If None, use :rc:`image.interpolation`. If 'none', the image is
        shown as is without interpolating. 'none' is only supported in
        agg, ps and pdf backends and will fall back to 'nearest' mode
        for other backends.

        Parameters
        ----------
        s : {'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None
        Nzimage.interpolationrh   T)r{   r|   ru   r   r}   rb   r   r   r   sr8   r8   r9   r     s    
z_ImageBase.set_interpolationc                 C   s.   |dkrd}t jddg|d || _d| _dS )z
        Set when interpolation happens during the transform to RGBA.

        Parameters
        ----------
        s : {'data', 'rgba'} or None
            Whether to apply up/downsampling interpolation in data or rgba
            space.
        Nr2   rn   )r   T)r   r}   r   r   r   r8   r8   r9   r   
  s
    
z"_ImageBase.set_interpolation_stagec                 C   s   |   }| jdko|jo|jS )z>Return whether the image can be composited with its neighbors.r   )r   r   r   Zis_separable)r   r5   r8   r8   r9   rP     s    
z_ImageBase.can_compositec                 C   s"   |dkrt jd }|| _d| _dS )z
        Set whether image resampling is used.

        Parameters
        ----------
        v : bool or None
            If None, use :rc:`image.resample`.
        Nzimage.resampleT)r{   r|   rk   r   )r   vr8   r8   r9   r   "  s    	
z_ImageBase.set_resamplec                 C   s   | j S )z(Return whether image resampling is used.)rk   r   r8   r8   r9   ra   0  s    z_ImageBase.get_resamplec                 C   s   t || _d| _dS )z
        Set whether the resize filter normalizes the weights.

        See help for `~.Axes.imshow`.

        Parameters
        ----------
        filternorm : bool
        TN)bool_filternormr   )r   r   r8   r8   r9   r~   4  s    

z_ImageBase.set_filternormc                 C   s   | j S )z8Return whether the resize filter normalizes the weights.)r   r   r8   r8   r9   rc   A  s    z_ImageBase.get_filternormc                 C   s(   t |}|dkrtd|| _d| _dS )z
        Set the resize filter radius only applicable to some
        interpolation schemes -- see help for imshow

        Parameters
        ----------
        filterrad : positive float
        r   z+The filter radius must be a positive numberTN)r   r   
_filterradr   )r   r   rr8   r8   r9   r   E  s
    	z_ImageBase.set_filterradc                 C   s   | j S )zReturn the filterrad setting.)r   r   r8   r8   r9   rd   T  s    z_ImageBase.get_filterrad)NNNNTrp   F)r   FT)r   F)!r   
__module____qualname____doc__zorderry   r   r   r   r   r#   r   r   r!   r   rw   Zallow_rasterizationrA   r   r   r   r   r\   r   r   rP   r   ra   r~   rc   r   rd   __classcell__r8   r8   r   r9   r=      sT          	    
  

0r=   c                	       sj   e Zd ZdZejdddddd	 fd
dZdddZdddZdd Z	dd Z
dd Zdd Z  ZS )	AxesImagea>	  
    An image attached to an Axes.

    Parameters
    ----------
    ax : `~.axes.Axes`
        The axes the image will belong to.
    cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
        The Colormap instance or registered colormap name used to map scalar
        data to colors.
    norm : str or `~matplotlib.colors.Normalize`
        Maps luminance to 0-1.
    interpolation : str, default: :rc:`image.interpolation`
        Supported values are 'none', 'antialiased', 'nearest', 'bilinear',
        'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
        'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
        'sinc', 'lanczos', 'blackman'.
    interpolation_stage : {'data', 'rgba'}, default: 'data'
        If 'data', interpolation
        is carried out on the data provided by the user.  If 'rgba', the
        interpolation is carried out after the colormapping has been
        applied (visual interpolation).
    origin : {'upper', 'lower'}, default: :rc:`image.origin`
        Place the [0, 0] index of the array in the upper left or lower left
        corner of the axes. The convention 'upper' is typically used for
        matrices and images.
    extent : tuple, optional
        The data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.
    filternorm : bool, default: True
        A parameter for the antigrain image resize filter
        (see the antigrain documentation).
        If filternorm is set, the filter normalizes integer values and corrects
        the rounding errors. It doesn't do anything with the source floating
        point values, it corrects only integers according to the rule of 1.0
        which means that any sum of pixel weights must be equal to 1.0. So,
        the filter function must produce a graph of the proper shape.
    filterrad : float > 0, default: 4
        The filter radius for filters that have a radius parameter, i.e. when
        interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
    resample : bool, default: False
        When True, use a full resampling method. When False, only resample when
        the output image is larger than the input image.
    **kwargs : `.Artist` properties
    3.6r   nameNTrp   Frq   c
                   s0   || _ t j|f|||||||	|
d| d S )N)r   r   rh   rv   r   r   r   rr   )_extentr   ry   )r   r   r   r   rh   rv   extentr   r   r   rr   r   r   r8   r9   ry     s    
zAxesImage.__init__c                 C   s.   | j \}}}}t||||g}|| jjS r;   )r  r   Zfrom_extentsZtransformedr   Z	transData)r   r.   r+   x1r,   y1r6   r8   r8   r9   get_window_extent  s    zAxesImage.get_window_extentr   c                 C   st   |   }|  \}}}}tt||g||gg}	t|	|}
|  rT|  pZ| jj	n| j
j	}| j| j|	|
|||dS )Nr   )r   r   r   r   r]   r   rQ   Zget_clip_boxr   r6   figurer   r   )r   r.   r/   r   r5   r  Zx2r  y2r6   Ztransformed_bboxr   r8   r8   r9   r!     s    
 zAxesImage.make_imagec                 C   s   |   dkS )z9Return whether the image would be better drawn unsampled.r   )r\   r   r8   r8   r9   r     s    z AxesImage._check_unsampled_imagec                 C   s   | | _ \}}}}||f||ff}| j| ||g| jjdd< ||g| jjdd< | j rt| jj||fdd | j r| jj	||fdd d| _
dS )a(  
        Set the image extent.

        Parameters
        ----------
        extent : 4-tuple of float
            The position and size of the image as tuple
            ``(left, right, bottom, top)`` in data coordinates.

        Notes
        -----
        This updates ``ax.dataLim``, and, if autoscaling, sets ``ax.viewLim``
        to tightly fit the image, regardless of ``dataLim``.  Autoscaling
        state is not changed, so following this with ``ax.autoscale_view()``
        will redo the autoscaling in accord with ``dataLim``.
        N)autoT)r  r   Zupdate_datalimZsticky_edgesr3   r4   Zget_autoscalex_onZset_xlimZget_autoscaley_onZset_ylimr   )r   r  r   r   r   r   Zcornersr8   r8   r9   
set_extent  s    

zAxesImage.set_extentc                 C   sV   | j dk	r| j S |  }|\}}| jdkr>d|d |d dfS d|d d|d fS dS )<Return the image extent as tuple (left, right, bottom, top).Nrt               ?)r  r   rv   )r   sznumrowsnumcolsr8   r8   r9   r     s    

zAxesImage.get_extentc                 C   s   |   \}}}}| jdkr$|| }}|  }t||g||gg}tddg|jd |jd gg}|   }	|	t||d7 }	|	|j	|j
g}
tt|
rdS |
t\}}d|  kr|jd k rn nd|  kr|jd k sn dS |||f S dS )z
        Return the image value at the event position or *None* if the event is
        outside the image.

        See Also
        --------
        matplotlib.artist.Artist.get_cursor_data
        rt   r   r   )ZboxinZboxoutN)r   rv   r   r   r$   r   r   r   r^   r3   r4   rN   r   r   r   r'   )r   eventr   r   r   r   arrZdata_extentZarray_extentr5   Zpointjir8   r8   r9   get_cursor_data  s    	

 :zAxesImage.get_cursor_data)NNNNNTrp   F)N)r   F)r   r   r   r   r   make_keyword_onlyry   r  r!   r   r
  r   r  r   r8   r8   r   r9   r   Y  s&   /        


r   c                       s   e Zd ZdZdd fdd
Zdd Zdd	d
Zdd Zdd Z fddZ	dd Z
dd Zdd Z fddZ fddZ  ZS )NonUniformImageFr   r   c                   s   t  j|f| | | dS )z
        Parameters
        ----------
        interpolation : {'nearest', 'bilinear'}, default: 'nearest'

        **kwargs
            All other keyword arguments are identical to those of `.AxesImage`.
        N)r   ry   r   )r   r   rh   r   r   r8   r9   ry     s    	zNonUniformImage.__init__c                 C   s   dS )z)Return False. Do not use unsampled image.Fr8   r   r8   r8   r9   r     s    z&NonUniformImage._check_unsampled_imager   c                 C   s  | j d krtd|rtd| j }|jdkr|jtjkrJ| j|dd}n8t|d d d d tj	f dd}d|d d d d df< n|jtjkrd| 
tj}|jd dkrtt|jd	d dtj}||d d d d d	df< d|d d d d df< |}| jj}| jjj\}}}	}
tt|	d
 t|d
  | }tt|
d
 t|d
  | }t|j|j|}t|j|j|}| jdkr(| jd d | jdd   d }| jd d | jdd   d }||}||}t|tj  tj!"||jd  | tj#||df}nt$| j|d d	t%| jd }t$| j|d d	t%| jd }tj!"||jd  |}t$tj&|| j|  t'| j| tj(dd	d}t$tj&|| j|  t'| j| tj(dd	d}t"d| d| }t"|d| }t"d| |}t"||}t)||dftj}t*dD ]}|d d d d |f #d}|||  }||||jd d  |  7 }|||dd  |  7 }||||jd d d  |  7 }||d d d d |f< qH|||t+ fS )Nr   z*unsampled not supported on NonUniformImagerV   Tr   r   rl   rU   r   r  r   r   r   r   )r   ),r   r   r   r   r   r   r    r   repeatZnewaxisr   r$   r&   tupler   viewLimr6   extentsr'   rF   linspacer+   r  r,   r  r   _Ax_AysearchsortedZascontiguousarrayviewuint32raveladdouterreshaper   r   divider`   r   r   ranger   )r   r.   r/   r   rm   BvlrH   rI   r   r   r)   r(   x_pixy_pixZx_midZy_midx_inty_intr   Zidx_intZx_fracZy_fracZf00Zf10Zf01Zf11Zchanacbufr8   r8   r9   r!     s    

"     

      "zNonUniformImage.make_imagec                 C   s   t |t j}t |t j}tj|dd}|j|j  krBdkr`n n|jdd |j|j kshtd|jdkrztd|jd	kr|jd d
krtd|jd	kr|jd dkr|jdd}|| _	|| _
|| _d| _d| _dS )a  
        Set the grid for the pixel centers, and the pixel values.

        Parameters
        ----------
        x, y : 1D array-like
            Monotonic arrays of shapes (N,) and (M,), respectively, specifying
            pixel centers.
        A : array-like
            (M, N) ndarray or masked array of values to be colormapped, or
            (M, N, 3) RGB array, or (M, N, 4) RGBA array.
        Tr   r   r   rV   zAxes don't match array shaperV   rU   zCan only plot 2D or 3D datarU   )r   rU   r   z?3D arrays must have three (RGB) or four (RGBA) color componentsr   ZaxisN)r   r]   r   r   r   r   r$   r   squeezer   r  r  r   r   r   r3   r4   rm   r8   r8   r9   r   Y  s     6
zNonUniformImage.set_datac                 G   s   t dd S NzMethod not supportedr   r   r   r8   r8   r9   r   y  s    zNonUniformImage.set_arrayc                    s(   |dk	r|dkrt dt | dS )z
        Parameters
        ----------
        s : {'nearest', 'bilinear'} or None
            If None, use :rc:`image.interpolation`.
        N)r   r   z?Only nearest neighbor and bilinear interpolations are supported)r   r   r   r   r   r8   r9   r   |  s    z!NonUniformImage.set_interpolationc                 C   s6   | j d krtd| jd | jd | jd | jd fS )NzMust set data firstr   r   )r   r   r  r  r   r8   r8   r9   r     s    
zNonUniformImage.get_extentc                 C   s   d S r;   r8   r   r8   r8   r9   r~     s    zNonUniformImage.set_filternormc                 C   s   d S r;   r8   r   r8   r8   r9   r     s    zNonUniformImage.set_filterradc                    s"   | j d k	rtdt | d S Nz'Cannot change colors after loading data)r   r   r   set_norm)r   r   r   r8   r9   r8    s    
zNonUniformImage.set_normc                    s"   | j d k	rtdt | d S r7  )r   r   r   set_cmap)r   r   r   r8   r9   r9    s    
zNonUniformImage.set_cmap)r   F)r   r   r   Z	mouseoverry   r   r!   r   r   r   r   r~   r   r8  r9  r   r8   r8   r   r9   r     s   
F r  c                       sZ   e Zd ZdZejdddd fdd	Zdd
dZdd Zdd Z	dd Z
dd Z  ZS )PcolorImagez
    Make a pcolor-style plot with an irregular rectangular grid.

    This uses a variation of the original irregular image code,
    and it is used by pcolorfast for the corresponding grid type.
    r   r   r   Nc                    s6   t  j|||d | | |dk	r2| ||| dS )a  
        Parameters
        ----------
        ax : `~.axes.Axes`
            The axes the image will belong to.
        x, y : 1D array-like, optional
            Monotonic arrays of length N+1 and M+1, respectively, specifying
            rectangle boundaries.  If not given, will default to
            ``range(N + 1)`` and ``range(M + 1)``, respectively.
        A : array-like
            The data to be color-coded. The interpretation depends on the
            shape:

            - (M, N) ndarray or masked array: values to be colormapped
            - (M, N, 3): RGB array
            - (M, N, 4): RGBA array

        cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
            The Colormap instance or registered colormap name used to map
            scalar data to colors.
        norm : str or `~matplotlib.colors.Normalize`
            Maps luminance to 0-1.
        **kwargs : `.Artist` properties
        )r   r   N)r   ry   r   r   )r   r   r3   r4   rm   r   r   r   r   r8   r9   ry     s    !
zPcolorImage.__init__r   Fc                 C   s  | j d krtd|rtd| jd krN| j| j dd}t|dddgd| _| j}t| jj	
 d}t|d	 tj}|d |k r| |dd
gd d f< |d d dd
gf< | jjj\}}}	}
t|	d t|d  }t|
d t|d  }tt|| }tt|| }| jj}t|j|j|}t|j|j|}| j|}| j|}|tj tj ||j!d  | tj"||df}|||t# fS )Nr   z&unsampled not supported on PColorImageTr  )r   r   )r   r   Zconstantr   rl   r   r  r   r   )$r   r   r   r   r   r   padr   r   patchZget_facecolorr]   r   r    allr6   r  rF   r'   r  r  r+   r  r,   r  r  r   r  r!  r"  r#  r$  r%  r$   r&  r   )r   r.   r/   r   rm   Zpadded_AbgrH   rI   r   r   r)   r(   r*  r+  r,  r-  r.  r   r8   r8   r9   r!     s>    

(zPcolorImage.make_imagec                 C   s   dS )NFr8   r   r8   r8   r9   r     s    z"PcolorImage._check_unsampled_imagec                 C   s  t j|dd}|dkr4tjd|jd d tjd}nt|tj }|dkrltjd|jd d tjd}nt|tj }|jdd |jd |jd fkrt	d|jdd |jd |jd ff |j
d	krt	d
|j
dkr|jd dkr|jdd}n|jd dkrt	d|d |d k rT|ddd }|dddddf }|d |d k r|ddd }|ddd }|| _|| _|| _d| _d| _dS )aq  
        Set the grid for the rectangle boundaries, and the data values.

        Parameters
        ----------
        x, y : 1D array-like, optional
            Monotonic arrays of length N+1 and M+1, respectively, specifying
            rectangle boundaries.  If not given, will default to
            ``range(N + 1)`` and ``range(M + 1)``, respectively.
        A : array-like
            The data to be color-coded. The interpretation depends on the
            shape:

            - (M, N) ndarray or masked array: values to be colormapped
            - (M, N, 3): RGB array
            - (M, N, 4): RGBA array
        Tr   Nr   r   r   rV   z2Axes don't match array shape. Got %s, expected %s.r1  zA must be 2D or 3DrU   r   r2  r   z+3D arrays must have RGB or RGBA as last dim)r   r   r   Zaranger$   r   r]   r#  rB   r   r   r3  r   r  r  r   r   r4  r8   r8   r9   r     s>    " 
zPcolorImage.set_datac                 G   s   t dd S r5  r   r6  r8   r8   r9   r   &  s    zPcolorImage.set_arrayc                 C   s   |j |j }}|| jd k sF|| jd ksF|| jd k sF|| jd krJd S t| j|d }t| j|d }z| j||f W S  tk
r   Y d S X d S )Nr   r   r   )ZxdataZydatar  r  r   r   r   
IndexError)r   r  r3   r4   r  r  r8   r8   r9   r  )  s    zPcolorImage.get_cursor_data)NNNNN)r   F)r   r   r   r   r   r  ry   r!   r   r   r   r  r   r8   r8   r   r9   r:    s        %
!6r:  c                       sR   e Zd ZdZdZdZejdddd fdd		Zd
d Z	dddZ
dd Z  ZS )FigureImagezAn image attached to a figure.r   r   r   r   r   Nc                    s:   t  jd|||d || _|| _|| _| | d| _dS )
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        kwargs are an optional list of Artist keyword args
        N)r   r   rv   r   )r   ry   r  oxoyr   r/   )r   figr   r   ZoffsetxZoffsetyrv   r   r   r8   r9   ry   >  s    
zFigureImage.__init__c                 C   s8   |   \}}d| j |d | j d| j |d | j fS )r  r  r  )r   rB  rC  )r   r  r  r8   r8   r9   r   Y  s
     zFigureImage.get_extentr   Fc           	   	   C   s   |j | jj  }t| j| | j| g| j| | jjd  | j| | jjd  gg}| j \}}||j 9 }||j 9 }tddg||gg}| j| j||||| |ddS )Nr   r   F)r/   r   r   )	dpir  r   rB  rC  r   r$   Zget_size_inchesr   )	r   r.   r/   r   Zfacr6   r)   r(   r   r8   r8   r9   r!   _  s&    

     zFigureImage.make_imagec                 C   s   t j| | d| _dS )zSet the image array.TN)r   rz   r   r   r   r8   r8   r9   r   p  s    zFigureImage.set_data)NNr   r   N)r   F)r   r   r   r   r   r   r   r  ry   r   r!   r   r   r8   r8   r   r9   r@  7  s        
r@  c                       sL   e Zd ZdZejdddd fd	d
	ZdddZdd ZdddZ	  Z
S )	BboxImagez;The Image class whose size is determined by the given bbox.r   r   r   NTrp   Fc	           
   
      s,   t  jd|||||||d|	 || _dS )rA  N)r   r   rh   rv   r   r   r   )N)r   ry   r6   )
r   r6   r   r   rh   rv   r   r   r   r   r   r8   r9   ry   y  s     	zBboxImage.__init__c                 C   sF   |d kr|    }t| jtr&| jS t| jr:| |S tdd S )NzUnknown type of bbox)Z
get_figureZ_get_rendererr<   r6   r
   callabler   )r   r.   r8   r8   r9   r    s    

zBboxImage.get_window_extentc                 C   sT   |  |\}}|dk	r||fS |  s.di fS |j|j }}|  ||}|i fS r   )r   r   r3   r4   r  r   )r   r   r   r   r3   r4   r8   r8   r9   r     s    zBboxImage.containsr   c           	      C   sl   |  \}}| | }| j||g  _| |}tddg||gg}t|| _| j| j|||||dS )Nr   r   )	Zget_canvas_width_heightr  r   Z_pointsr   r   Z
_transformr   r   )	r   r.   r/   r   r)   r(   Zbbox_inZbbox_outr   r8   r8   r9   r!     s    

    zBboxImage.make_image)NNNNTrp   F)N)r   F)r   r   r   r   r   r  ry   r  r   r!   r   r8   r8   r   r9   rF  v  s          
rF  c              
   C   s  ddl m} |dkrt| trT|| }t|jdkr<d}qt| j	 dd }qt
| drdd}qt
| drt| jj	 dd }qd}n|}|dkrtjjntjj}t| trt|| jdkrtd|| ,}t|tjjrt|nt|W  5 Q R  S Q R X dS )	a  
    Read an image from a file into an array.

    .. note::

        This function exists for historical reasons.  It is recommended to
        use `PIL.Image.open` instead for loading images.

    Parameters
    ----------
    fname : str or file-like
        The image file to read: a filename, a URL or a file-like object opened
        in read-binary mode.

        Passing a URL is deprecated.  Please open the URL
        for reading and pass the result to Pillow, e.g. with
        ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.
    format : str, optional
        The image file format assumed for reading the data.  The image is
        loaded as a PNG file if *format* is set to "png", if *fname* is a path
        or opened file with a ".png" extension, or if it is an URL.  In all
        other cases, *format* is ignored and the format is auto-detected by
        `PIL.Image.open`.

    Returns
    -------
    `numpy.array`
        The image data. The returned array has shape

        - (M, N) for grayscale images.
        - (M, N, 3) for RGB images.
        - (M, N, 4) for RGBA images.

        PNG images are returned as float arrays (0-1).  All other formats are
        returned as int arrays, with a bit depth determined by the file's
        contents.
    r   )parseNr   r   geturlr  zPlease open the URL for reading and pass the result to Pillow, e.g. with ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.)urllibrH  r<   strurlparser   schemer   suffixru   hasattrr  r   PngImagePluginZPngImageFiler   openr   _pil_png_to_float_arrayr   )r   rY   rH  parsedextZimg_openr1   r8   r8   r9   imread  s0    '





rU  d   )metadata
pil_kwargsc             	   C   s  ddl m}
 t| tjr"t| } |dkrTt| trFt| jdd nt	j
d  }|dkr|	dk	rrtd| |
|dd	}|j|||||d
d |j| ||d
|d n|dkrt	j
d }|dkr|ddd }t|tr|jdkr|jdkr|jd dkr|}n&tj|d}||| |j|d
d}|	dkrBi }	|jd |jd f}tjd||dddd}|dkrd|	kr|rtd n`ddt	j di|dk	r|ni }tj  |	d< }| D ] \}}|dk	r| || q|dkr\d}t	j
d }t!"|d r$t	j
d! }t#d"d# t$%|D }tj&d$||}|'|| |}|	(d%| |	(d&||f |j)| f|	 dS )'a  
    Colormap and save an array as an image file.

    RGB(A) images are passed through.  Single channel images will be
    colormapped according to *cmap* and *norm*.

    .. note ::

       If you want to save a single channel image as gray scale please use an
       image I/O library (such as pillow, tifffile, or imageio) directly.

    Parameters
    ----------
    fname : str or path-like or file-like
        A path or a file-like object to store the image in.
        If *format* is not set, then the output format is inferred from the
        extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
        If *format* is set, it determines the output format.
    arr : array-like
        The image data. The shape can be one of
        MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
    vmin, vmax : float, optional
        *vmin* and *vmax* set the color scaling for the image by fixing the
        values that map to the colormap color limits. If either *vmin*
        or *vmax* is None, that limit is determined from the *arr*
        min/max value.
    cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
        A Colormap instance or registered colormap name. The colormap
        maps scalar data to colors. It is ignored for RGB(A) data.
    format : str, optional
        The file format, e.g. 'png', 'pdf', 'svg', ...  The behavior when this
        is unset is documented under *fname*.
    origin : {'upper', 'lower'}, default: :rc:`image.origin`
        Indicates whether the ``(0, 0)`` index of the array is in the upper
        left or lower left corner of the axes.
    dpi : float
        The DPI to store in the metadata of the file.  This does not affect the
        resolution of the output image.  Depending on file format, this may be
        rounded to the nearest integer.
    metadata : dict, optional
        Metadata in the image file.  The supported keys depend on the output
        format, see the documentation of the respective backends for more
        information.
    pil_kwargs : dict, optional
        Keyword arguments passed to `PIL.Image.Image.save`.  If the 'pnginfo'
        key is present, it completely overrides *metadata*, including the
        default 'Software' key.
    r   FigureNr   zsavefig.format)ZpdfZpsr   svgz'Cannot use 'pil_kwargs' when saving to F)rE  frameonT)r   r   r   rv   resize)rE  rY   ZtransparentrW  rs   ru   r   r)  rU   r   )r   r  RGBArawr   pnginfoz@'metadata' is overridden by the 'pnginfo' entry in 'pil_kwargs'.ZSoftwarezMatplotlib versionz, https://matplotlib.org/)Zjpgjpegra  zsavefig.facecolorr	  zfigure.facecolorc                 s   s   | ]}t |d  V  qdS )rl   N)r'   r>   r8   r8   r9   r@   z  s     zimsave.<locals>.<genexpr>RGBrY   rE  )*matplotlib.figurerZ  r<   osPathLikefspathrK  r   rN  r{   r|   ru   r   Zfigimagesavefig
memoryviewrY   r   r$   r   rz   Zset_climr   r   r   
frombufferr   r   __version__rP  ZPngInfoitemsadd_textr   Z
_str_equalr  r   Zto_rgbnewZpaste
setdefaultr   )r   r  r   r   r   rY   rv   rE  rW  rX  rZ  rD  rn   smZ	pil_shaper1   r`  kr   Z	facecolorcolorZ
backgroundr8   r8   r9   imsave  s    2



      

 



rr  c              
   C   s   | j dkrt| S | j drp| d| j }| j drHt|d}nt|d}|| jddd 	d	S z| 
d
} W n, tk
r } ztd|W 5 d}~X Y nX t| S dS )a`  
    Load a `PIL image`_ and return it as a numpy int array.

    .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html

    Returns
    -------
    numpy.array

        The array shape depends on the image type:

        - (M, N) for grayscale images.
        - (M, N, 3) for RGB images.
        - (M, N, 4) for RGBA images.
    )r^  ZRGBXrb  LzI;16r_  r)  z>u2z<u2Nr   z=u2r^  zUnknown image mode)moder   asarray
startswithtobytesendswithri  r&  rB   r   convertr   r   )ZpilImager_  r3   errr8   r8   r9   r     s    

r   c                 C   s  | j }| jj}|dkr(t| tjS |dkrBtj| dtjdS |dkr\tj| dtjdS |dkrvtj| dtjdS |d	krtj| d
tjdS |dkrtj| dtjdS |dkrtj| ddtjdS |dkrtj| ddtjdS |dkrtj| dtjdS t	d| dS )z2Convert a PIL `PNGImageFile` to a 0-1 float array.1zL;2rU   r   zL;4   rs  rl   zI;16Bi  rb  Pr^  ZLAzUnknown PIL rawmode: N)
rt  r   Z
im_rawmoder   ru  r   r   r'  ry  r   )Zpil_pngrt  rawmoder8   r8   r9   rR    s*    
rR  r   r   Fc                 C   s   t | }|j\}}}d}	||	 | }
||	 | }|rTddlm} |j||
f|	d}n$ddlm} |||
f|	d}t| |jddddgddg g d	}|j	|dd
|d |j
||	d |S )a  
    Make a thumbnail of image in *infile* with output filename *thumbfile*.

    See :doc:`/gallery/misc/image_thumbnail_sgskip`.

    Parameters
    ----------
    infile : str or file-like
        The image file. Matplotlib relies on Pillow_ for image reading, and
        thus supports a wide range of file formats, including PNG, JPG, TIFF
        and others.

        .. _Pillow: https://python-pillow.org/

    thumbfile : str or file-like
        The thumbnail filename.

    scale : float, default: 0.1
        The scale factor for the thumbnail.

    interpolation : str, default: 'bilinear'
        The interpolation scheme used in the resampling. See the
        *interpolation* parameter of `~.Axes.imshow` for possible values.

    preview : bool, default: False
        If True, the default backend (presumably a user interface
        backend) will be used which will cause a figure to be raised if
        `~matplotlib.pyplot.show` is called.  If it is False, the figure is
        created using `.FigureCanvasBase` and the drawing backend is selected
        as `.Figure.savefig` would normally do.

    Returns
    -------
    `.Figure`
        The figure instance containing the thumbnail.
    rV  r   N)ZfigsizerE  rY  r   r	  F)aspectr\  ZxticksZyticksT)r  r   rh   )rE  )rU  r$   Zmatplotlib.pyplotZpyplotr  rc  rZ  r   Zadd_axesZimshowrg  )infileZ	thumbfiler[   rh   previewr   ZrowscolsdepthrE  r(   r)   ZpltrD  rZ  r   r8   r8   r9   	thumbnail  s&    '  r  )r   )N)N)NNNNNrV  )r   r   F)Jr   r   rd  loggingpathlibr   rW   Znumpyr   ZPIL.PngImagePluginr   Z
matplotlibr{   r   r   r   r   Zmatplotlib._imageZmatplotlib.artistZartistrw   Zmatplotlib.backend_basesr   Zmatplotlib.colorscolorsr   Zmatplotlib.transformsr	   r
   r   r   r   r   r   	getLoggerr   r   r-   ZBILINEARZBICUBICZSPLINE16ZSPLINE36ZHANNINGZHAMMINGZHERMITEZKAISERZQUADRICZCATROMZGAUSSIANZBESSELZMITCHELLZSINCZLANCZOSZBLACKMANrb   setZinterpolations_namesr:   rS   rk   ro   rx   rz   r=   r   r  r:  r@  rF  rU  rr  r   rR  r  r8   r8   r8   r9   <module>   s   $

9 
0 8    w (  ?G
N     x#  