OpenCV学习笔记(二)OpenCV循环保存图片及图片信息的方法
编写OpenCV程序过程中,难免会有逐帧测试视频的需求,这里演示一个OpenCV读取视频,并逐帧保存为图片的Demo。
循环保存视频的Demo
// An highlighted block
#include "iostream"
#include <unistd.h>
#include "opencv2/opencv.hpp"
#include "string"
using namespace std;
using namespace cv;
int main()
{
stringstream tempString;
string picName;
int numOfFrame = 0;
Mat Frame;
VideoCapture capture;
capture.open("test.avi");
if (!capture.isOpened())
{
printf("--(!)Error opening video capture\n");
sleep(2);
return -1;
}
else
{
printf("--(*)Opening video capture success\n");
}
//新建ofstream对象,将原本打印在命令行的输入,打印在temp.txt中。
ofstream boxout("temp.txt");
while(1)
{
numOfFrame ++;
capture >> Frame;
if (Frame.empty())
{
printf("Frame is empty\n");
sleep(2);
break;
}
tempString.clear(); //为什么要clear呢
tempString << numOfFrame;
tempString << ".jpg";
tempString >> picName;
bool writeFlag;
writeFlag = imwrite("./saveImage/" + picName,Frame);
if(!writeFlag)
{
printf("write frame unsuccessful\n");
}
else
{
boxout << "write image " << numOfFrame << " successful" << endl;
printf("write %d image successful\n");
sleep(1);
}
}
capture.release();
return 0;
}
总结:上述代码调用了stringstream对象,实现了int数转换为string对象:
tempString << numOfFrame;
tempString << ".jpg";
tempString >> picName;
即实现了逐帧读取视频。