OpenCV的waitKey不响应?

3

我是opencv的新手,也许有些地方我还没有理解。我有一个等待按键'a'的waitkey,并且另一个是用于中断和退出程序的break。 其中一个似乎很好用,但两个一起使用的时候就会出问题。我没有收到编译器的错误或警告。包含的代码可以拍摄一系列枚举图片,但当我按下键盘上的字母 '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(1) == 113 改成 waitKey(0) == 113,这样它会等待一个按键,而不仅仅是 1 毫秒。 - DimChtz
3个回答

3

您只需要使用一个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;
}

这个程序可以有效地退出,但不再更新帧。当我按下'a'键时,它会更新,但在此之前不会更新。 - j0h
现在,您可以通过按下除 aq 以外的任何键来进入下一帧。如果您想自动进入下一帧,请在 waitKey 中放置大于 0 的值(以毫秒为单位)。您可以使用 int key = (waitKey(1) & 0xFF); - Miki

1

你正在使用Visual Studio吗?代码没有问题。对于我的情况,我只是将Debug更改为Release。就这样。

在此输入图片描述


1

来自文档

当delay小于等于0时,函数waitKey会无限期地等待按键事件,当它是正数时,会等待delay毫秒。

因此,如果将0(或负值)传递给waitKey,则会一直等待直到有按键按下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接