Python Forum
VideoWriter unreadable output using tempfile
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
VideoWriter unreadable output using tempfile
#1
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')
Reply
#2
SOLVED:

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error on open of file created with tempfile.TemporaryDirectory() Brian177 4 6,400 Apr-05-2021, 07:12 PM
Last Post: Brian177
  Create tempfile that use in loop for insert into DB Firsttimepython 2 2,168 May-29-2020, 04:15 PM
Last Post: Firsttimepython
  Help with Tempfile Required KirkmanJ 2 2,617 Aug-28-2018, 10:40 AM
Last Post: KirkmanJ

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020