Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opencv handling arrow keys with waitKey() function

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;
}
like image 562
Amily Avatar asked Aug 09 '17 02:08

Amily


People also ask

What does Waitkey do in OpenCV?

waitkey() function of Python OpenCV allows users to display a window for given milliseconds or until any key is pressed. It takes time in milliseconds as a parameter and waits for the given time to destroy the window, if 0 is passed in the argument it waits till any key is pressed.

What does Waitkey 0 do?

For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display).

What does cv2 Waitkey return?

cv2. waitkey(1) waits for 1 ms and returns the code of the key on keyboard if it is pressed.


2 Answers

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

like image 171
Headcrab Avatar answered Sep 21 '22 04:09

Headcrab


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.

like image 35
middle Avatar answered Sep 19 '22 04:09

middle