使用waitKey()函数处理OpenCV中的箭头键

20

我想处理箭头键,但是当我打印waitKey()函数的输入值时,它为0。我不知道为什么。我尝试将数据类型从“int”更改为“char”,但这并不起作用。我该如何解决这个问题。

int pos = 100;
imshow("image", image);
onChange(pos, (void *)&image);
createTrackbar("threshold", "image", &pos, 255, onChange, (void*)&image);
while (1) {
    int Key = waitKey();
    cout << Key << endl;
    if (Key == 27) break;
    if (Key == 2490368) {
        pos--;
        onChange(pos, (void *)&image);
    }
    if(Key == 2621440){
        pos++;
        onChange(pos, (void *)&image);
    }
    if (pos < 0 || pos > 255) pos = 0;
}
4个回答

29

请使用waitKeyEx()函数代替。正如文档所述:

  

类似于waitKey(),但返回完整的按键代码。

  

按键代码是特定于实现的,取决于使用的后端:QT / GTK / Win32

在我的系统上,它给出了:

左:2424832 上:2490368 右:2555904 下:2621440

虽然有许多在线资源称waitKey()可用于箭头,但在我的Windows系统上它也没有返回正确的键代码(始终返回0)。猜测这也是特定于实现的。也许是因为waitKey()返回ASCII码,但箭头键没有它们(如此处所述)。


我注意到你提到了“使用的后端”,例如在Win32中,我们可以只需执行0x10000 * 0x25 = 2424832(_左箭头_),这样我们也可以使用msdn上的虚拟键代码https://learn.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes。 - Ido

4

注意,这取决于版本,在 Windows 上,使用3.0版本的waitKey()函数提供完整的键码,但是当我更改到3.3版本时,箭头键突然返回0。


0

以下是我的临时解决方案

#ifndef _WIN32
int myWaitKey(int wait) {
    int c = cv::waitKey(wait);
    return c;
}
#pragma message("linux..")
#else
#include <conio.h> // to support _getch
int myWaitKey(int wait) {
    int c = cvWaitKey(wait);
    if (c == 0) {
        int c = _getch();   //capture the key code and insert into c
        if (c == 0 || c == 224)
            c = _getch();
    }
    //if (c!=-1) printf("%d\n",c);
    return c;
}
#endif

0

在你的代码中使用waitkey(),按住左键点击cv2.trackbar图标,并使用箭头键以1为增量移动


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接