2016-08-22 47 views
2

我是新來的opencv,也許有什麼我只是不理解。 我有一個waitkey,等待字母a,另一個應該打破,並導致退出。 一個或另一個似乎工作正常,但不是兩個。我不會收到編譯器錯誤或警告。所包含的代碼將針對枚舉的圖片進行一系列操作,但按下鍵盤上的字母'q'時不會關閉。 我在做什麼錯?opencv waitkey沒有響應?

#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'鍵退出程序?

+0

將'waitKey(1)== 113'改爲'waitKey(0)== 113'。這樣它將等待一個按鍵,而不僅僅是1毫秒。 – DimChtz

回答

1

the documentation

功能waitKey等待鍵事件無限(當延遲< = 0)或用於延遲毫秒,當它是正的。

因此,如果您將0(或負值)傳遞給waitKey,它將一直等到按下按鍵。

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; 
} 
+0

該程序有效退出,但不再更新幀。當我按下'a'鍵時,它會更新,但不會更新。 – j0h

+0

現在您可以通過按任意鍵,然後_a_和_q_來進入下一幀。如果您想自動進入下一幀,請在waitKey中輸入一個大於0(以毫秒爲單位)的值。你可以使用'int key =(waitKey(1)&0xFF);' – Miki