Last active
March 27, 2024 10:22
-
-
Save waffleau/6e074573d4bece3f7a007ed8536512b5 to your computer and use it in GitHub Desktop.
Extract dominant colours from an image in Ruby using MiniMagick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def self.extract_dominant_colors(image_path, quantity=5, threshold=0.01) | |
image = MiniMagick::Image.open(image_path) | |
# Get image histogram | |
result = image.run_command('convert', image_path, '-format', '%c', '-colors', quantity, '-depth', 8, 'histogram:info:') | |
# Extract colors and frequencies from result | |
frequencies = result.scan(/([0-9]+)\:/).flatten.map { |m| m.to_f } | |
hex_values = result.scan(/(\#[0-9ABCDEF]{6,8})/).flatten | |
total_frequencies = frequencies.reduce(:+).to_f | |
# Create frequency/color pairs [frequency, hex], | |
# sort by frequency, | |
# ignore fully transparent colours | |
# select items over frequency threshold (1% by default), | |
# extract hex values, | |
# return desired quantity | |
frequencies | |
.map.with_index { |f, i| [f / total_frequencies, hex_values[i]] } | |
.sort { |r| r[0] } | |
.reject { |r| r[1].end_with?('FF') } | |
.select { |r| r[0] > threshold } | |
.map { |r| r[1][0..6] } | |
.slice(0, quantity) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't it reject values ending in
00
instead ofFF
?