使用 openCV 编写视频 - 没有为轨道 0 设置关键帧

Ben*_*n S 5 c++ video opencv

我正在尝试使用以下代码使用 openCV 2.4.6.1 修改和编写一些视频:

cv::VideoCapture capture( video_filename );

    // Check if the capture object successfully initialized
    if ( !capture.isOpened() ) 
    {
        printf( "Failed to load video, exiting.\n" );
        return -1;
    }

    cv::Mat frame, cropped_img;

    cv::Rect ROI( OFFSET_X, OFFSET_Y, WIDTH, HEIGHT );


    int fourcc = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));
    double fps = 30;
    cv::Size frame_size( RADIUS, (int) 2*PI*RADIUS );
    video_filename = "test.avi";
    cv::VideoWriter writer( video_filename, fourcc, fps, frame_size );

    if ( !writer.isOpened() && save )
    {
        printf("Failed to initialize video writer, unable to save video!\n");
    }

    while(true)
    {   
        if ( !capture.read(frame) )
        {
            printf("Failed to read next frame, exiting.\n");
            break;
        }

        // select the region of interest in the frame
        cropped_img = frame( ROI );                 

        // display the image and wait
        imshow("cropped", cropped_img);

        // if we are saving video, write the unwrapped image
        if (save)
        {
            writer.write( cropped_img );
        }

        char key = cv::waitKey(30);
Run Code Online (Sandbox Code Playgroud)

当我尝试使用 VLC 运行输出视频“test.avi”时,我收到以下错误:avidemux 错误:没有为轨道 0 设置关键帧。我使用的是 Ubuntu 13.04,并且我尝试使用用 MPEG- 编码的视频- 4 和 libx264。我认为修复应该很简单,但找不到任何指导。实际代码可在https://github.com/benselby/robot_nav/tree/master/video_unwrap 获得。提前致谢!

gka*_*war 2

这似乎是写入的帧与打开的 VideoWriter 对象之间的大小不匹配的问题。当我尝试将网络摄像头中的一系列调整大小的图像写入视频输出时,我遇到了这个问题。当我删除调整大小步骤并仅从初始测试框架中获取大小时,一切都运行良好。

为了修复我的调整大小代码,我基本上通过处理运行了一个测试帧,然后在创建 VideoWriter 对象时拉动了它的大小:

#include <cassert>
#include <iostream>
#include <time.h>

#include "opencv2/opencv.hpp"

using namespace cv;

int main()
{
    VideoCapture cap(0);
    assert(cap.isOpened());

    Mat testFrame;
    cap >> testFrame;
    Mat testDown;
    resize(testFrame, testDown, Size(), 0.5, 0.5, INTER_NEAREST);
    bool ret = imwrite("test.png", testDown);
    assert(ret);

    Size outSize = Size(testDown.cols, testDown.rows);
    VideoWriter outVid("test.avi", CV_FOURCC('M','P','4','2'),1,outSize,true);
    assert(outVid.isOpened());

    for (int i = 0; i < 10; ++i) {
        Mat frame;
        cap >> frame;

        std::cout << "Grabbed frame" << std::endl;

        Mat down;
        resize(frame, down, Size(), 0.5, 0.5, INTER_NEAREST);

        //bool ret = imwrite("test.png", down);
        //assert(ret);
        outVid << down;


        std::cout << "Wrote frame" << std::endl;
        struct timespec tim, tim2;
        tim.tv_sec = 1;
        tim.tv_nsec = 0;
        nanosleep(&tim, &tim2);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的猜测是你的问题在于尺寸计算:

cv::Size frame_size( RADIUS, (int) 2*PI*RADIUS );
Run Code Online (Sandbox Code Playgroud)

我不确定你的帧来自哪里(即如何设置捕获),但可能在舍入或其他地方你的尺寸会变得混乱。我建议做类似于我上面的解决方案的事情。