Skip to content

Instantly share code, notes, and snippets.

@retro
Created October 2, 2010 16:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save retro/607766 to your computer and use it in GitHub Desktop.
Save retro/607766 to your computer and use it in GitHub Desktop.
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}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment