
    ij ,                     T    d dl mZ d dlmZ d dlmZ  ed       G d de             Zy)    )backend)keras_export)BaseImagePreprocessingLayerz9keras.layers.ContrastLimitedAdaptiveHistogramEqualizationc                   J     e Zd ZdZ	 	 	 	 d fd	ZddZd Zd Z fdZ xZ	S )	,ContrastLimitedAdaptiveHistogramEqualizationa
  Contrast Limited Adaptive Histogram Equalization (CLAHE) layer.

    CLAHE is a variant of Adaptive Histogram Equalization (AHE) which takes care
    of over-amplification of the contrast. It operates on small regions in the
    image, called tiles, rather than the entire image. The neighboring tiles are
    then combined using bilinear interpolation to remove the artificial
    boundaries. This algorithm can be applied to improve the contrast of an
    image.

    **Note:** This layer computes histograms using `self.backend.nn.one_hot`,
    which can be highly memory-intensive. For large batch sizes or
    high-resolution images, it may lead to high memory consumption or
    out-of-memory errors.

    Args:
        value_range: Optional list/tuple of 2 floats specifying the lower
            and upper limits of the input data values. Defaults to `(0, 255)`.
        clip_limit: Float. Limits the noise amplification in near-constant
            regions. Defaults to 4.0.
        tile_grid_size: Tuple of 2 integers `(height, width)`.
            Specifies the number of tiles to divide the image into.
            Defaults to `(8, 8)`.
        data_format: String, either `"channels_last"` or `"channels_first"`.
            The ordering of the dimensions in the inputs. `"channels_last"`
            corresponds to inputs with shape `(batch, height, width, channels)`
            while `"channels_first"` corresponds to inputs with shape
            `(batch, channels, height, width)`. It defaults to the
            `image_data_format` value found in your Keras config file at
            `~/.keras/keras.json`. If you never set it, then it will be
            `"channels_last"`.

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format,
        or `(..., channels, height, width)`, in `"channels_first"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`,
        or `(..., channels, height, width)`,
        in `"channels_first"` format.

    Example:

    ```python
    import keras
    import numpy as np

    # Create a CLAHE layer with default parameters
    clahe = keras.layers.ContrastLimitedAdaptiveHistogramEqualization()

    # Apply CLAHE to an image
    # image values should be in the range[0, 255] by default
    input_image = np.random.randint(0, 256, (1, 256, 256, 3))
    output_image = clahe(input_image)

    # For normalized images[0, 1]
    clahe_normalized=keras.layers.ContrastLimitedAdaptiveHistogramEqualization(
        value_range=(0.0, 1.0)
    )
    norm_image = np.random.rand(1, 256, 256, 3)
    output_norm = clahe_normalized(norm_image)
    ```
    c                     t        |   di | || _        || _        || _        t        j                  |      | _        y )N )super__init__value_range
clip_limittile_grid_sizer   standardize_data_formatdata_format)selfr   r   r   r   kwargs	__class__s         /var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/layers/preprocessing/image_preprocessing/clahe.pyr   z5ContrastLimitedAdaptiveHistogramEqualization.__init__K   s?     	"6"&$,"::;G    c                    | j                   dk(  ret        |j                        dk(  r'| j                  j                  j                  |d      }n&| j                  j                  j                  |d      }|j                  }| j                  || j                  dd      }| j                  |      }| j                  |d| j                  d      }| j                  j                  ||      }| j                   dk(  rft        |j                        dk(  r(| j                  j                  j                  |d      }|S | j                  j                  j                  |d	      }|S )
Nchannels_first   r            )r   r   r   r      float32dtyper   r   r   r   )r   r   r   )r   lenshaper   numpy	transposer!   _transform_value_ranger   _clahecast)r   imagestransformationtrainingoriginal_dtypes        r   transform_imagesz=ContrastLimitedAdaptiveHistogramEqualization.transform_imagesY   s9   //6<< A%++55flK++55fiH,,D$$hi - 
 V$,,Hd..i - 
 ""6>://6<< A%++55flK  ++55fiHr   c           	         d}t        |j                        dk(  r)| j                  j                  j	                  |d      }d}| j                  j
                  j                  |      }|j                  d   |j                  d   n|d   }|j                  d   |j                  d   n|d   }|j                  d   |j                  d   n|d   }|j                  d   |j                  d   n|d   }| j                  \  }}	||z   dz
  |z  }
||	z   dz
  |	z  }|
|z  |z
  }||	z  |z
  }t        |t              rt        |t              r|dk(  r|dk(  r|}n| j                  j                  j                  |d      }| j                  j                  j                  |d	||f      }| j                  j                  j                  |ddgd|gd|ggd
      }| j                  j                  j                  |d	|||z   ||z   f      }| j                  j                  j                  |d      }| j                  j                  j                  ||||
|	||f      }| j                  j                  j                  |d      }| j                  j                  j                  ||||	||
|z  f      }| j                  j                  |d      }| j                  j                  j                  |dd      }| j                  j                  j                  | j                  j                  j!                  |d      d      }| j"                  dkD  r| j"                  |
|z  z  dz  }| j                  j                  ||j$                        }| j                  j                  j                  |d|      }| j                  j                  j                  ||z
  d	d      }|dz  }||z   }| j                  j                  j'                  |d	      }| j                  j                  j)                  |d	d      }||z
  dz  }| j                  j                  |
|z  |j$                        |z
  }| j                  j                  j+                  |dk(  | j                  j                  j-                  |      |      }||z  }| j                  j                  j                  |dd      }|d d ddd d d d d d f   } |d d d	d d d d d d d f   }!| j                  j                  j/                  | ||!gd      }"|"d d d d ddd d d d f   }#|"d d d d d	d d d d d f   }$| j                  j                  j/                  |#|"|$gd      }"|
