Python OpenCV cv.WaitKey spits back weird output on Ubuntu modulo 256 maps correctly
Question: 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?


Answer: 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](http://opencv.itseez.com/modules/highgui/doc/user_interface.html?highlight=waitkey#cv2.waitKey).

