如何在每次拍摄视频并将其写入文件时提供不同的文件名
how to give different file name every time i capture video and write it to file?
我是opencv的新手。我正在做这个项目的一部分。
在下面的代码中,我已经使用VideoWriter类来存储名为MyVideo.avi的视频,正如我在下面代码中指定的那样。但每次我拍摄视频时,它都会以相同的名称存储,即被覆盖。所以我想用电脑日期和时间来命名它。请帮我修改这个
#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;
}
文件名在源代码中进行硬编码。
初始化oVideoWriter
对象时,请使用以下代码:
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);
这将把filename设置为当前日期和时间。阅读有关日期/时间格式的文档。
有很多方法可以在运行时创建文件名:
按字符串创建
std::string filename = "image";
filename += "_001";
filename += ".img";
ostringstream
创建:
std::ostringstream name_stream;
name_stream << "image" << 2 << ".img";
std::string filename = name_stream.str();
snprintf
创建:
char buffer[128];
int chars_printed = snprintf(buffer, sizeof(buffer),
"image_%03d.img",
3);
std::string filename(buffer);
创建文件名的方法可能更多,但这些示例就足够了。选择一个适合你需要的。
相关文章:
- 不带预处理器的调用方法/文件的文件名/行号
- 如何在目录及其子文件夹中构建文件名字符串向量?
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 生成文件文件名参数
- 如何让我的代码显示文件名不正确或文件中数字的平均值?
- 如何更改目录中文件夹中的文件名
- 从 C++ 中的文件路径中提取文件名
- 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex
- 如何更改变量文件名的文件路径?
- 有没有办法打印包含当前文件的文件的文件名
- CMake 意外地将最后一个文件名预置到可执行文件中
- Qt - 如何在 30 天后删除日志文件,文件名不固定
- 将文件重命名为已存在的文件名
- 如何在 Windows 上从 C++11 统计信息对象的文件序列号中查找文件名
- Xcode 8.3.2 中的错误警告:文件的非可移植路径 - 指定的路径与磁盘上的文件名不同
- 如何在C 中读取具有前缀和时间戳为文件名的文件
- 使用文件名作为字符串从任意souce .cpp文件中调用函数
- 预处理器指令:为什么使用#Define的标题文件标识符与标头文件名不同
- 如何通过键入文件名来获取文件的目录。(C++)
- 如何根据用户输入指定的文件名打开文件