Open In App

How to draw Filled rectangle to every frame of video by using Python-OpenCV?

In this article, we will discuss how to draw a filled rectangle on every frame of video through OpenCV in Python.

Stepwise Implementation:

Syntax:



cap = cv2.VideoCapture(“path”)

Syntax:



output = cv2.VideoWriter(“output.avi”, cv2.VideoWriter_fourcc(*’MPEG’), 30, (1080, 1920))

Syntax:

cv2.rectangle(frame, (100, 100), (500, 500), (0, 255, 0), -1)

Syntax:

output.write(frame)

Example:

In this example, we add a green rectangle to the video.

Input Video:




import cv2
  
  
def main():
    
    # reading the input
    cap = cv2.VideoCapture("input.mp4")
  
    output = cv2.VideoWriter(
        "output.avi", cv2.VideoWriter_fourcc(*'MPEG'), 
      30, (1080, 1920))
  
    while(True):
        ret, frame = cap.read()
        if(ret):
              
            # adding filled rectangle on each frame
            cv2.rectangle(frame, (100, 150), (500, 600),
                          (0, 255, 0), -1)
              
            # writing the new frame in output
            output.write(frame)
            cv2.imshow("output", frame)
            if cv2.waitKey(1) & 0xFF == ord('s'):
                break
        else:
            break
  
    cv2.destroyAllWindows()
    output.release()
    cap.release()
  
  
if __name__ == "__main__":
    main()

Output:


Article Tags :