C# 图形类中未赋值局部变量的使用
代码中的“gr.DrawLine()”部分出现错误。它给我的错误是: 在“gr”中使用未分配的局部变量 我想在我的矩形中为EmguCV中的ROI创建一个红色边框。这是我的代码:C# 图形类中未赋值局部变量的使用,c#,emgucv,C#,Emgucv,代码中的“gr.DrawLine()”部分出现错误。它给我的错误是: 在“gr”中使用未分配的局部变量 我想在我的矩形中为EmguCV中的ROI创建一个红色边框。这是我的代码: public static Mat crop_roi(Mat input_img) { Image<Gray, byte> img = input_img.ToImage<Gray, byte>(); double w = input
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;
}
public static Mat crop\u roi(Mat input\u img)
{
图像img=input_img.ToImage();
双w=输入宽度;
双h=输入高度;
矩形r=新矩形((int)(100*0.2),(int)(100*0.4),(int)(w*0.6),(int)(h*0.6));
Pen p=新笔(颜色为红色);
Graphics gr=Graphics.FromImage(img);
gr.DrawRectangle(p,r.X,r.Bottom-1,r.X,r.Y);
图像输出=图像复制(r);
返回输出.Mat;
}
我希望你能帮助我。谢谢大家! 发生此错误的原因是您的
图形
对象gr
从未被赋值,因此出现以下问题:
在“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();
要从图像(如位图)创建图形
对象,可以执行以下操作:
//Getting it from a Bitmap.
Graphics gr = Graphics.FromImage(myBitmap);
有关在C#中创建
图形
对象的详细信息,您可以查看文档。所以我需要一个表单?但是我没有表格。这是一个控制台应用程序。我使用了您的建议,但“Graphics gr=Graphics.FromImage(img);”给了我一个错误:无法从'Emgu.CV.Image.Structure.Gray,byte>转换为System.Drawing.Image“请提供更多帮助。@Ibanez1408,如果我更新的答案对您有帮助,或者您还有任何问题,请告诉我。您知道img
是否属于Bitmap
类型吗?”?您还可以查看如何创建图形对象。我必须将图像转换为位图才能正常工作。谢谢你给我指明了正确的方向。