imageToBlackOnWhite function
Binarize an input image by converting it to black and white based on a brightness threshold.
This function takes an input ui.Image and converts it to a black and white image
where pixels brighter than the specified backgroundBrightNestthreshold_0_255
become white, and those below become black.
Parameters:
inputImage
: The source image to be binarized.backgroundBrightNestthreshold_0_255
: Optional. The brightness threshold used to determine black or white pixels. Defaults to 190. Range is 0-255.
Returns: A Future that resolves to a new ui.Image containing the binarized version of the input image.
Throws: An Exception if it fails to get image data from the input image.
Implementation
Future<ui.Image> imageToBlackOnWhite(
final ui.Image inputImage, {
final int backgroundBrightNestthreshold_0_255 = 190,
}) async {
final int width = inputImage.width;
final int height = inputImage.height;
final Uint8List pixels = await imageToUint8List(inputImage);
// Create a new Uint8List for the output image
final Uint8List outputPixels = Uint8List(width * height * 4);
for (int i = 0; i < pixels.length; i += 4) {
final int r = pixels[i];
final int g = pixels[i + 1];
final int b = pixels[i + 2];
// ignore: unused_local_variable
final int a = pixels[i + 3];
// Calculate brightness using a weighted average
final double brightness = (0.299 * r + 0.587 * g + 0.114 * b);
// If brightness is above the threshold, set pixel to white, otherwise black
if (brightness > backgroundBrightNestthreshold_0_255) {
// make this the background paper
outputPixels[i] = 255; // R
outputPixels[i + 1] = 255; // G
outputPixels[i + 2] = 255; // B
} else {
// make this the foreground ink
outputPixels[i] = 0; // R
outputPixels[i + 1] = 0; // G
outputPixels[i + 2] = 0; // B
}
// remove alpha
outputPixels[i + 3] = 255; // A
}
return await createImageFromPixels(outputPixels, width, height);
}