Saving a Video using OpenCV

OpenCV is an open-source and most popular computer vision library that contains several computer vision algorithms. You can read, display, write and doing lots of other operations on images and videos using OpenCV. The OpenCV module generally used in popular programming languages like C++, Python, Java. To save a video in OpenCV cv.VideoWriter() method is used.

Note: For more information, refer to Introduction to OpenCV.

Syntax: cv.VideoWriter(filename, fourcc, fps, frameSize)



Parameters:

filename: Input video file
fourcc: 4-character code of codec used to compress the frames
fps: framerate of videostream
framesize: Height and width of frame

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to save a 
# video using OpenCV
  
   
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 'filename.avi' file.
result = cv2.VideoWriter('filename.avi'
                         cv2.VideoWriter_fourcc(*'MJPG'),
                         10, size)
    
while(True):
    ret, frame = video.read()
  
    if ret == True
  
        # Write the frame into the
        # file 'filename.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(1) & 0xFF == ord('s'):
            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")

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.