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

vbo*_*can 14 c# vb.net image image-processing colormatrix

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

vbo*_*can 25

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

  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);                
        }
Run Code Online (Sandbox Code Playgroud)

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

  • 这将做B&W(不是灰度):`New ColorMatrix(New Single()()_ {New Single(){1.5,1.5,1.5,0,0},_ New Single(){1.5,1.5,1.5,0 ,0},_ New Single(){1.5,1.5,1.5,0,0},_ New Single(){0,0,0,1,0},_ New Single(){-1,-1, -1,0,1}})` (4认同)

Nor*_*rga 6

您不需要颜色矩阵来实现此目的,只需将编码更改为 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


SSS*_*SSS 5

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
Run Code Online (Sandbox Code Playgroud)