B
    ]t\#                 @   s  d Z ddlm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
Z
ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlT dd	l 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j0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:d
Z;e<e;Z=d*ddZ>d+ddZ?dd Z@G dd dejAejBZCG dd deCZDG dd deDZEG dd deDZFG dd deCZGG dd deCZHd,ddZId-d!d"ZJd#d$ ZKd.d(d)ZLdS )/zR
The image module supports basic image loading, rescaling and display
operations.
    )BytesIO)ceilN)rcParams)allow_rasterization)FigureCanvasBase)*)Affine2DBboxBaseBboxBboxTransformIdentityTransformTransformedBbox)nonenearestbilinearZbicubicZspline16Zspline36ZhanningZhammingZhermiteZkaiserZquadricZcatromZgaussianZbesselZmitchellZsincZlanczosZblackman      ?c          	   C   sZ  t | dkr"tjdtjdddfS g }g }x| D ]x}|||\}}}}	|dk	r0||9 }||9 }||||| ptdf |t||g||jd  ||jd  gg q0W 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}xH|D ]@\}}}}t ||
j ||
j }	tj|||	tjd|d	 q W ||
j| |
j| fS )
aD  
    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 instance

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

    Returns
    -------
    tuple : image, offset_x, offset_y
        Returns the tuple:

        - image: A numpy array of the same type as the input images.

        - offset_x, offset_y: The offset of the image (left, bottom)
          in the output figure.
    r   )r   r      )dtypeNg      ?   r   F)resamplealpha)lennpemptyuint8
make_imageappend	get_alphar
   shapeunionzerosintheightwidthr   	translatex0y0_imager   NEAREST)ZimagesrenderermagnificationpartsZbboxesimagedataxytransbboxoutputr    r3   /lib/python3.7/site-packages/matplotlib/image.pycomposite_images>   s,    
.
r5   c                s   t dd |D }|dk	r|n }|s.|sHxx|D ]}| q4W n`g    fdd}x:|D ]2}t|tr| r | ql|  | qlW |  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).0r.   r3   r3   r4   	<genexpr>   s    z0_draw_list_compositing_images.<locals>.<genexpr>Nc                 s   t  dkr d  nnt  dkrt \} }}| jdkr }|j |  	|t
|t
||  |   d d = d S )Nr   r   )r   drawr5   sizenew_gcZset_clip_rectangler1   Zset_clip_pathZget_clip_path
draw_imager   roundrestore)r-   lbgc)image_groupmagparentr)   r3   r4   flush_images   s    
z3_draw_list_compositing_images.<locals>.flush_images)anyZoption_image_nocompositer:   get_image_magnificationr6   r7   can_compositer   )r)   rE   ZartistsZsuppress_compositeZ
has_imagesZnot_compositearF   r3   )rC   rD   rE   r)   r4   _draw_list_compositing_imagesx   s    


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   N      g      ?)r   r    r   r   r   )AZrgbar3   r3   r4   _rgb_to_rgba   s    "rO   c                   s   e Zd ZdZdd Zd7dd	Z fd
dZdd Zdd Zdd Z	d8ddZ
d9ddZdd Zdd Ze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-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Z  ZS ):r7   r   c             C   s   dt | jjj S )NzAxesImage(%g,%g;%gx%g))tupleaxesr1   bounds)selfr3   r3   r4   __str__   s    z_ImageBase.__str__NT      @Fc	       
      K   sz   t j|  tj| || d| _|dkr2td }|| _| | | 	| | 
| | | || _d| _| |	 dS )a  
        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

        TNzimage.origin)martistArtist__init__cmScalarMappableZ
_mouseoverr   originset_filternormset_filterradset_interpolationset_resamplerQ   _imcacheupdate)
rS   axcmapnorminterpolationr[   
filternorm	filterradr   kwargsr3   r3   r4   rX      s    



z_ImageBase.__init__c                s   t   }d |d< |S )Nr`   )super__getstate__)rS   state)	__class__r3   r4   rj      s    
z_ImageBase.__getstate__c             C   s"   | j dkrtd| j jdd S )z+Get the numrows, numcols of the input imageNz"You must first set the image array   )_ARuntimeErrorr   )rS   r3   r3   r4   get_size   s    
z_ImageBase.get_sizec             C   s   t j| | d| _dS )z
        Set the alpha value used for blending - not supported on all backends.

        Parameters
        ----------
        alpha : float
        N)rV   rW   	set_alphar`   )rS   r   r3   r3   r4   rq      s    z_ImageBase.set_alphac             C   s   d| _ d| _tj|  dS )zb
        Call this whenever the mappable is changed so observers can
        update state
        N)r`   
