Recursive AI

Adaptive image thresholding in C#

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

Adaptive thresholding separates dark marks from their local background.

Terminal
dotnet add package RecursiveAI.OneImage

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

C#
using OneImage;
 
// page.png: gray test page, in the zip.
Image.Load("page.png")
    .AdaptiveThreshold(thresholdLimit: 0.85f)
    .Save("adaptive.png");
Console.WriteLine("Wrote adaptive.png");
Text
Wrote adaptive.png

Unzip the example, then dotnet run.

The full program

page.png is a generated 128 × 64 gray page. Its paper value is 90 + x; rows 24–39 contain four-pixel-wide bars every 24 pixels, each 45 levels darker than the paper. The full program recreates this lighting gradient and compares local and global thresholds.

C#
using OneImage;
 
// A gray page with a left-to-right lighting gradient and dark bars.
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++)
{
    int paper = 90 + x;
    bool ink = y >= 24 && y < 40 && x % 24 < 4;
    byte value = (byte)(ink ? paper - 45 : paper);
    pixels[y * width + x] = new(value, value, value, 255);
}
Image input = Image.FromPixels<Rgba32>(pixels, width, height);
input.Save("page.png");
Image local = input.AdaptiveThreshold(thresholdLimit: 0.85f);
Image global = input.Threshold(level: 0.5);
local.Save("adaptive.png");
global.Save("global.png");
var result = local.ToArray<Rgba32>();
Console.WriteLine($"Size: {local.Width}x{local.Height}");
Console.WriteLine($"Adaptive black pixels: {result.Count(p => p.R == 0)}");
Console.WriteLine($"Global black pixels: {global.ToArray<Rgba32>().Count(p => p.R == 0)}");
Console.WriteLine($"Output red values: {string.Join(",", result.Select(p => p.R).Distinct().Order())}");

dotnet run prints:

Text
Size: 128x64
Adaptive black pixels: 381
Global black pixels: 2560
Output red values: 0,255

A threshold limit outside 0–1 throws ArgumentOutOfRangeException; CMYK and Lab inputs throw ImageOperationException.

Variations

Choose two output colors and a different local cutoff.

C#
using OneImage;
 
Image.Load("page.png")
    .AdaptiveThreshold(
        upper: new Rgba32(255, 255, 255, 255),
        lower: new Rgba32(20, 40, 100, 255),
        thresholdLimit: 0.9f)
    .Save("two-color.png");
Console.WriteLine("Wrote two-color.png");
Text
Wrote two-color.png

The short answer

Use Image.AdaptiveThreshold() for Bradley adaptive thresholding. A pixel becomes the lower color when its brightness is at or below thresholdLimit times its neighborhood’s mean brightness; otherwise it becomes the upper color. The defaults are opaque black, opaque white and a limit of 0.85. The returned image is 8-bit RGBA and the operation applies to every frame.

This is preprocessing, not text recognition. The result can be a black-and-white image without identifying any characters. The example makes no claim about recognition accuracy: it shows exactly how two threshold strategies classify a known synthetic page.

How do I apply adaptive thresholding in C#?

Load the image, call the method and save the returned result, as in the snippet at the top. The provided page has darker paper on its left and lighter paper on its right. Each bar is darker than nearby paper, but some paper on the left is darker than ink on the right. That is the situation in which one global cutoff can classify background and foreground inconsistently.

The full program also saves global.png with a global threshold of 0.5. On this exact fixture, the adaptive output contains 381 black pixels and the global output contains 2,560. Counts alone do not establish which result is correct; inspect their positions against the generated bars and the paper gradient. The adaptive output’s red samples are only 0 and 255, and its size stays 128 × 64.

Use the variation when the output must have colors other than black and white. The upper and lower colors define the output alpha too. Source alpha is not a separate coverage channel preserved by this operation, so do not assume a transparent input keeps its original transparency.

What is adaptive thresholding in image processing?

OneImage uses Rec. 709 luminance of the stored 8-bit RGB samples for brightness, rounded to a whole number. It compares that brightness with a local mean, not a local Gaussian-weighted mean and not an automatically selected global cutoff. The window geometry is tied to image width rather than supplied as a block-size parameter.

Specifically, s = max(1, width / 16) using integer division. The documented square reaches s - 2 pixels before and s + 1 pixels after the current pixel in each direction. At the image boundary it is clipped and the mean uses the pixels that exist. Resizing an image therefore changes the effective neighborhood as well as the pixel samples; it is not just a cheaper way to run the same calculation.

The implementation uses an integral image over each tile and its margin. It computes lazily when pixels are requested. Saving the output is enough to trigger computation, while simply constructing the pipeline does not demonstrate a completed decode.

How is adaptive thresholding different from global image thresholding?

A global threshold uses the same level everywhere. It is suitable when one cutoff separates the values you need across the image. Adaptive thresholding instead compares each pixel with a neighborhood, which changes the cutoff as local illumination changes. The University of Edinburgh’s explanation of adaptive thresholding illustrates local methods and the importance of neighborhood size.

Neither strategy guarantees meaningful segmentation on arbitrary content. Texture, local shadows and marks similar in brightness to their surroundings can all affect the output. Use the known page here to understand the parameter, then inspect representative inputs from your own task. Raising thresholdLimit raises the local cutoff toward the neighborhood mean; lowering it requires a pixel to be further below that mean to become the lower color.

All oneimage recipes