Home > Uncategorized > Remove #Grey from an image using C# #ImageProcessing

Remove #Grey from an image using C# #ImageProcessing

Image processing in C# is surprisingly fast, and not too difficult. Here is a simple example of how to remove greys from an image, an extract only colour.

Firstly, a pure Grey is one defined as a colour where the Red, Green, and blue component are exactly equal. This spans the spectrum from White (all 255), to Black (all 0). In natural photographs, then the Grey may not be exactly pure, with small variations in the colour components.

So, lets see the core processing code:

public static byte[] PreprocessStep(byte[] input)
{
Stream sInput = new MemoryStream(input);
var imgEasy = Bitmap.FromStream(sInput) as Bitmap;
var img2dEasy = new Color[imgEasy.Width, imgEasy.Height];
for (int i = 0; i < imgEasy.Width; i++)
{
for (int j = 0; j < imgEasy.Height; j++)
{
Color pixel = imgEasy.GetPixel(i, j);

// Preprocessing
if (pixel.R == pixel.G && pixel.B == pixel.G)
{
// Convert all greys to white.
pixel = Color.White;
}

img2dEasy[i, j] = pixel;
}
}

var imgOut = new Bitmap(imgEasy.Width, imgEasy.Height);
for (int i = 0; i < imgEasy.Width; i++)
{
for (int j = 0; j < imgEasy.Height; j++)
{
imgOut.SetPixel(i, j, img2dEasy[i, j]);
}
}
var stream = new MemoryStream();
imgOut.Save(stream, ImageFormat.Png);
var bytes = stream.ToArray();
return bytes;
}

This accepts an image as a byte array, and outputs a byte array in PNG format. by accepting and returning a byte array, it makes it more “pluggable” into different inputs and outputs, like Files, HTTP streams etc.

Here’s how to use it with an input and output file.

static void Main(string[] args)
{
var strExePath = AppDomain.CurrentDomain.BaseDirectory;
var strEasyImage = strExePath + “il_570xN.1036233188_neqb.jpg”;
var sIn = new FileStream(strEasyImage,FileMode.Open);
var br = new BinaryReader(sIn);
var bIn = br.ReadBytes((int)sIn.Length);
sIn.Close();
var bOut = PreprocessStep(bIn);
var sOut = new FileStream(strExePath + “flower.png”,FileMode.Create);
sOut.Write(bOut,0,bOut.Length);
sOut.Close();
}

 

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: