【OpenCV】waitKey()函数为什么不工作了?

在通过imshow()显示图像时,要想能够正常的看到所要显示的图像,通常都要waitKey()函数的参与。下面来看看waitKey()函数。

函数原型:

Waits for a pressed key.

int waitKey(int delay = 0);

Parameters

delay – Delay in milliseconds. 0 is the special value that means “forever”.

The function waitKey waits for a key event infinitely (when delay ≤ 0 )or for delay milliseconds, when it ispositive. Since the OS has a minimum time between switching threads, the function will not wait exactly delay ms,itwill wait at least delay ms, depending on what else is running on your computer at that time.It returns the code ofthe pressed key or -1 if no key was pressed before the specified time had elapsed.

Note1: This function is the only method in HighGUI that can fetch and handle events, so it needs to be calledperiodically for normal event processing unless HighGUI is used within an environment that takes care of eventprocessing.

Note2: The function only works if there is at least one HighGUI window created and the window is active. If there areseveral HighGUI windows, any of them can be active.

函数实现:

int waitKey(int delay){return cvWaitKey(delay);}对cvWaitKey()函数做一个简单的说明:

int cvWaitKey( int delay ){int time0 = GetTickCount();for(;;){// 忽略了窗口和消息处理部分…if( (delay > 0 && abs((int)(GetTickCount() – time0)) >= delay) || hg_windows == 0 )return -1;if( delay <= 0 )GetMessage(&message, 0, 0, 0);else if( PeekMessage(&message, 0, 0, 0, PM_REMOVE) == FALSE ){Sleep(1);continue;}// 忽略了窗口和消息处理部分…}}从上面的代码中即可以看出当delay<=0以及delay>0时,函数cvWaitKey()是怎么分别来处理的。下面给出一个例子:

#include <opencv2/opencv.hpp>using namespace cv;using namespace std;int main(){Mat img = imread("Lena.jpg");// waiKey1…int key1 = -2;key1 = waitKey(5000);cout << "key1: " << key1 << endl;// waiKey2…imshow("img", img);int key2 = -3;key2 = waitKey(5000);cout << "key2: " << key2 << endl;// waiKey3…double time = (double)getTickCount();waitKey(5000);time = (double)getTickCount() – time;time = time / getTickFrequency() * 1000;cout << "time: " << time << endl;return 0;}

在第二个waitKey中在相应时间内没有按任何键,测试结果为:

在第二个waitKey中在相应时间内按下空格键,测试结果为:

有点迷惑,有时候time会小于5000,为什么?

在cvWaitKey()中的变量hg_windows的定义如下:

static CvWindow* hg_windows = 0;在cvNamedWindow()函数中hg_windows的值将会被改变而不再为0。

所以在上例中,,第一个waitKey()的前面既没有imshow()函数,也没有cvNamedWindow()函数,所以hg_windows保持不变。

因此在第一个waitKey()中,cvWaitKey()函数在执行到

if( (delay > 0 && abs((int)(GetTickCount() – time0)) >= delay) || hg_windows == 0 )return -1;便会直接返回-1;

在第二个waitKey()中,因为在之前有调用imshow()函数,所以明天继续。。。

巨龟千岁,却也平淡无奇;昙花瞬间,却能绚丽无比。

【OpenCV】waitKey()函数为什么不工作了?

相关文章:

你感兴趣的文章:

标签云: