Visual C++使用OpenCV讀取影片

這隻程式僅提供讀取功能,寫入影片檔案可以參考


#define _CRT_SECURE_NO_WARNINGS  // disable warnings for safe : fopen

#include <iostream>
#include <opencv.hpp> // C++ version
#include <cv.h>  // C version

using namespace std;
using namespace cv; // from C++ version

int main(int argc, char** argv)
{
  string video_path = argc>1?argv[1]:"intelligentroom_raw.avi";

  // get cam feed and show in new window
  VideoCapture cap(video_path.c_str());
  if (!cap.isOpened())
  {
    cerr << "Cannot open the video file" << endl;
    cerr << "Path=" << video_path << endl;
    return -1;
  }

  int width     = (int)cap.get(CV_CAP_PROP_FRAME_WIDTH);
  int height    = (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  int numframe  = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
  double fps    = cap.get(CV_CAP_PROP_FPS);
 
  cout << "Video's Resolution (w,h) = " << width << "," << height << endl;
  cout << "Total Frames = " << numframe << endl;
  cout << "FPS = " << fps << endl;

  Mat frame;

  namedWindow(video_path, CV_WINDOW_FREERATIO|CV_WINDOW_NORMAL);

  int frame_cnt = 0;
  int each_frame_timing = 1000/fps;
  clock_t st_time, ed_time;
  int elapsed_time, wait_time;

  st_time = clock();
  while (cap.read(frame))
  {
    imshow(video_path, frame);
    //resizeWindow(video_path, width*2, height*2);

    cout << "frame:" << frame_cnt++;

    ed_time = clock();
    elapsed_time = (double)(ed_time-st_time) / CLOCKS_PER_SEC;
    wait_time = each_frame_timing-elapsed_time<=0?1:each_frame_timing-elapsed_time;
    if (waitKey(wait_time) == 27)
    {
      // If 'esc' key is pressed, break loop
      cout << "esc key is pressed by user" << endl;
      break;
    }

    cout << " waiting time:" << wait_time << endl;
    st_time = clock();
  }

  cout << "end of frame" << endl;
  return 0;
}

留言