|z  }%||	z  }&| j                  j                  j1                  |%d      }'| j                  j                  j1                  |&d      }(|'|
dz  z
  |
z  })|(|dz  z
  |z  }*|)dz   })|*dz   }*| j                  j                  j3                  |)      }+| j                  j                  j3                  |*      },|+dz   }-|,dz   }.|)|+z
  }/|*|,z
  }0| j                  j                  j                  |+d|dz         }+| j                  j                  j                  |-d|dz         }-| j                  j                  j                  |,d|	dz         },| j                  j                  j                  |.d|	dz         }.| j                  j                  |+d      }+| j                  j                  |-d      }-| j                  j                  |,d      },| j                  j                  |.d      }.d}1|1|z  }2|2|	dz   z  }3|3|dz   z  }4| j                  j                  j                  |"d      }5| j                  j                  | j                  j                  j                  |dd      d      }6| j                  j                  j1                  |d      d d d d d f   }7| j                  j                  j1                  |d      d d d d d f   }8|+d d d d d f   }9|-d d d d d f   }:|,d d d d d f   };|.d d d d d f   }<|/d d d d d f   }=|0d d d d d f   }>|7|4z  |8|1z  z   |6z   }?|?|9|3z  z   |;|2z  z   }@| j                  j                  j5                  |5|@      }A|?|9|3z  z   |<|2z  z   }B| j                  j                  j5                  |5|B      }C|?|:|3z  z   |;|2z  z   }D| j                  j                  j5                  |5|D      }E|?|:|3z  z   |<|2z  z   }F| j                  j                  j5                  |5|F      }G|Ad|>z
  z  |C|>z  z   }H|Ed|>z
  z  |G|>z  z   }I|Hd|=z
  z  |I|=z  z   }J|Jd d d |d |d d f   }J|r'| j                  j                  j7                  Jd      }JJS )NFr   r   )axisTr   r   r"   	symmetric)moder   )r   r   r      r   r   int32r      g      p@)r0   keepdimsg     o@r   r    g       @g      ?)r1   )r#   r$   r   r%   expand_dimscorer   
isinstanceintr&   reshapepadr)   clipsumnnone_hotr   r!   cumsumminwhere	ones_likeconcatenatearangefloortakesqueeze)Kr   r*   	unbatchedr$   
batch_sizeheightwidthchannelsgrid_hgrid_wtile_htile_wpad_hpad_wpadded_imagesimages_nchw	images_3d	padded_3dpadded_nchwtiled
tiled_flat	tiled_inthistslimitclippedexcessredistcdfcdf_min	numeratordenominatorcdf_normtopbottom
cdf_paddedleftrightH_paddedW_paddedy_rangex_rangey_gridx_gridy0x0y1x1wywxstride_cstride_xstride_ystride_bcdf_flatpixelsb_idxc_idxy0_ey1_ex0_ex1_ewy_ewx_ebase_idxidx_nwval_nwidx_neval_neidx_swval_swidx_seval_se
top_interp
bot_interpresultsK                                                                              r   r(   z3ContrastLimitedAdaptiveHistogramEqualization._claheu   s	   	v||!\\''33F3CFI!!''/%||A:FLLOa 	 %+LLO$?aU1X#)<<?#>QE!H&,ll1o&A6<<?uQx,,6/A%&0&.1$/&F*&E) uc"5#&

"M,,,,66v|LK**22b&%0I **..QFQJE
;+ / I ,,,,44B&5.%%-HK !LL..88\M
 ""**B
 "",,U4FG\\''//J&6/J

 LL%%j':	LL&&++Iq#>	 ""&&LLOO##Is3" ' 

 ??QOOv7%?ELL%%eU[[9Ell((--eQ>G\\''++b4 , F e^Ff$E ll  ''B'7,,$$((2(E7]e+	ll''CgMll((..1LL((5

 {*<<%%**8Q< q!A#q!Q'!RS!Q/*\\''33(F#! 4 

 !Q!Q/*1aa?+\\''33:u%A 4 

 F?F?,,$$++HI+F,,$$++HI+FVc\*f4Vc\*f4##\\%%f-\\%%f-#X#Xb[b[\\$$RFQJ7\\$$RFQJ7\\$$RFQJ7\\$$RFQJ7\\r7+\\r7+\\r7+\\r7+h&vz*vz*<<%%--j%@""LL##M1c:G
 ""))*G)DtT4
 ""))(')B$a
 $4%&$4%&$a%&$a%&$4%&$a%&8#eh&66?D8O+dXo=##((6:D8O+dXo=##((6:D8O+dXo=##((6:D8O+dXo=##((6:sTz*Vd]:
sTz*Vd]:
sTz*Z$->>7F7FUFA-.\\''//Q/?Fr   c                     |S )Nr	   )r   input_shapes     r   compute_output_shapezAContrastLimitedAdaptiveHistogramEqualization.compute_output_shape2  s    r   c                     t         |          }|j                  | j                  | j                  | j
                  | j                  d       |S )N)r   r   r   r   )r
   
get_configupdater   r   r   r   )r   configr   s     r   r   z7ContrastLimitedAdaptiveHistogramEqualization.get_config5  sJ    #%#//"oo"&"5"5#//		
 r   )r   g      @)   r   N)NT)
__name__
__module____qualname____doc__r   r.   r(   r   r   __classcell__)r   s   @r   r   r      s8    ?F H8{z
 
r   r   N)	keras.srcr   keras.src.api_exportr   Qkeras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layerr   r   r	   r   r   <module>r      s6     -
 IJv3N v Kvr   