Skip to content

Instantly share code, notes, and snippets.

@ckolderup
Created March 28, 2017 17:52
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 ckolderup/c02c002d2a4f2d3536227e80432aa933 to your computer and use it in GitHub Desktop.
Save ckolderup/c02c002d2a4f2d3536227e80432aa933 to your computer and use it in GitHub Desktop.
def self.generate_video(file,idx)
ipl_image = IplImage::load(file.path)
rm_image = Image.read(file.path).first
op = CvHaarClassifierCascade::load('haarcascade_frontalface_alt.xml')
chosen = op.detect_objects(ipl_image).to_a.sample
raise "no face found" if chosen.nil?
face_center_x = chosen.center.x
face_center_y = chosen.center.y
height = rm_image.rows
width = rm_image.columns
og_height = height
og_width = width
avg_scale_factor = 50 * ((chosen.width.to_f / width) + (chosen.height.to_f / height) / 2)
step = [avg_scale_factor / 300, 0.0005].max
if height > width
height = [600, height + (height % 2)].min
width = (width.to_f * height.to_f / og_height).to_i
width = width + (width % 2)
else
width = [800, width + (width % 2)].min
height = (height.to_f * width.to_f / og_width).to_i
height = height + (height % 2)
end
scale = "#{width}:#{height}"
out_video_path = "output/output-#{idx}.mp4"
audio_library_path = 'sounds/song1'
audio_path = Dir.glob("#{audio_library_path}/*.mp3").sample
input = "-i #{file.path}"
audio_input = "-i #{audio_path}"
vid_params = "-c:v libx264 -r 30 -pix_fmt yuvj420p"
command = "/Users/casey/bin/ffmpeg -y -loglevel fatal -loop 1 #{input} #{audio_input} #{vid_params}"
zoom_speed = step
x_comp = "'iw*#{face_center_x/og_width}-(iw/zoom/2)'"
y_comp = "'ih*#{face_center_y/og_height}-(ih/zoom/2)'"
pan = "x=#{x_comp}:y=#{y_comp}"
zoompan = "-vf \"scale=iw*2:ih*2,zoompan=z='zoom+#{zoom_speed}':d=500:#{pan},scale=#{scale}\""
duration = "-t 10"
input_map = "-map 0:0 -map 1:0"
`#{command} #{zoompan} #{duration} #{input_map} #{out_video_path}`
out_video_path
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment