将图像转换为灰度 C# 视觉对象 14

本文关键字:视觉 对象 灰度 图像 转换 | 更新日期: 2023-09-27 18:34:40

我在通过视觉Microsoft将图像转换为 C# 中的灰度时遇到了一点麻烦

目前我已经设置了我的代码,在我的 GUI 中我可以调整图像大小,图片 1我希望能够通过单击按钮将显示的图像转换为灰度。下面的代码!.一旦我按下灰度按钮,我的应用程序就会冻结。我哪里出错了

   private void buttonGrayscale_Scale(object sender, EventArgs e)
    {
        Bitmap bmMyImage = new Bitmap((Bitmap)PictureBox1.Image);
        bmMyImage=MakeGrayscale(bmMyImage);
        PictureBox1.Image = (Image)bmMyImage;
    }
    public static Bitmap MakeGrayscale(Bitmap original)
    {
        //make an empty bitmap the same size as orgininal
        Bitmap newBitmap = new Bitmap(original.Width, original.Height);
        for (int i = 0; i < original.Width; i++)
        {
            for (int j = 0; j < original.Height; j++)
            {
                Color c = newBitmap.GetPixel(i, j);
                int r = c.R;
                int g = c.G;
                int b = c.B;
                int avg = (r + g + b) / 3;
                newBitmap.SetPixel(i, j, Color.FromArgb(avg, avg, avg));
            }
        }
        return newBitmap;
    }

将图像转换为灰度 C# 视觉对象 14

也许您想从原始像素而不是从空位图中获取像素?

Color c = original.GetPixel(i, j);

您不需要将位图转换为图像。

private void buttonGrayscale_Scale(object sender, EventArgs e)
    {
        Bitmap bmMyImage=MakeGrayscale(PictureBox1.Image);
        PictureBox1.Image=bmMyImage;
    }

功能是:

public static Bitmap MakeGrayscale(Image original)
...