protected override void BuildObjectsMap( UnmanagedImage image )
{
this.stride = image.Stride;
// check pixel format
if ( ( image.PixelFormat != PixelFormat.Format8bppIndexed ) &&
( image.PixelFormat != PixelFormat.Format24bppRgb ) &&
( image.PixelFormat != PixelFormat.Format32bppRgb ) &&
( image.PixelFormat != PixelFormat.Format32bppArgb ) &&
( image.PixelFormat != PixelFormat.Format32bppPArgb ) )
{
throw new UnsupportedImageFormatException( "Unsupported pixel format of the source image." );
}
// allocate temporary labels array
tempLabels = new int[( imageWidth + 2 ) * ( imageHeight + 2 )];
// fill boundaries with reserved value
for ( int x = 0, mx = imageWidth + 2; x < mx; x++ )
{
tempLabels[x] = -1;
tempLabels[x + ( imageHeight + 1 ) * ( imageWidth + 2 )] = -1;
}
for ( int y = 0, my = imageHeight + 2; y < my; y++ )
{
tempLabels[y * ( imageWidth + 2 )] = -1;
tempLabels[y * ( imageWidth + 2 ) + imageWidth + 1] = -1;
}
// initial objects count
objectsCount = 0;
// do the job
unsafe
{
byte* src = (byte*) image.ImageData.ToPointer( );
int p = imageWidth + 2 + 1;
if ( image.PixelFormat == PixelFormat.Format8bppIndexed )
{
int offset = stride - imageWidth;
// for each line
for ( int y = 0; y < imageHeight; y++ )
{
// for each pixel
for ( int x = 0; x < imageWidth; x++, src++, p++ )
{
// check for non-labeled pixel
if ( ( *src > backgroundThresholdG ) && ( tempLabels[p] == 0 ) )
{
objectsCount++;
LabelPixel( src, p );
}
}
src += offset;
p += 2;
}
}
else
{
pixelSize = Bitmap.GetPixelFormatSize( image.PixelFormat ) / 8;
int offset = stride - imageWidth * pixelSize;
// for each line
for ( int y = 0; y < imageHeight; y++ )
{
// for each pixel
for ( int x = 0; x < imageWidth; x++, src += pixelSize, p++ )
{
// check for non-labeled pixel
if ( (
( src[RGB.R] > backgroundThresholdR ) ||
( src[RGB.G] > backgroundThresholdG ) ||
( src[RGB.B] > backgroundThresholdB )
) &&
( tempLabels[p] == 0 ) )
{
objectsCount++;
LabelColorPixel( src, p );
}
}
src += offset;
p += 2;
}
}
}
// allocate labels array
objectLabels = new int[imageWidth * imageHeight];
for ( int y = 0; y < imageHeight; y++ )
{
Array.Copy( tempLabels, ( y + 1 ) * ( imageWidth + 2 ) + 1, objectLabels, y * imageWidth, imageWidth );
}
}