簡體   English   中英

opencv的waitkey沒有響應?

[英]opencv waitkey not responding?

我是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時),或者等待正數時等待的延遲毫秒。

因此,如果將0(或負值)傳遞給waitKey,它將永遠等待直到按鍵。

您正在使用Visual Studio嗎? 代碼沒有錯。 就我而言,我只是將Debug更改為Release 就這樣。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM