Skip to content

Instantly share code, notes, and snippets.

@waffleau
waffleau / extract_dominant_colors.rb
Last active March 27, 2024 10:22
Extract dominant colours from an image in Ruby using MiniMagick
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