Image Processing v2
I was tearing into v1.5 of Microsoft Robotics Studio (http://www.microsoft.com/robotics) and came across a novel way to process the pixels in an image. In previous posts I was using unmanaged C# code and pointers to move around the image. This worked well but is hard to manage. They take the approach of just dumping the entire image to a byte[], pure genius, now why did I not think of that. I will be rebuilding my library to utilize this technique but I thought this was so cool that I just had to share it!
/// <summary>
/// Coverts a bitmap to a byte[] then prints out the contents to a file
/// </summary>
public void PrintImage()
{
string file = "image.bmp";
Bitmap bitmap = Bitmap.FromFile(file) as Bitmap;
byte[] frame = ConvertBitmap(bitmap);
int height = bitmap.Height;
int width = bitmap.Width;
using (StreamWriter sWriter = new StreamWriter(file + ".txt"))
{
int offset;
//header
sWriter.WriteLine(string.Format("({0}, {1}) {2},{3},{4}", "COL", "ROW", "RED", "GREEN", "BLUE"));
//loop over rows
for (int y = 0; y < height; y++)
{
offset = y * width * 3;
//loop ober columns
for (int x = 0; x < width; x++, offset += 3)
{
int r, g, b;
b = frame[offset];
g = frame[offset + 1];
r = frame[offset + 2];
//pixel information
sWriter.WriteLine(string.Format("({0}, {1}) {2},{3},{4}", x, y, r, g, b));
}
}
}
}
/// <summary>
/// Convert a bitmap to a byte array
/// </summary>
/// <param name="bitmap">image to convert</param>
/// <returns>image as bytes</returns>
private byte[] ConvertBitmap(Bitmap bitmap)
{
//Code excerpted from Microsoft Robotics Studio v1.5
BitmapData raw = null; //used to get attributes of the image
byte[] rawImage = null; //the image as a byte[]
try
{
//Freeze the image in memory
raw = bitmap.LockBits(
new Rectangle(0, 0, (int)bitmap.Width, (int)bitmap.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb
);
int size = raw.Height * raw.Stride;
rawImage = new byte[size];
//Copy the image into the byte[]
System.Runtime.InteropServices.Marshal.Copy(raw.Scan0, rawImage, 0, size);
}
finally
{
if (raw != null)
{
//Unfreeze the memory for the image
bitmap.UnlockBits(raw);
}
}
return rawImage;
}