在 C++ 中使用 OpenCV 录制特定时间的视频

Record video of a certain time using OpenCV in C++

我正在研究图像处理(OpenCC 3.0、C++)。

其实我想做的是:

  1. 将视频录制为 1 分钟(这是我的问题)
  2. 录制视频后,读取录制的视频(第一步解决后我会做这一步)
  3. 做必要的图像处理过程(我已经做了这一步)
  4. 返回状态 1 并执行相同的过程,直到到达完成订单。

我附上 state 1 的代码。 (此代码,录制视频并写入文件,直到按 ESC 键。)

你能帮我吗,我如何录制 1 分钟或 10 分钟或任何特定时间的视频?

我想录制 1 分钟的视频。

#include "opencv2/opencv.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main() {

    VideoCapture vcap(0);
    if (!vcap.isOpened()) {
        cout << "Error opening video stream or file" << endl;
        return -1;
    }

    int frame_width = vcap.get(CV_CAP_PROP_FRAME_WIDTH);
    int frame_height = vcap.get(CV_CAP_PROP_FRAME_HEIGHT);
    VideoWriter video("/MyVideo.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);

    for (;;) {

        Mat frame;
        vcap >> frame;
        video.write(frame);
        imshow("Frame", frame);
        char c = (char)waitKey(33);
        if (c == 27) break;
    }
    return 0;
}`

行得通。

这是我的代码。我试图在上一个代码中获取 10 秒的视频,但我得到了 16 秒的视频。你能解释一下这是为什么吗?

#include "opencv2/opencv.hpp"
#include <iostream>
#include <ctime>
#include <cstdio>
#include <time.h>
#include <stdio.h>

    using namespace std;
    using namespace cv;

    int main() {

        //////////////////// Added Part
        time_t start, end;
        //////////////////// Added Part
        VideoCapture vcap(0);
        if (!vcap.isOpened()) {
            cout << "Error opening video stream or file" << endl;
            return -1;
        }
        int frame_width = vcap.get(CV_CAP_PROP_FRAME_WIDTH);
        int frame_height = vcap.get(CV_CAP_PROP_FRAME_HEIGHT);
        VideoWriter video("C:\Users\lenovo\Desktop\OpenCV Webcam Video Record With R Key\WebcamRecorder\WebcamRecorder\data\MyVideo.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);

        //////////////////// Added Part
        time(&start);
        //////////////////// Added Part

        for (;;) {

            Mat frame;
            vcap >> frame;
            video.write(frame);
            imshow("Frame", frame);
            char c = (char)waitKey(33);
            if (c == 27) break;

            //////////////////// Added Part
            time(&end);
            double dif = difftime(end, start);
            printf("Elasped time is %.2lf seconds.", dif);
            if (dif==10)
            {
                std::cout << "DONE" << dif<< std::endl;
                break;
            }
            //////////////////// Added Part
        }
        return 0;
    }

how can I record video 1 min or 10 min or any certain time?

就在 for 循环之前 启动时钟以获取当前时间并将其存储到名为 的变量中start_time.

for 循环

中的这段代码下方
char c = (char)waitKey(33);
        if (c == 27) break;

使用另一个变量获取当前时间,命名为cur_time.

cur_time 中减去 start_time 得到经过的时间。 如果你看到它到达使用 if 条件 的时间,那么 break loop.

不要在for循环中声明cur_time变量,先声明一下。

您可以使用此参考资料Easily measure elapsed time