_rgbacacherY   rZ   changed)rS   r3   r3   r4   rs      s    z_ImageBase.changed      ?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rh|rh|	d	 d
ks|
d	 d
krhtt|	}tt|
}||	 |	 }||
 |
 }|t 
d	| d	| 7 }nt|	}t|
}|s|jdkrtd|j	|jdkr|j}| }| }|tjjkrtdtd }}|jdkr.|j}|jtjtjfkr^|jtjkr&t !d|j tj}n0|"tj|"tj }|dkrXtj}ntj}tj#|j	|d}||dd< | j$%| t| j$j&t| j$j' }| j$j'|d  }|tjkrdnd}|||  }||k rd}n
t|}|||  }||krd}n
t|}|dk	s&|dk	r4t(|||}||8 }|"|) }|"|) }||krr||| d  }|d7 }tj*||f|jd}t+,|||t-| .  | / d	| 0 | 1  ~|d8 }||kr||| d 9 }||7 }t2| j$t3j4r|"|j}tj#|j	tjd}|j5j	|j	krLt6|j5ttj7td|dd< nd|dd< tj*||f|jd}t+,|||t-| .  dd| 0 | 1  ~t8|}t9|}d||< | $tj:||} n|j	d dkrt;|}n |j	d dkrtd|j	f tj*||df|jd} | < }!|!dkr.d	}!t+,|| |t-| .  | / |!| 0 | 1  | j=| ddd} |jdkr| < }!|!dkrd}!| dddddf }"t>t>|"tj| |! tj?|"dd< n| j@dkr| j=|d|jdkd| _@| j@} tA||B C B }#| 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 )ae  
        Normalize, rescale and color 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 (MxN) with a dtype of `float32`,
        `float64`, `float128`, `uint16` or `uint8`, or an RGBA image (MxNx4)
        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
        in cases where you want exact scaling, however, such as
        FigureImage.

        Returns the resulting (image, x, y, trans), where (x, y) is
        the upper left corner of the result in pixel space, and
        `trans` is the affine transformation from the 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   Nupperr   g      ?g        )rm   rL   zInvalid dimensions, got {}rm   fz4Casting input data from '{0}' to 'float64'for imshowg    חA)r   g    cAg     @g?g?TrL   r   zInvalid dimensions, got %sF)bytesrd   )Hro   r;   r
   intersectionr#   r"   r[   r   r$   r   scaler   r%   r&   get_transform	is_affiner!   r   ndim
ValueErrorformatr   minmaxr   ZmaZmaskedZint32Zkindfloat32Zfloat16float64warningswarnastyper   rd   Zautoscale_Nonevmaxvminclipitemr    r'   r   	_interpd_get_interpolationget_resampleget_filternormget_filterradr6   mcolorsZNoNormmaskwherenanarrayisnanZmasked_arrayrO   r   to_rgbaasarrayr   r`   r   frozeninvertedyminymaxxminxmax)$rS   rN   Zin_bboxZout_bboxZ	clip_bboxr*   	unsampledround_to_pixel_borderZclipped_bboxZout_width_baseZout_height_baseZt0tZ	out_widthZ
out_heightZextra_widthZextra_heightZ	inp_dtypeZa_minZa_maxZscaled_dtypeZdaZA_scaledZdvZvmidZfactZnewminZnewmaxZA_resampledr   Zout_maskZ	out_alphar2   r   Zalpha_channelZsubsetr3   r3   r4   _make_image  s"   



 




	













	




 $z_ImageBase._make_imagec             C   s   t dd S )Nz)The make_image method must be overridden.)ro   )rS   r)   r*   r   r3   r3   r4   r     s    z_ImageBase.make_imagec             C   sV   | j |dd\}}}}|dkr"dS t |jd |jd | }|||||| dS )zu
        draw unsampled image. The renderer should support a draw_image method
        with scale parameter.
        T)r   Nr   r   )r   r   rz   r   r=   )rS   r)   rB   imr@   rA   r0   r3   r3   r4   _draw_unsampled_image  s
    z _ImageBase._draw_unsampled_imagec             C   s   dS )z{
        return True if the image is better to be drawn unsampled.
        The derived class needs to override it.
        Fr3   )rS   r)   r3   r3   r4   _check_unsampled_image)  s    z!_ImageBase._check_unsampled_imagec       	      O   s   |   sd| _d S |  jdkr*d| _d S | }| | ||   || 	  |
|   | |r|  jr| || n0| || \}}}}|d k	r||||| |  d| _d S )NFr   )get_visiblestale	get_arrayr;   r<   Z_set_gc_cliprq   r   Zset_urlZget_urlZset_gidZget_gidr   r{   r|   r   r   rH   r=   r?   )	rS   r)   argsrh   rB   r   r@   rA   r0   r3   r3   r4   r:   0  s(    


z_ImageBase.drawc       	      C   s   t | jr| | |S |j|j }}|  \}}}}||krF|| }}||krX|| }}|dk	r|dk	r||  koz|kn  o||  ko|kn  }nd}|i fS )zI
        Test whether the mouse event occurred within the image.
        NF)callable	_containsxdataydata
get_extent)	rS   
mouseeventr.   r/   r   r   r   r   insider3   r3   r4   containsN  s    


2z_ImageBase.containsc             C   s<   | j | jdkr| jddd n| jddd}t|| dS )z&Write the image to png file with fnamelowerNrv   T)rx   rd   )r   r[   rn   _png	write_png)rS   fnamer   r3   r3   r4   r   f  s    "
z_ImageBase.write_pngc             C   s  t j|dd| _| jjtjkr8t| jjtds8td| jj	dksh| jj	dkr`| jj
d dkshtd	| jj	dkrt| jjtjrd
nd}| j dk s|| j k rtd t| jd|| _| jjtjkrt| jjtjr| jtj| _d| _d| _d| _dS )z
        Set the image array.

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

        Parameters
        ----------
        A : array-like
        T)copyZ	same_kindz'Image data cannot be converted to floatrm   rL   rv   )rL   r   z!Invalid dimensions for image datarM   r   r   zmClipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).N)cbooksafe_masked_invalidrn   r   r   r   Zcan_castfloat	TypeErrorr}   r   Z
issubdtypeZintegerr   r   _logZwarningr   r   r`   rr   r   )rS   rN   Zhighr3   r3   r4   set_datal  s&    
z_ImageBase.set_datac             C   s   |  | dS )z
        Retained for backwards compatibility - use set_data instead.

        Parameters
        ----------
        A : array-like
        N)r   )rS   rN   r3   r3   r4   	set_array  s    z_ImageBase.set_arrayc             C   s   | j S )a*  
        Return the interpolation method the image uses when resizing.

        One of 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36',
        'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom',
        'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', or 'none'.

        )_interpolation)rS   r3   r3   r4   r     s    	z_ImageBase.get_interpolationc             C   s8   |dkrt d }| }|tkr(td|| _d| _dS )a(  
        Set the interpolation method the image uses when resizing.

        if None, use a value from rc setting. 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 : {'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'}

        Nzimage.interpolationzIllegal interpolation stringT)r   r   r   r~   r   r   )rS   sr3   r3   r4   r^     s    z_ImageBase.set_interpolationc             C   s   |   }| jdko|jo|jS )zS
        Returns `True` if the image can be composited with its neighbors.
        r   )r{   r   r|   Zis_separable)rS   r0   r3   r3   r4   rI     s    
