Skip to content

Instantly share code, notes, and snippets.

@jazzyjackson
Last active May 30, 2020 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jazzyjackson/44299bb553b84ffcb649c89ce0fa5fed to your computer and use it in GitHub Desktop.
Save jazzyjackson/44299bb553b84ffcb649c89ce0fa5fed to your computer and use it in GitHub Desktop.
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