使用ColorMatrix 类的另一种解决方案。
您可以使用接受ImageAttributes 参数的Graphics.DrawImage 重载。
ImageAttributes.SetColorMatrix() 设置颜色调整矩阵,可选择针对特定类别(位图、钢笔、画笔等)并且可以被指示要跳过灰色,请仅修改灰色或所有颜色。
ImageAttributes.SetThreshold() 方法允许调节颜色截止点(阈值)以微调亮度。
它接受从0 到1 的值。
当设置为0 时,图像全白,设置为1 时全黑(参见相关文档)。
还要考虑“反转”取决于原始位图颜色模式,因此请尝试不同的方法。有时,反转亮度可以为您带来更好的结果,但有时却不能。
您的 OCR 必须经过“培训”,以验证哪些值更适合它。
看看这些文章:
Recoloring (MSDN)
ASCII Art Generator (CodeProject)
亮度矩阵:
R=Red G=Green B=Blue A=Alpha Channel W=White (Brightness)
修改亮度组件以获得“反转”
R G B A W
R [1 0 0 0 0]
G [0 1 0 0 0]
B [0 0 1 0 0]
A [0 0 0 1 0]
W [b b b 0 1] <= Brightness
using System.Drawing;
using System.Drawing.Imaging;
// ...
Image colorImage = Clipboard.GetImage();
// Default values, no inversion, no threshold adjustment
var bmpBlackWhite = BitmapToBlackAndWhite(colorImage);
// Inverted, use threshold adjustment set to .75f
var bmpBlackWhite = BitmapToBlackAndWhite(colorImage, true, true, .75f);
// ...
private Bitmap BitmapToBlackAndWhite(Image image, bool invert = false, bool useThreshold = false, float threshold = .5f)
{
var mxBlackWhiteInverted = new float[][]
{
new float[] { -1, -1, -1, 0, 0},
new float[] { -1, -1, -1, 0, 0},
new float[] { -1, -1, -1, 0, 0},
new float[] { 0, 0, 0, 1, 0},
new float[] { 1, 1, 1, 0, 1}
};
var mxBlackWhite = new float[][]
{
new float[] { 1, 1, 1, 0, 0},
new float[] { 1, 1, 1, 0, 0},
new float[] { 1, 1, 1, 0, 0},
new float[] { 0, 0, 0, 1, 0},
new float[] {-1, -1, -1, 0, 1}
};
var bitmap = new Bitmap(image.Width, image.Height);
using (var g = Graphics.FromImage(bitmap))
using (var attributes = new ImageAttributes()) {
attributes.SetColorMatrix(new ColorMatrix(invert ? mxBlackWhiteInverted : mxBlackWhite));
// Adjust the threshold as needed
if (useThreshold) attributes.SetThreshold(threshold);
var rect = new Rectangle(Point.Empty, image.Size);
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
return bitmap;
}
}