简体   繁体   中英

Flow of control_Mouse click events_OpenCV_Python

I wrote a program in Python using Open CV to draw small circles on a black image and join them with a line to test the use of mouse click events. However I do not understand the flow of control in the code. I got these 2 variations from 2 sources.

Please explain to me the flow of control in both of them.

First code:

import cv2
import numpy as np

x2,y2,c=0,0,0

def click (event,x,y,flags,param):
    global x2,y2,c
    if event==cv2.EVENT_LBUTTONDOWN:
        cv2.circle(img, (x,y), 5, (0,0,255),-1) 
        if (c==0):
            cv2.imshow('image',img)
        else:
            cv2.line(img, (x2,y2), (x,y), (255,255,0), 1, cv2.LINE_AA)
            cv2.imshow('image',img)
        x2,y2=x,y
        c=c+1

img=np.zeros((700,700,3), np.uint8)
cv2.imshow('image',img)

cv2.setMouseCallback('image',click)
cv2.waitKey(0)
cv2.destroyAllWindows()

Second code:

import cv2
import numpy as np

x2,y2,c=0,0,0

def click (event,x,y,flags,param):
    global x2,y2,c
    if event==cv2.EVENT_LBUTTONDOWN:
        cv2.circle(img, (x,y), 5, (0,0,255),-1) 
        if (c!=0):
            cv2.line(img, (x2,y2), (x,y), (255,255,0), 1, cv2.LINE_AA)
        x2,y2=x,y
        c=c+1

img=np.zeros((700,700,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',click)

while (True):
    cv2.imshow('image',img)
    if cv2.waitKey(20)==ord('q'):
        break

cv2.destroyAllWindows()

The only differences in the code are:

cv2.imshow('image',img)
cv2.setMouseCallback('image',click)
cv2.waitKey(0)

in part 1, and

cv2.namedWindow('image') 
cv2.setMouseCallback('image',click)

while (True):
    cv2.imshow('image',img)
    if cv2.waitKey(20)==ord('q'):
        break

in part 2.

Both codes set up a callback function "cv2.setMouseCallback" , and in part 1, an endless delay cv2.waitKey(0) is called following that, essentially pausing the main body while acquiring any callbacks. If you press any key, the program will continue flowing.

In part 2, a named window is set up - not necessary to do anything in particular. An infinite while (True) loop is set up to continuously check if a specific key has been pressed - in this case, 'q', which would break the program out of the loop. This loop also continuously invokes cv2.imgshow - which is redundant since the callback function calls cv2.imgshow after any changes. A loop like this is useful if you want to add additional keystrokes to check for - maybe 'r' to revert the image state to beginning, or anything else you might think of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM