Remove Background
In my earlier post I put together an image processing class (http://drowningintechnicaldebt.com/blogs/shawnweisfeld/archive/2006/11/06/Bitmap-Processing-in-C_2300_.aspx). I needed a method that did some segmentation based on a given color. It needed to take in the color and a threshold and it would black out any pixels that are not within the color threshold. Here is the code:
public static Bitmap RemoveBackground(Bitmap b, Color c, int threshold)
{
ImagerBitmap i = new ImagerBitmap(b.Clone() as Bitmap);
int maxGreen = c.G + threshold;
int minGreen = c.G - threshold;
int maxRed = c.R + threshold;
int minRed = c.R - threshold;
int maxBlue = c.B + threshold;
int minBlue = c.B - threshold;
for (int column = 0; column < i.Bitmap.Width; column++)
{
for (int row = 0; row < i.Bitmap.Height; row++)
{
Color px = i.GetPixel(column, row);
if (px.G > minGreen && px.G < maxGreen
&& px.R > minRed && px.R < maxRed
&& px.B > minBlue && px.B < maxBlue)
{
//i.SetPixel(column, row, Color.FromArgb(255, 255, 255));
}
else
{
i.SetPixel(column, row, Color.Black);
}
}
}
i.UnlockBitmap();
return i.Bitmap.Clone() as Bitmap;
}