
    1-Ph*                         d Z ddlZddlZddlZddlmZ ddlmZm	Z	 ddl
mZ ddlmZ d	Z ee	          dd            Zd Zd Zd ZdS )z
Adapted from "Contrast Limited Adaptive Histogram Equalization" by Karel
Zuiderveld, Graphics Gems IV, Academic Press, 1994.

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

Relicensed with permission of the author under the Modified BSD license.
    N   )_supported_float_type)	adapt_rgb	hsv_value   )rescale_intensity)img_as_uinti @  {Gz?   c                 `   t          | j                  }t          |           } t          j        t          | dt          dz
  f                                        t          j        t                              } |t          d | j
        D                       }nPt          |t          j                  r|f| j        z  }n*t          |          | j        k    rt!          d|           d |D             }t#          | |||          } |                     |d	          } t          |           S )
a  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[, ...][, C]) ndarray
        Input image.
    kernel_size : int or array_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[, ...][, C]) ndarray
        Equalized image with float64 dtype.

    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.

    .. versionchanged:: 0.17
        The values returned by this function are slightly shifted upwards
        because of an internal change in rounding behavior.

    References
    ----------
    .. [1] http://tog.acm.org/resources/GraphicsGems/
    .. [2] https://en.wikipedia.org/wiki/CLAHE#CLAHE
    r   r   )	out_rangeNc                 4    g | ]}t          |d z  d          S )   r   )max).0ss     [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/exposure/_adapthist.py
<listcomp>z&equalize_adapthist.<locals>.<listcomp>Q   s$    AAASa^^AAA    z"Incorrect value of `kernel_size`: c                 ,    g | ]}t          |          S  intr   ks     r   r   z&equalize_adapthist.<locals>.<listcomp>W   s    ///a3q66///r   F)copy)r   dtyper	   nproundr   
NR_OF_GRAYastypemin_scalar_typetupleshape
isinstancenumbersNumberndimlen
ValueError_clahe)imagekernel_size
clip_limitnbinsfloat_dtypes        r   equalize_adapthistr1      s'   f (44KEH&uJN8KLLLMMTT
:&& E AAU[AAABB	K	0	0 M"nuz1	[		UZ	'	'KkKKLLL//;///K5+z599ELL5L11EU###r   c           
      r  !" | j         }| j        }d |D             }d t          || j                  D             }t	          j        | d t          ||          D             d          } dt          |z  z   }t	          j        t          t	          j        t                              }	|	|z  }	|	|          } d t          | j        |          D             }
t	          j	        |
|g          j
                                        }t	          j	        t	          j        d	|d
z  d
          t	          j        d|d
z  d
          g                                          }d t          ||
          D             }| t          |                                       |          }t	          j        ||          }|j        }|                    t          j        |
          df          }t          j        |          }|dk    r't#          t	          j        ||z  dd                    }n|}t	          j        t          j        d||          }t	          j        t*          d||          }t-          |d	t          dz
  |          }|                    |d|         dz             }t	          j        |d t/          |          D             d	d	ggz   d          }d t          | j        |          D             }t	          j	        ||g          j
                                        }t	          j	        t	          j        d	|d
z  d
          t	          j        d|d
z  d
          g                                          }|                     |          }t	          j        ||          }|j        }t	          j        |t          j        |          t          j        |j        |d                   f          }t	          j        t          d |ddd         D                       ddi!d !D             !d t3          !          D             "t	          j        |j        t          j                  }t3          t	          j        d
g|z             D ]\  }}|t          d t          ||          D                                }|                    t          j        |          df          }t	          j        ||d          }t	          j        !"fdt3          |ddd                   D             d	          }|||z                      |j                  z  }|                    |          }|                    |          }t	          j	        t	          j        d	|          t	          j        ||d
z            g          j
                                        }t	          j        ||          }|                    | j                  }t          d t          ||| j                  D                       } ||          }|S )a.  Contrast Limited Adaptive Histogram Equalization.

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

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

    The number of "effective" graylevels in the output image is set by `nbins`;
    selecting a small value (e.g. 128) speeds up processing and still produces
    an output image of good quality. A clip limit of 0 or larger than or equal
    to 1 results in standard (non-contrast limited) AHE.
    c                     g | ]}|d z  S r   r   r   s     r   r   z_clahe.<locals>.<listcomp>}   s    555Aa555r   c           	      t    g | ]5\  }}|||z  z
  |z  t          t          j        |d z                      z   6S )g       @)r   r   ceil)r   r   r   s      r   r   z_clahe.<locals>.<listcomp>   sS       Aq 
QUa#bga#g..///  r   c                     g | ]	\  }}||g
S r   r   )r   p_ip_fs      r   r   z_clahe.<locals>.<listcomp>   s     LLLS#sLLLr   reflect)moder   )r   c                 >    g | ]\  }}t          ||z            d z
  S r   r   r   r   r   s      r   r   z_clahe.<locals>.<listcomp>   s*    HHH$!Qs1q5zzA~HHHr   r   r   c                 L    g | ]!\  }}t          |d z  |d z  ||z  z             "S r4   slice)r   r   ns      r   r   z_clahe.<locals>.<listcomp>   s6    WWWTQ5aa!a%00WWWr   )axesg        N)	minlength)r.   )rD   c                     g | ]}d d gS r=   r   )r   _s     r   r   z_clahe.<locals>.<listcomp>   s    :::q!f:::r   edgec                 8    g | ]\  }}t          ||z            S r   r   r>   s      r   r   z_clahe.<locals>.<listcomp>   s&    DDDdas1q5zzDDDr   c                 <    g | ]}t          j        |          |z  S r   )r   aranger   s     r   r   z_clahe.<locals>.<listcomp>   s%    <<<Q	!q <<<r   indexingijc                 Z    g | ](}t          j        |                                          )S r   )r   	transposeflatten)r   cs     r   r   z_clahe.<locals>.<listcomp>   s,    888Abl1oo%%''888r   c                     g | ]
\  }}d |z
  S r=   r   )r   dimrQ   s      r   r   z_clahe.<locals>.<listcomp>   s     888FC!a%888r   c                 :    g | ]\  }}t          |||z             S r   r@   )r   erB   s      r   r   z_clahe.<locals>.<listcomp>   s(    $T$T$TAU1a!e__$T$T$Tr   axisc                 6    g | ]\  }}g|         |         S r   r   )r   drU   coeffs
inv_coeffss      r   r   z_clahe.<locals>.<listcomp>   s,    JJJDAqj&!!$Q'JJJr   c                 <    g | ]\  }}}t          |||z
            S r   r@   )r   r8   r9   r   s       r   r   z_clahe.<locals>.<listcomp>   s<     	
 	
 	
S! #q3w	
 	
 	
r   )r(   r   zipr$   r   padr    rK   r"   arrayTrP   r#   reshaperO   mathprodr   clipapply_along_axisbincountclip_histogrammap_histogramrangemeshgrid	enumeratezerosfloat32ndindextake_along_axisr!   )#r,   r-   r.   r/   r(   r   pad_start_per_dimpad_end_per_dimbin_sizelutns_histhist_blocks_shapehist_blocks_axis_orderhist_sliceshist_blockshist_block_assembled_shapekernel_elementsclimhist	map_arrayns_procblocks_shapeblocks_axis_orderblocksblocks_flattened_shaperesultiedgerH   	edge_mapsedge_mappededge_coeffsblocks_axis_rebuild_orderunpad_slicesrZ   r[   s#                                    @@r   r+   r+   ^   s   2 :DKE
 65555 U[11  O
 FLLC(9?$K$KLLL  E :&&H
)Jb&8&D&D
E
E
ECHCJE IH#ek;*G*GHHHG';!788:BBDDX	1dQh	"	"BIa1$=$=> gii  XWSg=V=VWWWKk**+334EFFK,{1GHHHK!,!2%%ty'9'92&>??K i,,OC27:7DAABB r{BuMMMD~r4DIIIDq*q./BBD<<25D59EABBD t::eDkk:::q!fXEFSSSI EDc%+{&C&CDDDG8Wk2335==??L	1dQh	"	"BIa1$=$=> gii  ]]<((F\&'8999F#\Z7!3!3TYv|DEE?R5S5S TUUF [	<<+ddd*;<<<	=	=HL F 98888F88i&7&7888J Xfl"*555F qcDj!:;; C Cte$T$TT7ASAS$T$T$TUUV	%%ty'9'92&>??	 (FDDD gJJJJJId44R4j4I4IJJJA
 
 	;,44V\BBB]]5!!F ^^233F "	1d		RYtTAX667! !		  \&'@AAAF^^EK((F 	
 	
"#4ou{SS	
 	
 	
 L L!FMr   c                    | |k    }| |         }|                                 |j        |z  z
  }|| |<   || j        z  }||z
  }| |k     }|| |         j        |z  z  }| |xx         |z  cc<   t          j        | |k    | |k               }| |         }	||	                                 |	j        |z  z
  z  }|| |<   |dk    r|}
t	          | j                  D ]p}| |k     }t          dt          j        |          |z            }||d|         }| |d|         |xx         dz  cc<   |t          j        |          z  }|dk    r nq|
|k    rn|dk    | S )a  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.
    r   r   N)sumsizer   logical_andri   r   count_nonzero)r|   r.   excess_maskexcessn_excessbin_incrupperlow_maskmid_maskmidprev_n_excessindex
under_mask	step_sizes                 r   rg   rg      s   ( #K+Fzz||fkJ66H"D 49$H!Ee|HX#h..HNNNhNNN~demTJ->??H
x.C		CHz111HDN
Q,, 49%% 	 	E
*JAr/
;;xGHHI#E$49$45J!	!":...!3...(444H1}} H$$ Q,, Kr   c                     t          j        | d                              t                    }|||z
  |z  z  }||z  }t          j        |d||           |                    t
                    S )a  Calculate the equalized lookup table (mapping).

    It does so by cumulating the input histogram.
    Histogram bins are assumed to be represented by the last array dimension.

    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.
    rD   rV   N)a_mina_maxout)r   cumsumr!   floatrd   r   )r|   min_valmax_valn_pixelsr   s        r   rh   rh   "  sl    , )Dr
"
"
"
)
)%
0
0CGg))C7NCGCt74444::c??r   )Nr
   r   )__doc__rb   r&   numpyr   _shared.utilsr   color.adapt_rgbr   r   exposurer   utilr	   r    r1   r+   rg   rh   r   r   r   <module>r      s           1 1 1 1 1 1 2 2 2 2 2 2 2 2 ' ' ' ' ' '      
 9C$ C$ C$ C$LK K K\3 3 3l    r   