Opencv waitkey没有响应

opencv waitkey not responding?

本文关键字:响应 waitkey Opencv      更新时间:2023-10-16

我是opencv的新手,也许有些事情我只是不理解。我有一个侍应生,等待字母a,另一个应该是坏了,导致出口。其中一种或另一种似乎都可以,但不能两者都用。我没有得到编译器错误或警告。所包含的代码将为枚举的图片拍摄一系列,但当我按键盘上的字母"q"时不会关闭。我做错了什么?

#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int main(int argc, char** argv){
    VideoCapture cap;
    // open the default camera, use something different from 0 otherwise;
    if(!cap.open(0))
        return 0;
     // Create mat with alpha channel
    Mat mat(480, 640, CV_8UC4);       
    int i = 0;
    for(;;){ //forever
          Mat frame;
          cap >> frame;
          if( frame.empty() ) break; // end of video stream
          imshow("this is you, smile! :)", frame);
          if( waitKey(1) == 97 ){ //a
             String name = format("img%04d.png", i++); // NEW !
             imwrite(name, frame); 
             }
          if( waitKey(1) == 113 ) break; // stop capturing by pressing q
    }
return 0;
}

如何使用"q"键退出程序?

您只需要使用一个waitKey,获取按下的键,并采取相应的操作。

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv){
    VideoCapture cap;
    // open the default camera, use something different from 0 otherwise;
    if (!cap.open(0))
        return 0;
    // Create mat with alpha channel
    Mat mat(480, 640, CV_8UC4);
    int i = 0;
    for (;;){ //forever
        Mat frame;
        cap >> frame;
        if (frame.empty()) break; // end of video stream
        imshow("this is you, smile! :)", frame);
        // Get the pressed value
        int key = (waitKey(0) & 0xFF);
        if (key == 'a'){ //a
            String name = format("img%04d.png", i++); // NEW !
            imwrite(name, frame);
        }
        else if (key == 'q') break; // stop capturing by pressing q
        else {
            // Pressed an invalid key... continue with next frame
        }
    }
    return 0;
}

来自文档:

waitKey函数无限等待一个键事件(当delay <= 0时)或等待延迟毫秒(当delay <= 0时)。

所以如果你传递0(或负值)给waitKey,它将永远等待直到按下一个键。

您正在使用Visual Studio吗?代码没有任何问题。在我的例子中,我把Debug换成了Release。这是所有。

输入图片描述