什么是遍历图片像素最有效的方法?

3
我有两张1280x800的图片需要比较,因为我需要每秒执行循环操作,所以我非常担心效率问题。
我可以想到很多方法来循环遍历Bitmap对象像素,但我不知道哪种方法更有效。目前我正在使用简单的for循环,但它使用了太多内存和处理器资源,这是我目前无法承受的。
一些微调只会导致更多的处理器资源占用或者更多的内存占用。
如果您有任何提示、信息或经验,我非常感激。我也愿意使用外部库,如果它们有更好的效率。

2
不安全的、LockBits、int*、BitmapData.Scan0、UnlockBits - Xi Sigma
1
请注意,andrew的答案中的链接仅适用于24bppRGB,而不是通用的ARGB。很容易进行调整,请参见例如这里!我不喜欢使用unsafe,但我必须承认,它甚至比Lockbits稍微快一点。 - TaW
可能是在BMP中遍历像素的重复问题。 - Sam Axe
1个回答

4

from https://dev59.com/am025IYBdhLWcg3wZ1Ry#6094092

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];
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接