Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opencv waitkey not responding?

Tags:

c++

opencv

Im new to opencv, and perhaps there is something Im just not understanding. I have a waitkey, that waits for the letter a, and another that is supposed to break, and cause an exit. one, or the other seems to work fine, but not both. I do not get compiler errors, or warnings. The code included will take a series for enumerated pictures, but not close when I press the letter 'q' on my keyboard. What am I doing wrong?

#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;
}

how can I get the 'q' key to exit the program?

like image 893
j0h Avatar asked Jun 08 '26 02:06

j0h


2 Answers

You just need to use one waitKey, get the pressed key, and take corresponding action.

#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;
}
like image 129
Miki Avatar answered Jun 10 '26 14:06

Miki


From the documentation:

The function waitKey waits for a key event infinitely (when delay <= 0 ) or for delay milliseconds, when it is positive.

So if you pass 0 (or a negative value) to waitKey, it will wait forever until a key press.

like image 37
Chris Avatar answered Jun 10 '26 15:06

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!