Here is a function that takes a transparent and white image and attempts to turn it into a bool array.
My unit test code gives me 2 images that I would expect (see below) but the "numberOfMasked" is always higher then I expect. For example if the "maskBuffer" has one pixel marked (see mask_image_test.bmp below) then although "mask_bool_test70.bmp") creates an image with one pixel marked. For some reason the actual number of bools marked as true is much higher and seemingly random. I have seen it range from 25 - > 70.
public static bool[] ConvertImageToBoolAray(Bitmap maskbuffer)
{
bool[] mask = null;
int w = maskbuffer.Width;
int h = maskbuffer.Height;
#region unit_test
maskbuffer.Save("mask_image_test.bmp");
#endregion
lock (maskbuffer)
{
BitmapData bmpData = maskbuffer.LockBits(new Rectangle(0, 0, w, h),
ImageLockMode.ReadOnly,
PixelFormat.Format8bppIndexed);
const int numBmpChannel = 1;
int maskIndex = 0;
int bmpIndex = 0;
unsafe
{
byte* pixels = (byte*) bmpData.Scan0;
int numPixels = w*h;
mask = new bool[numPixels];
for (;
maskIndex < numPixels;
bmpIndex += numBmpChannel, maskIndex++)
{
byte red = pixels[bmpIndex];
bool masked = red != 0;
mask[maskIndex] = masked;
}
}
maskbuffer.UnlockBits(bmpData);
}
#region unit_test
byte[] boolAsByte = Array.ConvertAll(mask, b => b ? (byte)1 : (byte)0);
Bitmap maskBitmap = GLImageConvertor.ConvertByteBufferToBitmap(boolAsByte, w, h, PixelFormat.Format8bppIndexed);
int numberOfMasked = mask.Count(b => b);
maskBitmap.Save("mask_bool_test" + numberOfMasked + ".bmp");
#endregion
return mask;
}
Anyone got any ideas for this strange behavior?
Debugging shows that in the "pixels" memory, there is splots of bytes that I would not expect, I would expect to see one byte set to "FF" but instead I have random parts of data.
mask_image_test.bmp:
mask_bool_test70.bmp: