C# PictureBox 显示视频的问题

C# 用 OpenCVSharp 开发视频处理应用,通常用 PictureBox 循环显示图片(视频帧)来显示视频。比如:

VideoCapture capture = new VideoCapture(0);
Mat image = new Mat();

while (true)
{
     capture.Read(image);
     if(image.Empty())
         break;

     pictureBox1.Image = image.ToBitmap();

     Thread.Sleep(interval);
     Application.DoEvents();
​​​​​​​}

这里有两个问题需要考虑:

1. Application.DoEvents() 必不可少,否则界面及控件没有机会更新,视频无法显示,窗口也被卡死不能动弹。

2. 循环中 sleep 时间,最合适的是用视频的帧率来计算,intervel = (int)(1000/fps)

3. 另外还可以采用在定时器程序中读取视频帧并显示的方法,同样可以避免主线程阻塞。

4. 更复杂的方案:多线程异步编程。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#,可以使用OpenCVSharp库来实现PictureBox播放视频的功能。以下是实现该功能的步骤: 1. 首先,需要安装OpenCVSharp库。可以在NuGet包管理器搜索并安装OpenCVSharp4。 2. 在窗体添加一个PictureBox控件,并设置其大小和位置。 3. 在代码导入OpenCVSharp的命名空间。 4. 使用VideoCapture类打开视频文件,并使用Mat类读取每一帧图像。 5. 将读取到的图像转换为Bitmap格式,并将其赋值给PictureBox的Image属性。 6. 在需要的时候,可以使用Graphics类在PictureBox上绘制方框。 以下是示例代码: ```csharp using OpenCvSharp; using System; using System.Drawing; using System.Windows.Forms; namespace VideoPlayer { public partial class Form1 : Form { private VideoCapture capture; private Mat frame; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { capture = new VideoCapture("video.mp4"); frame = new Mat(); timer1.Interval = 33; // 设置定时器间隔为33毫秒,即每秒30帧 timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { capture.Read(frame); // 读取一帧图像 if (!frame.Empty()) { Bitmap bitmap = BitmapConverter.ToBitmap(frame); // 将Mat转换为Bitmap pictureBox1.Image = bitmap; // 显示图像 } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { // 在PictureBox上绘制方框 e.Graphics.DrawRectangle(Pens.Red, new Rectangle(100, 100, 200, 200)); } } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值