z_ImageBase.can_compositec             C   s    |dkrt d }|| _d| _dS )zv
        Set whether or not image resampling is used.

        Parameters
        ----------
        v : bool
        Nzimage.resampleT)r   	_resampler   )rS   vr3   r3   r4   r_     s    z_ImageBase.set_resamplec             C   s   | j S )z"Return the image resample boolean.)r   )rS   r3   r3   r4   r     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   )rS   rf   r3   r3   r4   r\     s    

z_ImageBase.set_filternormc             C   s   | j S )z8Return whether the resize filter normalizes the weights.)r   )rS   r3   r3   r4   r     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   )rS   rg   rr3   r3   r4   r]     s
    	z_ImageBase.set_filterradc             C   s   | j S )zReturn the filterrad setting.)r   )rS   r3   r3   r4   r      s    z_ImageBase.get_filterrad)NNNNTrU   F)rt   FT)rt   F)__name__
__module____qualname__zorderrT   rX   rj   rp   rq   rs   r   r   r   r   r   r:   r   r   r   r   r   r^   rI   r_   r   r\   r   r]   r   __classcell__r3   r3   )rl   r4   r7      sD         
 	 
  
)
r7   c                   sZ   e Zd Zdd Z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 )	AxesImagec             C   s   dt | jjj S )NzAxesImage(%g,%g;%gx%g))rP   rQ   r1   rR   )rS   r3   r3   r4   rT     s    zAxesImage.__str__Nr         @Fc
          
      s.   || _ t j|f|||||||	d|
 dS )a  
        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

        )rc   rd   re   r[   rf   rg   r   N)_extentri   rX   )rS   rb   rc   rd   re   r[   extentrf   rg   r   rh   )rl   r3   r4   rX   	  s    zAxesImage.__init__c             C   s.   | j \}}}}t||||g}|| jjS )N)r   r
   Zfrom_extentsZtransformedrQ   Z	transData)rS   r)   r%   x1r&   y1r1   r3   r3   r4   get_window_extent1  s    zAxesImage.get_window_extent      ?c             C   sX   |   }|  \}}}}tt||g||gg}	t|	|}
| j| j|	|
| jj	||dS )N)r   )
r{   r   r
   r   r   r   r   rn   rQ   r1   )rS   r)   r*   r   r0   r   Zx2r   Zy2r1   Ztransformed_bboxr3   r3   r4   r   6  s    
zAxesImage.make_imagec             C   s   |   dko| S )zK
        Return whether the image would be better drawn unsampled.
        r   )r   Zoption_scale_image)rS   r)   r3   r3   r4   r   A  s    z AxesImage._check_unsampled_imagec             C   s   | | _ \}}}}||f||ff}| j| ||g| jjdd< ||g| jjdd< | jjrr| jj||fdd | jjr| jj	||fdd d| _
dS )ab  
        extent is data axes (left, right, bottom, top) for making image plots

        This updates ax.dataLim, and, if autoscaling, sets 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   rQ   Zupdate_datalimZsticky_edgesr.   r/   Z_autoscaleXonZset_xlimZ_autoscaleYonZset_ylimr   )rS   r   r   r   r   r   Zcornersr3   r3   r4   
set_extentH  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 )z.Get the image extent: left, right, bottom, topNru   g      g      ?)r   rp   r[   )rS   Zsznumrowsnumcolsr3   r3   r4   r   \  s    

zAxesImage.get_extentc             C   s   |   \}}}}| jdkr$|| }}|  }t||g||gg}tddg|jdd g}t||d}	|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%Get the cursor data for a given eventru   r   Nrm   )ZboxinZboxoutr   )r   r[   r   r
   r   r   r   r   Ztransform_pointrG   r   r   r   r!   )rS   eventr   r   r   r   arrZdata_extentZarray_extentr0   r/   r.   Zpointijr3   r3   r4   get_cursor_datah  s    

