C++ 如何在每次捕获视频并将其写入文件时指定不同的文件名?
我是opencv的新手。我正在做这个项目的一部分 在下面的代码中,我使用了VideoWriter类来存储名为MyVideo.avi的视频,正如我在下面的代码中指定的那样。 但每次我捕获视频时,它都以相同的名称存储,即它被覆盖。 所以我想用计算机日期和时间来命名它。 请帮助我修改此C++ 如何在每次捕获视频并将其写入文件时指定不同的文件名?,c++,qt,opencv,image-processing,computer-vision,C++,Qt,Opencv,Image Processing,Computer Vision,我是opencv的新手。我正在做这个项目的一部分 在下面的代码中,我使用了VideoWriter类来存储名为MyVideo.avi的视频,正如我在下面的代码中指定的那样。 但每次我捕获视频时,它都以相同的名称存储,即它被覆盖。 所以我想用计算机日期和时间来命名它。 请帮助我修改此 #include "opencv2/highgui/highgui.hpp" #include <iostream> using namespace cv; using namespace std; i
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char* argv[])
{
VideoCapture cap(0); // open the video camera no. 0
if (!cap.isOpened()) // if not success, exit program
{
cout << "ERROR: Cannot open the video file" << endl;
return -1;
}
namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video
cout << "Frame Size = " << dWidth << "x" << dHeight << endl;
Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
VideoWriter oVideoWriter ("D:/MyVideo.avi", CV_FOURCC('P','I','M','1'), 20, frameSize, true); //initialize the VideoWriter object
if ( !oVideoWriter.isOpened() ) //if not initialize the VideoWriter successfully, exit the program
{
cout << "ERROR: Failed to write the video" << endl;
return -1;
}
while (1)
{
Mat frame;
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "ERROR: Cannot read a frame from video file" << endl;
break;
}
oVideoWriter.write(frame); //writer the frame into the file
imshow("MyVideo", frame); //show the frame in "MyVideo" window
if (waitKey(10) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
#包括“opencv2/highgui/highgui.hpp”
#包括
使用名称空间cv;
使用名称空间std;
int main(int argc,char*argv[])
{
VideoCapture(0);//打开0号摄像机
如果(!cap.isopend())//如果不成功,退出程序
{
cout有许多方法可以在运行时创建文件名:
按字符串创建
由ostringstream创建
:
创建文件名的方法可能更多,但这些示例应该足够了。选择一种适合您需要的方法。文件名在源代码中是硬编码的 初始化OvidoWriter对象时,请使用以下代码:
const QString filename = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH.mm.ss") + ".avi";
VideoWriter oVideoWriter(filename, CV_FOURCC('P','I','M','1'), 20, frameSize, true);
这会将文件名设置为当前日期和时间。关于日期/时间格式。你自己尝试过获取日期和时间吗?@NathanOliver我搜索了很多。然后我想出了循环videoWriter类的主意。我不知道如何做。
std::ostringstream name_stream;
name_stream << "image" << 2 << ".img";
std::string filename = name_stream.str();
char buffer[128];
int chars_printed = snprintf(buffer, sizeof(buffer),
"image_%03d.img",
3);
std::string filename(buffer);
const QString filename = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH.mm.ss") + ".avi";
VideoWriter oVideoWriter(filename, CV_FOURCC('P','I','M','1'), 20, frameSize, true);