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)
Syntax:
output.write(frame)
Example: Program to write to video
Video Used:
Python
import cv2
def main():
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):
cv2.rectangle(frame, ( 100 , 100 ), ( 500 , 500 ), ( 0 , 255 , 0 ), 3 )
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:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jan, 2023
Like Article
Save Article