I'd like to write a program that in its simplest form opens a window showing a webcam capture using OpenCV and printing the coordinates of the mouse cursor hovering over the window in terminal. For this i want to use a callback function. My problem is that this callback function does not seem to run. I do not get any error messages when running the program, but nothing seem to happen when I hover my cursor over the camera window.
I suspect that the cause for this might be that my callback function is in the class CallBack, and that cv.SetMouseCallback cannot access it or something. I am new to both OpenCV and callback functions, so any suggestions on what my problem might be or what I'm missing here would be appreciated.
My simplified code is shown below for reference. Thanks in advance.
import cv
class CallBack:
def __init__(self):
cv.NamedWindow("Camera", cv.CV_WINDOW_AUTOSIZE );
self.capture = cv.CaptureFromCAM(0)
def on_mouse(self,event, x, y, flag, param):
if(event == cv.CV_EVENT_MOUSEMOVE):
print param
print x,y
def callback(self):
while True:
src = cv.QueryFrame(self.capture)
s = "Hello World"
cv.SetMouseCallback("Camera",self.on_mouse, param = s)
cv.ShowImage("Camera", src)
if __name__ == '__main__':
cb = CallBack()
cb.callback()
if __name__part, is inside theclassdefinition. Is that correct?class CallBack(object):). (2) Don't put extra parens around things likeifconditions; it throws off experienced Python readers and makes them wonder why you thought it was necessary (is there some operator precedence that needs to be overridden? or a tuple or genexp? or …).on_mouse? You onlyprintanything inside theif. What if the problem is that you've got the params wrong, or theeventisn't what you expected? It would look exactly the same as not calling your code at all, right?self.on_mouse, that gives you a bound method, which anyone (includingcv.SetMouseCallback) can just treat as acallableand call. It doesn't need any special access. (And even if it did, all methods are "public" in Python, so that wouldn't be a problem.)