Title: Mask saturated pixels in C#
This example helps you make a mask image from a picture by converting saturated pixels to black. The key is the following MaskPixels method.
private Bitmap MaskPixels(Bitmap bitmap,
PixelTypes pixel_type, int threshold)
{
Bitmap bm = new Bitmap(bitmap);
Bitmap32 bm32 = new Bitmap32(bm);
bm32.LockBitmap();
int width = bm.Width;
int height = bm.Height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
byte r, g, b, a;
bm32.GetPixel(x, y, out r, out g, out b, out a);
bool mask_pixel = false;
switch (pixel_type)
{
case PixelTypes.Red:
mask_pixel = ((r >= g + threshold) && (r > b + threshold));
break;
case PixelTypes.Green:
mask_pixel = ((g >= r + threshold) && (g > b + threshold));
break;
case PixelTypes.Blue:
mask_pixel = ((b >= r + threshold) && (b > g + threshold));
break;
}
if (mask_pixel)
bm32.SetPixel(x, y, 0, 0, 0, 255);
else
bm32.SetPixel(x, y, 255, 255, 255, 255);
}
}
bm32.UnlockBitmap();
return bm;
}
This method makes a copy of the original bitmap and makes a Bitmap32 associated with the copy. (For information on the Bitmap32 class, see my post Use the Bitmap32 class to manipulate image pixels very quickly in C#.)
The code then loops through the copy's pixels. If a pixel's selected color component is at least the cutoff value and greater than the other two color components, then the code sets the mask_pixel variable to true to indicate that this pixel should be part of the mask image.
For example, if the selected component is red, then the code checks whether the pixel's red component is at least as large as the cutoff value and that it is greater than the pixel's green and blue components.
After examining the pixel, if mask_pixel is true, the code sets the pixel's new color to black. If mask_pixel is false, the code sets the pixel's new color to white.
Notice that the code sets the new color's alpha (opacity) component to 255 in either case so it is a solid black or white.
The rest of the program is relatively straightforward.
You may need to use an editor to clean up the result. For example, the picture at the top of the post contains some random areas that happened to have a reddish tinge in the original image but that shouldn't be part of the mask image. You can use PS Paint or some other program to remove those pixels and to fill in any small gaps inside a masked area.
Be sure to save the result in PNG, BMP, or some other lossless format.
Download the example to experiment with it and to see additional details.
|