I am trying to make threshold process on an image. The image of type "tif" and i am getting this error says
SetPixel is not supported for images with indexed pixel formats
This is my code and p11
is the image name
for (int r = 0; r < p11.Width; r++)
{
// whiteColor = 0;
// blackColor = 0;
for (int c = 0; c < p11.Height; c++)
{
num1 = int.Parse(p11.GetPixel(r, c).A.ToString()); // gets the alpha component value of this colout
num2 = int.Parse(p11.GetPixel(r, c).B.ToString()); // gets the Blue component value of this colout
num3 = int.Parse(p11.GetPixel(r, c).R.ToString()); // gets the Red component value of this colout
num4 = int.Parse(p11.GetPixel(r, c).G.ToString()); // gets the green component value of this colout
if( T <= num1 && T <= num2 && T <= num3 && T <= num4)
{
}
else
{
p11.SetPixel(r, c, Color.Black);
}
}
}
Indexed pixel format is when the image data contains no direct colors but entries of a palette, which indirectly references colors. 8 and less bit-per-pixel images are typically indexed ones. To access the list of actual colors see the Palette
property of the Bitmap
.
SetPixel
cannot be used for these images as it expects a color as parameter. To manipulate the image content you need to obtain the BitmapData
by the LockBits
method. In the example below the TransformColor
gets a palette index and returns another one.
private unsafe static void ManipulateIndexedBitmap(Bitmap bitmap)
{
int bpp = Image.GetPixelFormatSize(bitmap.PixelFormat);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.ReadWrite, bitmap.PixelFormat);
try
{
byte* line = (byte*)bitmapData.Scan0;
// scanning through the lines
for (int y = 0; y < bitmapData.Height; y++)
{
// scanning through the pixels within the line
for (int x = 0; x < bitmapData.Width; x++)
{
switch (bpp)
{
// a pixel is 1 byte - there are up to 256 palette entries
case 8:
line[x] = (byte)TransformColor(line[x]);
break;
// a pixel is 4 bits - there are up to 16 palette entries
case 4:
// First pixel is the high nibble
int pos = x >> 1;
byte nibbles = line[pos];
if ((x & 1) == 0)
{
nibbles &= 0x0F;
nibbles |= (byte)(TransformColor(nibbles) << 4);
}
else
{
nibbles &= 0xF0;
nibbles |= (byte)TransformColor(nibbles >> 4);
}
line[pos] = nibbles;
break;
// a pixel is 1 bit - there are exactly two palette entries
case 1:
// First pixel is MSB.
pos = x >> 3;
byte mask = (byte)(128 >> (x & 7));
if (TransformColor(((line[pos] & mask) == 0) ? 0 : 1) == 0)
line[pos] &= (byte)~mask;
else
line[pos] |= mask;
break;
}
}
line += bitmapData.Stride;
}
}
finally
{
bitmap.UnlockBits(bitmapData);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.