替换图像的颜色

我试图用白色替换图片的黑色,反之亦然。 这实际上是我的OCR代码可以更好地在白色背景上读取它。 它目前从剪贴板获取图像

Image img = Clipboard.GetImage(); pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; pictureBox1.Image = img; 

我已经看到了一些其他问题,他们正在使用实际位图,但我如何直接从剪贴板处理它?

使用ColorMatrix的另一种解决方案。

您可以修改ImageAttributes.SetColorMatrix以更改图像的颜色。
调节阈值以微调亮度。

ImageAttributes.SetThreshold

如果设置为0,则图像全部为白色,如果设置为1则相反。

还要考虑“反转”取决于原始位图颜色模式,因此请尝试不同的方法。 有时不反转像素的亮度可以为您提供更好的解决方案。

您必须“训练”OCR,以validation哪些值更适合它。

看看这些:
重新着色(MSDN)
ASCII艺术生成器(CodeProject)

亮度矩阵:R =红色G =绿色B =蓝色A = Alpha通道W =白色(亮度)
修改亮度组件以获得“反转”

  RGBAW 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 [bbb 0 1] <= Brightness 

从文件中获取图像

 string _path = @"Image Path"; FileStream _fs = new FileStream(_path, FileMode.Open, FileAccess.Read); Image _img = new Bitmap(_fs); 

或ClipBoard

 Image _img = Clipboard.GetImage(); 

 using System.Drawing; using System.Drawing.Imaging; var BW_Inverted_matrix = 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.5f, 1.5f, 1.5f, 0, 1} //Adjusted: to combine with threshold }; var BW_matrix = 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} }; using (Graphics gr = Graphics.FromImage(_img)) { // Adjust the threshold as needed float _threshold = 0.2f; ImageAttributes _ImageAttributes = new ImageAttributes(); _ImageAttributes.SetColorMatrix(new ColorMatrix(BW_Inverted_matrix)); _ImageAttributes.SetThreshold(_threshold); Rectangle _rect = new Rectangle(0, 0, _img.Width, _img.Height); gr.DrawImage(_img, _rect, 0, 0, _img.Width, _img.Height, GraphicsUnit.Pixel, _ImageAttributes); } 

您可以使用System.Drawimg.Imaging命名空间中的ColorMap和ImageAttributes类直接替换图像中的像素:

 Image img = Clipboard.GetImage(); if (img != null) { ColorMap[] cm = new ColorMap[1]; cm[0] = new ColorMap(); cm[0].OldColor = Color.Black; cm[0].NewColor = Color.White; ImageAttributes ia = new ImageAttributes(); ia.SetRemapTable(cm); using (Graphics g = Graphics.FromImage(img)) { g.DrawImage(img, new Rectangle(Point.Empty, img.Size), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia); } pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; pictureBox1.Image = img; } 

如果您的图像是B&W,则在OpenCV中非常容易:

 // bmp is your bitmap var inverted = (255 - bitmap.ToMat()).ToMat(). .ToBitamp() // or .ToWriteableBitmap() // or .ToBitmapSource() 

如果这是你在整个应用程序中的唯一操作,OpenCV可能有点矫枉过正