MP4轉.JPG
阿新 • • 發佈:2018-10-31
#include<opencv2\opencv.hpp>
#include <iostream>
#include <stdio.h>
#include<fstream>
using namespace std;
using namespace cv;
//獲取視訊中的人臉
int main()
{
//開啟視訊檔案:其實就是建立一個VideoCapture結構
VideoCapture capture("new.mp4");
//檢測是否正常開啟:成功開啟時,isOpened返回ture
if (!capture.isOpened())
cout << "fail toopen!" << endl;
//獲取整個幀數
long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
cout << "整個視訊共" << totalFrameNumber << "幀" << endl;
//設定開始幀()
long frameToStart = 1;
capture.set(CV_CAP_PROP_POS_FRAMES, frameToStart);
cout << "從第" << frameToStart << "幀開始讀" << endl;
//設定結束幀
int frameToStop = totalFrameNumber;
if (frameToStop < frameToStart)
{
cout << "結束幀小於開始幀,程式錯誤,即將退出!" << endl;
return -1;
}
else
{
cout << "結束幀為:第" << frameToStop << "幀" << endl;
}
//獲取幀率
double rate = capture.get(CV_CAP_PROP_FPS);
cout << "幀率為:" << rate << endl;
//定義一個用來控制讀取視訊迴圈結束的變數
bool stop = false;
//承載每一幀的影象
Mat frame;
//顯示每一幀的視窗
namedWindow("Extractedframe");
//兩幀間的間隔時間:
//int delay = 1000/rate;
double delay = 1000 / rate;
//利用while迴圈讀取幀
//currentFrame是在迴圈體中控制讀取到指定的幀後迴圈結束的變數
long currentFrame = frameToStart;
//濾波器的核
int kernel_size = 3;
Mat kernel = Mat::ones(kernel_size, kernel_size, CV_32F) / (float)(kernel_size*kernel_size);
while (!stop)
{
//讀取下一幀
if (!capture.read(frame))
{
cout << "讀取視訊失敗" << endl;
return -1;
}
cout << "正在讀取第" << currentFrame << "幀" << endl;
imshow("Extractedframe", frame);
cout << "正在寫第" << currentFrame << "幀" << endl;
stringstream str;
str << "face//"<<currentFrame << ".jpg";
cout << str.str() << endl;
//waitKey(intdelay=0)當delay≤ 0時會永遠等待;當delay>0時會等待delay毫秒
//當時間結束前沒有按鍵按下時,返回值為-1;否則返回按鍵
//int c = waitKey(delay);
int c = waitKey(10);
//按下ESC或者到達指定的結束幀後退出讀取視訊
if ((char)c == 27 || currentFrame > frameToStop)
{
stop = true;
}
//按下按鍵後會停留在當前幀,等待下一次按鍵
if (currentFrame % 5==0)
imwrite(str.str(), frame);
currentFrame = currentFrame + 1;
}
//關閉視訊檔案
capture.release();
return 0;
}