#dotnet – Display a video file🎥 in Winform using #OpenCV and #net5

Buy Me A Coffee

Hi !

Super short post today, however is the base of the next series of posts around OpenCV and .Net 5. I already wrote on how to work with a webcam, and now it’s time to share a simple piece of code to show

How to open and process a video frame by frame

I’ve downloaded a “traffic cam” video from Youtube, and this is the output in a Winform.

Super easy ! And as usual, the source code

using System;
using System.Threading;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using Size = OpenCvSharp.Size;
namespace Demo13_WinFormVideoFromFile
public partial class Form1 : Form
private bool _run = false;
private VideoCapture _capture;
private Mat _image;
private Thread _cameraThread;
private string _videoFile = "4K camera example for Traffic Monitoring (Road).mp4";
private delegate void SafeCallDelegate(string text);
public Form1()
Load += Form1_Load;
Closed += Form1_Closed;
private void Form1_Closed(object sender, EventArgs e)
private void btnStart_Click(object sender, EventArgs e)
_capture = new VideoCapture(_videoFile);
_run = true;
private void btnStop_Click(object sender, EventArgs e)
_run = false;
private void Form1_Load(object sender, EventArgs e)
_image = new Mat();
_cameraThread = new Thread(new ThreadStart(CaptureCameraCallback));
private void CaptureCameraCallback()
while (true)
if (!_run) continue;
var startTime = DateTime.Now;
if (_image.Empty()) return;
var imageRes = new Mat();
Cv2.Resize(_image, imageRes, new Size(320, 240));
var bmpWebCam = BitmapConverter.ToBitmap(imageRes);
pictureBoxWebCam.Image = bmpWebCam;

And the source video

Happy coding!


El Bruno


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.