U
    3dM                     @   s  d Z ddlmZ ddlmZmZm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
lmZ dddddgZd%ddZdd Zd&ddZdde
jdfddZde
jddddZd'de
jedddZd(ddZd)dd Zddd!d"dZd#d Z G d$d deZ!dS )*zj
The :mod:`sklearn.feature_extraction.image` submodule gathers utilities to
extract features from images.
    )product)IntegralNumberRealN)sparse)
as_strided   )check_arraycheck_random_state)Interval)BaseEstimatorPatchExtractorextract_patches_2dgrid_to_graphimg_to_graphreconstruct_from_patches_2d   c                 C   s   t | | | | ||f}t |ddddddf  |ddddddf  f}t |ddddf  |ddddf  f}t |dd  |dd  f}t |||f}|S )a%  Returns a list of edges for a 3D image.

    Parameters
    ----------
    n_x : int
        The size of the grid in the x direction.
    n_y : int
        The size of the grid in the y direction.
    n_z : integer, default=1
        The size of the grid in the z direction, defaults to 1
    Nr   )nparangereshapeZvstackravelhstack)n_xn_yn_zZverticesZ
edges_deepZedges_rightZ
edges_downedges r   D/tmp/pip-unpacked-wheel-zrfo1fqw/sklearn/feature_extraction/image.py_make_edges_3d"   s    B6&r   c              	   C   s   |j \}}}t|| d ||  | d ||  | | d ||  | f || d ||  | d ||  | | d ||  | f  }|S )Nr   r   )shaper   abs)r   img_r   r   Zgradientr   r   r   _compute_gradient_3d6   s"    r$   c                 C   s   t | j}||   }t t |d |t |d |}|dd|f }|dk	r\|| }t| rr| }nd}t t 	| t |d }|| }|dkr|S ||fS dS )z'Apply a mask to edges (weighted or not)r   r   N)
r   r   sizer   logical_andZin1dlenmaxZsearchsortedZflatnonzero)maskr   weightsZindsZind_maskmaxvalorderr   r   r   _mask_edges_weightsJ   s    $
r-   c                 C   sp  t | ||}|dkr(|dkr"t}n|j}|dk	rzt|}t||}|dk	rjt|||\}}| | }	n| }	|	j	}
nh|dk	r|j
tdd}tj|td}t||}t|}
n| | | }
tj|jd |d}tj|
|d}	t|
}t|d |d f}t|d |d f}tjt|||	ft||ft||fff|
|
f|d}|tjkrh| S ||S )z5Auxiliary function for img_to_graph and grid_to_graphNF)dtypecopy)r.   r   r   )r   intr.   r   
atleast_3dr$   r-   Zsqueezer   r%   ZastypeboolZasarraysumZonesr    r   r   r   
coo_matrixZndarrayZtoarray)r   r   r   r)   r"   	return_asr.   r   r*   ZdiagZn_voxelsZdiag_idxZi_idxZj_idxgraphr   r   r   	_to_graph^   sD    



r7   r)   r5   r.   c                C   s*   t | } | j\}}}t||||| ||S )a  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 of shape (height, width) or (height, width, channel)
        2D or 3D image.
    mask : ndarray of shape (height, width) or             (height, width, channel), dtype=bool, default=None
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class,             default=sparse.coo_matrix
        The class to use to build the returned adjacency matrix.
    dtype : dtype, default=None
        The data of the returned sparse matrix. By default it is the
        dtype of img.

    Returns
    -------
    graph : ndarray or a sparse matrix class
        The computed adjacency matrix.

    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    r7   )r"   r)   r5   r.   r   r   r   r   r   r   r      s    $
