C++ 使用waitKey暂停并播放视频

C++ 使用waitKey暂停并播放视频,c++,opencv,C++,Opencv,我在OpenCV中有一个VideoCapture,我可以成功地显示给定的视频。我现在想做的是暂停并按一个键播放(可选,只要它工作)。我一直在读关于waitKey的书,但是关于这整件事,我没有(ASCII)和如何绑定密钥。据我所知,它用于让highgui处理,但也可用于其他目的 如果很难/不可能暂停视频并再次启动它,我很乐意在按下该键时延迟一段时间 非常感谢您的帮助 你不需要像绑定键这样的东西。我编写了一个示例代码,每当您按下“p”,它都会播放/暂停视频 #include <iostream

我在OpenCV中有一个
VideoCapture
,我可以成功地显示给定的视频。我现在想做的是暂停并按一个键播放(可选,只要它工作)。我一直在读关于
waitKey
的书,但是关于这整件事,我没有(ASCII)和如何绑定密钥。据我所知,它用于让
highgui
处理,但也可用于其他目的

如果很难/不可能暂停视频并再次启动它,我很乐意在按下该键时延迟一段时间


非常感谢您的帮助

你不需要像绑定键这样的东西。我编写了一个示例代码,每当您按下“p”,它都会播放/暂停视频

#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;
}
#包括
#包括
#包括
#包括“opencv2/opencv_modules.hpp”
#包括“opencv2/highgui/highgui.hpp”
使用名称空间std;
使用名称空间cv;
int main(int argc,字符**argv)
{
bool playVideo=true;
视频捕获cap(argv[1]);
如果(!cap.isOpened())
{

CUT

我以前也有过同样的问题。我用Python来解决它,而不是C++,但是我认为后面的逻辑是相同的。

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()

如果您想暂停并使用
p
播放,请使用

if(cv::waitKey(1) == 'p')
    while(cv::waitKey(1) != 'p');

关于for
cv::waitKey(delay)
,当
delay时,我认为不需要标记
playVideo
waitKey(0)
将无限期暂停,因此它将阻止while循环,直到按下一个键。文档。yes waitKey(0)将无限期暂停,但在这种情况下,您必须为显示的每一帧按一个键
import cv2
cap = cv2.VideoCapture(0) # getting video from webcam
while cap.isOpened():
    ret, img = cap.read()

    cv2.imshow("Frame",img)

    key = cv2.waitKey(1)
    if key == ord('q'):
        break
    if key == ord('p'):
        cv2.waitKey(-1) #wait until any key is pressed
cap.release()
cv2.destroyAllWindows()