我正在使用摄像头拍摄的1000万像素图像。LockBits对于我的需求来说似乎太慢 - 替代方案?
其目的是在矩阵(二维数组)中注册每个像素的灰度值。
我第一次使用GetPixel,但它花了25秒来做到这一点。现在我使用Lockbits,但它需要10秒,如果我不将结果保存在文本文件中,则需要3秒。
我的导师说他们不需要注册结果,但3秒仍然太慢。所以我在我的程序中做了什么错误,还是比我的应用程序中的Lockbits更快?
这里是我的代码:
public void ExtractMatrix()
{
Bitmap bmpPicture = new Bitmap(nameNumber + ".bmp");
int[,] GRAY = new int[3840, 2748]; //Matrix with "grayscales" in INTeger values
unsafe
{
//create an empty bitmap the same size as original
Bitmap bmp = new Bitmap(bmpPicture.Width, bmpPicture.Height);
//lock the original bitmap in memory
BitmapData originalData = bmpPicture.LockBits(
new Rectangle(0, 0, bmpPicture.Width, bmpPicture.Height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
//lock the new bitmap in memory
BitmapData newData = bmp.LockBits(
new Rectangle(0, 0, bmpPicture.Width, bmpPicture.Height),
ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
//set the number of bytes per pixel
// here is set to 3 because I use an Image with 24bpp
int pixelSize = 3;
for (int y = 0; y < bmpPicture.Height; y++)
{
//get the data from the original image
byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride);
//get the data from the new image
byte* nRow = (byte*)newData.Scan0 + (y * newData.Stride);
for (int x = 0; x < bmpPicture.Width; x++)
{
//create the grayscale version
byte grayScale =
(byte)((oRow[x * pixelSize] * .114) + //B
(oRow[x * pixelSize + 1] * .587) + //G
(oRow[x * pixelSize + 2] * .299)); //R
//set the new image's pixel to the grayscale version
// nRow[x * pixelSize] = grayScale; //B
// nRow[x * pixelSize + 1] = grayScale; //G
// nRow[x * pixelSize + 2] = grayScale; //R
GRAY[x, y] = (int)grayScale;
}
}
你可能使用[TPL]加快这(http://msdn.microsoft.com/en-us/library/dd537608。 aspx)使for循环并行运行。 – 2013-05-07 11:14:33
是否将图像锁定为图像原始格式时指定的像素格式? – CodesInChaos 2013-05-07 11:19:34
找到哪个部分很慢。你正在做1000万次迭代。如果在内部循环中可以进行优化,则可以获得很大的性能提升。 – CodeCaster 2013-05-07 11:21:23