Create a gist now

Instantly share code, notes, and snippets.

require 'rubygems'
require 'rmagick'
require 'color_namer'
img ='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
colors_hash[shade] += frequency.to_i
quantized.destroy! # prevent memory leaks
# normalize color frequency to percentage
sum = colors_hash.inject(0){ |s,c| s + c.last.to_i }.to_f{ |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