Skip to content

Instantly share code, notes, and snippets.

@Olefine Olefine/dominant colors
Last active Dec 15, 2015

What would you like to do?
dominant colors
require 'RMagick'
TOP_N = 10 # Number of swatches
# Create a 1-row image that has a column for every color in the quantized
# image. The columns are sorted decreasing frequency of appearance in the
# quantized image.
def sort_by_decreasing_frequency(img)
hist = img.color_histogram
# sort by decreasing frequency
sorted = hist.keys.sort_by {|p| -hist[p]}
new_img =, 1)
new_img.store_pixels(0, 0, hist.size, 1, sorted)
def get_pix(img)
palette =
pixels = img.get_pixels(0, 0, img.columns, 1)
pixels.each do |p|
puts p.to_color(Magick::AllCompliance, false, 8, true)
original ="").first
# reduce number of colors
quantized = original.quantize(TOP_N, Magick::RGBColorspace)
# Create an image that has 1 pixel for each of the TOP_N colors.
normal = sort_by_decreasing_frequency(quantized)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.