:zAxesImage.get_cursor_data)NNNNNr   r   F)N)r   F)r   r   r   rT   rX   r   r   r   r   r   r   r   r3   r3   )rl   r4   r     s           

r   c                   s|   e Zd Zdd fdd
Zdd Zdd	d
Zdd Zdd Zdd Zdd Z	dd Z
dd Z fddZ fddZ  ZS )NonUniformImager   )re   c               s   t  j|f| | | dS )z
        kwargs are identical to those for AxesImage, except
        that 'nearest' and 'bilinear' are the only supported 'interpolation'
        options.
        N)ri   rX   r^   )rS   rb   re   rh   )rl   r3   r4   rX   ~  s    zNonUniformImage.__init__c             C   s   dS )z;
        return False. Do not use unsampled image.
        Fr3   )rS   r)   r3   r3   r4   r     s    z&NonUniformImage._check_unsampled_image      ?Fc             C   s  | j d krtd|rtd| j }|jdkr|jtjkrV| j|dd}| j	 | _
n>t|d d d d tjf dd}d|d d d d df< d| _
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< |}d
| _
| jjj\}}}}	| jjj\}
}}}t|d t|
d  }t|d t|d  }||9 }||9 }t| j| j|t|t|||| |||	 ft| j }||
|t fS )Nz"You must first set the image arrayz*unsampled not supported on NonUniformImagerm   T)rx   r   rM   rL   r   Fg      ?)r   )rn   ro   r~   r}   r   r   r   r   rc   is_grayis_grayscalerepeatZnewaxisr   r   r    rP   rQ   viewLimrR   r1   extentsr>   r'   Zpcolor_Ax_Ayr!   r   r   r   )rS   r)   r*   r   rN   Br%   r&   Zv_widthZv_heightr@   rA   r   r   r#   r"   r   r3   r3   r4   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.

          *x* and *y* are monotonic 1-D ndarrays of lengths N and M,
             respectively, specifying pixel centers

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.
        T)r   r   r   rm   zAxes don't match array shape)rm   rL   zCan only plot 2D or 3D datarL   )r   rL   r   z?3D arrays must have three (RGB) or four (RGBA) color componentsN)r   r   r   r   r   r}   r   r   rn   r   r   r`   r   )rS   r.   r/   rN   r3   r3   r4   r     s     6
zNonUniformImage.set_datac             G   s   t dd S )NzMethod not supported)NotImplementedError)rS   r   r3   r3   r4   r     s    zNonUniformImage.set_arrayc             C   s(   |dk	r|dkrt dt| | dS )z|
        Parameters
        ----------
        s : str, None
            Either 'nearest', 'bilinear', or ``None``.
        N)r   r   z?Only nearest neighbor and bilinear interpolations are supported)r   r   r^   )rS   r   r3   r3   r4   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   rv   )rn   ro   r   r   )rS   r3   r3   r4   r     s    
zNonUniformImage.get_extentc             C   s   d S )Nr3   )rS   r   r3   r3   r4   r\     s    zNonUniformImage.set_filternormc             C   s   d S )Nr3   )rS   r   r3   r3   r4   r]     s    zNonUniformImage.set_filterradc                s"   | j d k	rtdt | d S )Nz'Cannot change colors after loading data)rn   ro   ri   set_norm)rS   rd   )rl   r3   r4   r     s    
zNonUniformImage.set_normc                s"   | j d k	rtdt | d S )Nz'Cannot change colors after loading data)rn   ro   ri   set_cmap)rS   rc   )rl   r3   r4   r     s    
zNonUniformImage.set_cmap)r   F)r   r   r   rX   r   r   r   r   r^   r   r\   r]   r   r   r   r3   r3   )rl   r4   r   }  s   	
'r   c                   sL   e Zd ZdZ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.
    Nc                s6   t  j|||d | | |dk	r2| ||| dS )z
        cmap defaults to its rc setting

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

        Additional kwargs are matplotlib.artist properties
        )rd   rc   N)ri   rX   ra   r   )rS   rb   r.   r/   rN   rc   rd   rh   )rl   r3   r4   rX     s    
