What would be a good TRUE black and white colormatrix?

24,959

Solution 1

I've finally found a solution to my problem:

  1. Transform the image to grayscale, using well a known colormatrix.
  2. Use SetThreshold method of the ImageAttributes class to set the threshold that separates black from white.

Here is the C# code:

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);                
        }

I've benchmarked this code and it is approximately 40 times faster than pixel by pixel manipulation.

Solution 2

You dont need a color matrix to achive this, just simply change encoding to CCITT! That only Black & White. Result remains correct and result file size is very small. Also much more efficient and faster than System.DrawImage.

This is the perfect solution:

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);
        }
    }
}

Solution 3

VB.NET version:

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

Solution 4

If you want it to look halfway decent, you'll probably want to apply some form of dithering.

Here's a full discussion, if a bit dated:

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

Share:
24,959
vbocan
Author by

vbocan

I am a software engineer based in Timișoara, Romania. I currently hold the position of software architect for Oce Software, a Canon company. I invented a dialect of the Forth programming language and implemented the first Forth compiler for the .NET platform. I reverse-engineered the communication protocol of some GPS trackers and wrote from scratch a vehicle tracking system that is currently used to track my two cars. I hold a PhD in computer science and I am the author of several papers and a book chapter. In the 90s I wrote several computer viruses in assembly language for my own research and I was the first to devise a technique to deter heuristic virus scanners. On the personal side, I am divorced and I have a lovely baby girl, my greatest achievement ever. In short, a humble man.

Updated on July 13, 2022

Comments

  • vbocan
    vbocan almost 2 years

    I want to convert an image from color to B/W (i.e. no grayscale, just black and white). Does anyone have a good colormatrix to achieve this?

  • vbocan
    vbocan about 14 years
    I want black and white because this would be part of an image recognition process, i.e. spotting some shapes regardless of their colors.
  • 500 - Internal Server Error
    500 - Internal Server Error about 14 years
    In that case, you can probably get away with something along the lines of "Pixel[x, y] = ((R(x, y) + G(x, y) + B(x, y)) / 3) >= 127 ? 1 : 0".
  • vbocan
    vbocan about 14 years
    This is what I've already tried, but altering the image pixel by pixel in very slow.
  • Todd Main
    Todd Main almost 14 years
    This will do B&W (not grayscale): 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}})
  • filozof
    filozof about 13 years
    @Otaku: Nope, your code won't work. It will give a sharper edge, but still grey values.
  • Todd Main
    Todd Main about 13 years
    @Pedery: you must not be implementing it correctly, that is exactly how to do black and white (no shades of grey whatsoever).
  • Bender Bending
    Bender Bending almost 7 years
  • Nicolas Belley
    Nicolas Belley over 5 years
    Any idea how to do that in a Android Xamarin solution? No access to EncoderParameters, neither ImageCodeInfo...
  • Norbert Varga
    Norbert Varga over 5 years
    I think You could use BitmapEncoder class for this in Xamarin as well. You are going to scan delivery notes with phone?
  • Nicolas Belley
    Nicolas Belley over 5 years
    No, I was trying to circumvent the epson SDK because we had some problems with it, and print directlty to the printer socket.