opencvsharp打开摄像头并在picturebox中显示
时间: 2024-02-12 12:06:27 浏览: 152
opencv打开摄像头
4星 · 用户满意度95%
您可以尝试以下代码:
```csharp
using System;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace OpenCvSharpDemo
{
public partial class Form1 : Form
{
private VideoCapture capture;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
capture = new VideoCapture(0);
capture.Open(0);
capture.FrameWidth = pictureBox1.Width;
capture.FrameHeight = pictureBox1.Height;
capture.Fps = 30;
capture.Start();
Timer timer = new Timer();
timer.Interval = 33;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
Mat frame = capture.RetrieveMat();
if (frame != null)
{
pictureBox1.Image = BitmapConverter.ToBitmap(frame);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
capture.Stop();
capture.Dispose();
}
}
}
```
上面是一个 WinForm 的例子,其中包含一个名为 `pictureBox1` 的 `PictureBox` 控件。在 `Form1_Load` 事件中,我们创建一个名为 `capture` 的 `VideoCapture` 对象并将其绑定到设备 0(即默认摄像头)。我们还设置了捕获的帧的宽度和高度以及每秒帧率。然后,我们启动捕获并启动一个计时器,该计时器每隔 33 毫秒就会更新 `pictureBox1` 中的图像。最后,在 `Form1_FormClosing` 事件中,我们停止捕获并释放资源。
阅读全文