Skip to content

Instantly share code, notes, and snippets.

@pokotyamu
Last active September 12, 2016 01:18
Show Gist options
  • Save pokotyamu/8a553fe1ecb1fb4f0e5750dc0bfb4127 to your computer and use it in GitHub Desktop.
Save pokotyamu/8a553fe1ecb1fb4f0e5750dc0bfb4127 to your computer and use it in GitHub Desktop.
画像の色から一番使われているやつで枠を作る
require 'RMagick' # require してライブラリを読み込み
require 'pp'
path = 'test.png'
image = Magick::Image.read("./images/#{File.basename(path)}").first
img = image.resize_to_fit(200,200)
# 画像内で使用されている色の一覧を集計
histogram = img.color_histogram.inject({}) {|h, pair|
color = pair[0].to_color( Magick::AllCompliance, false, 16, true )
h[color] ||= 0
h[color] += pair[1]
h
}.sort_by { |pair| pair[1] * -1 }
#割合を算出
pixel_count = img.rows * img.columns
histogram = histogram.map {|i|
{:color=>i[0], :rate=>(i[1].to_f/pixel_count*10000).to_i/100.0 }
}.reject {|i| i[:rate] <= 0 } # 0.01%未満は除外
# 枠作り
org_width = image.columns > 600 ? image.columns : 600
org_hight = image.rows > 600 ? image.rows : 600
convert_image = Magick::Image.new(org_width, org_hight){
self.background_color = histogram.first[:color]
}
width = (org_width - image.columns) / 2
hight = (org_hight - image.rows) / 2
convert_image.composite!(image, width, hight, Magick::OverCompositeOp)
convert_image.write("convert_#{File.basename(path)}")
#後処理
image.destroy!
convert_image.destroy!
#色の一覧を表示
# histogram.each {|color|
# puts "#{color[:color]} : #{color[:rate]}%"
# }
# image = Magick::ImageList.new('./images/sample.jpeg').first.resize_to_fit(200,200)
# pixels = image.get_pixels(0, 0, image.columns, image.rows)
# puts pixels.size
# puts pixels[0].red # 赤(色のビット数によって 0 ~ 255, 65535, 4294967295, 上限は 2 ** Magick::QuantumDepth で求められる。)
# puts pixels[0].green # 緑
# puts pixels[0].blue # 青
# puts pixels[0].to_hsla # [色相, 彩度, 明度, 透明度]
# #new_image = image.blur_image(20.0, 10.0)
# image.write('./images/convert.jpeg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment