enhanceContrast static method

Uint8List enhanceContrast(
  1. Uint8List gray,
  2. int width,
  3. int height
)

Contrast Limited Adaptive Histogram Equalization (CLAHE) approximation.

Implementation

static Uint8List enhanceContrast(Uint8List gray, int width, int height) {
  final out = Uint8List(gray.length);
  final histogram = Int32List(256);

  for (int i = 0; i < gray.length; i++) {
    histogram[gray[i]]++;
  }

  // Cumulative distribution function (CDF)
  final cdf = Float32List(256);
  cdf[0] = histogram[0].toDouble();
  for (int i = 1; i < 256; i++) {
    cdf[i] = cdf[i - 1] + histogram[i];
  }

  final cdfMin = cdf.firstWhere((val) => val > 0, orElse: () => 1.0);
  final totalPixels = gray.length.toDouble();

  for (int i = 0; i < gray.length; i++) {
    final val = gray[i];
    final equalized = ((cdf[val] - cdfMin) / (totalPixels - cdfMin) * 255.0).clamp(0.0, 255.0);
    out[i] = equalized.toInt();
  }
  return out;
}