<-- Home

Ruby版的badapple!

以前写过一个C++版的,可以在我的博客园那里看到……
还是一样的套路,先用ffmpeg将视频截取成位图序列,然后根据图像每一像素的灰度值用相应的字符替换

ffmpeg -i badapple.mp4 -r 8 -vcodec bmp ./p/%04d.bmp

然后我使用了rmagick来处理图像,将ffmpeg截取的1754张图像转化成字符画存入一个文本文件中

require 'rubygems'  
require 'rmagick'  

characters = "@#$%&BAQGDOcexo~*^+-'. "
len = characters.length
$img
def GetColor x, y, w, h
  r = 0
  g = 0
  b = 0
  0.upto(w - 1) do |i|
    if(i + x < $img.columns)
      0.upto(h - 1) do |j|
        if(j + y < $img.rows)
          color =  $img.pixel_color(x + i,y + j)
          r += color.red / 257
          g += color.green / 257
          b += color.blue / 257
        end
      end
    end
  end
  [r / (w * h), g / (w * h), b / (w * h)]
end

file = File.new("badapple.txt","w")

1.upto(1754) do |id|
  $img =  Magick::Image.read("p/%04d.bmp" % id )[0]
  0.step($img.rows - 1, 12) do |i|
    0.step($img.columns - 1, 6) do |j|
      bri = 0
      GetColor(j, i, 12, 6).each { |x| bri += x }
      bri =  bri / 3
      span = 255 / len
      cidx = bri / span
      cidx -= 1 if cidx == len
      file.print characters[cidx]
    end
  file.print "\n"
  end
end

接下来就是播放了

file = File.open("badapple.txt","r")
while !file.eof? do 
  1.upto(32) do
    puts file.gets 
    end
    sleep 1.0 / 8
  puts `clear`
end
file.close

下面是效果,截取了5秒
rubybadapple.gif