Python Forum

Full Version: VideoWriter unreadable output using tempfile
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When I use opencv-python's VideoWriter to a local mp4 filepath, the code below works perfectly and the mp4 file is saved to disk. This save to disk operation should work the same as saving to a tempfile.

To test using a tempfile, I simply change the VideoWriter filename to the file_out.name (via NamedTemporaryFile) and copy to disk to verify that it worked correctly. The output I get is an equally sized mp4 file, but it can't be opened by any video player - so something must be wrong with the file.


Code that Worked Correctly
video = cv2.VideoWriter('/path/to/test_output.mp4',cv2.VideoWriter_fourcc(*'avc1'),20,(width,height))

for i in range(len(images)):
    video.write(np.asarray(images[i]))
Code that Created an Unreadable mp4 Output
file_out = tempfile.NamedTemporaryFile(suffix='.mp4')

video = cv2.VideoWriter(file_out.name,cv2.VideoWriter_fourcc(*'avc1'),20,(width,height))

for i in range(len(images)):
    video.write(np.asarray(images[i]))

shutil.copy(file_out.name, '/path/to/test_output.mp4')
SOLVED:

VideoWriter output MUST be released for output of copied file to be valid.
video.release()
This fixes the problem.