另一种解决方案使用色彩矩阵 https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imaging.colormatrix class.
您可以使用图形.DrawImage https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawimage接受一个重载图像属性 https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imaging.imageattributes争论。
ImageAttributes.SetColorMatrix() https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imaging.imageattributes.setcolormatrix设置颜色调整矩阵,可选择针对特定类别(位图、钢笔、画笔等),并且可以指示跳过灰色、仅修改灰色或所有颜色。
The ImageAttributes.SetThreshold() https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imaging.imageattributes.setthreshold方法允许调节颜色截止点(阈值)以微调亮度。
它接受来自的值0
to 1
.
当设置为0
,图像全白,设置为全黑1
(请参阅有关它的文档)。
还要考虑到“反转”取决于原始位图颜色模式,因此请尝试不同的方法。有时,反转亮度可以给您带来更好的结果,有时则不然。
您的 OCR 必须经过“训练”,以验证哪些值更适合它。
看看这些文章:
重新着色(MSDN) https://msdn.microsoft.com/en-us/library/windows/desktop/ms533809(v=vs.85).aspx
ASCII 艺术生成器 (CodeProject) https://www.codeproject.com/Articles/10949/ASCII-Art-Generator
亮度矩阵:
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;
}
}