opencv读取视频并保存为图片
生活随笔
收集整理的這篇文章主要介紹了
opencv读取视频并保存为图片
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.功能:
? ? ?opencv讀取指定文件夾中的視頻文件,按照一定的間隔截取某些幀,將這些幀圖像連續(xù)命名,存儲(chǔ)在指定文件夾里。
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) {//初始化一個(gè)視頻文件捕捉器CvCapture* capture = cvCaptureFromAVI(filename);//獲取視頻幀數(shù)信息cvQueryFrame(capture);int numFrames = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);//視頻幀數(shù)//printf("frame numbers : %d/n",numFrames);//定義和初始化變量int thisframe = 0;IplImage* img = 0;char image_name[100];//用來存儲(chǔ)保存的圖片名字while(1){img = cvQueryFrame(capture); //獲取一幀圖片if (!img || thisframe >= numFrames)//若圖像為空或超出總幀數(shù)跳出,則跳出{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;//設(shè)置間隔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;// 描述:將視頻幀轉(zhuǎn)成圖片輸出 void main() {// 獲取視頻文件 VideoCapture cap("E:\\C_pagram\\readvideo\\readvideo\\Wildlife.wmv");// 獲取視頻總幀數(shù) long totalFrameNumber = cap.get(CV_CAP_PROP_FRAME_COUNT);cout << "total frames: " << totalFrameNumber << endl;//輸出總幀數(shù)Mat frame;bool flags = true;long currentFrame = 0;while (flags){// 讀取視頻每一幀 cap.read(frame);stringstream str;str << "_" << currentFrame << ".jpg";// 設(shè)置每50幀獲取一次幀 if (currentFrame % 50 == 0 && !frame.empty())//當(dāng)圖片不為空時(shí)保存{// 將幀轉(zhuǎn)成圖片輸出 imwrite("E:\\C_pagram\\readvideo\\readvideo\\data\\image" + str.str(), frame);}// 結(jié)束條件 if (currentFrame >= totalFrameNumber){flags = false;}currentFrame++;}system("pause"); }3.注意
(1)輸入文件路徑時(shí),用//或者\(yùn)都可以;
(2)sprintf里面圖片名稱可以組合起來,用逗號(hào)隔開,其中 outfile已經(jīng)是字符串的格式,不用加雙引號(hào);
(3)if (!img)?{break;}這句判斷沒加之前導(dǎo)出的圖片最后一張是空的;
(4)局部定義IplImage* img = 0;就局部釋放該指針cvReleaseImage(&img);
(5)程序(2)輸出的第一張圖為全黑的不為空,最后一張圖為空,加上判斷可以去掉最后一張空圖;
? ? ??if (currentFrame % 50 == 0 && !frame.empty())若不為空,保存
? ? ??if (currentFrame % 50 == 0 && frame.data)若frame的data有數(shù)據(jù),保存
? ? ?以上兩種方法都可以。
總結(jié)
以上是生活随笔為你收集整理的opencv读取视频并保存为图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Opencv中IplImage的四字节对
- 下一篇: opencv连续读图