Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

h.264 encoding directly from numpy

I want to directly encode videos from numpy arrays of video frames. Open-cv offers such functionality via the cv2.VideoWriter, however I need the h.264 codec which is not available. The best I have so far is using open-cv to write the video and then reencode it via:

# write video from numpy arrays via cv2
out = cv2.VideoWriter("/tmp/video.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, size)
for frame in frames:
    out.write(frame)
out.release()
# reencode video with ffmpeg
os.system("ffmpeg -y -i /tmp/video.mp4 -vcodec libx264 /tmp/video2.mp4")

However, I think that the first encoding is not loss less, so I am instead looking for a solution where I can directly encode videos from python.

Thanks for your help!

like image 426
Chris Holland Avatar asked Oct 14 '25 18:10

Chris Holland


1 Answers

scikit-video provides the feature:

import skvideo.io

outputfile = "/tmp/video.mp4"
writer = skvideo.io.FFmpegWriter(outputfile, outputdict={'-vcodec': 'libx264'})
for frame in frames:
    writer.writeFrame(frame)
writer.close()
like image 113
Chris Holland Avatar answered Oct 17 '25 06:10

Chris Holland