opencv版本: opencv3.3.0
系统:win10
编译环境:vs2017
该代码实现了视频读取以后保存视频以及图片,视频保存在工程里,图片保存在任意指定位置。
// 2018_4_17.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "core/core.hpp"
#include
#include
#include
#include
#include
#include
#include
#include
#include //for camera
#include
#include
#include
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/ml/ml.hpp"
#include
#include
#include
#include
using namespace std;
using namespace cv;
int main(int argc, char ** argv)
{
char filename[1024];
if (argc == 1)
sprintf(filename, "%s", "camera.avi");
if (argc == 2)
sprintf(filename, "%s", "123");
VideoCapture capture;
capture.open(0);
if (!capture.isOpened())
{
cout << "Could not initialize capturing...\n" << endl;
return -1;
}
//按时间格式命名
time_t now = time(NULL);////获取1970.1.1至当前秒数time_t
struct tm * timeinfo = localtime(&now); //创建TimeDate,并转化为当地时间,
//struct tm * timeinfo = gmtime ( &currTime ); //创建TimeDate,并转化为GM时间,
char path[60];
strftime(path, 60, "%Y_%m_%d_%H_%M_%S", timeinfo);
char strPath[100];
sprintf(strPath, "%s.avi", path);//将创建文件的命令存入cmdchar中
//保存为avi格式视频
Mat frame;
VideoWriter writer;
writer.open(strPath, CV_FOURCC('X', 'V', 'I', 'D'), 25, Size(640, 480), true);//Size(640, 480)//Size(frame.rows, frame.cols)//"cam.avi"
int n = 1;
while (true)
{
capture >> frame;
char* cstr = new char[120];
// sprintf(cstr, "%s%d%s", "E:\\OpenCVWorkSpace\\saveCamAsVideo\\saveCamAsVideo\\savedPic\\Pic", n++, ".jpg");
sprintf(cstr, "%s%d%s", "E:\\OCR_Recognition\\shipin_capture\\shipin_capture", n++, ".jpg");
imwrite(cstr, frame);
imshow("Video_Capture", frame);
if (frame.empty())
{
break;
}
writer << frame;
waitKey(3);
}
//return 0;
}
视频保存的命名格式为日期时间
图片为地址,加最后一个参数+n
#include
#include
using namespace cv;
void main()
{
VideoCapture capture(0);
VideoWriter writer("VideoTest.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25.0, Size(640, 480));
while (capture.isOpened())
{
Mat frame;
if ((frame.rows==0)||(frame.cols==0))
{
printf("frame capture failed\n");
system("pause");
exit(0);
}
capture >> frame;
writer << frame;
imshow("video", frame);
if (cvWaitKey(20) == 27)
{
break;
}
}
}
其中VideoWriter writer(“VideoTest.avi”, CV_FOURCC(‘M’, ‘J’, ‘P’, ‘G’), 25.0, Size(640, 480));这一行代码中后面的两个参数分别是帧率与保存视频的宽和高。一般可利用下列两行代码获取,上述示例代码中为了方便,直接用的指定的值。
int rate = capture.get(CV_CAP_PROP_FPS);//帧率
writer.open("C:\\Users\\lenovo\\Documents\\04.avi",CV_FOURCC('M', 'J', 'P', 'G'),rate,Size(frame.cols,frame.rows),true);