Dovyski / cvui

A (very) simple UI lib built on top of OpenCV drawing primitives

Home Page:https://dovyski.github.io/cvui/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: Catch keys

TheMikeyR opened this issue · comments

The waitkey returns an ascii representation of the keystroke pressed, it would be really nice if we can catch this to keybindings for functions.

Python example, load image, if 's' is registered, save image and exit. If escape is clicked exit.

import cv2
img = cv2.imread('lena.jpg',0 )
cv2.imshow('WindowName', img)
k = cv2.waitKey(0)
if k == 27:  # wait for ESC key to exit
    cv2.destroyAllWindows()
elif k == ord('s'):  # wait for 's' key to save and exit
    cv2.imwrite('lena.png', img)
    cv2.destroyAllWindows()

I did not understand your request completely. Do you mean having some sort of callback that is automatically called when an specific key is pressed?

@Dovyski yes so you can add keybindings to a opencv window. E.g. click 's' to execute a function or use arrow keys to adjust a rectangle's position. Do you want some example on how to use it with OpenCV?

I got it now. If you can provide some examples as you suggested, they will be very helpful.

Here is a python mockup, where you can interact with a rectangle, make it grow, shrink and move it around on a canvas. It prints the key pressed, in the terminal from where the script is executed.

Key bindings
WASD = Grow/shrink square
Arrows Keys = Move square
R = Reset square to start position
+ = Grow square in both width and height
- = Shrink square in both width and height
Escape = Quit program

Code

import cv2
import numpy as np


def main():
    window_name = "Move Rectangle Using Keyboard Demo"
    cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
    x, y, w, h = (180, 180, 40, 40)
    while(True):
        frame = np.zeros((400, 400, 3))
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
        cv2.imshow(window_name, frame)
        key = cv2.waitKey(1)
        if key > -1:
            print("Key pressed:", key)
        if key == 27:  # escape
            # Quit program
            break
        if key == 32:  # space
            pass
        if key == 81:  # left
            x = x - 10
        if key == 82:  # up
            y = y - 10
        if key == 84:  # down
            y = y + 10
        if key == 83:  # right
            x = x + 10
        if key == 114:  # r = reset
            x, y, w, h = (180, 180, 40, 40)
        if key == 119:  # w
            h = h + 10
        if key == 97:  # a
            w = w - 10
        if key == 115:  # s
            h = h - 10
        if key == 100:  # d
            w = w + 10
        if key == 43:  # +
            w = w + 10
            h = h + 10
        if key == 45:  # -
            w = w - 10
            h = h - 10

    cv2.destroyAllWindows()
    print("Exiting program")
    exit()


if __name__ == "__main__":
    main()