3

I've 2 images that I need to compare of 1280x800 each and I'm too worried about the efficiency as I'll have to do the same operations that include looping each second

I can think of so many ways to loop through a Bitmap object pixels but I don't know which would be more efficient, for now I am using simple for loop but it uses too much memory and processing which I could not afford at this point

Some tweaks here and there and all it does is less memory for more processing or the other way around

Any tips, information or experience is highly appreciated, I'm also open to use external libraries if they have much better efficiency.

VC.One
  • 14,790
  • 4
  • 25
  • 57
user3761832
  • 563
  • 2
  • 7
  • 18
  • 2
    `unsafe` `LockBits` `int*` `BitmapData.Scan0` `UnlockBits` – Xi Sigma Apr 04 '15 at 11:38
  • 1
    Note that the link in andrew's answer works only for 24bppRGB, not the generic ARGB. Not hard to adapt, see e.g. [here](http://stackoverflow.com/questions/28792723/adding-or-subtracting-color-from-an-image-in-a-picturebox-using-c-sharp/28799612?s=8|0.3058#28799612)! I don't like to use unsafe, but I have to admit, it is even a __little__ faster than Lockbits. – TaW Apr 04 '15 at 12:49
  • possible duplicate of [Travel through pixels in BMP](http://stackoverflow.com/questions/6020406/travel-through-pixels-in-bmp) – Sam Axe Apr 04 '15 at 13:27

1 Answers1

4

from https://stackoverflow.com/a/6094092/1856345

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];
    }
}
jakob_a
  • 91
  • 1
  • 6
Andrew
  • 218
  • 4
  • 18