1.功能:
opencv读取指定文件夹中的视频文件,按照一定的间隔截取某些帧,将这些帧图像连续命名,存储在指定文件夹里。
2.代码如下:
(1)IplImage
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>void Video_to_image(char* filename,char * outfile, int interval)
{//初始化一个视频文件捕捉器CvCapture* capture = cvCaptureFromAVI(filename);//获取视频帧数信息cvQueryFrame(capture);int numFrames = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);//视频帧数//printf("frame numbers : %d/n",numFrames);//定义和初始化变量int thisframe = 0;IplImage* img = 0;char image_name[100];//用来存储保存的图片名字while(1){img = cvQueryFrame(capture); //获取一帧图片if (!img || thisframe >= numFrames)//若图像为空或超出总帧数跳出,则跳出{break;}if (thisframe % interval == 0){sprintf(image_name,"%s%s%d%s", outfile,"image", thisframe, ".jpg");//保存的图片名cvSaveImage(image_name, img); //保存一帧图片}thisframe++;}cvReleaseCapture(&capture);cvReleaseImage(&img);
}
int main()
{char filename[100] = "E://C_pagram//readvideo//readvideo//readvideo//Wildlife.wmv";char outfile[100] = "E://C_pagram//readvideo//readvideo//data//";int interval = 10;//设置间隔Video_to_image(filename,outfile, interval); //输入视频文件路径及名称、帧间隔return 0;
}
(2)Mat
#define _CRT_SECURE_NO_DEPRECATE#include <iostream>
#include "cv.h"
#include "opencv2/opencv.hpp" using namespace std;
using namespace cv;// 描述:将视频帧转成图片输出
void main()
{// 获取视频文件 VideoCapture cap("E:\\C_pagram\\readvideo\\readvideo\\Wildlife.wmv");// 获取视频总帧数 long totalFrameNumber = cap.get(CV_CAP_PROP_FRAME_COUNT);cout << "total frames: " << totalFrameNumber << endl;//输出总帧数Mat frame;bool flags = true;long currentFrame = 0;while (flags){// 读取视频每一帧 cap.read(frame);stringstream str;str << "_" << currentFrame << ".jpg";// 设置每50帧获取一次帧 if (currentFrame % 50 == 0 && !frame.empty())//当图片不为空时保存{// 将帧转成图片输出 imwrite("E:\\C_pagram\\readvideo\\readvideo\\data\\image" + str.str(), frame);}// 结束条件 if (currentFrame >= totalFrameNumber){flags = false;}currentFrame++;}system("pause");
}
3.注意
(1)输入文件路径时,用//或者\都可以;
(2)sprintf里面图片名称可以组合起来,用逗号隔开,其中 outfile已经是字符串的格式,不用加双引号;
(3)if (!img) {break;}这句判断没加之前导出的图片最后一张是空的;
(4)局部定义IplImage* img = 0;就局部释放该指针cvReleaseImage(&img);
(5)程序(2)输出的第一张图为全黑的不为空,最后一张图为空,加上判断可以去掉最后一张空图;
if (currentFrame % 50 == 0 && !frame.empty())若不为空,保存
if (currentFrame % 50 == 0 && frame.data)若frame的data有数据,保存
以上两种方法都可以。