ماذا سيكون colormatrix بالأبيض والأسود الحقيقي؟
-
02-10-2019 - |
سؤال
أرغب في تحويل صورة من اللون إلى B/W (أي لا يوجد رمادي ، فقط بالأبيض والأسود). هل لدى أي شخص colormatrix جيد لتحقيق ذلك؟
المحلول
لقد وجدت أخيرًا حلاً لمشكلتي:
- تحويل الصورة إلى رمادي ، باستخدام colormatrix المعروف.
- يستخدم setThreshold طريقة ImageAttributes فئة لتعيين العتبة التي تفصل الأسود عن الأبيض.
هنا رمز 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
إذا كنت تريد أن تبحث في منتصف الطريق لائقًا ، فربما تريد تطبيق شكل من أشكال المخلل.
إليك مناقشة كاملة ، إذا كانت مؤرخة قليلاً:
أنت لا تحتاج إلى مصفوفة ملونة لتحقيق هذا ، ما عليك سوى تغيير الترميز إلى 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);
}
}
}
لا تنتمي إلى StackOverflow