Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Writing to video with OpenCV

  • Last Updated : 17 Oct, 2021

In this article, we will discuss how to write to a video using OpenCV in Python.


  • Import the required libraries into the working space.
  • Read the video on which you have to write.


cap = cv2.VideoCapture("path")
  • Create a output file using cv2.VideoWriter_fourcc() method


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

  • Then edit the frames of the video by adding shapes to it (for the example given here, the same can be applied to any other technique.).


cv2.rectangle(frame, (100,100), (500,500), (0,255,0), 3)

  • Then write the video.



Example: Program to write to video

Video Used: 


import cv2
def main():
    # reading the input
    cap = cv2.VideoCapture("input.mp4")
    output = cv2.VideoWriter(
        "output.avi", cv2.VideoWriter_fourcc(*'MPEG'), 30, (1080, 1920))
        ret, frame =
            # adding rectangle on each frame
            cv2.rectangle(frame, (100, 100), (500, 500), (0, 255, 0), 3)
            # writing the new frame in output
            cv2.imshow("output", frame)
            if cv2.waitKey(1) & 0xFF == ord('s'):
if __name__ == "__main__":


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!