Search code examples
pythonglobal-variables

Python Global Variable based on mouseClick


I am trying to define a ROI using OpenCV mouse event call back and the below code does not recognize the global variables defined in the mouseClick function.

import cv2

def mouseClick(event,xPos,yPos,flags,params):
    global pnt1
    global pnt2
    global evt

    pnt1 = (xPos,yPos)
    pnt2 = (xPos,yPos)
    evt = event
    
    

cam=cv2.VideoCapture(0, cv2.CAP_DSHOW)


cv2.namedWindow("My WebCam")
cv2.setMouseCallback("My WebCam",mouseClick)


while True:
    ignore, frame = cam.read()
    cv2.imshow("My WebCam",frame)
    
    print(pnt1,pnt2,evt)

    if cv2.waitKey(1) == ord('q'):
        break
cam.release()

When I run this program, I get an error saying pnt1 is not defined when executing the print statement inside the while loop. Any suggestions on what I am doing wrong? Thanks for all your help and taking the time to read this question.

print(pnt1,pnt2,evt)
NameError: name 'pnt1' is not defined

Solution

  • You need to assign pnt1, pnt2, and evt outside of the mouseClick() function. The mouse callback may not necessarily run before the program reaches the print() statement -- if this is the case, then those variables will be undefined.

    import cv2
    
    pnt1 = None
    pnt2 = None
    evt = None
    
    def mouseClick(event,xPos,yPos,flags,params):
        global pnt1
        global pnt2
        global evt
    
        pnt1 = (xPos,yPos)
        pnt2 = (xPos,yPos)
        evt = event
    
    ...
    

    (remainder of the code is unchanged, omitted for brevity)