OpenCV获取视频的每一帧并保存为.jpg图片

  • 时间:
  • 浏览:27

本文真例为各人分享了OpenCV获得视频的每帧并保留为图片的详细代码,供各人参考,详细内容以下

#include
#include 
#include 
#include 

using namespace std;
using namespace cv;

//获得视频中的人脸

int main()
{
 //翻开视频文件:实在便是成立1个VideoCapture构造 
 VideoCapture capture("1.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 = 30;

 if (frameToStop < frameToStart)
 {
  cout << "完毕帧小于起头帧,法式毛病,行将加入!" << endl;
  return ⑴;
 }
 else
 {
  cout << "完毕帧为:第" << frameToStop << "帧" << endl;
 }

 //获得帧率 
 double rate = capture.get(CV_CAP_PROP_FPS);
 cout << "帧率为:" << rate << endl;
 //界说1个用去掌握读与视频轮回完毕的变量 
 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)
 {
  //读与下1帧 
  if (!capture.read(frame))
  {
   cout << "读与视频失利" << endl;
   return ⑴;
  }


  cout << "正正在读与第" << currentFrame << "帧" << endl;
  imshow("Extractedframe", frame);

  cout << "正正在写第" << currentFrame << "帧" << endl;
  stringstream str;
  str << currentFrame << ".jpg";
  cout << str.str() << endl;
  imwrite(str.str(), frame);

  //waitKey(intdelay=0)当delay≤ 0时会永久期待;当delay>0时会期待delay毫秒 
  //其时间完毕前出有按键按下时,前往值为⑴;不然前往按键 
  //int c = waitKey(delay);
  int c = waitKey(1000);
  //按下ESC或抵达指定的完毕帧撤退退却出读与视频 
  if ((char)c == 27 || currentFrame > frameToStop)
  {
   stop = true;
  }
  //按下按键后会停止正在以后帧,期待下1次按键 
  if (c >= 0)
  {
   waitKey(0);
  }
  currentFrame++;

 }
 //封闭视频文件 
 capture.release();
 waitKey(0);
 return 0;
}

以上便是本文的全数内容,期望对各人的进修有所帮忙,也期望各人多多撑持剧本之家。