Document scanning
A page photographed with a phone becomes a clean scan without leaving the device: Bmage measures whether the photo is sharp enough and how far its lines are tilted, levels it, separates the ink from the paper under uneven light, reads the codes printed on it through BbScanner, and saves the result as a two-colour PNG a fraction of the size.
Try it
Steps
The code
Sharpness and tilt are measurements, not operations: they depend on the pixels, so they are taken once and their result recorded in the pipeline, which then replays exactly. The adaptive threshold compares every pixel with the window around it, so a shadow across the page neither blackens the paper nor loses the text, as one level for the whole page would.
using var photo = await loader.LoadAsync(file);
// Measured once; a soft photo is better taken again than cleaned up.
if (ImageSharpness.Measure(photo) < minimumSharpness) return AskForAnotherPhoto();
var pipeline = ImagePipeline.Create();
if (DocumentSkew.Estimate(photo) is { Confidence: > 0.3 } skew)
pipeline = pipeline.Rotate(skew.Angle, Rgba32.White, expandCanvas: false);
pipeline = pipeline.AdaptiveThreshold(radius: 18); // about a line of text
using var scan = await pipeline.ExecuteAsync(photo);
var png = await exporter.EncodeAsync(scan, new ImageExportOptions
{
Format = ImageFormat.Png,
MaxColors = 2, // a 1-bit indexed PNG
});
Codes are read by BbScanner's managed decoders straight from the Bmage image, with no copy and no canvas. When a
photo does not read as it is, ReadBarcodes tries it sharpened, then enlarged, and says which worked.
It needs the Bit.Bmage.BbScanner package.
Notes
- The tilt is found from the lines of text, projected at each candidate angle; a page of a photo with no lines gets little confidence, and the page applies no level below 30%.
- Two colours make a 1-bit PNG:
MaxColors = 2writes an indexed image of one bit a pixel, usually many times smaller than the photo and still exact, since the scan has only black and white in it. - Read the codes before thresholding. The decoders binarise locally themselves; given the photo, they see the shades the threshold would throw away.
- Everything here runs on the device. On a server the same calls work unchanged, with the managed codecs.