Python opencv的waitKey()函数使用其他键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14494101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:38:04  来源:igfitidea点击:

Using other keys for the waitKey() function of opencv

pythonopencv

提问by md1hunox

I'm working on a program (python ,opencv) in which I use the spacebarto go to the next frame, and Escto exit the program. These are the only two keys i've got working. I tried to find out about more keys , tried various codes for them but didnt work. especially arrow keys.

我正在开发一个程序(python,opencv),在该程序中我使用spacebar转到下一帧并Esc退出程序。这是我唯一可以使用的两个键。我试图找出更多的键,为它们尝试了各种代码,但没有用。尤其是方向键。

I found thisabout waitkey, but it doesn't work.

我发现了这个关于waitkey,但它不起作用。

So my question is, How do I catch other keys besides escand spacebarto trigger certain functions in my python-opencv program?

所以我的问题是,除了在我的 python-opencv 程序中,我如何捕捉其他键escspacebar触发某些功能?

采纳答案by Abid Rahman K

You can use ord()function in Python for that.

ord()为此,您可以在 Python 中使用函数。

For example, if you want to trigger 'a' key press, do as follows :

例如,如果要触发“a”键按下,请执行以下操作:

if cv2.waitKey(33) == ord('a'):
   print "pressed a"

See a sample code here: Drawing Histogram

在此处查看示例代码:绘制直方图

UPDATE :

更新 :

To find the key value for any key is to print the key value using a simple script as follows :

要查找任何键的键值,请使用如下简单脚本打印键值:

import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(33)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print k # else print its value

With this code, I got following values :

使用此代码,我得到了以下值:

Upkey : 2490368
DownKey : 2621440
LeftKey : 2424832
RightKey: 2555904
Space : 32
Delete : 3014656
...... # Continue yourself :)

回答by Tomasz Gandor

The keycodes returned by waitKeyseem platform dependent. However, it may be very educative, to see what the keys return (and by the way, on my platform, Escdoes not return 27...)

waitKey似乎平台相关返回的键码。但是,查看键返回的内容可能很有教育意义(顺便说一句,在我的平台上,Esc不返回 27...)

The integers thay Abid's answer lists are mosty useless to the human mind (unless you're a prodigy savant...). However, if you examine them in hex, or take a look at the Least Significant Byte, you may notice patterns...

Abid 的答案列表中的整数对人类的思维几乎毫无用处(除非您是神童……)。但是,如果您以十六进制检查它们,或查看最低有效字节,您可能会注意到模式......

My script for examining the return values from waitKeyis below:

我用于检查返回值的脚本waitKey如下:

#!/usr/bin/env python

import cv2
import sys

cv2.imshow(sys.argv[1], cv2.imread(sys.argv[1]))
res = cv2.waitKey(0)
print('You pressed %d (0x%x), LSB: %d (%s)' % (res, res, res % 256,
    repr(chr(res%256)) if res%256 < 128 else '?'))

You can use it as a minimal, command-line image viewer.

您可以将其用作最小的命令行图像查看器。

Some results, which I got:

我得到的一些结果:

  • q letter:

    You pressed 1048689 (0x100071), LSB: 113 ('q')

  • Escape key (traditionally, ASCII 27):

    You pressed 1048603 (0x10001b), LSB: 27 ('\x1b')

  • Space:

    You pressed 1048608 (0x100020), LSB: 32 (' ')

  • q 字母:

    你按下了 1048689 (0x100071), LSB: 113 ('q')

  • 转义键(传统上,ASCII 27):

    你按下了 1048603 (0x10001b), LSB: 27 ('\x1b')

  • 空间:

    你按下了 1048608 (0x100020), LSB: 32 (' ')

This list could go on, however you see the way to go, when you get 'strange' results.

这个列表可以继续下去,但是当你得到“奇怪”的结果时,你会看到要走的路。

BTW, if you want to put it in a loop, you can just waitKey(0)(wait forever), instead of ignoring the -1return value.

顺便说一句,如果你想把它放在一个循环中,你可以waitKey(0)(永远等待),而不是忽略-1返回值。

EDIT: There's more to these high bits than meets the eye - please see Andrew C's answer (hint: it has to do with keyboard modifiers like all the "Locks" e.g. NumLock).

编辑:这些高位比眼睛看到的更多 - 请参阅 Andrew C 的回答(提示:它与所有“锁”(例如 NumLock)等键盘修饰符有关)。

My recent experience shows however, that there is a platform dependence - e.g. OpenCV 4.1.0 from Anaconda on Python 3.6 on Windows doesn't produce these bits, and for some (important) keys is returns 0from waitKey()(arrows, Home, End, PageDn, PageUp, even Deland Ins). At least Backspacereturns 8(but... why not Del?).

然而,我最近的经验表明,存在平台依赖性 - 例如 Windows 上 Python 3.6 上的 Anaconda 的 OpenCV 4.1.0 不会产生这些位,并且对于某些(重要)键是0waitKey()(箭头HomeEndPageDnPageUp、 甚至DelIns)。至少Backspace返回8(但是......为什么不Del呢?)。

So, for a cross platform UI you're probably restricted to W, A, S, D, letters, digits, Esc, Spaceand Backspace;)

因此,对于跨平台 UI,您可能仅限于WASD、 字母、数字EscSpaceBackspace;)

回答by Poka Yoke

For C++:

对于 C++:

In case of using keyboard characters/numbers, an easier solution would be:

如果使用键盘字符/数字,更简单的解决方案是:

int key = cvWaitKey();

switch(key)
{
   case ((int)('a')):
   // do something if button 'a' is pressed
   break;
   case ((int)('h')):
   // do something if button 'h' is pressed
   break;
}

回答by Andrew C.

The answers which have already been posted suggest that some of the unusual values obtained by waitKeyare due to platform differences. Below, I propose that (at least on some platforms) the apparently odd behaviour of waitKeyis due to keyboard modifiers. This post looks similar to Tomasz's answer because I initially wrote this as an edit, which was rejected.

已经发布的答案表明,获得的一些异常值waitKey是由于平台差异造成的。下面,我建议(至少在某些平台上)明显奇怪的行为waitKey是由于键盘修饰符造成的。这篇文章看起来与 Tomasz 的回答相似,因为我最初将其写为编辑,但遭到拒绝。



The keycodes returned by waitKeychange depending on which modifiers are enabled. NumLock, CapsLock, and the Shift, Ctrl, and Alt keys all modify the keycode returned by waitKeyby enabling certain bits above the two Least Significant Bytes. The smallest of these flags is Shift at 0x10000.

waitKey更改返回的键码取决于启用的修饰符。NumLock、CapsLock 和 Shift、Ctrl 和 Alt 键都waitKey通过启用两个最低有效字节上方的某些位来修改返回的键码。这些标志中最小的标志是 0x10000 处的 Shift。

A modified version of the script Tomasz posted is given below:

下面给出了 Tomasz 发布的脚本的修改版本:

#!/usr/bin/env python

import cv2
import sys

cv2.imshow(sys.argv[1], cv2.imread(sys.argv[1]))
res = cv2.waitKey(0)
print 'You pressed %d (0x%x), 2LSB: %d (%s)' % (res, res, res % 2**16,
    repr(chr(res%256)) if res%256 < 128 else '?')

Which give the following results:

这给出了以下结果:

  • q letter with NumLock:

    You pressed 1048689 (0x100071), 2LSB: 113 ('q')

  • Escape key with CapsLock but not NumLock:

    You pressed 131099 (0x2001b), 2LSB: 27 ('\x1b')

  • Space with Shift and NumLock:

    You pressed 1114144 (0x110020), 2LSB: 32 (' ')

  • Right Arrow Key with Control, NumLock off:

    You pressed 327507 (0x4ff53), 2LSB: 65363 ('S')

  • q 带 NumLock 的字母:

    你按下了 1048689 (0x100071), 2LSB: 113 ('q')

  • 带有 CapsLock 而不是 NumLock 的转义键:

    你按下了 131099 (0x2001b), 2LSB: 27 ('\x1b')

  • 带有 Shift 和 NumLock 的空格:

    你按下了 1114144 (0x110020), 2LSB: 32 (' ')

  • 带 Control 的右箭头键,关闭 NumLock:

    你按下了 327507 (0x4ff53), 2LSB: 65363 ('S')

I hope that helps to explain the unusual behaviour of waitKeyand how to get the actual key pressed regardless of the state of NumLock and CapLock. From here it's relatively simple to do something like:

我希望这有助于解释不waitKey考虑 NumLock 和 CapLock 状态的异常行为以及如何按下实际键。从这里开始执行以下操作相对简单:

ctrlPressed = 0 != res & (1 << 18)

...as the "control key" flag is bit 19. Shift is at bit 17, the state of CapsLock at bit 18, Alt is at bit 20, and NumLock is at bit 21.

...因为“控制键”标志位于第 19 位。Shift 位于第 17 位,CapsLock 的状态位于第 18 位,Alt 位于第 20 位,NumLock 位于第 21 位。

回答by 00zetti

With Ubuntu and C++ I had problems with the Character/Integer cast. I needed to use cv::waitKey()%256to obtain the correct ASCII value.

在 Ubuntu 和 C++ 中,我遇到了字符/整数转换的问题。我需要使用cv::waitKey()%256来获取正确的 ASCII 值。

回答by GodIsAnAstronaut

If you want to pause the program to take screenshots of the progress

如果您想暂停程序以截取进度

(shown in let's say cv2.imshow)

(显示在让我们说 cv2.imshow 中)

cv2.waitKey(0)would continue after pressing "Scr" button (or its combination), but you can try this

cv2.waitKey(0)按下“Scr”按钮(或其组合)后会继续,但你可以试试这个

cv2.waitKey(0)
input('')

cv2.waitkey(0) to give the program enough time to process everything you want to see in the imshow and input('')

cv2.waitkey(0) 给程序足够的时间来处理你想在 imshow 和 input('') 中看到的所有内容

to make it wait for you to press Enter in the console window

让它等待您在控制台窗口中按 Enter

this works on python 3

这适用于python 3

回答by Jayhello

As to me, the below code does't work, when it runs,the image will step to the next quickly without your press:

对我来说,下面的代码不起作用,当它运行时,图像会在没有你按下的情况下快速跳转到下一个:

import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(33)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print k # else print its value

But this works:

但这有效:

def test_wait_key():
    lst_img_path = [
        '/home/xy/yy_face_head/face_det_test/111.png',
        '/home/xy/yy_face_head/face_det_test/222.png'
        #.....more path ...
    ]

    for f_path in lst_img_path:
        img = cv2.imread(f_path)
        cv2.imshow('tmp', img)
        c = cv2.waitKey(0) % 256

        if c == ord('a'):
            print "pressed a"
        else:
            print 'you press %s' % chr(c)

Output as below:

输出如下:

enter image description here

在此处输入图片说明

回答by Joe Rytting

This works the best for me:

这对我来说效果最好:

http://www.asciitable.com/

http://www.asciitable.com/

Sometimes it's the simple answers that are the best ;+)

有时,最好的答案是简单的答案;+)

回答by gerry174

I too found this perplexing. I'm running Ubuntu 18 and found the following: If the cv.imshow window has focus, you'll get one set of values in the terminal - like the ASCII values discussed above.

我也觉得这很令人困惑。我正在运行 Ubuntu 18 并发现以下内容:如果 cv.imshow 窗口具有焦点,您将在终端中获得一组值 - 就像上面讨论的 ASCII 值。

If the Terminal has focus, you'll see different values. IE- you'll see "a" when you press the a key (instead of ASCII value 97) and "^]" instead of "27" when you press Escape.

如果终端有焦点,您将看到不同的值。IE - 当您按 a 键(而不是 ASCII 值 97)时,您会看到“a”,当您按 Escape 时,您会看到“^]”而不是“27”。

I didn't see the 6 digit numbers mentioned above in either case and I used similar code. It seems the value for waitKey is the polling period in mS. The dots illustrate this.

在任何一种情况下,我都没有看到上面提到的 6 位数字,我使用了类似的代码。waitKey 的值似乎是以毫秒为单位的轮询周期。点说明了这一点。

Run this snippet and press keys while focus is on the test image, then click on the terminal window and press the same keys.

运行此代码段并在焦点位于测试图像上时按下键,然后单击终端窗口并按下相同的键。

    import cv2
    img = cv2.imread('test.jpg') 
    cv2.imshow('Your test image', img)

    while(1):
      k = cv2.waitKey(300)
      if k == 27:
        break
      elif k==-1:
       print "."
       continue
      else:
        print k 

回答by iGian

This prints the key combination directly to the image:

这会将组合键直接打印到图像上:

z pressed an ctrl + z pressed

z 按下 ctrl + z 按下

The first window shows 'z'pressed, the second shows 'ctrl' + 'z'pressed. When a key combination is used, a question mark appear.

第一个窗口显示已'z'按下,第二个窗口显示已'ctrl' + 'z'按下。使用组合键时,会出现一个问号。

Don't mess up with the question mark code, which is 63.

不要弄乱问号代码,即63.

import numpy as np
import cv2

im = np.zeros((100, 300), np.uint8)
cv2.imshow('Keypressed', im)
while True:
  key = cv2.waitKey(0)
  im_c = im.copy()
  cv2.putText(
    im_c,
    f'{chr(key)} -> {key}',
    (10, 60), 
    cv2.FONT_HERSHEY_SIMPLEX, 
    1,
    (255,255,255),
    2)
  cv2.imshow('Keypressed', im_c)
  if key == 27: break # 'ESC'