【发布时间】:2016-02-20 13:44:39
【问题描述】:
我一直在尝试实现此处看到的图像比较算法:http://www.dotnetexamples.com/2012/07/fast-bitmap-comparison-c.html
我遇到的问题是,当我尝试使用下面粘贴的方法(上面链接中的稍微修改的版本)一个接一个地比较大量图像时,我的结果似乎不准确。特别是,如果我尝试比较太多不同的图像,即使是相同的图像有时也会被检测为不同。问题似乎是数组中的某些字节是不同的,正如您在屏幕截图中看到的那样,我已经包含了两个正在比较的相同图像(当我反复比较大约 100 个图像的数组中的图像时会发生这种情况 - 但是有实际上数组中只有 3 个唯一图像):
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;
}
我添加了一条注释以显示该错误发生在方法中的哪个位置。我认为这与未正确分配内存有关,但我无法弄清楚错误的根源是什么。
我可能还应该提到,当我将图像转换为这样的字节数组时,我没有遇到任何问题:
ImageConverter converter = new ImageConverter();
byte[] b1bytes = (byte[])converter.ConvertTo(image1, typeof(byte[]));
但是,这种方法要慢得多。
【问题讨论】:
标签: c# image image-processing memory-management bitmap