ó
 ‰\c           @   s¹   d  Z  d d l m Z d d l Z d d l Z d d l m Z m Z d d l	 m
 Z
 m Z d d l m Z d Z e
 e ƒ d d	 d
 d „ ƒ Z d d „ Z d „  Z d „  Z d „  Z d S(   sé  
Adapted code from "Contrast Limited Adaptive Histogram Equalization" by Karel
Zuiderveld <karel@cv.ruu.nl>, Graphics Gems IV, Academic Press, 1994.

http://tog.acm.org/resources/GraphicsGems/

The Graphics Gems code is copyright-protected.  In other words, you cannot
claim the text of the code as your own and resell it. Using the code is
permitted in any program, product, or library, non-commercial or commercial.
Giving credit is not required, though is a nice gesture.  The code comes as-is,
and if there are any flaws or problems with any Gems code, nobody involved with
Gems - authors, editors, publishers, or webmasters - are to be held
responsible.  Basically, don't be a jerk, and remember that anything free
comes with no guarantee.
iÿÿÿÿ(   t   divisionNi   (   t   img_as_floatt   img_as_uint(   t	   adapt_rgbt	   hsv_value(   t   rescale_intensityi   g{®Gáz„?i   c         C   s÷   t  |  ƒ }  t |  d d t d f ƒ}  | d k rY |  j d d |  j d d f } nP t | t j ƒ r~ | f |  j } n+ t	 | ƒ |  j k r© t
 d j | ƒ ƒ n  g  | D] } t | ƒ ^ q° } t |  | | | | ƒ }  t |  ƒ }  t |  ƒ S(   s1  Contrast Limited Adaptive Histogram Equalization (CLAHE).

    An algorithm for local contrast enhancement, that uses histograms computed
    over different tile regions of the image. Local details can therefore be
    enhanced even in regions that are darker or lighter than most of the image.

    Parameters
    ----------
    image : (M, N[, C]) ndarray
        Input image.
    kernel_size: integer or list-like, optional
        Defines the shape of contextual regions used in the algorithm. If
        iterable is passed, it must have the same number of elements as
        ``image.ndim`` (without color channel). If integer, it is broadcasted
        to each `image` dimension. By default, ``kernel_size`` is 1/8 of
        ``image`` height by 1/8 of its width.
    clip_limit : float, optional
        Clipping limit, normalized between 0 and 1 (higher values give more
        contrast).
    nbins : int, optional
        Number of gray bins for histogram ("data range").

    Returns
    -------
    out : (M, N[, C]) ndarray
        Equalized image.

    See Also
    --------
    equalize_hist, rescale_intensity

    Notes
    -----
    * For color images, the following steps are performed:
       - The image is converted to HSV color space
       - The CLAHE algorithm is run on the V (Value) channel
       - The image is converted back to RGB space and returned
    * For RGBA images, the original alpha channel is removed.

    References
    ----------
    .. [1] http://tog.acm.org/resources/GraphicsGems/
    .. [2] https://en.wikipedia.org/wiki/CLAHE#CLAHE
    t	   out_rangei    i   i   s$   Incorrect value of `kernel_size`: {}N(   R   R   t
   NR_OF_GREYt   Nonet   shapet
   isinstancet   numberst   Numbert   ndimt   lent
   ValueErrort   formatt   intt   _claheR   (   t   imaget   kernel_sizet
   clip_limitt   nbinst   k(    (    s:   lib/python2.7/site-packages/skimage/exposure/_adapthist.pyt   equalize_adapthist   s    /%i€   c         C   s·  | d k r |  St  t j |  j d | d ƒ ƒ } t  t j |  j d | d ƒ ƒ } t  t j |  j d | ƒ ƒ } t  t j |  j d | ƒ ƒ } d t | } t j t ƒ }	 |	 | }	 t j | | | f d t  ƒ}
 x"t | ƒ D]} xt | ƒ D]ý } |  | | | d | … | | | d | … f } | d k rrt  | | j	 | ƒ } | d k  rxd } qxn t } |	 | j
 ƒ  } t j | ƒ } t j | t j | | j	 d t  ƒƒ } t | | ƒ } t | d t d | j	 ƒ } | |
 | | f <qý Wqê Wd } x¨t | d ƒ D]–} d } | d k rJ| d } d } d } nC | | k rs| d } | d } | } n | } | d } | d } xt | d ƒ D]} | d k rÉ| d } d } d } nC | | k rò| d } | d } | } n | } | d } | d } |
 | | f } |
 | | f } |
 | | f } |
 | | f } t j | | | ƒ } t j | | | ƒ } t |  | | | | | | |	 ƒ | | 7} qžW| | 7} qW|  S(   sQ  Contrast Limited Adaptive Histogram Equalization.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    kernel_size: 2-tuple of int
        Defines the shape of contextual regions used in the algorithm.
    clip_limit : float
        Normalized clipping limit (higher values give more contrast).
    nbins : int, optional
        Number of gray bins for histogram ("data range").

    Returns
    -------
    out : (M, N) ndarray
        Equalized image.

    The number of "effective" greylevels in the output image is set by `nbins`;
    selecting a small value (eg. 128) speeds up processing and still produce
    an output image of good quality. The output image will have the same
    minimum and maximum value as the input image. A clip limit smaller than 1
    results in standard (non-contrast limited) AHE.
    g      ð?i    i   t   dtypeg        g       @(   R   t   npt   ceilR	   t   floorR   t   aranget   zerost   ranget   sizet   ravelt   bincountt   appendt   clip_histogramt   map_histogramt   interpolate(   R   R   R   R   t   nrt   nct   row_stept   col_stept   bin_sizet   lutt	   map_arrayt   rt   ct   sub_imgt   climt   histt   rstartt   cstartt   r_offsett   rUt   rBt   c_offsett   cLt   cRt   mapLUt   mapRUt   mapLBt   mapRBt   cslicet   rslice(    (    s:   lib/python2.7/site-packages/skimage/exposure/_adapthist.pyR   [   s|    $$  
(
	

	


	

	

c         C   s¹  |  | k } |  | } | j  ƒ  | j | } t | |  j ƒ } | | } | |  | <|  | k  } | |  | j | 8} |  | c | 7<|  | k |  | k  @} |  | }	 | |	 j | |	 j  ƒ  8} | |  | <| }
 xâ | d k r´d } x³ | d k rš| |  j k  rš|  d k  } t |  |  | k  j | ƒ } t | d ƒ } t j | |  j | ƒ } t | | <| |  | k  @} |  | c d 7<| | j  ƒ  8} | d 7} qè W|
 | k r«Pn  | }
 qÓ W|  S(   sé  Perform clipping of the histogram and redistribution of bins.

    The histogram is clipped and the number of excess pixels is counted.
    Afterwards the excess pixels are equally redistributed across the
    whole histogram (providing the bin count is smaller than the cliplimit).

    Parameters
    ----------
    hist : ndarray
        Histogram array.
    clip_limit : int
        Maximum allowed bin count.

    Returns
    -------
    hist : ndarray
        Clipped histogram.
    i    i   (   t   sumR    R   t   maxR   R   t   True(   R2   R   t   excess_maskt   excesst   n_excesst   bin_incrt   uppert   low_maskt   mid_maskt   midt   prev_n_excesst   indext
   under_maskt	   step_sizet   indices(    (    s:   lib/python2.7/site-packages/skimage/exposure/_adapthist.pyR$   É   s<    






c         C   s]   t  j |  ƒ j t ƒ } t | | ƒ | } | | 9} | | 7} | | | | k <| j t ƒ S(   s¡  Calculate the equalized lookup table (mapping).

    It does so by cumulating the input histogram.

    Parameters
    ----------
    hist : ndarray
        Clipped histogram.
    min_val : int
        Minimum value for mapping.
    max_val : int
        Maximum value for mapping.
    n_pixels : int
        Number of pixels in the region.

    Returns
    -------
    out : ndarray
       Mapped intensity LUT.
    (   R   t   cumsumt   astypet   floatR   (   R2   t   min_valt   max_valt   n_pixelst   outt   scale(    (    s:   lib/python2.7/site-packages/skimage/exposure/_adapthist.pyR%     s    

c         C   s/  | j  | j  } t j t j | j  ƒ t j | j  ƒ ƒ \ }	 }
 |	 d d … d d d … f d |
 d d d … d } } |  t | d ƒ t | d d ƒ … t | d ƒ t | d d ƒ … f } | | } | | | | |	 | | |
 | | | |	 | | | } | | d d … d d … f <|  S(   s·  Find the new grayscale level for a region using bilinear interpolation.

    Parameters
    ----------
    image : ndarray
        Full image.
    xslice, yslice : array-like
       Indices of the region.
    map* : ndarray
        Mappings of greylevels from histograms.
    lut : ndarray
        Maps grayscale levels in image to histogram levels.

    Returns
    -------
    out : ndarray
        Original image with the subregion replaced.

    Notes
    -----
    This function calculates the new greylevel assignments of pixels within
    a submatrix of the image. This is done by a bilinear interpolation between
    four different mappings in order to eliminate boundary artifacts.
    Niÿÿÿÿi   i    (   R    R   t   meshgridR   R   (   R   t   xslicet   ysliceR;   R<   R=   R>   R,   t   normt   x_coeft   y_coeft
   x_inv_coeft
   y_inv_coeft   viewt   im_slicet   new(    (    s:   lib/python2.7/site-packages/skimage/exposure/_adapthist.pyR&   #  s    ;$(
i @  (   t   __doc__t
   __future__R    R   t   numpyR   t   utilR   R   t   color.adapt_rgbR   R   t   exposureR   R   R   R   R   R$   R%   R&   (    (    (    s:   lib/python2.7/site-packages/skimage/exposure/_adapthist.pyt   <module>   s   	>n	=	