Last active
December 13, 2015 17:38
-
-
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
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
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