rgr117
rgr117

Reputation: 21

Mouse click events on a live stream with Opencv and python

i am new to opencv -python. I want to draw a rectangle in a live stream video captured from my webcam. While drawing the rectangle,the video must freeze. I am successful in drawing a rectangle on a image,but i don't know how to do the same on a live video using opencv and python . Please help..

Upvotes: 1

Views: 7283

Answers (1)

Julio Schurt
Julio Schurt

Reputation: 2094

This is a code that I'm using to draw a rectange in videos.

The code works like that:

  1. click on video and the script save the start point
  2. click again and the script save the end point and draw the rectangle
  3. click again to start drawing another retangle

    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()
    

Upvotes: 3

Related Questions