Apply a color threshold to an image in C#

[color threshold]

The example Provide gamma correction for an image in C# uses the ImageAttribute object’s SetGamma method to gamma correct an image. This example uses the SetThreshold method to apply a color threshold to an image.

The SetThreshold method takes as a parameter a float between 0 and 1. When you use the ImageAttributes object to draw a pixel, the pixel’s color components (on a 0 to 1 scale) are compared to the threshold value. If the component is greater than or equal to the threshold, it is set to 1. If the component is less than the threshold, it is set to 0.

For example, suppose a pixel’s color components on a 0 to 255 scale are R = 128, G = 200, and B = 180. Converting those components to a 0 to 1 scale (where 0 ≡ 0 and 255 ≡ 1) gives the component values R = 0.502, G = 0.784, and B = 0.706.

Now suppose the threshold is 0.75. For this pixel, the red and blue components are below the threshold so they are changed to 0. The green component is above the threshold so it is set to 1. The result is R = 0, G = 1, B = 0. Converting back to the normal 0 to 255 scale, R = 0, G = 255, B = 0, which is lime green.

The following AdjustThreshold method applies a threshold to an image.

// Perform threshold adjustment on the image.
private Bitmap AdjustThreshold(Image image, float threshold)
    // Make the result bitmap.
    Bitmap bm = new Bitmap(image.Width, image.Height);

    // Make the ImageAttributes object and set the threshold.
    ImageAttributes attributes = new ImageAttributes();

    // Draw the image onto the new bitmap
    // while applying the new ColorMatrix.
    Point[] points =
        new Point(0, 0),
        new Point(image.Width, 0),
        new Point(0, image.Height),
    Rectangle rect =
        new Rectangle(0, 0, image.Width, image.Height);
    using (Graphics gr = Graphics.FromImage(bm))
        gr.DrawImage(image, points, rect,
            GraphicsUnit.Pixel, attributes);

    // Return the result.
    return bm;

This method creates an ImageAttributes object and uses its SetThreshold method to set the threshold. It then uses the object to draw the original image onto a result Bitmap and returns the result. See the example Use an ImageAttributes object to adjust an image’s brightness in C# for additional details about how the drawing part works.

The end result is an image containing only primary and secondary colors, plus black and white.

The SetThreshold method is extremely fast so you can drag the scroll bar back and forth to change the image’s threshold in real time.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in drawing, graphics, image processing and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *