14
votes

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

4 Answers

21
votes

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).

4
votes

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.

0
votes

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
0
votes

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