【发布时间】:2011-02-14 07:45:33
【问题描述】:
我想将图像从彩色转换为黑白(即没有灰度,只有黑白)。有没有人有一个很好的色彩矩阵来实现这一点?
【问题讨论】:
标签: c# vb.net image image-processing colormatrix
我想将图像从彩色转换为黑白(即没有灰度,只有黑白)。有没有人有一个很好的色彩矩阵来实现这一点?
【问题讨论】:
标签: c# vb.net image image-processing colormatrix
我终于找到了解决问题的方法:
这是 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 倍。
【讨论】:
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}})
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
【讨论】:
您不需要颜色矩阵来实现这一点,只需将编码更改为 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);
}
}
}
【讨论】:
如果您希望它看起来不错,您可能需要应用某种形式的抖动。
这是一个完整的讨论,如果有点过时:
【讨论】: