I am running Ubuntu 11.10 (Lenovo T400) with OpenCV 2.2 (I believe as imports are done as import cv2.cv as cv). This problem also happens if i just 'import cv' instead.
I recently started having this problem, and it's kind of a weird one. I don't know anything significant I did, I have restarted since it started happening. I installed a couple programs, but I don't think those would affect this.
When I run with an artificial image showing (just a black image), I try to poll cv.WaitKey(10). It spits back garbage.
Here's my OpenCV code:
import cv2.cv as cv
import time
cv.NamedWindow("camera", 1)
img = cv.CreateImage((400,400), 8, 3)
valkeys = range(1,255)
f = open('/home/andrew/webuploads/keyboardtest', 'wb')
while True:
cv.ShowImage("camera", img)
k = cv.WaitKey(10)
if k is -1:
pass
else:
print 'writing %s' %str(k)
f.write((str(k)+' '))
f.close()
Here's the output I get from the program:
1048678 1048676 1048673 1048691 1048676 1048678 1048689 1048695 1048677 1048688 1048687 1048681 1048677 1048677 1048695 1048624 1048633 1048690 1048633 1048624 1048695 1048677 1048690 1048624 1048633 1048681 1048677 1048681 1048688 1048687 1048677 1048681 1048692 1048688 1048681 1048688 1048687 1048681 1048681 1048688 1048687 1048585 1048687 1048681 1048688 1048687 1048681 1114085 1179728 1179727 1179721 1179728 1179721 1245153 1245289 1179727 1179721 1179727 1179721 1179728 1179727 1245155 1441865 1179728 1179727 1179721 1179728 1179727 1179721 1179728 1179727 1179718 1179721 1179716 1179728 1179727 1179731 1179721 1179713 1179728 1179727 1179687 1179723 1179716 1179736 1179724 1179715 1179734 1179725 1179692 1179736 1179738 1179725 1179715 1179734 1179692 1245155 1441859
Now I can modulo 256 these numbers and get somewhat sensible results out (just tried it, it correctly identified all my keys), however, why would I need to do this? It did work previously without doing anything (print chr(k) would give me a letter). Anyone have any ideas?
The modulus works because the information about the key is stored in the last 8 bits of the return value. A k & 255
will also pick the last 8 bits:
>>> k = 1048678
>>> chr(k & 255)
'f'
In Python, chr(n)
will return the character corresponding to n. Unfortunately, OpenCV documentation presents no information about this issue.
As this problem persists with the current OpenCV package v2.4.2 of Ubuntu 13.04:
Both k % 256
and k & 255
would map -1
as well as 1048831
to 255
. To distinguish between these two cases an additional check like key < 0
would be necessary.
Not so if you subtract 0x100000
, which maps 1048831
to 255
and -1
to -1048577
, meaning that "no key" remains mapped to the only negative value.
k = cv2.waitKey(delay)
k -= 0x100000
if (k == 27):
print("<Esc>")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With