【发布时间】:2020-07-17 08:17:45
【问题描述】:
无法通过 C# + EmguCV 拍摄网络摄像头照片。 EmguCV 版本 3.1.0.1(由于 Visual Studio 2015、.NET Framework 4.5.2)。操作系统 Windows 10。我的代码(可以肯定的是 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;
Bitmap image;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (capture != null)
{
capture.QueryFrame().Dispose();
capture.Dispose();
}
if (image != null)
{
image.Dispose();
}
capture = new Capture();
image = capture.QueryFrame().Bitmap;
image.Save(Application.StartupPath + "\\img.jpg");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
if (capture != null)
{
capture.QueryFrame().Dispose();
capture.Dispose();
}
if (image != null)
{
image.Dispose();
}
}
}
}
}
奇怪的是,这段代码只工作一次,我得到了一张照片。但是,该应用程序会冻结所有后续尝试,而不会出现任何异常消息。重新启动计算机后,该应用程序仅再次正常工作一次。通过这种行为,似乎某些操作系统资源在代码执行后没有被释放。
【问题讨论】:
-
我可以建议你尝试使用 AForge.NET
-
Dispose()调用的顺序以及对capture.QueryFrame().Dispose()的调用对我来说似乎很可疑。QueryFrame()可能返回null,image实例可能包含对capture的引用,这是您首先处理的。您能否尝试以相反的顺序处理实例(创建的最后一个是第一个处理的)。另外,只实例化一次Capture实例(例如在构造函数中)是否会有所不同? -
我花了一些时间与网络摄像头交互并得出结论,并非所有库和 API 都是 100% 稳定的。您可能错误地使用了该库,但也可能是该库中的错误。最后,尝试其他方法可能是值得的。