#OpenCV – Open a video file πŸŽ₯ and save each frame as a PNG πŸ–Ό file to a folder πŸ“‚#Net5

Buy Me A Coffee

Hi !

A couple of days ago I wrote this post, and made the sample with Python. So today, same scenario, however with C# 9 and Net5.

This is a non-usual scenario, however I’m on a point where I need to extract all the frames from a video file. The reason: some of these frames will be used to train a Machine Learning model.

There are tools that can do this, however it’s a nice moment to do some OpenCV code. Let’s go for it. A couple of remarks

  • Video file must be in the same folder as python file, and the name is defined in video_file, line 7
  • There is a live preview of the video, comment line 24 to avoid this
  • You can stop the process at any time pressing the Q letter
using System;
using OpenCvSharp;

var videoFile = "01.mp4";

var capture = new VideoCapture(videoFile);
var window = new Window("El Bruno - OpenCVSharp Save Video Frame by Frame");
var image = new Mat();

var i = 0;
while (capture.IsOpened())
    if (image.Empty())

    var imgNumber = i.ToString().PadLeft(8, '0');

    var frameImageFileName = $@"frames\image{imgNumber}.png";
    Cv2.ImWrite(frameImageFileName, image);

    if (Cv2.WaitKey(1) == 113) // Q

Console.WriteLine("Complete !");

Happy coding!


El Bruno

More posts in my blog ElBruno.com.

More info in https://beacons.ai/elbruno


Leave a comment

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 )

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.

%d bloggers like this: