Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ExportVideo[prefix_, framerate_, frames_] := Module[{
digits = Ceiling @ Log10 @ Length @ frames
},
(* create directory (OK if already exist,
prints error and continues *)
CreateDirectory[prefix];
(* export each frame as a png with an enumerated filename,
padded with zeroes *)
Table[
Export[
StringJoin[prefix, "/", StringPadLeft[ToString[x], digits, "0"],
".png"],
frames[[x]]
],
{x, Length@frames}
];
(* concatenate the series of png images in order,
encoded with yuv420p and libx264 for most compatibility *)
RunProcess[{
"ffmpeg",
"-f", "image2",
"-framerate", ToString @ framerate,
"-i", StringJoin[prefix, "/%", ToString @ digits, "d.png"],
"-pix_fmt", "yuv420p",
"-c:v", "libx264",
"-movflags", "+faststart",
"-filter:v", "crop='floor(in_w/2)*2:floor(in_h/2)*2'",
StringJoin[prefix, "/", prefix, ".mp4"]
}];
(* create a pallete.png from the mp4 for the next step in gif \
creation *)
RunProcess[{
"ffmpeg",
"-i", StringJoin[prefix, "/", prefix, ".mp4"],
"-filter_complex", "[0:v] palettegen",
StringJoin[prefix, "/palette.png"]
}];
(* create a gif going back over the original images,
but now using the color palette produced from the mp4 *)
RunProcess[{
"ffmpeg",
"-f", "image2",
"-framerate", ToString @framerate,
"-i", StringJoin[prefix, "/%", ToString @ digits, "d.png"],
"-i", StringJoin[prefix, "/palette.png"],
"-filter_complex", "[0:v][1:v] paletteuse",
StringJoin[prefix, "/", prefix, ".gif"]
}]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment