在图形中使用未分配的局部变量 Class

Use of unassigned local variable in Graphics Class

我在代码的 "gr.DrawLine()" 部分遇到错误。它给我的错误是:

Use of unassigned local variable in 'gr'

我想在我的矩形中为 EmguCV 中的 ROI 创建一个红色边框。这是我的代码:

public static Mat crop_roi(Mat input_img)
        {
            Image<Gray, byte> img = input_img.ToImage<Gray, byte>();
            double w = input_img.Width;
            double h = input_img.Height;

            Rectangle r = new Rectangle((int)(100 * 0.2), (int)(100 * 0.4), (int)(w * 0.6), (int)(h * 0.6));

            Pen p = new Pen(Color.Red);
            Graphics gr = Graphics.FromImage(img);
            gr.DrawRectangle(p, r.X, r.Bottom - 1, r.X, r.Y);

            Image<Gray, byte> output = img.Copy(r);

            return output.Mat;
        }

希望你能帮助我。谢谢!

发生此错误的原因是您的 Graphics 对象 gr 从未被赋值 ,因此问题:

Use of unassigned local variable in 'gr'

解决此问题的一个简单示例是执行以下操作:

//To get it from a PaintEvent
Graphics gr = System.Windows.Forms.PaintEventArgs.Graphics;

//To get it from the drawing surface
Graphics gr = this.CreateGraphics(); 

要从图像(例如位图)创建 Graphics 对象,您可以执行以下操作:

//Getting it from a Bitmap.
Graphics gr = Graphics.FromImage(myBitmap);

有关在 C# 中创建 Graphics 对象的更多信息,您可以查看 this 文档。