opencv视频转图片并保存到文件夹下

实验时经常需要将视频保存为一帧一帧的图片,以获取实验结果,附代码如下:
#include <iostream>  
#include <vector>  
#include "opencv2\highgui\highgui.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 = 10;  
   
    //获取帧率  
    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[15];  
  
    while (!stop)   
    {  
        capture>>frame;  
        if(frame.empty())  
            break;  
        _itoa_s(num,temp_file,4,10); //4表示字符长度,10表示十进制,_itoa_s实现整型转字符串  
        filename = temp_file;  
        filename = path+filename+".jpg";    
		
		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(int argc,char** argv)  
{  
    string videoFromfile = "E:\\face.mp4";  //读取视频  
    string Imagespath    = "E:\\video2Image\\";    // 保存图片的文件夹路径一定要有,因为OpenCV不会自动创建文件夹  
    video2image(videoFromfile,Imagespath);    
    return 0;  
}  
运行结果:

参考:
http://blog.csdn.net/zhonghuan1992/article/details/38469315
http://www.cnblogs.com/yingying0907/archive/2012/08/11/2633426.html
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值