253.C# OpenCvSharp 本地摄像头

253.C# OpenCvSharp 本地摄像头

编码文章call10242025-01-08 14:37:1833A+A-

摘要


使用OpenCvSharp调用本地摄像头,用到基本类

VideoCapture类

  • VideoCapture(string filename):构造函数,用于打开视频文件。
  • VideoCapture(int device):构造函数,用于打开摄像头设备,其中device是摄像头的索引。
  • IsOpened():检查VideoCapture是否成功打开。
  • Read(Mat frame):读取下一帧视频并将其存储在Mat对象中。
  • Release():释放VideoCapture对象和相关资源。

正文


nuget 安装 OpenCVSharp4

这里OpenCvSharp4.runtime.win 库需要引用,不然会报错

DllNotFoundException: Unable to load DLL 'OpenCvSharpExtern' or one of its dependencies

OpenCvSharp.Extensions 库

一个例子

public partial class Form1 : Form
{
    private VideoCapture capture;
    public Form1()
    {
        InitializeComponent();
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        // 打开摄像头(通常是默认摄像头)
        capture = new VideoCapture(0);

        // 检查摄像头是否成功打开
        if (!capture.IsOpened())
        {
            MessageBox.Show("无法打开摄像头");
            Close();
            return;
        }

        // 设置视频帧捕获事件
        Task.Run(()=>{
            ProcessFrame();
        });
    }

    private void ProcessFrame()
    {
        while (true)
        {
            Mat frame = new Mat();
            capture.Read(frame);

            if (!frame.Empty())
            {
                // 在PictureBox中显示捕获的视频帧
                pic.Image = BitmapConverter.ToBitmap(frame);
            }
        }

    }


    private void btnClose_Click(object sender, EventArgs e)
    {
        // 释放资源并停止捕获
        if (capture != null && capture.IsOpened())
        {
            capture.Release();
        }
    }
}

增加一个截图功能

private void btnCapture_Click(object sender, EventArgs e)
{
    // 检查摄像头是否已经打开
    if (capture == null || !capture.IsOpened())
    {
        MessageBox.Show("请先打开摄像头");
        return;
    }

    // 创建一个Mat对象来存储截图
    Mat screenshot = new Mat();

    // 读取当前视频帧并将其复制到截图Mat
    capture.Read(screenshot);

    // 检查截图是否为空
    if (!screenshot.Empty())
    {
        // 为截图生成一个唯一的文件名
        string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        string screenshotFileName = #34;screenshot_{timestamp}.png";

        // 保存截图为图像文件
        screenshot.SaveImage(screenshotFileName);

        // 可以选择在窗口中显示截图
        // pictureBox.Image = BitmapConverter.ToBitmap(screenshot);

        MessageBox.Show(#34;截图已保存为 {screenshotFileName}");
    }
}

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4