通过C#和#x2B拍摄网络摄像头照片;EmguCV不是';行不通
通过C#+EmguCV拍摄网络摄像头照片是行不通的。EmguCV版本3.1.0.1(由于Visual Studio 2015、.NET Framework 4.5.2)。操作系统windows10。我的代码(dispose()太多,无法确定):通过C#和#x2B拍摄网络摄像头照片;EmguCV不是';行不通,c#,winforms,webcam,emgucv,C#,Winforms,Webcam,Emgucv,通过C#+EmguCV拍摄网络摄像头照片是行不通的。EmguCV版本3.1.0.1(由于Visual Studio 2015、.NET Framework 4.5.2)。操作系统windows10。我的代码(dispose()太多,无法确定): 奇怪的是,这个代码只工作了一次,我得到了一张照片。但是,该应用程序在所有后续尝试中都会冻结,没有任何异常消息。重新启动计算机后,应用程序仅能正常运行一次。有了这种行为,一些操作系统资源似乎在代码执行后没有被释放。我用@sunside建议修改了我的代码,它
奇怪的是,这个代码只工作了一次,我得到了一张照片。但是,该应用程序在所有后续尝试中都会冻结,没有任何异常消息。重新启动计算机后,应用程序仅能正常运行一次。有了这种行为,一些操作系统资源似乎在代码执行后没有被释放。我用@sunside建议修改了我的代码,它可以工作!在询问stackoverflow之前,我尝试了许多修改,包括不使用dispose,但都不起作用。 我不知道哪里出错了。工作代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using ZXing;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
Capture capture;
Mat mat;
Bitmap image;
public Form1()
{
InitializeComponent();
capture = new Capture();
this.FormClosing += Form1_FormClosing;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (image != null) image.Dispose();
if (mat != null) mat.Dispose();
mat = capture.QueryFrame();
image = mat.Bitmap;
image.Save(Application.StartupPath + "\\img.jpg");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (image != null) image.Dispose();
if (mat != null) mat.Dispose();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(capture != null) capture.Dispose();
}
}
}
我可以建议您尝试使用forge.net调用
Dispose()
的顺序以及调用capture.QueryFrame().Dispose()
对我来说似乎有点可疑QueryFrame()
可能返回null
,而image
实例可能包含对capture
的引用,您首先处理这些引用。您是否可以尝试按相反的顺序处理实例(最后创建的实例是第一个已处理的实例)。另外,只实例化一次Capture
实例(例如在构造函数中)是否会产生影响?我花了一些时间与网络摄像头进行交互,并得出结论,并非所有库和API都是100%稳定的。您可能错误地使用了库,但也可能是库中的bug。最后,尝试其他东西可能是值得的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using ZXing;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
Capture capture;
Mat mat;
Bitmap image;
public Form1()
{
InitializeComponent();
capture = new Capture();
this.FormClosing += Form1_FormClosing;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (image != null) image.Dispose();
if (mat != null) mat.Dispose();
mat = capture.QueryFrame();
image = mat.Bitmap;
image.Save(Application.StartupPath + "\\img.jpg");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (image != null) image.Dispose();
if (mat != null) mat.Dispose();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(capture != null) capture.Dispose();
}
}
}