//main.cpp
//处理视频流
#include <iostream>
#include <vector>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main(){
cv::VideoCapture cap;
cap.open("test.mp4");
//检测是否正常打开:成功打开时,isOpened返回ture
if(!cap.isOpened())
cout<<"fail to open!"<<endl;
long totalFrameNumber = cap.get(CV_CAP_PROP_FRAME_COUNT);
//获取整个帧数
cv::Mat frame;
cout<<"整个视频共"<<totalFrameNumber<<"帧"<<endl;
while(1)
{
cap>>frame;
if(frame.empty()) break;
//cv::imshow("当前视频",frame);
//write your own code here
cv::imshow("frame",frame);
if(cv::waitKey(30) >=0)
break;
}
return 0;
}
//main.cpp
//视频流存为图片序列
#include <iostream>
#include <vector>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
void video2image(string video,string path)
{
VideoCapture capture(video);
long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
cout << "total frames is:" << totalFrameNumber << "." << endl;
//设置开始帧
long frameToStart = 1;
capture.set(CV_CAP_PROP_POS_FRAMES, frameToStart);
cout << "from" <<frameToStart << "read" << endl;
//设置结束帧
int frameToStop = totalFrameNumber;
//获取帧率
double rate = capture.get(CV_CAP_PROP_FPS);
cout << "rate is:" << rate<< endl;
double delay = 1000 / rate;
//定义一个用来控制读取视频循环结束的变量
bool stop = false;
long currentFrame = frameToStart;
if(!capture.isOpened())
{
cerr<<"Failed to open a video"<<endl;
return ;
}
Mat frame;
int num=1;
string filename;
char temp_file[10];
while (!stop)
{
capture>>frame;
if(frame.empty())
break;
sprintf(temp_file, "%d", num);
filename = temp_file;
filename = path+filename+".jpg";
cout <<filename<<endl;
cout << "now is reading" << currentFrame << "." << endl;
imshow("Extractedframe",frame);
cout << "now is writing" << currentFrame << "." << endl;
imwrite(filename,frame);
int c = waitKey(delay);
//按下ESC或者到达指定的结束帧后退出读取视频
if ((char)c == 27 ||currentFrame > frameToStop)
{
stop = true;
}
//按下按键后会停留在当前帧,等待下一次按键
if (c >= 0)
{
waitKey(0);
}
num++;
currentFrame++;
}
capture.release();
waitKey(0);
}
int main() {
string videoFromfile = "test.mp4"; //读取视频
string Imagespath = "/home/yolo_slam/yolo_wrap/test/img/"; // 保存图片的文件夹路径一定要有,因为OpenCV不会自动创建文件夹
video2image(videoFromfile,Imagespath);
return 0;
}
编译命令:
/usr/bin/g++-5 main.cpp -std=c++11 -I/usr/local/include/opencv -I/usr/local/include -L/usr/local/lib -lopencv_stitching -lopencv_objdetect -lopencv_superres -lopencv_videostab -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_photo -lopencv_ml -lopencv_imgproc -lopencv_flann -lopencv_core -ldl -Wl,-rpath,. -o test
执行:
./test