LoginSignup
4
2

More than 5 years have passed since last update.

Rubyで画像をアニメ風に変換する

Posted at

動機

以下の記事に触発され、同じことをRubyで実装してみました。
画像処理で写真をアニメ風に変換する

ソースコード

animated_pict.rb
#!/usr/bin/env ruby

require 'rmagick'

def distance(first,second)
  first_f = first.map{|num| num.to_f} # 要素を実数に変換
  second_f = second.map{|num| num.to_f} # 要素を実数に変換
  first_f.zip(second_f).map{|f,s| (f-s)**2}.inject(:+)**(0.5)
end

color_set = [
  [0,0,0], [65535,65535,65535], [32768,0,0], [65535,0,0],
  [32768,32768,0], [65535,65535,0], [0,32768,0], [0,65535,0],
  [0,32768,32768], [0,65535,65535], [0,0,32768], [0,0,65535],
  [32768,0,32768], [65535,0,65535]
]

img = Magick::ImageList.new("pict.png")
img.rows.times do |row|
  img.columns.times do |column|
    pixel = img.pixel_color(column,row)
    distances = color_set.map{|color| distance(color, [pixel.red, pixel.green, pixel.blue])}
    color_hash = distances.zip(color_set).to_h
    min_dis_color = color_hash[distances.min] # 距離が一番近い色を取り出す
    new_color = Magick::Pixel.new(min_dis_color[0],min_dis_color[1],min_dis_color[2])
    img.pixel_color(column,row,new_color)
  end
end

img.write("animated_pict.png")

実行結果

元の画像
fruit.jpg

処理したあとの画像
anime_fruit.jpg

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2