图像的像素颜色不正确

时间:2011-12-23 18:31:24

标签: c# imaging

我正在尝试将2个图像与称为SAD(平方差的总和)的比较函数进行比较,我从每个图像中取出一个块,然后将像素转换为灰度,然后进行比较。 但问题是如果我比较两个相同的块,悲伤的结果不是0(所以有区别)。我检查了多个消息框,然后我看到程序返回错误的像素颜色:例如,黑色像素= 255而不是0。

这里是我的比较函数的代码:

 public double SAD(bloc Bc, bloc Br)
    {
        double sad = 0;
        {
            BitmapData bmp = image1.LockBits(new Rectangle(Bc.x, Bc.y, taille_bloc, taille_bloc), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            BitmapData bmp2 = image2.LockBits(new Rectangle(Br.x, Br.y, taille_bloc, taille_bloc), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            IntPtr ptr2 = bmp2.Scan0;
            IntPtr ptr = bmp.Scan0;
            int bytes = bmp.Width * bmp.Height * 3;
            double gris1, gris2;
            byte[] rgb = new byte[bytes];
            byte[] rgb2 = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgb, 0, bytes);
            System.Runtime.InteropServices.Marshal.Copy(ptr2, rgb2, 0, bytes);
            for (int i = 0; i < rgb.Length; i += 3)
            {

                 gris1 = rgb[i] * 0.2989 + rgb[i+1] * 0.5870 + rgb[i+2] * 0.1140;
                 gris2 = rgb2[i] * 0.2989 + rgb2[i + 1] * 0.5870 + rgb2[i + 2] *  0.1140;

                sad = sad + Math.Abs(gris2 - gris1);

            }
            image2.UnlockBits(bmp2);

            image1.UnlockBits(bmp);
        }

        return sad;

    }

如果我的解释不清楚请告诉我,我将重新制定

非常感谢你的帮助:)

1 个答案:

答案 0 :(得分:1)

一个可能的问题是您的字节数计算错误。你有:

int bytes = bmp.Width * bmp.Height * 3;

但位图填充,通常为4字节边界。你需要使用

int bytes = bmp.Stride * bmp.Height;

Stride是表示扫描线所需的字节数。对于24位图像,它将等于3 * bmp.Width PLUS填充所需的字节数(可能为零)。

要索引数组,然后逐行,并忽略填充字节。您必须在每行的开头初始化索引。

for (int row = 0; row < bmp.Height; ++row)
{
    int i = row * bmp.Stride;
    for (int p = 0; p < bmp.Width; ++p)
    {
        // do comparisons with rgb[i], rgb[i+1], rgb[i+2]
        i += 3;
    }
}