Skip to content

Instantly share code, notes, and snippets.

@zarazan
Last active December 13, 2015 17:38
Show Gist options
  • Save zarazan/4949678 to your computer and use it in GitHub Desktop.
Save zarazan/4949678 to your computer and use it in GitHub Desktop.
Detect the first three primary colors from an image using the RMagick gem
require 'RMagick'
include Magick
def convert_rgb(color)
color / 257
end
def convert_pixel(pixel)
{
:r => convert_rgb(pixel.red),
:g => convert_rgb(pixel.green),
:b => convert_rgb(pixel.blue)
}
end
def is_different(pixel1, pixel2)
margin = 40
if (pixel1[:r]-pixel2[:r]).abs > 40
true
else
false
end
end
def get_colors(file_name)
image = ImageList.new(file_name)
histogram = image.color_histogram
values = histogram.sort_by{ |k, v| v }.reverse
first_color = convert_pixel(values[0][0])
second_color = nil
third_color = nil
prev_color = first_color
values.each do |value|
color = convert_pixel(value[0])
if(is_different(prev_color, color))
third_color = color if !third_color && is_different(first_color, color) && second_color
second_color = color unless second_color
prev_color = color
end
end
[first_color, second_color, third_color]
end
puts get_colors('cover.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment