Dominant colours from images using MiniMagic

I have lately been playing around with images in Ruby using ImageMagick and I wanted to extract the common colours from a picture. ImageMagick can do this out of the box but the gem in ruby which wraps it, MiniMagic, does not expose the right features. Devishot has created a basic extension for MiniMagic, wrapping the functionality into a new method. I have extended the method from their implementation

  • Method now asks for how many colours it should return
  • The output is now an array of the major colours. Each array element is a hash that splits apart the colour information to make it easier to use.
module MiniMagick
  class Image
    def get_dominant_color(number_of_colors)
      colors = run_command("convert", path, "-format", "%c\n",  "-colors", number_of_colors, "-depth", 8, "histogram:info:").split("\n").map {|c| c.gsub(/[\s]+/, "") }
      colors = colors.map {|c| c.match(/(?<count>[0-9]+):\((?<r>[0-9]+),(?<g>[0-9]+),(?<b>[0-9]+)[,]*(?<alpha>[0-9]*)\)(?<hex>#[0-9A-F]+)/) }
      return colors.map {|c| 
        {
          count:  c[:count].to_i,
          r:      c[:r].to_i,
          g:      c[:g].to_i,
          b:      c[:b].to_i,
          hex:    c[:hex]
        }
      }
    end
  end
end
comments powered by Disqus