Skip to content

Instantly share code, notes, and snippets.

@kellishaver
Last active January 3, 2016 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellishaver/8430650 to your computer and use it in GitHub Desktop.
Save kellishaver/8430650 to your computer and use it in GitHub Desktop.
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 = Magick::ImageList.new(file)
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
}
end
end
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-------------------------------"
end
print "\n\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment