20

I want to handling arrow keys. but when I print out the input value for waitKey() function, It's 0. I don't know why. I try to change from "int" to "char" , but It doesn't work. How can I solve this problem.

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;
}
Amily
  • 325
  • 1
  • 4
  • 16

4 Answers4

29

Use waitKeyEx() function instead. As the documentation says:

Similar to waitKey(), but returns full key code.

Key code is implementation specific and depends on used backend: QT/GTK/Win32

On my system it gives: Left: 2424832 Up: 2490368 Right: 2555904 Down: 2621440

Although there are many online sources saying waitKey() works with arrows, it didn't return proper key codes on my Windows system either (always returned 0). Guess that is also implementation specific. Maybe because waitKey() returns ASCII-codes, but arrow keys don't have them (as explained here).

Headcrab
  • 6,838
  • 8
  • 40
  • 45
  • I just noted because of you reference to the _used backend_ for example in Win32 with can just do **0x10000 * 0x25 = 2424832** _(Left Arrow)_ and that way we could also use the virtual key codes from msdn https://learn.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes – Ido Apr 13 '19 at 17:38
4

Note that this depends on version, on windows with 3.0 waitKey() gave full key codes, but when I changed to 3.3, it suddenly returned 0 for arrow keys.

middle
  • 61
  • 2
0

Below is my temporary workaround

#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
FreeToGo
  • 360
  • 5
  • 8
0

with waitkey() in your code,keep the left click pressed on the cv2.trackbar icon and use the arrow keys to move in increments of 1