[英]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.我使用 Open CV 在 Python 中编写了一个程序,在黑色图像上绘制小圆圈并用一条线将它们连接起来,以测试鼠标单击事件的使用。 However I do not understand the flow of control in the code.
但是我不明白代码中的控制流。 I got these 2 variations from 2 sources.
我从 2 个来源获得了这 2 个变体。
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在第 1 部分,以及
cv2.namedWindow('image')
cv2.setMouseCallback('image',click)
while (True):
cv2.imshow('image',img)
if cv2.waitKey(20)==ord('q'):
break
in part 2.在第 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.两个代码都设置了一个回调函数
"cv2.setMouseCallback"
,在第 1 部分中,在此之后调用了一个无限延迟 cv2.waitKey(0) ,本质上是在获取任何回调时暂停主体。 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.在第 2 部分中,设置了一个命名窗口 - 不需要做任何特别的事情。 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.设置了一个无限的
while (True)
循环来持续检查是否按下了特定的键 - 在这种情况下,'q' 会使程序跳出循环。 This loop also continuously invokes cv2.imgshow
- which is redundant since the callback function calls cv2.imgshow
after any changes.该循环还不断调用
cv2.imgshow
- 这是多余的,因为回调函数在任何更改后都会调用cv2.imgshow
。 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.如果您想添加额外的按键来检查,这样的循环很有用 - 可能是 'r' 将图像状态恢复到开始状态,或者您可能想到的任何其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.