我想将图像从彩色转换为黑白(即没有灰度,只有黑白)。有没有人有一个好的色彩矩阵来实现这个目标?
答案 0 :(得分:24)
我终于找到了解决问题的方法:
这是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倍。
答案 1 :(得分:4)
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
答案 2 :(得分:2)
如果你希望它看起来不错,你可能想要应用某种形式的抖动。
这是一个完整的讨论,如果有点过时了:
答案 3 :(得分:1)
你不需要一个颜色矩阵来实现这个,只需简单地将编码改为CCITT!只有Black&白色。结果保持正确,结果文件大小非常小。也比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);
}
}
}