控制流Python OpenCv:为什么cv2.setMouseCallback不在循环内?

时间:2020-04-01 07:46:10

标签: opencv image-processing jupyter-notebook opencv-python

我对以下程序中的控制流程感到困惑。该代码的目的是在网络摄像头的实时视频流中绘制一个矩形。

工作原理:第一次单击将初始化矩形起始角的坐标,并将其标记为粗体。第二次单击将完成矩形。

现在我的问题是:为什么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()

3 个答案:

答案 0 :(得分:1)

回调是每次将鼠标移到显示窗口上方时调用的函数。它独立于main中的流程,即它处于新线程中,等待鼠标输入的更改。

在main中使用循环的原因是因为您要更新显示的图像。调用imshow之后,您需要调用waitKey以影响渲染。

答案 1 :(得分:1)

在事件上调用回调函数。与常规函数不同,您不需要每次都希望运行它时进行函数调用。

cv2.setMouseCallback('Test',draw_rectangle)会将函数draw_rectangle设置为对OpenCV窗口"Test"上从鼠标接收到的任何事件的响应。设置回调后,在while循环内,您将在"Test"窗口中捕获所有鼠标事件。

答案 2 :(得分:1)

cv2.setMouseCallback('Test',draw_rectangle)这个函数实际上是一个事件处理程序,它在每次鼠标左键单击时都设置对draw_rectangle函数的调用。 while循环中的其余代码用于所有动态操作,最后cv2.imshow将其呈现在图像中。

一个礼物令牌,用于更好地处理opencv closeWindows,仅关闭当前使用的窗口:

def showImage(imageName, image):
    img = image.copy()
    cv2.imshow(imageName, img)
    while(1):
        pressedKey = cv2.waitKey(0) & 0xFF

        if(pressedKey == ord('q')):
            cv2.destroyWindow(imageName)
            break
        else:
            cv2.putText(img, "\press q to exit", (10,10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color=(255,0,0))
            cv2.imshow(imageName, img)