C#中的3x3平均过滤器

时间:2014-02-22 13:41:09

标签: c# image

我已编写代码来平滑图像,它使用3x3平均滤镜。但似乎它没有用 图片输出几乎是黑色

public void Smooth(Bitmap bmpInput){

        Bitmap temp;

        Color c;
        float sum = 0;
        for (int i = 0; i < bmpInput.Width; i++)
        {
            for (int j = 0; j < bmpInput.Height; j++)
            {
                c = bmpInput.GetPixel(i, j);
                byte gray = (byte)(.333 * c.R + .333 * c.G + .333 * c.B); 
                bmpInput.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
            }
        }
        temp = bmpInput;
      for (int i = 0; i <= bmpInput.Width - 3; i++)
            for (int j = 0; j <= bmpInput.Height - 3; j++)
            {
                for (int x = i; x <= i + 2; x++)
                    for (int y = j; y <= j + 2; y++)
                    {
                        c = bmpInput.GetPixel(x,y);
                        sum = sum +  c.R ;
                    }
                int color = (int)Math.Round(sum/9,10);
                temp.SetPixel(i + 1, j + 1, Color.FromArgb(color, color, color));
                sum = 0;
            }
        bmpInput = temp;
    }

1 个答案:

答案 0 :(得分:1)

变量temp仍然指向完全相同的位图。您必须将temp分配给新的位图图像并使用它。或者,您可以将新像素值存储在临时数组中,然后将此数组的内容传回图像。