c                C   s   t | |||||dS )a`  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, default=1
        Dimension in z axis.
    mask : ndarray of shape (n_x, n_y, n_z), dtype=bool, default=None
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class,             default=sparse.coo_matrix
        The class to use to build the returned adjacency matrix.
    dtype : dtype, default=int
        The data of the returned sparse matrix. By default it is int.

    Returns
    -------
    graph : np.ndarray or a sparse matrix class
        The computed adjacency matrix.

    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.
    r8   )r7   )r   r   r   r)   r5   r.   r   r   r   r      s    &c                 C   s   | | d }|| d }|| }|rt |tr:||k r:|S t |trP||krP|S t |tr~d|  k rndk r~n nt|| S td| n|S dS )a%  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 : int or float, default=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.
    r   r   z!Invalid value for max_patches: %rN)
isinstancer   r   r0   
ValueError)i_hi_wp_hp_wmax_patchesn_hn_wZall_patchesr   r   r   _compute_n_patches   s    "rB      c                 C   s   | j }t|trt|g| }t|tr6t|g| }| j}tdd |D }| | j}t| jt| t| d }tt|t| }tt|t| }	t	| ||	d}
|
S )ay  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 : int or tuple of length arr.ndim.default=8
        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 : int or tuple of length arr.ndim, default=1
        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)slice).0str   r   r   	<genexpr>6  s     z#_extract_patches.<locals>.<genexpr>r   )r    strides)
ndimr9   r   tuplerI   r   arrayr    listr   )Zarrpatch_shapeextraction_stepZarr_ndimZpatch_stridesZslicesZindexing_stridesZpatch_indices_shaper    rI   patchesr   r   r   _extract_patches	  s    $


rQ   r?   random_statec                C   s  | j dd \}}|\}}||kr*td||kr:tdt| dd} | ||df} | j d }t| |||fdd	}	t|||||}
|rt|}|j|| d |
d
}|j|| d |
d
}|	||df }n|	}|d|||}|j d dkr ||
||fS |S dS )a_  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 : ndarray of 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 int (patch_height, patch_width)
        The dimensions of one patch.

    max_patches : int or float, default=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, default=None
        Determines the random number generator used for random sampling when
        `max_patches` is not None. Use an int to make the randomness
        deterministic.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    patches : array of 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.datasets import load_sample_image
    >>> from sklearn.feature_extraction import image
    >>> # Use the array data from the first image in this dataset:
    >>> one_image = load_sample_image("china.jpg")
    >>> print('Image shape: {}'.format(one_image.shape))
    Image shape: (427, 640, 3)
    >>> patches = image.extract_patches_2d(one_image, (2, 2))
    >>> print('Patches shape: {}'.format(patches.shape))
    Patches shape: (272214, 2, 2, 3)
    >>> # Here are just two of these patches:
    >>> print(patches[1])
    [[[174 201 231]
      [174 201 231]]
     [[173 200 230]
      [173 200 230]]]
    >>> print(patches[800])
    [[[187 214 243]
      [188 215 244]]
     [[187 214 243]
      [188 215 244]]]
    Nr   z@Height of the patch should be less than the height of the image.z>Width of the patch should be less than the width of the image.T)Zallow_ndr   r   )rN   rO   )r%   r   )r    r:   r	   r   rQ   rB   r
   randint)image
patch_sizer?   rS   r;   r<   r=   r>   Zn_colorsZextracted_patches	n_patchesrngZi_sZj_srP   r   r   r   r   D  s:    ;
  c                 C   s   |dd \}}| j dd \}}t|}|| d }|| d }t| tt|t|D ]0\}	\}
}||
|
| ||| f  |	7  < q\t|D ]N}
t|D ]@}||
|f  tt|
d |||
 t|d |||    < qq|S )a  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 : ndarray of 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 int (image_height, image_width) or         (image_height, image_width, n_channels)
        The size of the image that will be reconstructed.

    Returns
    -------
    image : ndarray of shape image_size
        The reconstructed image.
    Nr   r      )r    r   zeroszipr   rangefloatmin)rP   Z
image_sizer;   r<   r=   r>   r"   r@   rA   pijr   r   r   r     s    
$&@c                	   @   sv   e Zd ZU dZedgdeeddddeeddddgdgd	Ze	e
d
< dddd	ddZdddZdd Zdd ZdS )r   a  Extracts patches from a collection of images.

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

    .. versionadded:: 0.9

    Parameters
    ----------
    patch_size : tuple of int (patch_height, patch_width), default=None
        The dimensions of one patch.

    max_patches : int or float, default=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, default=None
        Determines the random number generator used for random sampling when
        `max_patches is not None`. Use an int to make the randomness
        deterministic.
        See :term:`Glossary <random_state>`.

    See Also
    --------
    reconstruct_from_patches_2d : Reconstruct image from all of its patches.

    Examples
    --------
    >>> from sklearn.datasets import load_sample_images
    >>> from sklearn.feature_extraction import image
    >>> # Use the array data from the second image in this dataset:
    >>> X = load_sample_images().images[1]
    >>> print('Image shape: {}'.format(X.shape))
    Image shape: (427, 640, 3)
    >>> pe = image.PatchExtractor(patch_size=(2, 2))
    >>> pe_fit = pe.fit(X)
    >>> pe_trans = pe.transform(X)
    >>> print('Patches shape: {}'.format(pe_trans.shape))
    Patches shape: (545706, 2, 2)
    Nr   r   Zneither)closedleftrS   rV   r?   rS   _parameter_constraintsc                C   s   || _ || _|| _d S rD   rd   )selfrV   r?   rS   r   r   r   __init__  s    zPatchExtractor.__init__c                 C   s   |    | S )a  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 of shape (n_samples, n_features)
            Training data.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
        )Z_validate_params)rf   Xyr   r   r   fit	  s    zPatchExtractor.fitc                 C   s   t | j| _|jdd \}}}t||||df}|jd }| jdkrZ|d |d f}n| j}|\}}t||||| j}	||	 f| }
|dkr|
|f7 }
t|
}t	|D ]0\}}t
||| j| jd|||	 |d |	 < q|S )a  Transform the image samples in `X` into a matrix of patch data.

        Parameters
        ----------
        X : ndarray of 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 of 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.
        NrY   r   
   r   rR   )r
   rS   r    r   r   rV   rB   r?   empty	enumerater   )rf   rh   Zn_imagesr;   r<   Z
n_channelsrV   r=   r>   rW   Zpatches_shaperP   iirU   r   r   r   	transform  s*    



zPatchExtractor.transformc                 C   s
   ddgiS )NZX_typesZ3darrayr   )rf   r   r   r   
_more_tagsM  s    zPatchExtractor._more_tags)N)__name__
__module____qualname____doc__rK   r   r   r   re   dict__annotations__rg   rj   ro   rp   r   r   r   r   r     s   
*

.)r   )N)r   )N)rC   r   )"rt   	itertoolsr   Znumbersr   r   r   Znumpyr   Zscipyr   Znumpy.lib.stride_tricksr   utilsr	   r
   Zutils._param_validationr   baser   __all__r   r$   r-   r4   r7   r   r0   r   rB   rQ   r   r   r   r   r   r   r   <module>   sD   

   
0*   -
%
;a+