To save a video using the cv2 library in Python, use cv2.VideoWriter_fourcc() method. The cv2.VideoWriter_fourcc() function creates a four-character code (FourCC) that specifies the video codec to be used when writing a video file.
The FourCC code is a sequence of four characters to identify the codec.
Syntax
cv2.VideoWriter(filename, fourcc, fps, frameSize)
Parameters
- filename: Input video file.
- fourcc: 4-character code of codec used to compress the frames.
- fps: framerate of the video stream.
- framesize: Height and width of the frame.
Example
import cv2 # Create an object to read # from camera video = cv2.VideoCapture(0) # We need to check if camera # is opened previously or not if (video.isOpened() == False): print("Error reading video file") # We need to set resolutions. # so, convert them from float to integer. frame_width = int(video.get(3)) frame_height = int(video.get(4)) size = (frame_width, frame_height) # Below VideoWriter object will create # a frame of above defined The output # is stored in 'output.avi' file. result = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 10, size) while(True): ret, frame = video.read() if ret == True: # Write the frame into the # file 'output.avi' result.write(frame) # Display the frame # saved in the file cv2.imshow('Frame', frame) # Press S on keyboard # to stop the process if cv2.waitKey('q') & 0xFF == ord(1): break # Break the loop else: break # When everything done, release # the video capture and video # write objects video.release() result.release() # Closes all the frames cv2.destroyAllWindows() print("The video was successfully saved")
In this example, first, I created an object for VideoCapture class.
Then we got the resolutions of the video object and converted it into an integer.
Then we call the cv2.VideoWriter() method and pass the name of the output video file, size, and codec.
Then we write one by one frame in the output.avi file.
The waitKey() function returns the pressed key as a number. Again, we will assume that we want to finish the program. So, if we press the q key, it will close the python window, and Video is saved in the filesystem.
The Video is stored in your current project folder because we have not specified the file path.
That is how you load and save the Video in Python using the OpenCV library.