Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Analyze an image for the 10 most common colors and their percentage.
require 'RMagick'
include Magick
puts "Enter the path to the image you wish to analyze:"
file = gets.chomp
image =
q = image.quantize(10, Magick::RGBColorspace)
palette = q.color_histogram.sort {|a, b| b[1] <=> a[1]}
total_depth = image.columns * image.rows
results = []
10.times do |i|
unless palette[i].nil?
p = palette[i]
r = p[0].red / 257
g = p[0].green / 257
b = p[0].blue / 257
rgb = "#{r},#{g},#{b}"
hex = r.to_s(16) + g.to_s(16) + b.to_s(16)
depth = p[1]
results << {
rgb: rgb,
hex: hex,
depth: depth
print "\n\nImage Color Analysis for: #{file}"
print "\n-------------------------------"
results.each do |r|
print "\nRGB Value: #{r[:rgb]}"
print "\nHex Value: ##{r[:hex]}"
print "\nPercentage: " + ((r[:depth].to_f / total_depth.to_f) * 100).round(2).to_s
print "\n-------------------------------"
print "\n\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment