動機
以下の記事に触発され、同じことを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")