其他分享
首页 > 其他分享> > OpenCVSharp入门教程 基础篇③——从本地摄像头获取媒体流

OpenCVSharp入门教程 基础篇③——从本地摄像头获取媒体流

作者:互联网

文章目录

一、界面布局

二、功能实现

2.1 打开摄像头

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 运行摄像头后台任务

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

四、运行

五、Demo源码

OpenCVSharpDemo工程源码点击下载

觉得好,就一键三连呗(点赞+收藏+关注)

标签:void,入门教程,private,frameBitmap,cameraWorker,pictureBox1,OpenCVSharp,摄像头
来源: https://blog.csdn.net/kangweijian/article/details/118706804