0

假设我有两个具有相同高度和宽度的图像。pic1.jpg 和 pic2.jpg。两个图像看起来非常相似,差异最小。在下面的例程的帮助下,我们可以得到两个图像之间的区别。下面的例程不是我的例程。

public class ImageDifferences
{
    private static ILog mLog = LogManager.GetLogger("ImageDifferences");

    public static unsafe Bitmap PixelDiff(Image a, Image b)
    {
        if (!a.Size.Equals(b.Size)) return null;
        if (!(a is Bitmap) || !(b is Bitmap)) return null;

        return PixelDiff(a as Bitmap, b as Bitmap);
    }

    public static unsafe Bitmap PixelDiff(Bitmap a, Bitmap b)
    {
        Bitmap output = new Bitmap(
            Math.Max(a.Width, b.Width),
            Math.Max(a.Height, b.Height),
            PixelFormat.Format32bppArgb);

        Rectangle recta = new Rectangle(Point.Empty, a.Size);
        Rectangle rectb = new Rectangle(Point.Empty, b.Size);
        Rectangle rectOutput = new Rectangle(Point.Empty, output.Size);

        BitmapData aData = a.LockBits(recta, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        BitmapData bData = b.LockBits(rectb, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        BitmapData outputData = output.LockBits(rectOutput, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

        try
        {
            byte* aPtr = (byte*)aData.Scan0;
            byte* bPtr = (byte*)bData.Scan0;
            byte* outputPtr = (byte*)outputData.Scan0;
            int len = aData.Stride * aData.Height;

            for (int i = 0; i < len; i++)
            {
                // For alpha use the average of both images (otherwise pixels with the same alpha won't be visible)
                if ((i + 1) % 4 == 0)
                    *outputPtr = (byte)((*aPtr + *bPtr) / 2);
                else
                    *outputPtr = (byte)~(*aPtr ^ *bPtr);

                outputPtr++;
                aPtr++;
                bPtr++;
            }

            return output;
        }
        catch (Exception ex)
        {

            return null;
        }
        finally
        {
            a.UnlockBits(aData);
            b.UnlockBits(bData);
            output.UnlockBits(outputData);
        }
    }
}
}

在获得差异后,我如何合并第一张图像上的差异。

这下面我们可以合并

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

但我们需要知道新图像将在第一张图像上绘制的 x 和 y。谁能告诉我如何从上述称为PixelDiff()的例程中获取 x 和 y 位置,谢谢。

4

1 回答 1

0

该例程对两个输入图像使用坐标 0,0,对差异图像使用相同的坐标,因此您将使用相同的坐标来绘制差异图像。

于 2012-12-11T19:11:08.670 回答