什么是真正的黑白色矩阵?

我想将图像从颜色转换为黑白(即没有灰度,只有黑白)。 有没有人有一个很好的色彩矩阵来实现这一目标?

我终于找到了解决问题的方法:

  1. 使用已知的颜色矩阵将图像转换为灰度。
  2. 使用ImageAttributes类的SetThreshold方法设置将黑色与白色分开的阈值。

这是C#代码:

using (Graphics gr = Graphics.FromImage(SourceImage)) // SourceImage is a Bitmap object { var gray_matrix = new float[][] { new float[] { 0.299f, 0.299f, 0.299f, 0, 0 }, new float[] { 0.587f, 0.587f, 0.587f, 0, 0 }, new float[] { 0.114f, 0.114f, 0.114f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; var ia = new System.Drawing.Imaging.ImageAttributes(); ia.SetColorMatrix(new System.Drawing.Imaging.ColorMatrix(gray_matrix)); ia.SetThreshold(0.8); // Change this threshold as needed var rc = new Rectangle(0, 0, SourceImage.Width, SourceImage.Height); gr.DrawImage(SourceImage, rc, 0, 0, SourceImage.Width, SourceImage.Height, GraphicsUnit.Pixel, ia); } 

我对这段代码进行了基准测试,它比逐像素操作快了大约40倍。

VB.NET版本:

 Using gr As Graphics = Graphics.FromImage(SourceImage) 'SourceImage is a Bitmap object' Dim gray_matrix As Single()() = { New Single() {0.299F, 0.299F, 0.299F, 0, 0}, New Single() {0.587F, 0.587F, 0.587F, 0, 0}, New Single() {0.114F, 0.114F, 0.114F, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1} } Dim ia As New System.Drawing.Imaging.ImageAttributes ia.SetColorMatrix(New System.Drawing.Imaging.ColorMatrix(gray_matrix)) ia.SetThreshold(0.8) Dim rc As New Rectangle(0, 0, SourceImage.Width, SourceImage.Height) gr.DrawImage(SourceImage, rc, 0, 0, SourceImage.Width, SourceImage.Height, GraphicsUnit.Pixel, ia) End Using 

如果你希望它看起来中等,你可能想要应用某种forms的抖动。

这里有一个完整的讨论,如果有点过时:

http://www.efg2.com/Lab/Library/ImageProcessing/DHALF.TXT

你不需要一个颜色矩阵来实现这一点,只需简单地将编码改为CCITT! 那只有黑与白。 结果保持正确,结果文件大小非常小。 也比System.DrawImage更有效,更快。

这是完美的解决方案:

 public void toCCITT(string tifURL) { byte[] imgBits = File.ReadAllBytes(tifURL); using (MemoryStream ms = new MemoryStream(imgBits)) { using (Image i = Image.FromStream(ms)) { EncoderParameters parms = new EncoderParameters(1); ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders() .FirstOrDefault(decoder => decoder.FormatID == ImageFormat.Tiff.Guid); parms.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionCCITT4); i.Save(@"c:\test\result.tif", codec, parms); } } }