zPcolorImage.__init__      ?Fc             C   s:  | j d krtd|rtd| jj }t|d}t	|d 
tj}| jjj\}}}}	t|d t|d  }
t|	d t|d  }tt|
| }
tt|| }| jd kr| j| j dd}|| _| j jdkr| j | _n| j}| jj}t| j| j|||
|j|j|j|jf|}|||t fS )	Nz"You must first set the image arrayz&unsampled not supported on PColorImager   rM   g      ?T)rx   rm   )rn   ro   r~   rQ   ZpatchZget_facecolorr   r   r   r   r   r   r1   r   r>   r!   rr   r}   rc   r   r   r   r'   Zpcolor2r   r   r%   r   r&   r   r   )rS   r)   r*   r   ZfcZbgr@   rA   r   r   r#   r"   rN   Zvlr   r3   r3   r4   r     s2    

zPcolorImage.make_imagec             C   s   dS )NFr3   )rS   r)   r3   r3   r4   r   0  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 |_d| _|j
dkr|jd dkr|dddddf |dddddf k r|dddddf |dddddf k rd| _nt	d|d |d k r|ddd }|dddddf }|d |d k r|ddd }|ddd }|| _|| _|| _d| _d| _dS )a  
        Set the grid for the rectangle boundaries, and the data values.

          *x* and *y* are monotonic 1-D ndarrays of lengths N+1 and M+1,
             respectively, specifying rectangle boundaries.  If None,
             they will be created as uniform arrays from 0 through N
             and 0 through M, respectively.

          *A* is an (M,N) ndarray or masked array of values to be
            colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
            array.

        T)r   Nr   r   )r   rm   z2Axes don't match array shape. Got %s, expected %s.)rm   rL   zA must be 2D or 3DrL   F)rL   r   z+3D arrays must have RGB or RGBA as last dimrv   )r   r   r   Zaranger   r   r   Zravelr;   r~   r}   r   allrn   r   r   rr   r   )rS   r.   r/   rN   r3   r3   r4   r   3  sB    "&
22zPcolorImage.set_datac             G   s   t dd S )NzMethod not supported)r   )rS   r   r3   r3   r4   r   j  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 }y| j||f S  tk
r   dS X dS )z%Get the cursor data for a given eventr   rv   Nr   )r   r   r   r   r   Zsearchsortedrn   
IndexError)rS   r   r.   r/   r   r   r3   r3   r4   r   m  s    zPcolorImage.get_cursor_data)NNNNN)r   F)r   r   r   __doc__rX   r   r   r   r   r   r   r3   r3   )rl   r4   r     s       
7r   c                   s@   e Zd ZdZdZd fdd	Zdd Zdd
dZdd Z  Z	S )FigureImager   r   Nc                s:   t  jd|||d || _|| _|| _| | d| _dS )z
        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)rd   rc   r[   g      ?)ri   rX   figureoxoyra   r*   )rS   figrc   rd   ZoffsetxZoffsetyr[   rh   )rl   r3   r4   rX     s    
zFigureImage.__init__c             C   s8   |   \}}d| j |d | j d| j |d | j fS )z.Get the image extent: left, right, bottom, topg      g      ?)rp   r   r   )rS   r   r   r3   r3   r4   r     s    zFigureImage.get_extent      ?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
   r   r   rn   r   Zget_size_inchesr   )	rS   r)   r*   r   Zfacr1   r#   r"   r   r3   r3   r4   r     s    

zFigureImage.make_imagec             C   s"   t j| tj|dd d| _dS )zSet the image array.T)r   N)rY   rZ   r   r   r   r   )rS   rN   r3   r3   r4   r     s    zFigureImage.set_data)NNr   r   N)r   F)
r   r   r   r   r   rX   r   r   r   r   r3   r3   )rl   r4   r   {  s       
r   c                   sF   e Zd ZdZd fdd	Z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.Nr         @FTc
          
      s:   t  jd|||||||d|
 || _|	| _t | _dS )aG  
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        interp_at_native is a flag that determines whether or not
        interpolation should still be applied when the image is
        displayed at its native resolution.  A common use case for this
        is when displaying an image for annotational purposes; it is
        treated similarly to Photoshop (interpolation is only used when
        displaying the image at non-native resolutions).


        kwargs are an optional list of Artist keyword args

        N)rc   rd   re   r[   rf   rg   r   )N)ri   rX   r1   interp_at_nativer   
_transform)rS   r1   rc   rd   re   r[   rf   rg   r   r   rh   )rl   r3   r4   rX     s    zBboxImage.__init__c             C   s   | j S )N)r   )rS   r3   r3   r4   r{     s    zBboxImage.get_transformc             C   sD   |d kr|   j}t| jtr$| jS t| jr8| |S tdd S )Nzunknown type of bbox)Z
get_figureZ_cachedRendererr6   r1   r	   r   r~   )rS   r)   r3   r3   r4   r     s    


zBboxImage.get_window_extentc             C   sL   t | jr| | |S |  s&di fS |j|j }}|  ||}|i fS )z7Test whether the mouse event occurred within the image.F)r   r   r   r.   r/   r   r   )rS   r   r.   r/   r   r3   r3   r4   r     s    
zBboxImage.contains      ?c       	      C   s~   |  \}}| | }| j||g  _| |}tddg||gg}ttddgddgg|| _| j| j|||||dS )Nr   r   )r   )	Zget_canvas_width_heightr   r   Z_pointsr
   r   r   r   rn   )	rS   r)   r*   r   r#   r"   Zbbox_inZbbox_outr   r3   r3   r4   r     s    
zBboxImage.make_image)NNNNr   r   FT)N)r   F)
r   r   r   r   rX   r{   r   r   r   r   r3   r3   )rl   r4   r     s          "
r   c       
   	   C   sb  dt ji}|dkrt| tr^tj| }t|jdkr<d}qt	j
