Rubyで画像をアニメ風に変換する
動機
以下の記事に触発され、同じことを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")
実行結果
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")
Author And Source
この問題について(Rubyで画像をアニメ風に変換する), 我々は、より多くの情報をここで見つけました https://qiita.com/mataneko_boy/items/7eaf17c9d38d69aacf3a著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .