繁体   English   中英

使用 C# 将图像转换为灰度时如何解决循环错误

[英]How to resolve loop error while converting image to gray scale with C#

我正在尝试使用 C# 进行一些图像处理,我在pictureBox1和另一个pictureBox2中有一个图像。 我将没有灰度的原始图像加载到第一个PictureBox中,然后放置一个按钮事件处理程序,将该帧内图像中的Bitmap处理为灰度,然后将处理结果显示到第二个PictureBox中。 当我单击按钮时,出现ArgumentOutOfRangeException: Parameter must be positive and < Width. (Parameter 'x') ArgumentOutOfRangeException: Parameter must be positive and < Width. (Parameter 'x') 按钮处理程序内的代码如下

//get the graysale representation of this image and assign
            Bitmap mymap= new Bitmap(image_path);
            //Rectangle myrect= new Rectangle(0,0,mymap.Width,mymap.Height);
            Bitmap newmap=new Bitmap(mymap.Height,mymap.Width,mymap.PixelFormat);
            Color p;
            for(int y = 0; y < mymap.Height; y++)
            {
                for(int x = 0; x < mymap.Width; x++)
                {
                    p=mymap.GetPixel(x,y);
                    //get the opacity of this color
                    int a=p.A;
                    //get the red component of this pixel
                    int r = p.R;
                    //get the green component of this pixel
                    int g = p.G;
                    //get the blue component of this pixel
                    int b = p.B;
                    //get the average of these colors which is the gray scale
                    int av=(b+g+r)/ 3;
                    //assign to the new Bitmap
                    newmap.SetPixel(x,y,Color.FromArgb(a,av,av,av));
                }
            }
            //assign to pictureBox 2
          pictureBox2.Image=newmap;

我究竟做错了什么?

改变这个:

Bitmap(mymap.Height,mymap.Width,mymap.PixelFormat);

对此:

Bitmap(mymap.Width,mymap.Height,mymap.PixelFormat);

Bitmap 构造函数需要参数: Width, Height, PixelFormat

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM