Guest User

Untitled

a guest
Jun 18th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. require 'rubygems'
  2. require 'rmagick'
  3. require 'color_namer'
  4.  
  5.  
  6. img = Magick::ImageList.new('photo.jpg')
  7.  
  8. img.resize_to_fit!(500) # resize the image to have faster quantization
  9. quantized = img.quantize(16) # quantize the photo to reduce number of colors
  10. img.destroy! # prevent memory leaks
  11.  
  12. colors_hash = {}
  13. quantized.color_histogram.each_pair do |pixel, frequency| # grab list of colors and frequency
  14.  
  15. shade = ColorNamer.name_from_html_hash(
  16. pixel.to_color(Magick::AllCompliance, false, 8, true)
  17. ).last # get shade of the color
  18.  
  19. # group the colors by shade
  20.  
  21. if colors_hash[shade].nil?
  22. colors_hash[shade] = frequency.to_i
  23. else
  24. colors_hash[shade] += frequency.to_i
  25. end
  26.  
  27. end
  28.  
  29. quantized.destroy! # prevent memory leaks
  30.  
  31. # normalize color frequency to percentage
  32.  
  33. sum = colors_hash.inject(0){ |s,c| s + c.last.to_i }.to_f
  34. colors_hash.map{ |c| c[1] = (c.last.to_f / sum * 100).round; c }.inject({}){ |h,c| h[c[0]] = c[1]; h }
  35. # returns {"Blue"=>19, "Green"=>39, "Brown"=>22, "Yellow"=>12, "Grey"=>8}
Add Comment
Please, Sign In to add comment