i trying read video opencv in c++, when video displayed, framerate slow, 10% of original framerate.
the whole code here:
// g++ `pkg-config --cflags --libs opencv` play-video.cpp -o play-video // ./play-video [video filename] #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; int main(int argc, char** argv) { // video filename should given argument if (argc == 1) { cerr << "please give video filename argument" << endl; exit(1); } const string videofilename = argv[1]; // open video file videocapture capture(videofilename); if (!capture.isopened()) { cerr << "error when reading video file" << endl; exit(1); } // compute frame duration int fps = capture.get(cv_cap_prop_fps); cout << "fps: " << fps << endl; int frameduration = 1000 / fps; // frame duration in milliseconds cout << "frame duration: " << frameduration << " ms" << endl; // read , display video file, image after image mat frame; namedwindow(videofilename, 1); while(true) { // grab new image capture >> frame; if(frame.empty()) break; // display imshow(videofilename, frame); // press 'q' quit char key = waitkey(frameduration); // waits display frame if (key == 'q') break; } // releases , window destroy automatic in c++ interface }
i tried video gopro hero 3+, , video macbook's webcam, same problem both videos. both videos played without problem vlc.
thanks in advance.
try reducing waitkey
frame wait time. waiting frame rate time (i.e. 33 ms), plus time takes grab frame , display it. means if capturing frame , displaying takes on 0ms (which does), guaranteed waiting long. or if want accurate, time how long part takes, , wait remainder, e.g. along lines of:
while(true) { auto start_time = std::chrono::high_resolution_clock::now(); capture >> frame; if(frame.empty()) break; imshow(videofilename, frame); auto end_time = std::chrono::high_resolution_clock::now(); int elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); //make sure call waitkey value > 0 int wait_time = std::max(1, elapsed_time); char key = waitkey(wait_time); // waits display frame if (key == 'q') break; }
the whole int wait_time = std::max(1, elapsed_time);
line ensure wait @ least 1 ms, opencv needs have call waitkey
in there fetch , handle events, , calling waitkey
value <= 0 tells wait infinity user input, don't want either (in case)