Posted By

kellishaver on 01/10/12


Tagged

images color imagemagick rmagick palette extract


Versions (?)

Extract most common colors from an image


 / Published in: Ruby
 

Takes an image (path or url) and extracts the 7 most common colors and returns their hex values.

  1. def extract_colors(src)
  2. image = Magick::ImageList.new(src)
  3. colors = []
  4. q = image.quantize(7, Magick::RGBColorspace)
  5. palette = q.color_histogram.sort {|a, b| b[1] <=> a[1]}
  6.  
  7. (0..6).each do |i|
  8. c = palette[i].to_s.split(',').map {|x| x[/\d+/]}
  9. c.pop
  10. c[0], c[1], c[2] = [c[0], c[1], c[2]].map { |s|
  11. s = s.to_i
  12. if s / 255 > 0 # not all ImageMagicks are created equal....
  13. s = s / 255
  14. end
  15. s = s.to_s(16)
  16. if s.size == 1
  17. '0' + s
  18. else
  19. s
  20. end
  21. }
  22. colors << '#' + c.join('')
  23. end
  24.  
  25. return colors
  26. end

Report this snippet  

You need to login to post a comment.