
    9i*                         S r SSKrSSKrSSKrSSKJr  SSKJrJ	r	  SSK
Jr  SSKJr  S	r\" \	5      SS
 j5       rS rS rS rg)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 @  c           	         [        U R                  5      n[        U 5      n [        R                  " [        U S[        S-
  4S95      R                  [        R                  " [        5      5      n Uc4  [        U R                   Vs/ s H  n[        US-  S5      PM     sn5      nOW[        U[        R                  5      (       a  U4U R                  -  nO'[!        U5      U R                  :w  a  [#        SU 35      eU Vs/ s H  n[%        U5      PM     nn['        XX#5      n U R                  USS9n [        U 5      $ s  snf s  snf )aN  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_range   z"Incorrect value of `kernel_size`: F)copy)r   dtyper	   nproundr   
NR_OF_GRAYastypemin_scalar_typetupleshapemax
isinstancenumbersNumberndimlen
ValueErrorint_clahe)imagekernel_size
clip_limitnbinsfloat_dtypesks          [/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/skimage/exposure/_adapthist.pyequalize_adapthistr'      s   f (4KEHH&uJN8KLMTT
:&E U[[A[Sa^[AB	K	0	0"nuzz1	[	UZZ	'=k]KLL#./;a3q6;K/5z9ELL5L1EU## B 0s   D?Ec                 (   U R                   nU R                  nU Vs/ s H  ofS-  PM	     nn[        XR                  5       VVs/ s H2  u  phXhU-  -
  U-  [	        [
        R                  " US-  5      5      -   PM4     n	nn[
        R                  " U [        Xy5       V
Vs/ s H  u  pX/PM
     snn
SS9n S[        U-  -   n[
        R                  " [        [
        R                  " [        5      S9nX-  nX   n [        U R                  U5       VVs/ s H  u  p[	        X-  5      S-
  PM     nnn[
        R                  " X/5      R                  R                  5       n[
        R                  " [
        R                  " SUS-  S5      [
        R                  " SUS-  S5      /5      R                  5       n[        X5       VVs/ s H  u  nn[        US-  US-  UU-  -   5      PM      nnnU [        U5         R!                  U5      n[
        R"                  " UUS9nUR                  nUR!                  [$        R&                  " U5      S	45      n[$        R&                  " U5      nUS
:  a%  [	        [
        R(                  " UU-  SS5      5      nOUn[
        R*                  " [
        R,                  S	UUS9n[
        R*                  " [.        S	UUS9n[1        US[        S-
  U5      nUR!                  USU S-   5      n[
        R                  " U[3        U5       Vs/ s H  nSS/PM	     snSS//-   SS9n[        U R                  U5       VVs/ s H  u  p[	        X-  5      PM     nnn[
        R                  " UU/5      R                  R                  5       n[
        R                  " [
        R                  " SUS-  S5      [
        R                  " SUS-  S5      /5      R                  5       nU R!                  U5      n[
        R"                  " UUS9nUR                  n[
        R                   " U[$        R&                  " U5      [$        R&                  " UR                  US 5      45      n[
        R4                  " [        USSS	2    Vs/ s H  n[
        R                  " U5      U-  PM     sn5      SS06nU V s/ s H'  n [
        R"                  " U 5      R                  5       PM)     nn [7        U5       V!V s/ s H  u  n!n SU -
  PM     n"n!n [
        R8                  " UR                  [
        R:                  S9n#[7        [
        R<                  " S/U-  6 5       H  u  n$n%U[        [        U%U5       V&Vs/ s H  u  n&n[        U&U&U-   5      PM     snn&5         n'U'R!                  [$        R&                  " U5      S	45      n'[
        R>                  " U'US	S9n([
        R&                  " [7        U%SSS	2   5       V)V&s/ s H  u  n)n&U"U/U&   U)   PM     sn&n)S5      n*U#U(U*-  RA                  U#R                  5      -  n#M     U#RA                  U5      n#U#R!                  U5      n#[
        R                  " [
        R                  " SU5      [
        R                  " XDS-  5      /5      R                  R                  5       n+[
        R"                  " U#U+S9n#U#R!                  U R                  5      n#[        [        XyU R                  5       V
VVs/ s H  u  pn[        XU-
  5      PM     snnn
5      n,U#U,   n#U#$ s  snf s  snnf s  snn
f s  snnf s  snnf s  snf s  snnf s  snf s  sn f s  sn n!f s  snn&f s  sn&n)f s  snnn
f )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.
r   g       @reflect)moder   )r   r   )axesg        N)	minlength)r!   )r,   edgeindexingijaxis)!r   r   zipr   r   r   ceilpadr   aranger   arrayTflattenslicer   reshape	transposemathprodclipapply_along_axisbincountclip_histogrammap_histogramrangemeshgrid	enumeratezerosfloat32ndindextake_along_axisr   )-r   r    r!   r"   r   r   r%   pad_start_per_dimr$   pad_end_per_dimp_ip_fbin_sizelutns_histhist_blocks_shapehist_blocks_axis_ordern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coeffscdim
inv_coeffsresultiedger.   e	edge_mapsedge_mappeddedge_coeffsblocks_axis_rebuild_orderunpad_slicess-                                                r&   r   r   ^   s~   2 ::DKKE
 *55Aa5 [[11DA 
Ua#bgga#g.//1  
 FF$'(9$KL$K#$KLE :&&H
))Jb&8&8&D
ECCJE +.ekk;*GH*G$!s15zA~*GGH'!78::BBDXX	1dQh	"BIIa1$=>gi  >A=VW=VTQ5aa!a%0=VKWk*+334EFK,,{1GHK!,!2!2%%tyy'92&>?K ii,OC277:7DAB r{{BuMD~r4DIDq*q./BD<<25D9EABD teDk:kq!fk:q!fXEFSI '*%++{&CD&Cdas15z&CGD88Wk2355==?L	1dQh	"BIIa1$=>gi  ]]<(F\\&'89F#\\ZZ7!3TYYv||DE?R5S TUF [[	+dd*;<*;Q		!q *;<	=HLF 288Abll1o%%'F8&/&78&7FC!a%&7J8 XXfll"**5F qcDj!:;teT7AS$TASAU1a!e_AS$TUV	%%tyy'92&>?	 ((FD gg4=d4R4j4IJ4IDAqj&!!$Q'4IJA
 	;,44V\\BB < ]]5!F ^^23F "	1d	RYYtAX67!a	  \\&'@AF^^EKK(F   ##4u{{S	
S! #3wS	
L L!FMY 6 	M I
 X( ; E =88 %U K"	
sM   ]	9] ]]%] "]&
]+#]1
.]6];^^^c                 ~   X:  nX   nUR                  5       UR                  U-  -
  nXU'   X@R                  -  nX-
  nX:  nX@U   R                  U-  -  nX==   U-  ss'   [        R                  " X:  X:  5      nX   n	XIR                  5       U	R                  U-  -
  -  nXU'   US:  a  Un
[	        U R                  5       Hd  nX:  n[        S[        R                  " U5      U-  5      nXSU2   nXSU2   U==   S-  ss'   U[        R                  " U5      -  nUS::  d  Md    O   X:X  a   U $ US:  a  M  U $ )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_andrD   r   count_nonzero)rZ   r!   excess_maskexcessn_excessbin_incrupperlow_maskmid_maskmidprev_n_excessindex
under_mask	step_sizes                 r&   rB   rB      sa   ( #KFzz|fkkJ66H" 99$H!E|HX##h..HNhN~~dmT->?H
.C	CHHz111HN
Q, 499%E*JAr//
;xGHI#$49$45J!	!":.!3.((44H1} & $K Q, K    c                     [         R                  " U SS9R                  [        5      nXBU-
  U-  -  nXA-  n[         R                  " USX$S9  UR                  [
        5      $ )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.
r,   r1   N)a_mina_maxout)r   cumsumr   floatr?   r   )rZ   min_valmax_valn_pixelsr   s        r&   rC   rC   "  sV    , ))Dr
"
)
)%
0Cg))CNCGGCt74::c?r   )Ng{Gz?   )__doc__r=   r   numpyr   _shared.utilsr   color.adapt_rgbr   r   exposurer   utilr	   r   r'   r   rB   rC    r   r&   <module>r      sT       1 2 ' 
 9C$ C$LK\3lr   