I’m currently working on a photography website project. Something I wanted to explore was how much data it is possible to extract from a simple set of photos, with the potential to later use this data for various visualizations.

Dribble — a website for designers to post views of their latest works — displays a colour palette of the most common colours for each image. These images can then be used as a tag for users to browse images by color.

This seems like a very useful piece of data to maintain for images and it’s possible with RMagick.

Implementation

To return the n most common colors in hex format, providing the filesystem path of the image:

def top_colors(image_path, n=8)
  image = Magick::Image.read(image_path).first
  colors = []
  quantized = image.quantize(n, Magick::RGBColorspace)
  palette = quantized.color_histogram.sort {|a, b| b[1] <=> a[1]}

  palette.length.times.each do |i|
    c = palette[i][0].to_s.split(',').map {|x| x[/\d+/]}
    c.pop
    c[0], c[1], c[2] = [c[0], c[1], c[2]].map { |s|
      s = s.to_i
      if s / 255 > 0
        s = s / 255
      end
      s = s.to_s(16)
      if s.size == 1
        '0' + s
      else
        s
      end
    }
    colors << '#' + c.join('')
  end
end