C# - Converting Bitmap to byte[] using Marshal.Copy not working consistently?

家住魔仙堡 提交于 2020-01-07 03:06:25

问题


I have been trying to implement the image comparing algorithm seen here: http://www.dotnetexamples.com/2012/07/fast-bitmap-comparison-c.html

The problem I have been having is that when I try to compare a large amount of images one after another using the method pasted below (a slightly modified version from the link above), my results seem to be inaccurate. In particular, if I try to compare too many different images, even the ones that are the same will occasionally be detected as different. The problem seems to be that certain bytes in the array are different, as you can see in the screenshot I have included of two of the same images being compared (this occurs when I repeatedly compare images from an array of about 100 images - but there are actually only 3 unique images in the array):

private bool byteCompare(Bitmap image1, Bitmap image2) {
        if (object.Equals(image1, image2))
            return true;
        if (image1 == null || image2 == null)
            return false;
        if (!image1.Size.Equals(image2.Size) || !image1.PixelFormat.Equals(image2.PixelFormat))
            return false;

        #region Optimized code for performance

        int bytes = image1.Width * image1.Height * (Image.GetPixelFormatSize(image1.PixelFormat) / 8);

        byte[] b1bytes = new byte[bytes];
        byte[] b2bytes = new byte[bytes];

        Rectangle rect = new Rectangle(0, 0, image1.Width - 1, image1.Height - 1);

        BitmapData bmd1 = image1.LockBits(rect, ImageLockMode.ReadOnly, image1.PixelFormat);
        BitmapData bmd2 = image2.LockBits(rect, ImageLockMode.ReadOnly, image2.PixelFormat);

        try
        {
            Marshal.Copy(bmd1.Scan0, b1bytes, 0, bytes);
            Marshal.Copy(bmd2.Scan0, b2bytes, 0, bytes);

            for (int n = 0; n < bytes; n++)
            {
                if (b1bytes[n] != b2bytes[n])  //This line is where error occurs
                    return false;
            }
        }
        finally
        {
            image1.UnlockBits(bmd1);
            image2.UnlockBits(bmd2);
        }

        #endregion

        return true;
    }

I've added a comment to show where in the method this error is occurring. I assume it has something to do with the memory not being allocated properly, but I haven't been able to figure out what the source of the error is.

I should probably also mention that I don't get any issues when I convert the image to a byte array like so:

ImageConverter converter = new ImageConverter();
byte[] b1bytes = (byte[])converter.ConvertTo(image1, typeof(byte[]));

However, this approach is far slower.


回答1:


If (Width * bytesperpixel) != Stride, then there will be unused bytes at the end of each line that are not guaranteed to have any particular value and in practice can be filled with random garbage.

You need to iterate line by line, increment by Stride each time, and only checking the bytes that actually correspond to pixels on each line.




回答2:


Once you got the BitmapData object, the Stride can be found in that BitmapData object's Stride property. Make sure to extract that for both images.

Then, you have to loop over all pixels in the data so you can accurately determine where the image width for each line ends and the leftover data of the stride begins.

Also note this only works for high-colour images. Comparing 8-bit images is still possible (though you need to compare their palettes as well), but for lower than 8 you need to go bit-shifting to get the actual palette offset out of the image.

A simple workaround for that is to just paint your image on a new 32bpp image, effectively converting it to high colour.

public static Boolean CompareHiColorImages(Byte[] imageData1, Int32 stride1, Byte[] imageData2, Int32 stride2, Int32 width, Int32 height, PixelFormat pf)
{
    Int32 byteSize = Image.GetPixelFormatSize(pf) / 8;
    for (Int32 y = 0; y < height; y++)
    {
        for (Int32 x = 0; x < width; x++)
        {
            Int32 offset1 = y * stride1 + x * byteSize;
            Int32 offset2 = y * stride2 + x * byteSize;
            for (Int32 n = 0; n > byteSize; n++)
                if (imageData1[offset1 + n] != imageData2[offset2 + n])
                    return false;
        }
    }
    return true;
}


来源:https://stackoverflow.com/questions/33786563/c-sharp-converting-bitmap-to-byte-using-marshal-copy-not-working-consistentl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!