无法使用EmguCV C#从单帧视频中读取帧,但可以从一帧以上的其他视频中读取

时间:2019-04-11 02:02:40

标签: c# opencv video emgucv

当前,我们有一个应用程序可以使用C#对视频进行逐帧处理。到目前为止,一切都很好。

当我们试图增加对图像的支持时,偶然发现了一个奇怪的错误。我们首先使用我们的代码(第一个代码块)生成一个单帧视频,然后尝试按照以前视频的所有其他功能读取它。

但是我们无法从单帧-仅使用以下代码生成的单个帧 mp4-mp4中读取帧:

//(After checking if video is actually an image)
// Create Video
string VideoFileName = OFD.FileName; //Yes, OFD.FileName is valid

Mat FirstImage = CvInvoke.Imread(VideoFileName);
string ActuallyAnImage_Name = VideoFileName.Substring(0, VideoFileName.LastIndexOf("\\")) + "\\" + "ImageAsVideo.mp4"; //Create an mp4

VideoWriter w = new Emgu.CV.VideoWriter(ActuallyAnImage_Name, VideoWriter.Fourcc('H', '2', '6', '4'), 30.0, FirstImage.Size, true);

w.Write(FirstImage);
w.Dispose();

VideoFileName = ActuallyAnImage_Name;
Console.WriteLine("In OFD: VideoFileName = " + VideoFileName); //everything is correct.

VC = new VideoCapture(VideoFileName); //VC is a global variable of type `Emgu.CV.VideoCapture`

上面的代码没什么问题,它可以正确生成单帧mp4视频,甚至可以使用Windows Movie Player打开。

问题伴随着当我们尝试使用下面的功能尝试读取此单帧视频时发生的事情:

private Mat GetMat(int someFrameNumber) {
    Mat m = new Mat();

    try {
        VC.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.PosFrames, someFrameNumber);
        VC.Read(m);

        Mat resized = new Mat();

        //Note: pictureBox_display is the pictureBox where we display our video on the C# application
        Console.WriteLine(m.Size + " " + pictureBox_display.Size + " FNO: " + someFrameNumber + " VideoFile:" + VideoFileName);

         /* CONSOLE OUTPUT 
           When it works: {Width=720, Height=576} {Width=600, Height=480} FNO: 0 VideoFile:<correct path>

           When it doesn't work: {Width=0, Height=0} {Width=600, Height=480} FNO: 0 VideoFile:<correct path>
         */

        CvInvoke.ResizeForFrame(m, resized, pictureBox_display.Size);

        return resized;
    }
    catch {
        System.Windows.Forms.MessageBox.Show("ERROR: Cannot read video frame");
        return m;
    }
}

魔术地讲,当我们使用相同的第一个代码块来生成一个以上帧的视频时,整个代码块都可以正常工作。当视频为2(或更多)帧时,它可以很好地工作。

但是当它只有一帧时,代码会以Exception thrown: 'Emgu.CV.Util.CvException' in Emgu.CV.World.dll

光荣地失败

我们尝试过的无效的方法:

  • 使用QueryFrame
  • 加载只有一帧的视频并尝试阅读

任何人都可以帮助解决这个奇怪的问题吗?

0 个答案:

没有答案