使用Opencv和python在实时流上单击鼠标事件

时间:2015-11-22 10:31:56

标签: python opencv mouseevent

我是opencv -python的新手。 我想在从我的网络摄像头捕获的直播视频中绘制一个矩形。绘制矩形时,视频必须冻结。我成功地在图像上绘制了一个矩形,但我不知道如何使用opencv和python在实时视频上做同样的事情。请帮忙..

1 个答案:

答案 0 :(得分:2)

这是我用来在视频中绘制矩形的代码。

代码就是这样的:

  1. 点击视频,脚本保存起点
  2. 再次单击,脚本保存结束点并绘制矩形
  3. 再次点击开始绘制另一个视角

    import numpy as np
    import cv2
    
    rect = (0,0,0,0)
    startPoint = False
    endPoint = False
    
    def on_mouse(event,x,y,flags,params):
    
        global rect,startPoint,endPoint
    
        # get mouse click
        if event == cv2.EVENT_LBUTTONDOWN:
    
            if startPoint == True and endPoint == True:
                startPoint = False
                endPoint = False
                rect = (0, 0, 0, 0)
    
            if startPoint == False:
                rect = (x, y, 0, 0)
                startPoint = True
            elif endPoint == False:
                rect = (rect[0], rect[1], x, y)
                endPoint = True
    
    cap = cv2.VideoCapture('../videos/sample.avi')
    waitTime = 50
    
    #Reading the first frame
    (grabbed, frame) = cap.read()
    
    while(cap.isOpened()):
    
        (grabbed, frame) = cap.read()
    
        cv2.namedWindow('frame')
        cv2.setMouseCallback('frame', on_mouse)    
    
        #drawing rectangle
        if startPoint == True and endPoint == True:
            cv2.rectangle(frame, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 255), 2)
    
        cv2.imshow('frame',frame)
    
        key = cv2.waitKey(waitTime) 
    
        if key == 27:
            break
    
    cap.release()
    cv2.destroyAllWindows()