Try this. It's working for me (Windows 10).

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Answer from Nurul Akter Towhid on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ saving-a-video-using-opencv
Saving a Video using OpenCV - GeeksforGeeks
July 12, 2025 - Saving a video using OpenCV involves reading an existing video file frame-by-frame and writing each frame to a new video file.
Top answer
1 of 16
61

Try this. It's working for me (Windows 10).

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
2 of 16
34

jveitchmichaelis at https://github.com/ContinuumIO/anaconda-issues/issues/223 provided a thorough answer. Here I copied his answer:

The documentation in OpenCV says (hidden away) that you can only write to avi using OpenCV3. Whether that's true or not I've not been able to determine, but I've been unable to write to anything else.

However, OpenCV is mainly a computer vision library, not a video stream, codec and write one. Therefore, the developers tried to keep this part as simple as possible. Due to this OpenCV for video containers supports only the avi extension, its first version.

From: http://docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html

My setup: I built OpenCV 3 from source using MSVC 2015, including ffmpeg. I've also downloaded and installed XVID and openh264 from Cisco, which I added to my PATH. I'm running Anaconda Python 3. I also downloaded a recent build of ffmpeg and added the bin folder to my path, though that shouldn't make a difference as its baked into OpenCV.

I'm running in Win 10 64-bit.

This code seems to work fine on my computer. It will generate a video containing random static:

writer = cv2.VideoWriter("output.avi",
cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480))

for frame in range(1000):
    writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8'))

writer.release()

Some things I've learned through trial and error:

  • Only use '.avi', it's just a container, the codec is the important thing.
  • Be careful with specifying frame sizes. In the constructor you need to pass the frame size as (column, row) e.g. 640x480. However the array you pass in, is indexed as (row, column). See in the above example how it's switched?

  • If your input image has a different size to the VideoWriter, it will fail (often silently)

  • Only pass in 8 bit images, manually cast your arrays if you have to (.astype('uint8'))
  • In fact, never mind, just always cast. Even if you load in images using cv2.imread, you need to cast to uint8...
  • MJPG will fail if you don't pass in a 3 channel, 8-bit image. I get an assertion failure for this at least.
  • XVID also requires a 3 channel image but fails silently if you don't do this.
  • H264 seems to be fine with a single channel image
  • If you need raw output, say from a machine vision camera, you can use 'DIB '. 'RAW ' or an empty codec sometimes works. Oddly if I use DIB, I get an ffmpeg error, but the video is saved fine. If I use RAW, there isn't an error, but Windows Video player won't open it. All are fine in VLC.

In the end I think the key point is that OpenCV is not designed to be a video capture library - it doesn't even support sound. VideoWriter is useful, but 99% of the time you're better off saving all your images into a folder and using ffmpeg to turn them into a useful video.

๐ŸŒ
GitHub
gist.github.com โ€บ keithweaver โ€บ 4b16d3f05456171c1af1f1300ebd0f12
Stream and save video in Python with OpenCV ยท GitHub
# For more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html import cv2 as cv2 import cv2 as cv import numpy as np import os FILE_OUTPUT = 'output.avi' # Checks and deletes the output file # You cant have a existing file or it will through an error if os.path.isfile(FILE_OUTPUT): os.remove(FILE_OUTPUT) # Playing video from file: # cap = cv2.VideoCapture('vtest.avi') # Capturing video from webcam: cap = cv2.VideoCapture(0) currentFrame = 0 width = cap.set(cv2.CAP_PROP_FRAME_WIDTH, 160); height = cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 120); # Get cu
๐ŸŒ
Arahna
arahna.de โ€บ opencv-save-video
Save the video stream from your camera using OpenCV
cv2.VideoWriter_fourcc(โ€˜Dโ€™,โ€™Iโ€™,โ€™Vโ€™,โ€™3โ€™): MPEG-4.3 codec ... #include "opencv2/opencv.hpp" #include <iostream> using namespace std; using namespace cv; int main(){ // Create a VideoCapture object and use camera to capture the video VideoCapture cap(0); int fps = 30; // Check if camera opened successfully if(!cap.isOpened()){ cout << "Error opening video stream" << endl; return -1; } // Default resolutions of the frame are obtained.The default resolutions are system dependent.
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 4.13.0 โ€บ dd โ€บ d43 โ€บ tutorial_py_video_display.html
OpenCV: Getting Started with Videos
So we capture a video and process it frame-by-frame, and we want to save that video. For images, it is very simple: just use cv.imwrite().
๐ŸŒ
Chrisstrelioff
chrisstrelioff.ws โ€บ sandbox โ€บ 2024 โ€บ 04 โ€บ 25 โ€บ save_video_capture_using_opencv_python
Save video capture using opencv-python on Pop!_OS 22.04 @ chrisstrelioff.ws
April 25, 2024 - """ script02.py Testing video capture and writing files on Pop_OS! (Ubuntu) 22.04 operating system. Following documentation at: https://docs.opencv.org/4.x/dd/d43/tutorial_py_video_display.html """ import numpy as np import cv2 # pass argument 0 for device index (hopefully laptop cam) vcap = cv2.VideoCapture(0); if not vcap.isOpened(): print("Can't open camera!") exit() # get height and width of capture width = int(vcap.get(3)) height = int(vcap.get(4)) # bool for isColor is optional, BUT defaults to True!
๐ŸŒ
Learning About Electronics
learningaboutelectronics.com โ€บ Articles โ€บ How-to-save-a-video-Python-OpenCV.php
How to Save a Video File in Python using OpenCV
We can do many things to videos with OpenCV, such as even creating them such as through recording with a webcam. This video can then be saved so that you can store it somewhere such as on your PC or in a directory on your website.
Find elsewhere
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ opencv
Save frames from video files as still images with OpenCV in Python | note.nkmk.me
October 19, 2022 - This article describes how to capture and save frames from video files such as mp4 and avi as still image files with OpenCV in Python. If you simply want to save a video as a frame-by-frame still imag ...
๐ŸŒ
TechTutorialsX
techtutorialsx.com โ€บ home โ€บ python โ€บ python opencv: saving video from webcam
Python OpenCV: Saving Video from Webcam - techtutorialsx
December 17, 2020 - In case the frame was correctly captured, we will show it in a window and also write it to the file. To write the frame to the file, we need to call the write method on our VideoWriter object, passing as input the frame.
๐ŸŒ
Opencv-srf
opencv-srf.com โ€บ 2018 โ€บ 01 โ€บ save-images-and-videos-to-file.html
Save Images & Videos to File - OpenCV Tutorial C++
In the same way, you can save a video file after doing any modifications. //Uncomment the following line if you are compiling this code in Visual Studio //#include "stdafx.h" #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char* ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Record and Save Camera Video to a File in OpenCV and Python - YouTube
#computergraphics #computervision #python #machinelearning #datascience #opencv #opencvpython #datascience #datascienceinterview #robotics #controltheory #ma...
Published: December 15, 2023
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Write/Save/Record a Video File Using OpenCV | #98 (SHANE Updates! #7) - YouTube
In this video, we'll go through how to save a recording using Python and OpenCV. This will be important as we progress in machine learning and AI and to use...
Published: September 19, 2020
๐ŸŒ
Yinglinglow
yinglinglow.com โ€บ blog โ€บ 2018 โ€บ 06 โ€บ 23 โ€บ opencv-video
OpenCV - Recording and Save Video - Ying Ling
June 23, 2018 - Follow the code below (credits to this guy: https://www.learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/) if you want to record a live video. It opens the camera, records the video, closes the window when you press โ€˜qโ€™, and saves the video in .avi format.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ saving-operated-video-from-a-webcam-using-opencv
Saving Operated Video from a webcam using OpenCV - GeeksforGeeks
July 11, 2025 - With OpenCV, we can perform operations on the input video. OpenCV also allows us to save that operated video for further usage. For saving images, we use cv2.imwrite() which saves the image to a specified file location.
๐ŸŒ
OpenCV Q&A Forum
answers.opencv.org โ€บ question โ€บ 236984 โ€บ saving-video-from-frames-in-with-fourcc-codec-h264-and-h265-with-opencv
Saving video from frames in with fourcc codec h264 and h265 with opencv - OpenCV Q&A Forum
October 27, 2025 - @supra56 I tried filemanes with different extension like saveVideo.mkv, saveVideo.avi, saveVideo.mp4 ยท But still it is not working. ... import numpy as np import cv2 cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'X264') out = cv2.VideoWriter('output.mp4',fourcc, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break # Release everything if job is finished cap.release() out.release() cv2.destroyAllWindows()
๐ŸŒ
YouTube
youtube.com โ€บ case digital
How To Save Frames From A Video In OpenCV Python - YouTube
In this python tutorial, I show you how to save frames from a video in OpenCV Python! I show you how to tweak the previous code we worked with to meet the ne...
Published: July 1, 2024
Views: 424
๐ŸŒ
Etutorialspoint
etutorialspoint.com โ€บ index.php โ€บ 320-how-to-capture-a-video-in-python-opencv-and-save
How to capture a video in Python OpenCV and save
Simple Tutorials for PHP,HTML,JS,MySQL,MySQLi,OOPS,Python,NodeJS,ExpressJS,R with interview questions answers and technical blogs
๐ŸŒ
LearnOpenCV
learnopencv.com โ€บ home โ€บ image processing โ€บ reading and writing videos using opencv
Reading and Writing Videos using OpenCV | LearnOpenCV
October 15, 2025 - These are the main functions in ... capture object, which would help stream or display the video. cv2.VideoWriter โ€“ Saves the output video to a directory....
๐ŸŒ
OpenCV Q&A Forum
answers.opencv.org โ€บ question โ€บ 235950 โ€บ image-frame-saving-from-video-without-losing-resolution-and-quality
Image frame saving from Video without losing resolution and quality - OpenCV Q&A Forum
I want to save the images extracted from the video without losing any information, resolution and quality. I have saved using OpenCV in four formats png, bmp, jpg, tif The code is as below file = "video.MP4" video = cv2.VideoCapture(file) # Find OpenCV version (major_ver, minor_ver, subminor_ver) ...