比较一个像素与所有像素

时间:2015-06-16 11:43:16

标签: c# .net image image-processing

我想比较图像的像素与第二图像的所有像素,然后比较第二图像的所有像素的下一像素; 我正在使用这个代码,我在其中比较像素(字节转换)一个图像的一个像素与第二个像素,但我不想这种方法。请快速回复。 提前致谢。

 public static double GetDifferentPercentageSneller(ref Bitmap bmp1, ref Bitmap bmp2)
    {

        //if (bmp1 == null || bmp2 == null)

        //    return 100.0;



        //if (bmp1.Size != bmp2.Size)

        //    return 100.0;



        //if (bmp1.PixelFormat != bmp2.PixelFormat)

        //    return 100.0;



        int iMismatch = 0;

        int iMatch = 0;



        unsafe
        {

            BitmapData data1 = bmp1.LockBits(new Rectangle(0, 0, bmp1.Width, bmp1.Height), ImageLockMode.ReadOnly, bmp1.PixelFormat);

            BitmapData data2 = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadOnly, bmp2.PixelFormat);



            int pixelBytes = 0;



            switch (data1.PixelFormat)
            {

                case PixelFormat.Format32bppArgb:

                    pixelBytes = 4;

                    break;

                case PixelFormat.Format24bppRgb:

                    pixelBytes = 3;

                    break;

                default:

                    throw new Exception("Bitmap format not supported");

            }



            int paddingBytes = data1.Stride % pixelBytes;

            byte* location1 = (byte*)data1.Scan0;

            byte* location2 = (byte*)data2.Scan0;



            for (int y = 0; y < data1.Height; ++y)
            {

                for (int x = 0; x < data1.Width; ++x)
                {


                            if (*location1 == *location2)
                            {

                                iMatch++;


                            }
                            else
                            {

                                iMismatch++;

                            }
                    location1 += pixelBytes;

                    location2 += pixelBytes;

                }



                location1 += paddingBytes;

                location2 += paddingBytes;

            }



            bmp1.UnlockBits(data1);

            bmp2.UnlockBits(data2);

        }



        double percent = (double)iMatch/ (double)(iMismatch + iMatch);



        return percent * 100.0;

    }

1 个答案:

答案 0 :(得分:2)

您必须始终将LARGER图像(x,y)与SMALLER进行比较。虽然我不知道你究竟追求的是什么,但你可以这样做。

 BitmapImage Image1 = new BitmapImage(ImageStream);
 BitmapImage Image2 = new BitmapImage(ImageStream);
 int X = Image1.Width > Image2.Width ? Image2.Width : Image1.Width;
 int Y = Image1.Hieght > Image2.Height ? Image2.Heigth : Image1.Height;
 for(int x = 0; x < X; x++){
    for(int y = 0; y < Y; y++){
       Color color1 = Image1.GetPixel(x, y);
       Color color2 = Image2.GetPixel(x, y);
       // Do comparison here
    }
 }