
Question:
I have a VideoCapture
in OpenCV, I can successfully display a given video. What I want to do now is to pause and play by pressing a key (optional which one as long as it works). I have been reading about waitKey
but there is something about this whole thing I don't get (ASCII) and how to bind keys. What I understand it is used to let highgui
process but can also be used for other purposes?
If it is hard/impossible to pause a video and start it again I would be happy with just a delay when key is pressed.
Help is much appreciated!
Answer1:I have same problem as you before. I solved it in Python instead of C++, but I think the logic behind is same.
import cv2
cap = cv2.VideoCapture('my.avi')
while True:
ret, frame = cap.read()
key = cv2.waitKey(1) & 0xff
if not ret:
break
if key == ord('p'):
while True:
key2 = cv2.waitKey(1) or 0xff
cv2.imshow('frame', frame)
if key2 == ord('p'):
break
cv2.imshow('frame',frame)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
Answer2:You dont need anything like binding keys. I have written a sample code which will play/pause the video whenever you press <strong>"p"</strong>.
#include <iostream>
#include <fstream>
#include <string>
#include "opencv2/opencv_modules.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
bool playVideo = true;
VideoCapture cap(argv[1]);
if(!cap.isOpened())
{
cout<<"Unable to open video "<<argv[1]<<"\n";
return 0;
}
Mat frame;
while(1)
{
if(playVideo)
cap >> frame;
if(frame.empty())
{
cout<<"Empty Frame\n";
return 0;
}
imshow("Video",frame);
char key = waitKey(5);
if(key == 'p')
playVideo = !playVideo;
}
return 0;
}
Answer3:If you want to pause and play with p
use
if(cv::waitKey(1) == 'p')
while(cv::waitKey(1) != 'p');