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?
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;
}
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.
Are you using Visual Studio? There is nothing wrong with the code. For my case, I just change the Debug
to Release
. That's all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.