ó
‡ˆ\c           @   s?  d  Z  d d l m Z d d l Z d d l Z d d l m Z d d l m	 Z	 d d l
 m Z m Z d d l m Z d	 d
 d d d g Z d d „ Z d „  Z d d „ Z d d e j d d „ Z d e j d d „ Z d d e j e j d „ Z d d „ Z d d d „ Z d d d „ Z d „  Z d	 e f d „  ƒ  YZ d S(   sj   
The :mod:`sklearn.feature_extraction.image` submodule gathers utilities to
extract features from images.
iÿÿÿÿ(   t   productN(   t   sparse(   t
   as_stridedi   (   t   check_arrayt   check_random_state(   t   BaseEstimatort   PatchExtractort   extract_patches_2dt   grid_to_grapht   img_to_grapht   reconstruct_from_patches_2di   c         C   s  t  j |  | | ƒ j |  | | f ƒ } t  j | d d … d d … d d … f j ƒ  | d d … d d … d d … f j ƒ  f ƒ } t  j | d d … d d … f j ƒ  | d d … d d … f j ƒ  f ƒ } t  j | d  j ƒ  | d j ƒ  f ƒ } t  j | | | f ƒ } | S(   s-  Returns a list of edges for a 3D image.

    Parameters
    ===========
    n_x : integer
        The size of the grid in the x direction.
    n_y : integer
        The size of the grid in the y direction.
    n_z : integer, optional
        The size of the grid in the z direction, defaults to 1
    Niÿÿÿÿi   (   t   npt   aranget   reshapet   vstackt   ravelt   hstack(   t   n_xt   n_yt   n_zt   verticest
   edges_deept   edges_rightt
   edges_downt   edges(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   _make_edges_3d   s    ).1%()c         C   s›   | j  \ } } } t j | |  d | | |  d | | | |  d | | | f | |  d | | |  d | | | |  d | | | f ƒ } | S(   Ni    i   (   t   shapeR   t   abs(   R   t   imgR   R   R   t   gradient(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   _compute_gradient_3d5   s    c         C   s   t  j |  j ƒ } | |  j ƒ  } t  j t  j | d | ƒ t  j | d | ƒ ƒ } | d d … | f } | d k	 rƒ | | } n  t | j ƒ  ƒ r¤ | j ƒ  } n d } t  j	 t  j
 | j ƒ  ƒ t  j | d ƒ ƒ } | | } | d k rò | S| | f Sd S(   s'   Apply a mask to edges (weighted or not)i    i   N(   R   R   t   sizeR   t   logical_andt   in1dt   Nonet   lent   maxt   searchsortedt   unique(   t   maskR   t   weightst   indst   ind_maskt   maxvalt   order(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   _mask_edges_weightsB   s    .
c         C   s   t  |  | | ƒ } | d k rB | d k r6 t j } qB | j } n  | d k	 r» t j | ƒ } t | | ƒ } | d k	 r£ t | | | ƒ \ } } | j ƒ  | }	 n | j	 ƒ  }	 |	 j
 }
 nŸ | d k	 r| j d t j d t ƒ } t j | d t j ƒ} t | | ƒ } t j | ƒ }
 n |  | | }
 t j | j d d | ƒ} t j |
 d | ƒ}	 t j |
 ƒ } t j | d | d f ƒ } t j | d | d f ƒ } t j t j | | |	 f ƒ t j | | f ƒ t j | | f ƒ f f |
 |
 f d | ƒ} | t j k r| j ƒ  S| | ƒ S(   s:   Auxiliary function for img_to_graph and grid_to_graph
    t   dtypet   copyi   i    N(   R   R"   R   t   intR.   t
   atleast_3dR   R-   t   squeezeR   R   t   astypet   boolt   Falset   asarrayt   sumt   onesR   R   R   R   t
   coo_matrixt   ndarrayt   toarray(   R   R   R   R'   R   t	   return_asR.   R   R(   t   diagt   n_voxelst   diag_idxt   i_idxt   j_idxt   graph(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt	   _to_graphW   s@    	
c         C   s=   t  j |  ƒ }  |  j \ } } } t | | | | |  | | ƒ S(   sÈ  Graph of the pixel-to-pixel gradient connections

    Edges are weighted with the gradient values.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    img : ndarray, 2D or 3D
        2D or 3D image
    mask : ndarray of booleans, optional
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class, optional
        The class to use to build the returned adjacency matrix.
    dtype : None or dtype, optional
        The data of the returned sparse matrix. By default it is the
        dtype of img

    Notes
    -----
    For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was
    handled by returning a dense np.matrix instance.  Going forward, np.ndarray
    returns an np.ndarray, as expected.

    For compatibility, user code relying on this method should wrap its
    calls in ``np.asarray`` to avoid type issues.
    (   R   R1   R   RC   (   R   R'   R<   R.   R   R   R   (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyR	   „   s    c      
   C   s"   t  |  | | d | d | d | ƒS(   sÅ  Graph of the pixel-to-pixel connections

    Edges exist if 2 voxels are connected.

    Parameters
    ----------
    n_x : int
        Dimension in x axis
    n_y : int
        Dimension in y axis
    n_z : int, optional, default 1
        Dimension in z axis
    mask : ndarray of booleans, optional
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class, optional
        The class to use to build the returned adjacency matrix.
    dtype : dtype, optional, default int
        The data of the returned sparse matrix. By default it is int

    Notes
    -----
    For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was
    handled by returning a dense np.matrix instance.  Going forward, np.ndarray
    returns an np.ndarray, as expected.

    For compatibility, user code relying on this method should wrap its
    calls in ``np.asarray`` to avoid type issues.
    R'   R<   R.   (   RC   (   R   R   R   R'   R<   R.   (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyR   ¦   s    c         C   sÇ   |  | d } | | d } | | } | r¿ t  | t j ƒ rN | | k  rN | St  | t j ƒ rp | | k rp | St  | t j ƒ r¬ d | k  o™ d k  n r¬ t | | ƒ St d | ƒ ‚ n | Sd S(   s5  Compute the number of patches that will be extracted in an image.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    i_h : int
        The image height
    i_w : int
        The image with
    p_h : int
        The height of a patch
    p_w : int
        The width of a patch
    max_patches : integer or float, optional default is None
        The maximum number of patches to extract. If max_patches is a float
        between 0 and 1, it is taken to be a proportion of the total number
        of patches.
    i   i    s!   Invalid value for max_patches: %rN(   t
   isinstancet   numberst   Integralt   RealR0   t
   ValueError(   t   i_ht   i_wt   p_ht   p_wt   max_patchest   n_ht   n_wt   all_patches(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   _compute_n_patchesÌ   s    
i   c         C   s	  |  j  } t | t j ƒ r1 t | g | ƒ } n  t | t j ƒ rY t | g | ƒ } n  |  j } t d „  | Dƒ ƒ } |  | j } t j |  j ƒ t j | ƒ t j | ƒ d } t t	 | ƒ t	 | ƒ ƒ } t t	 | ƒ t	 | ƒ ƒ }	 t
 |  d | d |	 ƒ}
 |
 S(   sl  Extracts patches of any n-dimensional array in place using strides.

    Given an n-dimensional array it will return a 2n-dimensional array with
    the first n dimensions indexing patch position and the last n indexing
    the patch content. This operation is immediate (O(1)). A reshape
    performed on the first n dimensions will cause numpy to copy data, leading
    to a list of extracted patches.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    arr : ndarray
        n-dimensional array of which patches are to be extracted

    patch_shape : integer or tuple of length arr.ndim
        Indicates the shape of the patches to be extracted. If an
        integer is given, the shape will be a hypercube of
        sidelength given by its value.

    extraction_step : integer or tuple of length arr.ndim
        Indicates step size at which extraction shall be performed.
        If integer is given, then the step is uniform in all dimensions.


    Returns
    -------
    patches : strided ndarray
        2n-dimensional array indexing patches on first n dimensions and
        containing patches on the last n dimensions. These dimensions
        are fake, but this way no data is copied. A simple reshape invokes
        a copying operation to obtain a list of patches:
        result.reshape([-1] + list(patch_shape))
    c         s   s!   |  ] } t  d  d  | ƒ Vq d  S(   N(   t   sliceR"   (   t   .0t   st(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pys	   <genexpr>!  s    i   R   t   strides(   t   ndimRD   RE   t   Numbert   tupleRU   R   t   arrayR   t   listR   (   t   arrt   patch_shapet   extraction_stept   arr_ndimt   patch_stridest   slicest   indexing_stridest   patch_indices_shapeR   RU   t   patches(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   extract_patchesô   s    $		c         C   sv  |  j  d  \ } } | \ } } | | k r: t d ƒ ‚ n  | | k rU t d ƒ ‚ n  t |  d t ƒ}  |  j | | d f ƒ }  |  j  d } t |  d | | | f d d ƒ}	 t | | | | | ƒ }
 | r't | ƒ } | j | | d d	 |
 ƒ} | j | | d d	 |
 ƒ} |	 | | d
 f } n |	 } | j d | | | ƒ } | j  d d k rn| j |
 | | f ƒ S| Sd S(   s<  Reshape a 2D image into a collection of patches

    The resulting patches are allocated in a dedicated array.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    image : array, shape = (image_height, image_width) or
        (image_height, image_width, n_channels)
        The original image data. For color images, the last dimension specifies
        the channel: a RGB image would have `n_channels=3`.

    patch_size : tuple of ints (patch_height, patch_width)
        the dimensions of one patch

    max_patches : integer or float, optional default is None
        The maximum number of patches to extract. If max_patches is a float
        between 0 and 1, it is taken to be a proportion of the total number
        of patches.

    random_state : int, RandomState instance or None, optional (default=None)
        Pseudo number generator state used for random sampling to use if
        `max_patches` is not None.  If int, random_state is the seed used by
        the random number generator; If RandomState instance, random_state is
        the random number generator; If None, the random number generator is
        the RandomState instance used by `np.random`.

    Returns
    -------
    patches : array, shape = (n_patches, patch_height, patch_width) or
         (n_patches, patch_height, patch_width, n_channels)
         The collection of patches extracted from the image, where `n_patches`
         is either `max_patches` or the total number of patches that can be
         extracted.

    Examples
    --------

    >>> from sklearn.feature_extraction import image
    >>> one_image = np.arange(16).reshape((4, 4))
    >>> one_image
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    >>> patches = image.extract_patches_2d(one_image, (2, 2))
    >>> print(patches.shape)
    (9, 2, 2)
    >>> patches[0]
    array([[0, 1],
           [4, 5]])
    >>> patches[1]
    array([[1, 2],
           [5, 6]])
    >>> patches[8]
    array([[10, 11],
           [14, 15]])
    i   s@   Height of the patch should be less than the height of the image.s>   Width of the patch should be less than the width of the image.t   allow_ndiÿÿÿÿR\   R]   i   R   i    N(	   R   RH   R   t   TrueR   Rd   RQ   R   t   randint(   t   imaget
   patch_sizeRM   t   random_stateRI   RJ   RK   RL   t   n_colorst   extracted_patchest	   n_patchest   rngt   i_st   j_sRc   (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyR   .  s.    <		c         C   s0  | d  \ } } |  j  d d !\ } } t j | ƒ } | | d } | | d } xb t |  t t | ƒ t | ƒ ƒ ƒ D]< \ }	 \ }
 } | |
 |
 | … | | | … f c |	 7<qv Wxs t | ƒ D]e }
 x\ t | ƒ D]N } | |
 | f c t t |
 d | | |
 ƒ t | d | | | ƒ ƒ :<qÖ WqÃ W| S(   s  Reconstruct the image from all of its patches.

    Patches are assumed to overlap and the image is constructed by filling in
    the patches from left to right, top to bottom, averaging the overlapping
    regions.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    patches : array, shape = (n_patches, patch_height, patch_width) or
        (n_patches, patch_height, patch_width, n_channels)
        The complete set of patches. If the patches contain colour information,
        channels are indexed along the last dimension: RGB patches would
        have `n_channels=3`.

    image_size : tuple of ints (image_height, image_width) or
        (image_height, image_width, n_channels)
        the size of the image that will be reconstructed

    Returns
    -------
    image : array, shape = image_size
        the reconstructed image

    i   i   i   (   R   R   t   zerost   zipR    t   ranget   floatt   min(   Rc   t
   image_sizeRI   RJ   RK   RL   R   RN   RO   t   pt   it   j(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyR
   Ž  s    7.*&c           B   s5   e  Z d  Z d d d d „ Z d d „ Z d „  Z RS(   s5  Extracts patches from a collection of images

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    patch_size : tuple of ints (patch_height, patch_width)
        the dimensions of one patch

    max_patches : integer or float, optional default is None
        The maximum number of patches per image to extract. If max_patches is a
        float in (0, 1), it is taken to mean a proportion of the total number
        of patches.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    c         C   s   | |  _  | |  _ | |  _ d  S(   N(   Ri   RM   Rj   (   t   selfRi   RM   Rj   (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   __init__Ñ  s    		c         C   s   |  S(   s  Do nothing and return the estimator unchanged

        This method is just there to implement the usual API and hence
        work in pipelines.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            Training data.
        (    (   Rz   t   Xt   y(    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   fitÖ  s    c         C   s4  t  |  j ƒ |  _ | j d  \ } } } t j | | | | d f ƒ } | j d } |  j d k ry | d | d f } n	 |  j } | \ } } t | | | | |  j ƒ }	 | |	 f | }
 | d k rÖ |
 | f 7}
 n  t j	 |
 ƒ } xH t
 | ƒ D]: \ } } t | | |  j |  j ƒ | | |	 | d |	 +qò W| S(   s  Transforms the image samples in X into a matrix of patch data.

        Parameters
        ----------
        X : array, shape = (n_samples, image_height, image_width) or
            (n_samples, image_height, image_width, n_channels)
            Array of images from which to extract patches. For color images,
            the last dimension specifies the channel: a RGB image would have
            `n_channels=3`.

        Returns
        -------
        patches : array, shape = (n_patches, patch_height, patch_width) or
             (n_patches, patch_height, patch_width, n_channels)
             The collection of patches extracted from the images, where
             `n_patches` is either `n_samples * max_patches` or the total
             number of patches that can be extracted.

        i   iÿÿÿÿi
   i   N(   R   Rj   R   R   R   Ri   R"   RQ   RM   t   emptyt	   enumerateR   (   Rz   R|   t   n_imagesRI   RJ   t
   n_channelsRi   RK   RL   Rm   t   patches_shapeRc   t   iiRh   (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt	   transformã  s"    	/N(   t   __name__t
   __module__t   __doc__R"   R{   R~   R…   (    (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyR   »  s   (   Rˆ   t	   itertoolsR    RE   t   numpyR   t   scipyR   t   numpy.lib.stride_tricksR   t   utilsR   R   t   baseR   t   __all__R   R   R"   R-   R9   RC   R	   R0   R   RQ   Rd   R   R
   R   (    (    (    s?   lib/python2.7/site-packages/sklearn/feature_extraction/image.pyt   <module>   s2   		,"%(:`	-