2

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..

1
  • Please share what you done so far with piece of code. Commented Nov 23, 2015 at 6:38

1 Answer 1

4

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()
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.