ó
 \c           @   sŞ   d  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
 m Z m Z d e e d	  Z d
 d  Z d d  Z d   Z d d d d d  Z d S(   s)   
Methods to characterize image textures.
i˙˙˙˙Ni   (   t	   assert_nD(   t   img_as_float(   t   gray2rgbi   (   t
   _glcm_loopt   _local_binary_patternt   _multiblock_lbpc   
      C   s  t  |  d  t  | d d  t  | d d  t j |   }  |  j   } t j |  j t j  ro t d   n  |  j t j t j	 f k rĽ | d k rĽ t d   n  t j |  j t j  rá t j |  d k   rá t d   n  | d k rö d	 } n  | | k rt d
   n  t j | d t j } t j | d t j } t j | | t |  t |  f d t j d d } t |  | | | |  | r˛t j | d  } | | } n  | r| j t j  } t j t j | d d }	 d |	 |	 d k <| |	 :} n  | S(   sË  Calculate the grey-level co-occurrence matrix.

    A grey level co-occurrence matrix is a histogram of co-occurring
    greyscale values at a given offset over an image.

    Parameters
    ----------
    image : array_like
        Integer typed input image. Only positive valued images are supported.
        If type is other than uint8, the argument `levels` needs to be set.
    distances : array_like
        List of pixel pair distance offsets.
    angles : array_like
        List of pixel pair angles in radians.
    levels : int, optional
        The input image should contain integers in [0, `levels`-1],
        where levels indicate the number of grey-levels counted
        (typically 256 for an 8-bit image). This argument is required for
        16-bit images or higher and is typically the maximum of the image.
        As the output matrix is at least `levels` x `levels`, it might
        be preferable to use binning of the input image rather than
        large values for `levels`.
    symmetric : bool, optional
        If True, the output matrix `P[:, :, d, theta]` is symmetric. This
        is accomplished by ignoring the order of value pairs, so both
        (i, j) and (j, i) are accumulated when (i, j) is encountered
        for a given offset. The default is False.
    normed : bool, optional
        If True, normalize each matrix `P[:, :, d, theta]` by dividing
        by the total number of accumulated co-occurrences for the given
        offset. The elements of the resulting matrix sum to 1. The
        default is False.

    Returns
    -------
    P : 4-D ndarray
        The grey-level co-occurrence histogram. The value
        `P[i,j,d,theta]` is the number of times that grey-level `j`
        occurs at a distance `d` and at an angle `theta` from
        grey-level `i`. If `normed` is `False`, the output is of
        type uint32, otherwise it is float64. The dimensions are:
        levels x levels x number of distances x number of angles.

    References
    ----------
    .. [1] The GLCM Tutorial Home Page,
           http://www.fp.ucalgary.ca/mhallbey/tutorial.htm
    .. [2] Pattern Recognition Engineering, Morton Nadler & Eric P.
           Smith
    .. [3] Wikipedia, http://en.wikipedia.org/wiki/Co-occurrence_matrix


    Examples
    --------
    Compute 2 GLCMs: One for a 1-pixel offset to the right, and one
    for a 1-pixel offset upwards.

    >>> image = np.array([[0, 0, 1, 1],
    ...                   [0, 0, 1, 1],
    ...                   [0, 2, 2, 2],
    ...                   [2, 2, 3, 3]], dtype=np.uint8)
    >>> result = greycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4],
    ...                       levels=4)
    >>> result[:, :, 0, 0]
    array([[2, 2, 1, 0],
           [0, 2, 0, 0],
           [0, 0, 3, 1],
           [0, 0, 0, 1]], dtype=uint32)
    >>> result[:, :, 0, 1]
    array([[1, 1, 3, 0],
           [0, 1, 1, 0],
           [0, 0, 0, 2],
           [0, 0, 0, 0]], dtype=uint32)
    >>> result[:, :, 0, 2]
    array([[3, 0, 2, 0],
           [0, 2, 2, 0],
           [0, 0, 1, 2],
           [0, 0, 0, 0]], dtype=uint32)
    >>> result[:, :, 0, 3]
    array([[2, 0, 0, 0],
           [1, 1, 2, 0],
           [0, 0, 2, 1],
           [0, 0, 0, 0]], dtype=uint32)

    i   i   t	   distancest   angless^   Float images are not supported by greycomatrix. Convert the image to an unsigned integer type.s{   The levels argument is required for data types other than uint8. The resulting matrix will be at least levels ** 2 in size.i    s)   Negative-valued images are not supported.i   sU   The maximum grayscale value in the image should be smaller than the number of levels.t   dtypet   ordert   Ci   t   axesN(   i   i    i   i   (   i    i   (   R    t   npt   ascontiguousarrayt   maxt
   issubdtypeR   t   floatingt
   ValueErrort   uint8t   int8t   Nonet   signedintegert   anyt   float64t   zerost   lent   uint32R   t	   transposet   astypet   apply_over_axest   sum(
   t   imageR   R   t   levelst	   symmetrict   normedt	   image_maxt   Pt   Ptt	   glcm_sums(    (    s6   lib/python2.7/site-packages/skimage/feature/texture.pyt   greycomatrix   s:    W'-	$t   contrastc         C   sm  t  |  d d  |  j \ } } } } | | k s7 t  | d k sI t  | d k s[ t  t j d |  d |  f \ } } | d k r | | d } nf | d k rż t j | |  } nD | d k rä d d | | d } n | d k ró n t d |   | d
 k rDt j t j |  d d d d }	 t j	 |	  }
 n%| d	 k rvt j t j |  d d d d }
 nó| d k rt j
 | | f d t j }
 t j t |   j | d d d f  } t j t |   j d | d d f  } | t j t j | |  d d d } | t j t j | |  d d d } t j	 t j t j |  | d d d d  } t j	 t j t j |  | d d d d  } t j t j |  | | d d d } | d k  } t | | d k  <d |
 | <| t k } | | | | | | |
 | <nM | d  k ri| j | | d d f  } t j t j |  | d d! d" }
 n  |
 S(#   sě  Calculate texture properties of a GLCM.

    Compute a feature of a grey level co-occurrence matrix to serve as
    a compact summary of the matrix. The properties are computed as
    follows:

    - 'contrast': :math:`\sum_{i,j=0}^{levels-1} P_{i,j}(i-j)^2`
    - 'dissimilarity': :math:`\sum_{i,j=0}^{levels-1}P_{i,j}|i-j|`
    - 'homogeneity': :math:`\sum_{i,j=0}^{levels-1}\frac{P_{i,j}}{1+(i-j)^2}`
    - 'ASM': :math:`\sum_{i,j=0}^{levels-1} P_{i,j}^2`
    - 'energy': :math:`\sqrt{ASM}`
    - 'correlation':
        .. math:: \sum_{i,j=0}^{levels-1} P_{i,j}\left[\frac{(i-\mu_i) \
                  (j-\mu_j)}{\sqrt{(\sigma_i^2)(\sigma_j^2)}}\right]


    Parameters
    ----------
    P : ndarray
        Input array. `P` is the grey-level co-occurrence histogram
        for which to compute the specified property. The value
        `P[i,j,d,theta]` is the number of times that grey-level j
        occurs at a distance d and at an angle theta from
        grey-level i.
    prop : {'contrast', 'dissimilarity', 'homogeneity', 'energy',             'correlation', 'ASM'}, optional
        The property of the GLCM to compute. The default is 'contrast'.

    Returns
    -------
    results : 2-D ndarray
        2-dimensional array. `results[d, a]` is the property 'prop' for
        the d'th distance and the a'th angle.

    References
    ----------
    .. [1] The GLCM Tutorial Home Page,
           http://www.fp.ucalgary.ca/mhallbey/tutorial.htm

    Examples
    --------
    Compute the contrast for GLCMs with distances [1, 2] and angles
    [0 degrees, 90 degrees]

    >>> image = np.array([[0, 0, 1, 1],
    ...                   [0, 0, 1, 1],
    ...                   [0, 2, 2, 2],
    ...                   [2, 2, 3, 3]], dtype=np.uint8)
    >>> g = greycomatrix(image, [1, 2], [0, np.pi/2], levels=4,
    ...                  normed=True, symmetric=True)
    >>> contrast = greycoprops(g, 'contrast')
    >>> contrast
    array([[ 0.58333333,  1.        ],
           [ 1.25      ,  2.75      ]])

    i   R$   i    R(   i   t   dissimilarityt   homogeneityg      đ?t   ASMt   energyt   correlations   %s is an invalid propertyR   i   R   gVçŻŇ<(   R+   R,   R-   (   i    i   (   i    i    (   i    i   (   i    i    (   i    i   (   i    i    (   i    i   (   i    i    (   i    i   (   i    i    (   i    i   (   i    i    (   i    i   (   i    i    (   R(   R)   R*   (   i    i   (   i    i    (   R    t   shapet   AssertionErrorR   t   ogridt   absR   R   R   t   sqrtR   R   t   arrayt   ranget   reshapet   Truet   False(   R$   t   propt	   num_levelt
   num_level2t   num_distt	   num_anglet   It   Jt   weightst   asmt   resultst   diff_it   diff_jt   std_it   std_jt   covt   mask_0t   mask_1(    (    s6   lib/python2.7/site-packages/skimage/feature/texture.pyt   greycoprops   sR    9%#&**''  
!&t   defaultc         C   s   t  |  d  i t d  d 6t d  d 6t d  d 6t d  d	 6t d
  d 6} t j |  d t j }  t |  | | | | j    } | S(   sć  Gray scale and rotation invariant LBP (Local Binary Patterns).

    LBP is an invariant descriptor that can be used for texture classification.

    Parameters
    ----------
    image : (N, M) array
        Graylevel image.
    P : int
        Number of circularly symmetric neighbour set points (quantization of
        the angular space).
    R : float
        Radius of circle (spatial resolution of the operator).
    method : {'default', 'ror', 'uniform', 'var'}
        Method to determine the pattern.

        * 'default': original local binary pattern which is gray scale but not
            rotation invariant.
        * 'ror': extension of default implementation which is gray scale and
            rotation invariant.
        * 'uniform': improved rotation invariance with uniform patterns and
            finer quantization of the angular space which is gray scale and
            rotation invariant.
        * 'nri_uniform': non rotation-invariant uniform patterns variant
            which is only gray scale invariant [2]_.
        * 'var': rotation invariant variance measures of the contrast of local
            image texture which is rotation but not gray scale invariant.

    Returns
    -------
    output : (N, M) array
        LBP image.

    References
    ----------
    .. [1] Multiresolution Gray-Scale and Rotation Invariant Texture
           Classification with Local Binary Patterns.
           Timo Ojala, Matti Pietikainen, Topi Maenpaa.
           http://www.ee.oulu.fi/research/mvmp/mvg/files/pdf/pdf_94.pdf, 2002.
    .. [2] Face recognition with local binary patterns.
           Timo Ahonen, Abdenour Hadid, Matti Pietikainen,
           http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851,
           2004.
    i   t   DRJ   t   Rt   rort   Ut   uniformt   Nt   nri_uniformt   Vt   varR   (   R    t   ordR   R   t   doubleR   t   lower(   R   R$   RL   t   methodt   methodst   output(    (    s6   lib/python2.7/site-packages/skimage/feature/texture.pyt   local_binary_pattern	  s    -c         C   s4   t  j |  d t  j }  t |  | | | |  } | S(   s  Multi-block local binary pattern (MB-LBP).

    The features are calculated similarly to local binary patterns (LBPs),
    (See :py:meth:`local_binary_pattern`) except that summed blocks are
    used instead of individual pixel values.

    MB-LBP is an extension of LBP that can be computed on multiple scales
    in constant time using the integral image. Nine equally-sized rectangles
    are used to compute a feature. For each rectangle, the sum of the pixel
    intensities is computed. Comparisons of these sums to that of the central
    rectangle determine the feature, similarly to LBP.

    Parameters
    ----------
    int_image : (N, M) array
        Integral image.
    r : int
        Row-coordinate of top left corner of a rectangle containing feature.
    c : int
        Column-coordinate of top left corner of a rectangle containing feature.
    width : int
        Width of one of the 9 equal rectangles that will be used to compute
        a feature.
    height : int
        Height of one of the 9 equal rectangles that will be used to compute
        a feature.

    Returns
    -------
    output : int
        8-bit MB-LBP feature descriptor.

    References
    ----------
    .. [1] Face Detection Based on Multi-Block LBP
           Representation. Lun Zhang, Rufeng Chu, Shiming Xiang, Shengcai Liao,
           Stan Z. Li
           http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf
    R   (   R   R   t   float32R   (   t	   int_imaget   rt   ct   widtht   heightt   lbp_code(    (    s6   lib/python2.7/site-packages/skimage/feature/texture.pyt   multiblock_lbpD  s    )i    gŽGázć?g¸ëQ¸î?g      ŕ?c	      	   C   sô  t  j | d t  j } t  j | d t  j } t  j |   }	 t |  j  d k  rc t |   }	 n  t |	  }	 d d	 d
 d d d d d f }
 t  j |
  }
 |
 d d  d f c | 9<|
 d d  d f c | 9<| | } | | } xt	 |
  D]÷ \ } } | \ } } | | } | | } | d d | >@} | rd | |	 | | |  | | |  f | | } | |	 | | |  | | |  f <qő d | |	 | | |  | | |  f | | } | |	 | | |  | | |  f <qő W|	 S(   s  Multi-block local binary pattern visualization.

    Blocks with higher sums are colored with alpha-blended white rectangles,
    whereas blocks with lower sums are colored alpha-blended cyan. Colors
    and the `alpha` parameter can be changed.

    Parameters
    ----------
    image : ndarray of float or uint
        Image on which to visualize the pattern.
    r : int
        Row-coordinate of top left corner of a rectangle containing feature.
    c : int
        Column-coordinate of top left corner of a rectangle containing feature.
    width : int
        Width of one of 9 equal rectangles that will be used to compute
        a feature.
    height : int
        Height of one of 9 equal rectangles that will be used to compute
        a feature.
    lbp_code : int
        The descriptor of feature to visualize. If not provided, the
        descriptor with 0 value will be used.
    color_greater_block : tuple of 3 floats
        Floats specifying the color for the block that has greater
        intensity value. They should be in the range [0, 1].
        Corresponding values define (R, G, B) values. Default value
        is white (1, 1, 1).
    color_greater_block : tuple of 3 floats
        Floats specifying the color for the block that has greater intensity
        value. They should be in the range [0, 1]. Corresponding values define
        (R, G, B) values. Default value is cyan (0, 0.69, 0.96).
    alpha : float
        Value in the range [0, 1] that specifies opacity of visualization.
        1 - fully transparent, 0 - opaque.

    Returns
    -------
    output : ndarray of float
        Image with MB-LBP visualization.

    References
    ----------
    .. [1] Face Detection Based on Multi-Block LBP
           Representation. Lun Zhang, Rufeng Chu, Shiming Xiang, Shengcai Liao,
           Stan Z. Li
           http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf
    R   i   i˙˙˙˙i    i   Ni   (   i˙˙˙˙i˙˙˙˙(   i˙˙˙˙i    (   i˙˙˙˙i   (   i    i   (   i   i   (   i   i    (   i   i˙˙˙˙(   i    i˙˙˙˙(
   R   t   asarrayR   t   copyR   R.   R   R   R3   t	   enumerate(   R   R]   R^   R_   R`   Ra   t   color_greater_blockt   color_less_blockt   alphaRY   t   neighbour_rect_offsetst   central_rect_rt   central_rect_ct   element_numt   offsett   offset_rt   offset_ct   curr_rt   curr_ct   has_greater_valuet	   new_value(    (    s6   lib/python2.7/site-packages/skimage/feature/texture.pyt   draw_multiblock_lbpr  s:    :		



"'"((   i   i   i   (   i    gŽGázć?g¸ëQ¸î?(   t   __doc__t   numpyR   t   _shared.utilsR    t   utilR   t   colorR   t   _textureR   R   R   R   R7   R'   RI   RZ   Rb   Rt   (    (    (    s6   lib/python2.7/site-packages/skimage/feature/texture.pyt   <module>   s   p;	/