Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I used the following page from OpenCV 3.0.0 tutorial: Tutorial in docs

When I tried to use the example that saves videos, it doesn't work.

It displays the content from the webcam, and also creates a file called output.avi , but when I checked the size of ouput.avi , it was zero bytes.

I also tried using different codecs, like YUY2 .

I use Python 2.7.8 and OpenCV 3.0.0 and Windows 8.1

If anyone has a similar issue and is writing black and white image, you need to specify that the image is not in colour: out = cv2.VideoWriter('output.avi',fourcc, 20.0,(int(cap.get(3)),int(cap.get(4))), False) George Ogden Jun 27, 2022 at 20:18

I had the same problem and I solved it by specifying the video output resolution to exactly the same as input:

cap = cv2.VideoCapture('vtest.avi')
out = cv2.VideoWriter('output.avi',fourcc, 20.0,(int(cap.get(3)),int(cap.get(4))))

Of course make sure you got ffmpeg installed and working.

I was struggling with this problem for a few hours then I realized that I had typed the image's shape wrong.

It is (width, height), ie:

(image.shape[1], image.shape[0])

and not

(image.shape[0], image.shape[1])

This is how my working code looks like finally... (I am on a Windows machine):

video_path = FILENAME + '.avi'
size = images[0].shape[1], images[0].shape[0] ## <<<--- NOTICE THIS
video = cv2.VideoWriter(video_path,cv2.VideoWriter_fourcc(*'DIVX'), 60, size)  
for img in images:  
    video.write(img)
cv2.destroyAllWindows()
video.close()

More generally:

Look up the fourcc code of the video compression format you're after here, and whatever the code is - for instance 'FMP4' for FFMpeg - plug it in in the following manner:

cv2.VideoWriter_fourcc('F','M','P','4')
                Actually, (*'XVID') is the same as ('X', 'V', 'I', 'D')  Take a look at docs.python.org/dev/tutorial/…
– Alakazam
                Jan 28, 2019 at 12:55

Make sure you are using the correct fourcc 4-byte code. The example on the tutorial has:

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

This XVID code may only work for linux. The documentation above the example states (in the tutorial): "In Windows: DIVX (More to be tested and added)." So if you haven't, try replacing the fourcc line above with:

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

I use cv2.VideoWriter on linux quite often and it always works. So if the above doesn't work you can always try it on a linux vm.

I looked through my code and found that I have this line: fourcc = cv2.cv.CV_FOURCC('X', 'V', 'I', 'D'). This is for a Linux vm but you could make appropriate changes and try it. I don't know where I originally found this code but it works for me. – Scott Mar 30, 2015 at 15:25 It doesn't work on Linux, Debian Stretch stable. If yes for you, then you are a lucky man. For me it has created the output file once properly, once with 0 bytes length and 500-times no file was created (no error reported; command timing as if all works excellent) :((( – mirek Jul 7, 2017 at 17:13 @mirek I just tested it on ubuntu 16.04 with opencv3 installed and it is working for me. I tested with color image frames so as posted above I don't specify the isColor flag, however you may want to verify that you have this correctly set to True/False, as needed. This won't give an exception if you have it set incorrectly, you just get an "un-playable" video. If this doesn't help it may be that you need to install ffmpeg or alternative on your machine. – Scott Jul 7, 2017 at 19:31

In my case, I thought the codec was an obstacle but it wasn't. Instead, adjusting the dimensions being consumed by videoWriter() did the trick:

(ok, frame) = cv2.VideoCapture(videoPath).read()
 fourcc = cv2.VideoWriter_fourcc(*'XVID')
 out = cv2.VideoWriter(output, fourcc, 10.0, (1280, 720))

(1280,720) was used because frame.shape from my video outputs (1280, 720, 3). It made avi to mp4 and vice versa possible. Didn't have to worry about reconciling the codec.

Check the resolution of your images! I was trying with odd-shaped images (1284x709) and ended up with unreadable videos of 1k in size. After resizing my image to the closest 'common' resolution: image = cv2.resize(image, (1280,720)), it worked just fine.

Also, check for an error message. I had on my jupyter notebook: OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v', and by using the exact 4 letters as suggested (mp4v), respecting the case, the message disappeared. – nchaumont Mar 15, 2019 at 22:26

I suspect there are a lot of reasons video writing fails silently, and in my case, my frame was a composite of a 3 channel image and a 4 channel image (transparent overlay). Converting the end result to BGR format as follows allowed the video to save successfully.

width = 1280
height = 720
FPS = 30
fourcc = VideoWriter_fourcc(*'avc1')
video = VideoWriter('output.mp4', fourcc, float(FPS), (width, height))
for img in images:
  frame = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
  video.write(frame)
video.release()

On windows 7 and using Python 2.7 and OpenCV 2.4.8, I experienced the fact that if the file NAME is "output.mpg" would not write.

I solved it by changing to "output.avi".

I have the exact same issue. I am using OpenCV in C++, but I believe you can still pass -1 instead of choosing the codec so you can have a drop down menu of the available codecs even in python. From there I tried all different codecs and just like Leonard Zhou, the IYUV codec was the one that worked for me. Also note that it was the only one that worked even though I could use XVID just fine on another machine with the same code and same codec installer.

EDIT: What I suggested worked as a patch, the main issue was solved on my end by adding the opencv_ffmpeg dll in the executable's folder.

I changed the Video writer size to my screen resolution size and it worked.

here is the solution.

out = cv2.VideoWriter("output.avi", fourcc, 5.0, (1920, 1080))

It worked for me after I assigned the actual frame size and not what I thought the size was:

ret, frame = cap.read()
height, width, channels = frame.shape
codec = cv2.VideoWriter_fourcc(*"DIVX")
out=cv2.VideoWriter('new.avi',codec ,20.0,(width, height))

And put out.write(frame) inside the while loop before cv2.imshow("Frame", frame).

On my system, only 'DIVX' works whereas the encoding on the opencv documentation examples, 'M', 'J', 'P', 'G', just silently writes no file. I wish there was a way to verify the codec so that my code is more safely portable. – matanster Nov 7, 2021 at 17:13

After trying hours to find the error, I finally found it. So here are some things to keep in mind. (For Linux users particularly)

  • Use this codec ("MJPG").

    cv2.VideoWriter_fourcc(*'MJPG')
    
  • Do not forget to write the Boolean value as final argument (True for RGB and False for GrayScale) in

    cv2.VideoWriter(path, fourcc, float(frameRate), frameSize, True)
    
  • The argument, frameSize required by cv2.VideoWriter is a tuple of form (width, height) and not (height, width) which is the shape of image array if you open the image using cv2.read or Image.open. So don't forget to invert it.

    To state the obvious, make sure you're giving not only a correct path, but also a video name. i.e. path/'video.avi' and not just path/. It will fail silently otherwise.

    I had same issue that the video file was being created without any errors but it won't run and had a size of few KBs. Here's how I resolved it;

  • Make sure you have passed FPS argument in float value.
  • The output resolution needs to be same as of input video resolution.
  • The above methods work only for RGB frames/images. Incase you are trying to write a grayscale image, pass a parameter 0 to the VideoWriter():

    fourcc = cv2.VideoWriter_fourcc(*"MJPG")
    out = cv2.VideoWriter('output.avi', fourcc, 30, size, 0)
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

  •