遍历图片像素的最有效方法是什么
What is the most efficient way to loop through picture pixels
我有 2 张图像需要比较,每张都是 1280x800,我太担心效率了,因为我必须执行相同的操作,包括每秒循环
我可以想出很多方法来遍历 Bitmap 对象像素,但我不知道哪种方法更有效,因为现在我使用的是简单的 for 循环,但它使用了太多内存和处理,我可以暂时买不起
在这里和那里进行一些调整,它所做的只是减少内存以进行更多处理,反之亦然
非常感谢任何提示、信息或经验,如果外部库效率更高,我也愿意使用它们。
来自
Bitmap bmp = new Bitmap("SomeImage");
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];
byte[] r = new byte[bytes / 3];
byte[] g = new byte[bytes / 3];
byte[] b = new byte[bytes / 3];
// Copy the RGB values into the array.
Marshal.Copy(ptr, rgbValues, 0, bytes);
int count = 0;
int stride = bmpData.Stride;
for (int column = 0; column < bmpData.Height; column++)
{
for (int row = 0; row < bmpData.Width; row++)
{
b[count] = rgbValues[(column * stride) + (row * 3)];
g[count] = rgbValues[(column * stride) + (row * 3) + 1];
r[count++] = rgbValues[(column * stride) + (row * 3) + 2];
}
}
我有 2 张图像需要比较,每张都是 1280x800,我太担心效率了,因为我必须执行相同的操作,包括每秒循环
我可以想出很多方法来遍历 Bitmap 对象像素,但我不知道哪种方法更有效,因为现在我使用的是简单的 for 循环,但它使用了太多内存和处理,我可以暂时买不起
在这里和那里进行一些调整,它所做的只是减少内存以进行更多处理,反之亦然
非常感谢任何提示、信息或经验,如果外部库效率更高,我也愿意使用它们。
来自
Bitmap bmp = new Bitmap("SomeImage");
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];
byte[] r = new byte[bytes / 3];
byte[] g = new byte[bytes / 3];
byte[] b = new byte[bytes / 3];
// Copy the RGB values into the array.
Marshal.Copy(ptr, rgbValues, 0, bytes);
int count = 0;
int stride = bmpData.Stride;
for (int column = 0; column < bmpData.Height; column++)
{
for (int row = 0; row < bmpData.Width; row++)
{
b[count] = rgbValues[(column * stride) + (row * 3)];
g[count] = rgbValues[(column * stride) + (row * 3) + 1];
r[count++] = rgbValues[(column * stride) + (row * 3) + 2];
}
}