字节数组c#中的图像差异

时间:2016-01-11 22:33:01

标签: c# image difference lockbits

我正在尝试执行应该返回字节数组(rgb值)中两个图像之间的差异并通过UDP发送它的方法。代码:(没有发送此数组的部分,因为它现在无关紧要)

public void getdiff(Bitmap lol,Bitmap lol2)
    {

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            Rectangle rect = new Rectangle(0, 0, lol.Width, lol.Height);
            BitmapData bmpData = lol.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            IntPtr ptr = bmpData.Scan0;

            Rectangle rect2 = new Rectangle(0, 0, lol2.Width, lol2.Height);
            BitmapData bmpData2 = lol2.LockBits(rect2, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            IntPtr ptr2 = bmpData2.Scan0;



            int numBytes = bmpData.Stride * lol.Height;
            byte[] rgbValues = new byte[numBytes];

            int numBytes2 = bmpData2.Stride * lol2.Height;
            byte[] rgbValues2 = new byte[numBytes2];

            byte[] difference = new byte[numBytes];

            Marshal.Copy(ptr, rgbValues, 0, numBytes);
            Marshal.Copy(ptr2, rgbValues2, 0, numBytes2);


            for (int counter = 0; counter < rgbValues.Length; counter++)
            {
                if (rgbValues[counter] != rgbValues2[counter])
                {
                   difference[counter] = rgbValues[counter];

                }

            }

             Marshal.Copy(rgbValues, 0, ptr, numBytes);

            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            textBox1.Text = ts.Milliseconds.ToString();
            lol.UnlockBits(bmpData);
            lol2.UnlockBits(bmpData2);




    }

现在我有来自2个图像的2字节数组,我只是比较它们,当图像不同时,我会从所选图像中将足够的RGB值写入差异[]。问题是,当RGB值在两个图像中相等时,该差异阵列中的适当位置用0填充(三重0表示白色)。所以问题是,如果我将这种差异[]施加到目标图像上,它可能大部分都是白色的。我真的想使用Marshal.Copy和Lockbits,因为它非常有效。

问题是:如何存储这种图像差异,以避免在读取/强加它时使“for”循环倍增?也许我错过了一些方法?我想留下LockBits和Marshal.Copy,但如果你有更好的想法 - 请与我分享。

0 个答案:

没有答案