'cv2.VideoWriter only generate empty file

When I tried to make a video by opencv2, I always end up having an empty file. My python version is 2.7.13 and opencv version is 3.2.0. I am using Windows. I tried the code by @Creyesk but still get an empty file.

import cv2
import cv2.cv as cv
import numpy as np

writer = cv2.VideoWriter('test1.avi',cv.CV_FOURCC('P','I','M','1'),25,  (640,480))
for i in range(1000):
    x = np.random.randint(255,size=(480,640)).astype('uint8')
    x = np.repeat(x,3,axis=1)
    x = x.reshape(480, 640, 3)
    writer.write(x)

Thanks so much!



Solution 1:[1]

The issue seems to be in your fourCC argument. I tried the following arguments and it worked:

writer=cv2.VideoWriter("test1.avi", cv.CV_FOURCC(*'DIVX'), 25, (640,480))

Solution 2:[2]

As mentioned in the comment by @Gerard, there can be many reasons for this, since errors during construction of the writer or when adding frames, will not be raised as exceptions.

To check whether the constructor worked, you can call writer.isOpened() and check if it's True.

Then still errors can happen during writing frames, like when the frame does not have the same shape as passed to the constructor.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saransh Kejriwal
Solution 2 Philipp F