Created
June 14, 2018 10:19
-
-
Save Lirimy/4d39643abccc519e21c77d261c0b6079 to your computer and use it in GitHub Desktop.
Zebrafish
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SimpleAnimation | |
# | |
# This code is licensed under MIT license. | |
# Copyright (C) 2018 Lirimy | |
# | |
# This code contains copy and modification of Plots.jl. | |
# Plots.jl: Copyright (c) 2015: Thomas Breloff. | |
# | |
# *** Requirements *** | |
# | |
# Plots.jl | |
# Imagemagick.jl ? | |
# ffmpeg | |
# | |
# *** How to use *** | |
#= | |
include("SimpleAnimation.jl") | |
using SimpleAnimation | |
import Colors: Gray | |
import Plots: gif, mp4, frame | |
anim = SimpleAnim() | |
@time for i in 1:60 | |
img = Gray.(rand(240, 320)) | |
frame(anim, img) | |
end | |
mp4(anim, "anim.mp4") | |
=# | |
__precompile__(true) | |
module SimpleAnimation | |
import ColorTypes: Color | |
import FileIO: save | |
using Plots | |
export | |
SimpleAnim | |
struct SimpleAnim | |
dir::String | |
frames::Vector{Int} | |
end | |
function SimpleAnim() | |
tmpdir = convert(String, mktempdir()) | |
SimpleAnim(tmpdir, []) | |
end | |
struct AnimatedFile | |
filename::String | |
end | |
function Plots.frame(anim::SimpleAnim, img::Array{T, 2}) where T<:Color | |
i = length(anim.frames) + 1 | |
filename = @sprintf("%06d.bmp", i) | |
save(joinpath(anim.dir, filename), img) | |
push!(anim.frames, i) | |
end | |
file_extension(fn) = Base.Filesystem.splitext(fn)[2][2:end] | |
function Plots.mp4(anim::SimpleAnim, fn="out.mp4") | |
fn = abspath(fn) | |
run(`ffmpeg -v 0 -framerate 30 -i $(anim.dir)/%06d.bmp -y -vcodec libx264 -pix_fmt yuv420p $fn`) | |
AnimatedFile(fn) | |
end | |
function Plots.gif(anim::SimpleAnim, fn="out.gif") | |
fn = abspath(fn) | |
# generate a colorpalette first so ffmpeg does not have to guess it | |
run(`ffmpeg -v 0 -i $(anim.dir)/%06d.bmp -vf "palettegen=stats_mode=diff" -y "$(anim.dir)/palette.bmp"`) | |
# then apply the palette to get better results | |
run(`ffmpeg -v 0 -framerate 30 -loop 0 -i $(anim.dir)/%06d.bmp -i "$(anim.dir)/palette.bmp" -lavfi "paletteuse=dither=sierra2_4a" -y $fn`) | |
AnimatedFile(fn) | |
end | |
function Base.show(io::IO, ::MIME"text/html", afile::AnimatedFile) | |
ext = file_extension(afile.filename) | |
write(io, if ext == "gif" | |
"<img src=\"$(relpath(afile.filename))?$(rand())>\" />" | |
elseif ext == "mp4" | |
"<video controls><source src=\"$(relpath(afile.filename))?$(rand())>\" type=\"video/$ext\"></video>" | |
end) | |
end | |
end # module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment