public
Last active

  • Download Gist
extract_colors_from_image.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
require 'rubygems'
require 'rmagick'
require 'color_namer'
 
 
img = Magick::ImageList.new('photo.jpg')
 
img.resize_to_fit!(500) # resize the image to have faster quantization
quantized = img.quantize(16) # quantize the photo to reduce number of colors
img.destroy! # prevent memory leaks
 
colors_hash = {}
quantized.color_histogram.each_pair do |pixel, frequency| # grab list of colors and frequency
shade = ColorNamer.name_from_html_hash(
pixel.to_color(Magick::AllCompliance, false, 8, true)
).last # get shade of the color
# group the colors by shade
if colors_hash[shade].nil?
colors_hash[shade] = frequency.to_i
else
colors_hash[shade] += frequency.to_i
end
end
 
quantized.destroy! # prevent memory leaks
 
# normalize color frequency to percentage
 
sum = colors_hash.inject(0){ |s,c| s + c.last.to_i }.to_f
colors_hash.map{ |c| c[1] = (c.last.to_f / sum * 100).round; c }.inject({}){ |h,c| h[c[0]] = c[1]; h }
# returns {"Blue"=>19, "Green"=>39, "Brown"=>22, "Yellow"=>12, "Grey"=>8}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.