ó
Ë½÷Xc        	   @` s«  d  Z  d d l m Z m Z m Z d d l Z d d l Z d d l m Z m Z m	 Z	 m
 Z
 m Z m Z m Z m Z m Z m Z m Z m Z m Z y d d l m Z m Z Wn) e k
 r× d d l Z d d l Z n Xe e d ƒ sö e j e _ n  d d d	 d
 d d d d d g	 Z d d d d d „ Z e d d „ Z d d „ Z  e d d „ Z! d Z" d d d d d d d d „ Z# d d „ Z$ d „  Z% d d d „ Z& d „  Z' d S(   sÁ   
A collection of image utilities using the Python Imaging Library (PIL).

Note that PIL is not a dependency of SciPy and this module is not
available on systems that don't have PIL installed.

i    (   t   divisiont   print_functiont   absolute_importN(   t   amint   amaxt   ravelt   asarrayt   castt   aranget   onest   newaxist	   transposet   iscomplexobjt   uint8t
   issubdtypet   array(   t   Imaget   ImageFiltert	   frombytest	   fromimaget   toimaget   imsavet   imreadt	   bytescalet   imrotatet   imresizet   imshowt   imfilteriÿ   c         C` s  |  j  t k r |  S| d k r. t d ƒ ‚ n  | d k  rI t d ƒ ‚ n  | | k  rd t d ƒ ‚ n  | d	 k r |  j ƒ  } n  | d	 k rš |  j ƒ  } n  | | } | d k  r¿ t d ƒ ‚ n | d k rÔ d } n  t | | ƒ | } |  | | | } | j | | ƒ d j t ƒ S(
   s€  
    Byte scales an array (image).

    Byte scaling means converting the input image to uint8 dtype and scaling
    the range to ``(low, high)`` (default 0-255).
    If the input image already has dtype uint8, no scaling is done.

    Parameters
    ----------
    data : ndarray
        PIL image data array.
    cmin : scalar, optional
        Bias scaling of small values. Default is ``data.min()``.
    cmax : scalar, optional
        Bias scaling of large values. Default is ``data.max()``.
    high : scalar, optional
        Scale max value to `high`.  Default is 255.
    low : scalar, optional
        Scale min value to `low`.  Default is 0.

    Returns
    -------
    img_array : uint8 ndarray
        The byte-scaled array.

    Examples
    --------
    >>> from scipy.misc import bytescale
    >>> img = np.array([[ 91.06794177,   3.39058326,  84.4221549 ],
    ...                 [ 73.88003259,  80.91433048,   4.88878881],
    ...                 [ 51.53875334,  34.45808177,  27.5873488 ]])
    >>> bytescale(img)
    array([[255,   0, 236],
           [205, 225,   4],
           [140,  90,  70]], dtype=uint8)
    >>> bytescale(img, high=200, low=100)
    array([[200, 100, 192],
           [180, 188, 102],
           [155, 135, 128]], dtype=uint8)
    >>> bytescale(img, cmin=0, cmax=255)
    array([[91,  3, 84],
           [74, 81,  5],
           [52, 34, 28]], dtype=uint8)

    iÿ   s+   `high` should be less than or equal to 255.i    s+   `low` should be greater than or equal to 0.s0   `high` should be greater than or equal to `low`.s$   `cmax` should be larger than `cmin`.i   g      à?N(	   t   dtypeR   t
   ValueErrort   Nonet   mint   maxt   floatt   clipt   astype(   t   datat   cmint   cmaxt   hight   lowt   cscalet   scalet   bytedata(    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   !   s(    .
	c         C` s%   t  j |  ƒ } t | d | d | ƒS(   s‹  
    Read an image from a file as an array.

    Parameters
    ----------
    name : str or file object
        The file name or file object to be read.
    flatten : bool, optional
        If True, flattens the color layers into a single gray-scale layer.
    mode : str, optional
        Mode to convert image to, e.g. ``'RGB'``.  See the Notes for more
        details.

    Returns
    -------
    imread : ndarray
        The array obtained by reading the image.

    Notes
    -----
    `imread` uses the Python Imaging Library (PIL) to read an image.
    The following notes are from the PIL documentation.

    `mode` can be one of the following strings:

    * 'L' (8-bit pixels, black and white)
    * 'P' (8-bit pixels, mapped to any other mode using a color palette)
    * 'RGB' (3x8-bit pixels, true color)
    * 'RGBA' (4x8-bit pixels, true color with transparency mask)
    * 'CMYK' (4x8-bit pixels, color separation)
    * 'YCbCr' (3x8-bit pixels, color video format)
    * 'I' (32-bit signed integer pixels)
    * 'F' (32-bit floating point pixels)

    PIL also provides limited support for a few special modes, including
    'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
    (true color with premultiplied alpha).

    When translating a color image to black and white (mode 'L', 'I' or
    'F'), the library uses the ITU-R 601-2 luma transform::

        L = R * 299/1000 + G * 587/1000 + B * 114/1000

    When `flatten` is True, the image is converted using mode 'F'.
    When `mode` is not None and `flatten` is True, the image is first
    converted according to `mode`, and the result is then flattened using
    mode 'F'.

    t   flattent   mode(   R   t   openR   (   t   nameR,   R-   t   im(    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   i   s    3c         C` sB   t  | d d ƒ} | d k r. | j |  ƒ n | j |  | ƒ d S(   sæ  
    Save an array as an image.

    Parameters
    ----------
    name : str or file object
        Output file name or file object.
    arr : ndarray, MxN or MxNx3 or MxNx4
        Array containing image values.  If the shape is ``MxN``, the array
        represents a grey-level image.  Shape ``MxNx3`` stores the red, green
        and blue bands along the last dimension.  An alpha layer may be
        included, specified as the last colour band of an ``MxNx4`` array.
    format : str
        Image format. If omitted, the format to use is determined from the
        file name extension. If a file object was used instead of a file name,
        this parameter should always be used.

    Examples
    --------
    Construct an array of gradient intensity values and save to file:

    >>> from scipy.misc import imsave
    >>> x = np.zeros((255, 255))
    >>> x = np.zeros((255, 255), dtype=np.uint8)
    >>> x[:] = np.arange(255)
    >>> imsave('gradient.png', x)

    Construct an array with three colour bands (R, G, B) and store to file:

    >>> rgb = np.zeros((255, 255, 3), dtype=np.uint8)
    >>> rgb[..., 0] = np.arange(255)
    >>> rgb[..., 1] = 55
    >>> rgb[..., 2] = 1 - np.arange(255)
    >>> imsave('rgb_gradient.png', rgb)

    t   channel_axisi   N(   R   R   t   save(   R/   t   arrt   formatR0   (    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR       s
    %c         C` sÙ   t  j |  ƒ s t d ƒ ‚ n  | d	 k	 rN | |  j k r |  j | ƒ }  q nB |  j d k r d |  j k r~ |  j d ƒ }  q |  j d ƒ }  n  | r¨ |  j d ƒ }  n! |  j d k rÉ |  j d ƒ }  n  t |  ƒ } | S(
   s/  
    Return a copy of a PIL image as a numpy array.

    Parameters
    ----------
    im : PIL image
        Input image.
    flatten : bool
        If true, convert the output to grey-scale.
    mode : str, optional
        Mode to convert image to, e.g. ``'RGB'``.  See the Notes of the
        `imread` docstring for more details.

    Returns
    -------
    fromimage : ndarray
        The different colour bands/channels are stored in the
        third dimension, such that a grey-image is MxN, an
        RGB-image MxNx3 and an RGBA-image MxNx4.

    s   Input is not a PIL image.t   Pt   transparencyt   RGBAt   RGBt   Ft   1t   LN(   R   t   isImageTypet	   TypeErrorR   R-   t   convertt   infoR   (   R0   R,   R-   t   a(    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   Í   s    s7   Mode is unknown or incompatible with input array shape.c         C` sá  t  |  ƒ } t | ƒ r' t d ƒ ‚ n  t | j ƒ }	 t |	 ƒ d k po t |	 ƒ d k oo d |	 k po d |	 k }
 |
 s‡ t d ƒ ‚ n  t |	 ƒ d k rÄ|	 d |	 d f }	 | d k rê | j t j ƒ } t	 j
 | |	 | j ƒ  ƒ } | S| d k rÝt | d | d | d | d | ƒ} t	 j
 d	 |	 | j ƒ  ƒ } | d k	 rc| j t  | d t ƒj ƒ  ƒ nv | d
 k rÙt d d d d t ƒd d … t f t d d t ƒt d d … f } | j t  | d t ƒj ƒ  ƒ n  | S| d k r| | k } t	 j
 d |	 | j ƒ  ƒ } | S| d k r5t t | ƒ ƒ } n  | d k rVt t | ƒ ƒ } n  | d | | | | | | } | d k r´| j t j ƒ } t	 j
 | |	 | j ƒ  ƒ } n t t ƒ ‚ | S| d k rAd |	 k rþt j t  |	 ƒ d k ƒ d } qGt j t  |	 ƒ d k ƒ } t | ƒ r2| d } qGt d ƒ ‚ n | } |	 | } | d k rlt d ƒ ‚ n  t | d | d | d | d | ƒ} | d k r¿| j ƒ  } |	 d |	 d f }	 np | d k r÷t | d ƒ j ƒ  } |	 d |	 d f }	 n8 | d k r/t | d  ƒ j ƒ  } |	 d |	 d f }	 n  | d k rY| d k rPd } qYd } n  | d! k rtt t ƒ ‚ n  | d" k rž| d k ržt d ƒ ‚ qžn  | d# k rÈ| d k rÈt d ƒ ‚ qÈn  t	 j
 | |	 | ƒ } | S($   s±  Takes a numpy array and returns a PIL image.

    The mode of the PIL image depends on the array shape and the `pal` and
    `mode` keywords.

    For 2-D arrays, if `pal` is a valid (N,3) byte-array giving the RGB values
    (from 0 to 255) then ``mode='P'``, otherwise ``mode='L'``, unless mode
    is given as 'F' or 'I' in which case a float and/or integer array is made.

    Notes
    -----
    For 3-D arrays, the `channel_axis` argument tells which dimension of the
    array holds the channel data.

    For 3-D arrays if one of the dimensions is 3, the mode is 'RGB'
    by default or 'YCbCr' if selected.

    The numpy array must be either 2 dimensional or 3 dimensional.

    s&   Cannot convert a complex-valued array.i   i   i   s8   'arr' does not have a suitable array shape for any mode.i   i    R9   R;   R5   R'   R(   R%   R&   R   i   NR:   g      ð?t   Is!   Could not find channel dimension.s$   Channel axis dimension is not valid.R8   R7   t   YCbCrt   CMYKs   Invalid array shape for mode.(   NR;   R5   (   i   (   i   i   (   i    i   i   (   i   i   i    (   s   RGBs   RGBARB   RC   (   s   RGBRB   (   s   RGBARC   (   R   R   R   t   listt   shapet   lenR#   t   numpyt   float32R   R   t   tostringR   R   t
   putpaletteR   R   R
   R	   R   R   R   t   uint32t   _errstrt   flatnonzeroR   (   R3   R'   R(   R%   R&   t   palR-   R1   R$   RE   t   validt   data32t   imageR+   t   cat   numcht   strdata(    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR     s”    $"%#"""
$		t   bilinearc         C` sd   t  |  ƒ }  i d d 6d d 6d d 6d d 6d d	 6} t |  ƒ } | j | d
 | | ƒ} t | ƒ S(   s  
    Rotate an image counter-clockwise by angle degrees.

    Parameters
    ----------
    arr : ndarray
        Input array of image to be rotated.
    angle : float
        The angle of rotation.
    interp : str, optional
        Interpolation

        - 'nearest' :  for nearest neighbor
        - 'bilinear' : for bilinear
        - 'lanczos' : for lanczos
        - 'cubic' : for bicubic
        - 'bicubic' : for bicubic

    Returns
    -------
    imrotate : ndarray
        The rotated array of image.

    i    t   nearesti   t   lanczosi   RU   i   t   bicubict   cubict   resample(   R   R   t   rotateR   (   R3   t   anglet   interpt   funcR0   (    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   v  s
    )c         C` s»   t  |  ƒ } t j d ƒ \ } } y | j | ƒ Wn t d ƒ ‚ n Xd d l } | j | ƒ | j j d d ƒ } | j	 d | | f ƒ } | j
 | ƒ | d k r· t d ƒ ‚ n  d S(	   sò  
    Simple showing of an image through an external viewer.

    Uses the image viewer specified by the environment variable
    SCIPY_PIL_IMAGE_VIEWER, or if that is not defined then `see`,
    to view a temporary file generated from array data.

    Parameters
    ----------
    arr : ndarray
        Array of image data to show.

    Returns
    -------
    None

    Examples
    --------
    >>> a = np.tile(np.arange(255), (255,1))
    >>> from scipy import misc
    >>> misc.imshow(a)

    s   .pngs"   Error saving temporary image data.i    Nt   SCIPY_PIL_IMAGE_VIEWERt   sees   %s %ss   Could not execute image viewer.(   R   t   tempfilet   mkstempR2   t   RuntimeErrort   ost   closet   environt   gett   systemt   unlink(   R3   R0   t   fnumt   fnameRd   t   cmdt   status(    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   –  s    c   	      C` sö   t  |  d | ƒ} t | ƒ } t | t ƒ r\ | d } t t | j ƒ | j t ƒ ƒ } nN t t | ƒ t ƒ r– t t | j ƒ | j t ƒ ƒ } n | d | d f } i d d 6d d 6d d 6d	 d
 6d	 d 6} | j	 | d | | ƒ} t
 | ƒ S(   s  
    Resize an image.

    Parameters
    ----------
    arr : ndarray
        The array of image to be resized.

    size : int, float or tuple
        * int   - Percentage of current size.
        * float - Fraction of current size.
        * tuple - Size of the output image.

    interp : str, optional
        Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear', 'bicubic'
        or 'cubic').

    mode : str, optional
        The PIL image mode ('P', 'L', etc.) to convert `arr` before resizing.

    Returns
    -------
    imresize : ndarray
        The resized array of image.

    See Also
    --------
    toimage : Implicitly used to convert `arr` according to `mode`.
    scipy.ndimage.zoom : More generic implementation that does not use PIL.

    R-   g      Y@i   i    RV   RW   i   RU   i   RX   RY   RZ   (   R   t   typeR   t   intt   tupleR   t   sizeR#   R!   t   resizeR   (	   R3   Rq   R]   R-   R0   t   tst   percentR^   t   imnew(    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   À  s     
%%)c         C` s¨   i
 t  j d 6t  j d 6t  j d 6t  j d 6t  j d 6t  j d 6t  j d 6t  j d 6t  j	 d	 6t  j
 d
 6} t |  ƒ } | | k r‘ t d ƒ ‚ n  t | j | | ƒ ƒ S(   sP  
    Simple filtering of an image.

    Parameters
    ----------
    arr : ndarray
        The array of Image in which the filter is to be applied.
    ftype : str
        The filter that has to be applied. Legal values are:
        'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
        'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.

    Returns
    -------
    imfilter : ndarray
        The array with filter applied.

    Raises
    ------
    ValueError
        *Unknown filter type.*  If the filter you are trying
        to apply is unsupported.

    t   blurt   contourt   detailt   edge_enhancet   edge_enhance_moret   embosst
   find_edgest   smootht   smooth_moret   sharpens   Unknown filter type.(   R   t   BLURt   CONTOURt   DETAILt   EDGE_ENHANCEt   EDGE_ENHANCE_MOREt   EMBOSSt
   FIND_EDGESt   SMOOTHt   SMOOTH_MOREt   SHARPENR   R   R   t   filter(   R3   t   ftypet   _tdictR0   (    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyR   î  s    







((   t   __doc__t
   __future__R    R   R   RG   Ra   R   R   R   R   R   R   R	   R
   R   R   R   R   R   t   PILR   R   t   ImportErrort   hasattrt
   fromstringR   t   __all__R   R   t   FalseR   R   R   RL   R   R   R   R   R   (    (    (    s1   /tmp/pip-build-7oUkmx/scipy/scipy/misc/pilutil.pyt   <module>   s0   XH7-4q 	*.