【发布时间】:2016-12-05 09:52:06
【问题描述】:
考虑以下两个例程。
//Tested
///Working fine.
public static Bitmap ToBitmap(int [,] image)
{
int Width = image.GetLength(0);
int Height = image.GetLength(1);
int i, j;
Bitmap bitmap = new Bitmap(Width, Height);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, Width, Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
unsafe
{
byte* address = (byte*)bitmapData.Scan0;
for (i = 0; i < bitmapData.Height; i++)
{
for (j = 0; j < bitmapData.Width; j++)
{
// write the logic implementation here
address[0] = (byte)image[j, i];
address[1] = (byte)image[j, i];
address[2] = (byte)image[j, i];
address[3] = (byte)255;
//4 bytes per pixel
address += 4;
}//end for j
//4 bytes per pixel
address += (bitmapData.Stride - (bitmapData.Width * 4));
}//end for i
}//end unsafe
bitmap.UnlockBits(bitmapData);
return bitmap;// col;
}
//Tested
///Working fine.
public static int[,] ToInteger(Bitmap bitmap)
{
int[,] array2D = new int[bitmap.Width, bitmap.Height];
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format32bppRgb);
unsafe
{
byte* address = (byte*)bitmapData.Scan0;
int paddingOffset = bitmapData.Stride - (bitmap.Width * 4);//4 bytes per pixel
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
byte[] temp = new byte[4];
temp[0] = address[0];
temp[1] = address[1];
temp[2] = address[2];
temp[3] = address[3];
array2D[j, i] = BitConverter.ToInt32(temp, 0);
//4-bytes per pixel
address += 4;//4-channels
}
address += paddingOffset;
}
}
bitmap.UnlockBits(bitmapData);
return array2D;
}
这两个例程适用于 32bpp 图像。这些例程仅在像素格式设置为PixelFormat.Format32bpp 时有效。如果我使用PixelFormat.Format8bppIndexed,它会生成一个异常。
为了避免该异常(另外,由于地址计算问题,我无法实现byte和int之间的无缝转换),我需要每次将那个32位Bitmap转换为灰度int[,] 被转换回 Bitmap。我想摆脱这个问题。
Bitmap grayscale = Grayscale.ToGrayscale(InputImage);
//Here, the Bitmap is treated as a 32bit image
//to avoid the exception eventhough it is already
//an 8bpp grayscale image.
int[,] i1 = ImageDataConverter.ToInteger(grayscale);
Complex[,] comp = ImageDataConverter.ToComplex(i1);
int[,] i2 = ImageDataConverter.ToInteger(comp);
Bitmap b2 = ImageDataConverter.ToBitmap(i2);
//It is already a Grayscale image.
//But, the problem is, b2.PixelFormat is set to
//PixelFormat.Formap32bpp because of those routines.
//Hence the unnecessay conversion.
b2 = Grayscale.ToGrayscale(b2);
我需要修改它们以仅对 8bpp 索引(灰度)图像进行操作。
我怎样才能做到这一点?
【问题讨论】:
-
你要什么操作?您的意思是您希望能够传递
byte[,]而不是int[,]?如果不是,那么如何解释int[,]?每个 32 位值是否只存储 0 到 255 之间的值?他们真的在你写的时候被索引了吗?如果是这样,应该使用什么调色板?还是它们真的是灰度的(正如您也写的那样)?每个 32 位值中是否包含四个像素?无论哪种方式,如何解释 8 位值?你想输出一个 32bpp 的图像,还是应该输出也是 8bpp?您几乎忽略了规范的所有重要部分。
标签: c# image image-processing bitmap integer