Recursive AI

Equalize an image histogram in C#

OneImage is a free, open-source image library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Histogram equalization changes contrast. RGB input becomes gray.

Terminal
dotnet add package RecursiveAI.OneImage

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneImage;
 
// low-contrast.png: gray ramp, in the zip.
Image.Load("low-contrast.png")
    .HistogramEqualization()
    .Save("equalized.png");
Console.WriteLine("Wrote equalized.png");
Text
Wrote equalized.png

Unzip the example, then dotnet run.

The full program

low-contrast.png is a generated 128 × 64 gray ramp: each row has four pixels at each value from 100 through 131. The full program recreates it, runs global and clipped tile equalization, and measures the resulting red-channel ranges and occupied histogram bins.

C#
using OneImage;
 
// A low-contrast gray ramp, 100 through 131, repeated in rows.
const int width = 128, height = 64;
var pixels = new Rgba32[width * height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
    byte value = (byte)(100 + x / 4);
    pixels[y * width + x] = new(value, value, value, 255);
}
Image input = Image.FromPixels<Rgba32>(pixels, width, height);
input.Save("low-contrast.png");
Image global = input.HistogramEqualization();
Image local = input.HistogramEqualization(
    HistogramEqualizationMethod.AdaptiveTileInterpolation,
    clipHistogram: true, clipLimit: 32, tiles: 4);
global.Save("global.png");
local.Save("local.png");
foreach (var (name, image) in new[] {
    ("Input", input), ("Global", global), ("Local", local) })
{
    var values = image.ToArray<Rgba32>().Select(p => p.R).ToArray();
    int bins = image.Histogram().Channel(0).ToArray().Count(n => n > 0);
    Console.WriteLine($"{name}: {values.Min()}..{values.Max()}, {bins} occupied bins");
    Console.WriteLine($"{name} x=0,64,127: {values[0]},{values[64]},{values[127]}");
}

dotnet run prints:

Text
Input: 100..131, 32 occupied bins
Input x=0,64,127: 100,116,131
Global: 0..255, 32 occupied bins
Global x=0,64,127: 0,132,255
Local: 66..193, 36 occupied bins
Local x=0,64,127: 66,128,193

CMYK and Lab input throws ImageOperationException; out-of-range options throw ArgumentOutOfRangeException.

Variations

Use a moving local window instead of one global mapping.

C#
using OneImage;
 
Image.Load("low-contrast.png")
    .HistogramEqualization(
        HistogramEqualizationMethod.AdaptiveSlidingWindow,
        tiles: 16)
    .Save("sliding.png");
Console.WriteLine("Wrote sliding.png");
Text
Wrote sliding.png

The short answer

Use Image.HistogramEqualization() to remap an image’s luminance through its cumulative histogram. The default is one global mapping with 256 luminance levels and no clipping. For local mappings, choose AdaptiveTileInterpolation or AdaptiveSlidingWindow. The full program demonstrates global and clipped tile interpolation on the same low-contrast ramp.

This changes pixels. It is different from Histogram(), which only counts them. RGB colors become gray because the mapped luminance is written to all three channels. Alpha is carried over unchanged. Use this method when that grayscale result is appropriate, not when preserving a photograph’s colors is a requirement.

Why use histogram equalization?

It can spread concentrated luminance values over a wider output range. In the supplied fixture, all input values fall between 100 and 131. Global equalization maps them to 0 through 255. It still has 32 occupied bins, because remapping 32 distinct input levels does not create additional source detail. A wider range and a larger number of occupied bins are different properties.

The center sample at x=64 changes from 116 to 132 under the global mapping. The first sample becomes 0 and the last becomes 255. These concrete results let you check that the program ran the intended operation; they are not a quality score for arbitrary photographs.

The method uses Rec. 709 luminance of stored values, not a profile conversion to a new working space. Gray samples are already their own luminance. The University of Amsterdam’s histogram equalization notes explain cumulative-distribution mappings and why a discrete equalized histogram need not be uniform.

What is the difference between contrast stretching and histogram equalization?

A simple linear stretch maps a chosen input range to an output range with a fixed slope. Equalization uses the distribution of samples, so its mapping can allocate different output intervals to different parts of the input range. OneImage’s global method subtracts the first nonzero cumulative count and scales by the remaining count. A histogram with only one occupied bin maps to zero; it does not acquire texture.

Changing luminance levels changes histogram resolution. The default is 256; the API supports 2 through 65,536. Sixteen-bit images can use full 16-bit precision, while floating-point images are processed at 16-bit precision. Choosing more bins is not a way to recover detail from a source that never contained it.

Do not treat any wider histogram as automatically better. Depending on the input, redistributing values may emphasize unwanted differences as well as wanted ones. Keep the original and inspect the rendered output at the size where it will be used.

How do I apply adaptive histogram equalization in C#?

Select AdaptiveTileInterpolation as in the full program. Each grid tile gets a mapping, and output pixels interpolate nearby tile mappings. tiles: 4 means a 4 × 4 grid, not four-pixel tiles. The example also enables clipping with an absolute limit of 32 counts per bin. The excess counts are redistributed; the limit should be chosen with tile size in mind rather than treated as a normalized percentage.

On the supplied ramp, this local result spans 66–193 and has 36 occupied red-channel bins. It does not have to span the full global range. The local context and interpolation produce a different mapping at different positions.

The sliding-window variation builds a mapping for each pixel’s neighborhood instead. Its window width is derived from width / tiles. Both local methods remain grayscale-producing operations on RGB images. All methods are lazy and apply to every frame; the global and tile methods count the whole frame before delivering their first output tile. Save or read the result before assuming the processing has completed.

All oneimage recipes