| \}}| dd }qt| drt	j
| j\}}| dd }qd}n|}||kryddlm} W n$ tk
r   tdt| Y nX || 
}t|S Q R X || }t| trVtj| }t|jdkr:ttj|  }	||	S t| d
}	||	S Q R X n|| S dS )	a  
    Read an image from a file into an array.

    Parameters
    ----------
    fname : str or file-like
        The image file to read. This can be a filename, a URL or a Python
        file-like object opened in read-binary mode.
    format : str, optional
        The image file format assumed for reading the data. If not
        given, the format is deduced from the filename.  If nothing can
        be deduced, PNG is tried.

    Returns
    -------
    imagedata : :class:`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.

    Notes
    -----
    Matplotlib can only read PNGs natively. Further image formats are
    supported via the optional dependency on Pillow. Note, URL strings
    are not compatible with Pillow. Check the `Pillow documentation`_
    for more information.

    .. _Pillow documentation: http://pillow.readthedocs.io/en/latest/
    pngNr   namer   )Imagez_Only know how to handle extensions: %s; with Pillow installed matplotlib can handle more imagesrb)r   Zread_pngr6   strurllibparseZurlparser   Zschemeospathsplitextr   hasattrr   ZPILr   ImportErrorr~   listopenpil_to_arrayr   ZrequestZurlopenread)
r   r   ZhandlersZparsedZextbasenamer   r,   Zhandlerfdr3   r3   r4   imread  s<    !


r  d   c             C   s   ddl m} ddlm}	 t| ttddr4t| } |dks\|dkrt| tr| 	 
drtd||d	}
|
| |
|| |
|  n<|	|d
d}|| |j|||||dd |j| ||dd dS )a(  
    Save an array as in image file.

    The output formats available depend on the backend being used.

    Parameters
    ----------
    fname : str or file-like
        The filename or a Python file-like object to store the image in.
        The necessary output format is inferred from the filename extension
        but may be explicitly overwritten using *format*.
    arr : array-like
        The image data. The shape can be one of
        MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
    vmin, vmax : scalar, 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`, optional
        A Colormap instance or registered colormap name. The colormap
        maps scalar data to colors. It is ignored for RGB(A) data.
        Defaults to :rc:`image.cmap` ('viridis').
    format : str, optional
        The file format, e.g. 'png', 'pdf', 'svg', ... . If not given, the
        format is deduced form the filename extension in *fname*.
        See `.Figure.savefig` for details.
    origin : {'upper', 'lower'}, optional
        Indicates whether the ``(0, 0)`` index of the array is in the upper
        left or lower left corner of the axes.  Defaults to :rc:`image.origin`
        ('upper').
    dpi : int
        The DPI to store in the metadata of the file.  This does not affect the
        resolution of the output image.
    r   )FigureCanvasAgg)FigurePathLiker3   r   Nz.png)rc   r[   F)r   frameonT)rc   r   r   r[   Zresize)r   r   Ztransparent)Zmatplotlib.backends.backend_aggr  matplotlib.figurer  r6   getattrr   fspathr   r   endswithr   r   Zset_climr   Zfigimagesavefig)r   r   r   r   rc   r   r[   r   ZFigureCanvasr  r,   r   r3   r3   r4   imsave\  s"    %


r  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 y| 
d
} W n tk
r   tdY nX t| S dS )aX  Load a `PIL image`_ and return it as a numpy 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.

    )RGBAZRGBXZRGBLzI;16rawr   z>u2z<u2Nrv   z=u2r  zUnknown image mode)moder   r   
startswithtobytesr  Z
fromstringZreshaper;   r   Zconvertr~   ro   )ZpilImager  r.   r3   r3   r4   r    s    

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 )ac  
    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 -- must be PNG, Pillow-readable if you have `Pillow
        <http://python-pillow.org/>`_ installed.

    thumbfile : str or file-like
        The thumbnail filename.

    scale : float, optional
        The scale factor for the thumbnail.

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

    preview : bool, optional
        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 `~matplotlib.figure.savefig` would normally do.

    Returns
    -------
    figure : `~.figure.Figure`
        The figure instance containing the thumbnail.
    r  r   N)Zfigsizer   )r  r   r   F)aspectr  ZxticksZyticksT)r  r   re   )r   )r  r   Zmatplotlib.pyplotZpyplotr   r  r  r   Zadd_axesZimshowr  )ZinfileZ	thumbfilerz   re   Zpreviewr   ZrowsZcolsZdepthr   r"   r#   Zpltr   r  rb   r3   r3   r4   	thumbnail  s     $r  )r   )N)N)NNNNNr  )r  r   F)Mr   ior   Zmathr   r   ZloggingZurllib.parser   Zurllib.requestr   Znumpyr   Z
matplotlibr   Zmatplotlib.artistZartistrV   r   Zmatplotlib.backend_basesr   Zmatplotlib.colorsZcolorsr   Zmatplotlib.cmrY   Zmatplotlib.cbookr   Zmatplotlib._imager'   Zmatplotlib._pngr   Zmatplotlib.transformsr   r	   r
   r   r   r   Z	getLoggerr   r   r(   ZBILINEARZBICUBICZSPLINE16ZSPLINE36ZHANNINGZHAMMINGZHERMITEZKAISERZQUADRICZCATROMZGAUSSIANZBESSELZMITCHELLZSINCZLANCZOSZBLACKMANr   setZinterpolations_namesr5   rK   rO   rW   rZ   r7   r   r   r   r   r   r  r  r  r  r3   r3   r3   r4   <module>   sv    


;
-    Uxz =U
O 
8# 