Andrii Kozytskyi
Andrii Kozytskyi

Reputation: 157

OpenCvSharp VideoWriter writes an empty video

I am trying to read a vide file, resize the frames and write them to an output file:

using System;
using System.Drawing;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace VideoProcessing
{
    public class Player
    {
        private VideoCapture capture;
        private VideoWriter writer;

        private Mat matInternal;
        public Bitmap bmInternal;

        private bool bIsPlaying = false;
        public Timer MyTimer    = new Timer();

        const string outname = "output.avi";
        OpenCvSharp.Size dsize = new OpenCvSharp.Size(640, 480);   

        public void InitPlayer(string videoName)
        {
            capture = new VideoCapture(videoName);
            writer  = new VideoWriter(outname, FourCC.MJPG, capture.Fps, dsize);

            matInternal = Mat.Zeros(dsize, MatType.CV_8UC3);
            bmInternal = matInternal.ToBitmap();

            var delay = 1000 / (int)capture.Fps;

            MyTimer.Interval = delay;
            MyTimer.Tick += new EventHandler(mk_onTick());
            MyTimer.Start();
        }

        private Action<object, EventArgs>
        mk_onTick()
        {
            return (object sender, EventArgs e) =>
            {
                capture.Read(matInternal);
                if (matInternal.Empty())
                {
                    Console.WriteLine("Empty frame!");
                }
                else
                {
                    matInternal.Resize(dsize);
                    bmInternal = matInternal.ToBitmap();
                    writer.Write(matInternal);
                }
            };
        }

        public void Dispose()
        {
            capture.Dispose();
            writer.Dispose();
        }
        
    }
}

This is executed in my main function as follows:

using System;
using System.Drawing;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace VideoProcessing
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            var videoName = "input.mp4";

            var pl = new Player();

            pl.InitPlayer(videoName);

            // Some other code that executes in the meantime

            pl.Dispose();
        }

    }
}

The writer can get disposed before the video finishes, which is fine because this will later be adapted for live camera video streams. However, the VideoWriter here produces an apparently empty, 0 second long video file. The codec setting does not produce any errors, and the video is only at 24 FPS so it should not be running into any speed issues. What could be causing this?

Upvotes: 0

Views: 2518

Answers (1)

Adolphe
Adolphe

Reputation: 11

I think you have to delay your main thread. By adding Thread.Sleep(2000) for instance.

I try your code with camera and it works well.

Upvotes: 1

Related Questions