In this article, we will discuss how to write to a video using OpenCV in Python.
Approach
- Import the required libraries into the working space.
- Read the video on which you have to write.
Syntax:
cap = cv2.VideoCapture("path")
- Create a output file using cv2.VideoWriter_fourcc() method
Syntax:
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.).
Syntax:
cv2.rectangle(frame, (100,100), (500,500), (0,255,0), 3)
- Then write the video.
Syntax:
output.write(frame)
Example: Program to write to video
Video Used:
Python
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 rectangle on each frame cv2.rectangle(frame, ( 100 , 100 ), ( 500 , 500 ), ( 0 , 255 , 0 ), 3 ) # writing the new frame in output output.write(frame) cv2.imshow( "output" , frame) if cv2.waitKey( 1 ) & 0xFF = = ord ( 's' ): break cv2.destroyAllWindows() output.release() cap.release() if __name__ = = "__main__" : main() |
Output: