我对以下程序中的控制流程感到困惑。该代码的目的是在来自网络摄像头的实时视频流中绘制一个矩形。
工作原理:第一次单击将初始化矩形起始角的坐标,并用粗体圆圈标记。第二次单击将完成矩形。
现在我的问题是:为什么 cv2.setMouseCallback('Test',draw_rectangle) 语句不在循环内?
代码工作得很好,但我无法理解控制流程。请帮帮我。
import cv2
import os
os.environ["OPENCV_VIDEOIO_PRIORITY_MSMF"] = "0"
#CALLBACK FUNCTION RECTANGLE
def draw_rectangle(event,x,y,flags,param): #Param is the just the additional paramter which u can receive
global pt1, pt2, topLeft_Clicked, botRight_Clicked
if event ==cv2.EVENT_LBUTTONDOWN:
#Reset if rectangle is drawing i.e both var are true
if topLeft_Clicked and botRight_Clicked:
pt1=(0,0)
pt2=(0,0)
topLeft_Clicked=False
botRight_Clicked=False
if topLeft_Clicked == False:
pt1=(x,y)
topLeft_Clicked=True
elif botRight_Clicked == False:
pt2=(x,y)
botRight_Clicked=True
#GLOBAL VARIABLES
pt1=(0,0)
pt2=(0,0)
topLeft_Clicked= False
botRight_Clicked= False
#COnnect to the Callback
cap=cv2.VideoCapture(0)
cv2.namedWindow('Test')
cv2.setMouseCallback('Test',draw_rectangle)
while True:
ret,frame=cap.read()
#Drawing Based on Global Variables
if topLeft_Clicked: # If topleft is true
cv2.circle(frame,center=pt1,radius=5,color=(0,0,255),thickness=-1)
if topLeft_Clicked and botRight_Clicked:
cv2.rectangle(frame,pt1,pt2,(0,0,255),3)
cv2.imshow('Test',frame)
if(cv2.waitKey(1) & 0xFF==ord('q')):
break
cap.release()
cv2.destroyAllWindows()
最佳答案
事件发生时调用回调函数。与常规函数不同,您不需要每次希望它运行时都进行函数调用。
线路cv2.setMouseCallback('Test',draw_rectangle)
将设置函数 draw_rectangle
作为对 OpenCV 窗口上从鼠标接收到的任何事件的响应 "Test"
。设置回调后,在您的 while
内循环你将捕获 "Test"
上的所有鼠标事件窗口。
关于image-processing - 控制流程 Python OpenCv : Why cv2. setMouseCallback 不在循环内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60965905/