文章目录
一、界面布局
- 两个
Button
- 一个
PictureBox
- 一个
BackgroundWorker cameraWorker
二、功能实现
2.1 打开摄像头
- 打开摄像头
- 判断摄像头是否打开,否:提示并退出
- 摄像头后台任务
cameraWorker
开始运行
private void openCameraBtn_Click(object sender, EventArgs e)
{
if (cameraWorker.IsBusy)
{
closeCamera();
}
else
{
openCamera();
}
}
private void openCamera()
{
capture.Open(0, VideoCaptureAPIs.ANY);
if (!capture.IsOpened())
{
Close();
MessageBox.Show("打开摄像头失败");
return;
}
openCameraBtn.Text = "关闭摄像头";
cameraWorker.RunWorkerAsync();
}
private void closeCamera()
{
openCameraBtn.Text = "打开摄像头";
cameraWorker.CancelAsync();
capture.Release();
pictureBox1.Image = null;
}
2.2 运行摄像头后台任务
-
while
死循环 - 获取摄像头
frameMat
- 转换成
Bitmap
- 复制给
pictureBox1
private void cameraWorker_DoWork(object sender, DoWorkEventArgs e)
{
var bgWorker = (BackgroundWorker)sender;
while (!bgWorker.CancellationPending)
{
using (var frameMat = capture.RetrieveMat())
{
var frameBitmap = BitmapConverter.ToBitmap(frameMat);
bgWorker.ReportProgress(0, frameBitmap);
}
Thread.Sleep(100);
}
}
private void cameraWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var frameBitmap = (Bitmap)e.UserState;
pictureBox1.Image?.Dispose();
pictureBox1.Image = frameBitmap;
}
三、异常报错
System.TypeInitializationException:““OpenCvSharp.Internal.NativeMethods”的类型初始值设定项引发异常。”
内部异常
DllNotFoundException: 无法加载 DLL“OpenCvSharpExtern”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。
因为还少了一点dll
- 点击下载OpenCVSharp dll.zip
- 放到
\bin\Debug\下面
四、运行
- 堪称完美
五、Demo源码
OpenCVSharpDemo工程源码点击下载
觉得好,就一键三连呗(点赞+收藏+关注)