c# - 通过 C# + EmguCV 拍摄网络摄像头照片不起作用
问题描述
通过 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();
}
}
}
}
}
奇怪的是,这段代码只工作一次,我得到了一张照片。但是,该应用程序会冻结所有后续尝试,而不会出现任何异常消息。重新启动计算机后,该应用程序仅再次正常工作一次。通过这种行为,似乎某些操作系统资源在代码执行后没有被释放。
解决方案
我用@sunside 的建议修改了我的代码,它可以工作了!在询问 stackoverflow 之前,我尝试了许多修改,包括不处理,但它们没有工作。我不知道哪里出错了。工作代码在这里:
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();
}
}
}
推荐阅读
- docker - 我无法将 docker 的文件系统挂载到主机的文件系统
- python - 使用 multiprocessing lib 执行 python 脚本和使用 &-operator 在 bash 中执行的区别
- qt3d - QScreenRayCaster 未找到实体。我做错了什么?
- python - npm install --global Foundation-cli 不起作用
- java - MacOs 上 JNI 的线程“主”java.lang.UnsatisfiedLinkError 异常
- mysql - LEFT JOIN 中的列名重复 | MySQL
- mongodb - 即使在流星中自动发布后,客户也没有获得收藏
- javascript - 使用猫鼬,我可以使用单个模型自动推送和更新相关集合的更改(但不是模型实例)
- python - 优化用于转换变量的 python 代码
- java - Java ArrayList 用于存储用户输入并在输入 -999 时终止