Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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}
Add Comment
Please, Sign In to add comment