更新时间:2023-02-19 15:02:12
使用您可以使用 Graphics.DrawImage 接受 ImageAttributes 参数的重载.
ImageAttributes.SetColorMatrix()
设置颜色调整矩阵,可以选择针对特定类别(位图,笔,画笔等),并且可以指示其跳过灰色"颜色,仅修改灰色"颜色或修改所有颜色".
You can use the Graphics.DrawImage overload that accepts an ImageAttributes argument.ImageAttributes.SetColorMatrix()
sets the color-adjustment matrix, optionally targeting a specific category (Bitmap, Pen, Brush etc.) and can be instructed to skip the Gray Colors, modify the Gray colors only or all Colors.
ImageAttributes.SetThreshold()
方法允许调节颜色"截止点(阈值)以微调亮度.
它接受从 0
到 1
的值.
设置为 0
时,图像全为白色,设置为 1
时全为黑色(请参阅有关此文档的文档).
The ImageAttributes.SetThreshold()
method allows to regulate the Colors cutoff point (threshold) to fine tune the Brightness.
It accepts values from 0
to 1
.
When set to 0
, an image is all white, all black when set to 1
(see the Docs about it).
还认为倒置"是指取决于原始的位图颜色模式,因此请尝试其他方法.有时,将亮度反转可以使您获得更好的效果,有时却不能.
Also consider that the "Inversion" depends on the original bitmap color pattern, so try different approaches. Sometimes, inverting the brightness can give you a better result, sometime it doesn't.
您的OCR必须经过培训",以验证哪种值更适合它.
You OCR must be "trained", to verify what values suits it better.
看看这些文章:
重新着色(MSDN)
ASCII艺术生成器(CodeProject)
亮度矩阵: R =红色G =绿色B =蓝色A = Alpha通道W =白色(亮度)
修改亮度组件以获得反转"
Modify the Brightness component to obtain an "Inversion"
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;
}
}