1. 程式人生 > >opencv3讀取視頻並保存為圖片

opencv3讀取視頻並保存為圖片

empty extract opencv3 filename count xtra double using pat

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

void readvideoandsaveimage(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);
  //設置結束幀
  int frameToStop = 1000;

  //獲取幀率
  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;
      continue;
    }
    _itoa_s(num, temp_file, 4, 10); //4表示字符長度,10表示十進制,_itoa_s實現整型轉字符串
    filename = temp_file;
    filename = path + filename + ".jpg";

    imshow("Extractedframe", frame);

    imwrite(filename, frame);

    int c = waitKey(delay);
    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 = "D:\\images\\1.mp4"; //讀取視頻
  string Imagespath = "D:\\images\\2018-09-22\\"; // 保存圖片的文件夾路徑一定要有,因為OpenCV不會自動創建文件夾
  readvideoandsaveimage(videoFromfile, Imagespath);
  return 0;
}

------------------------------------------------------------------運行效果:

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

opencv3讀取視頻並保存為圖片