class Color
attr_reader :R, :G, :B
def initialize(r = rand(256), g = rand(256), b = rand(256))
@R = r
@G = g
@B = b
end
def inspect
return "{R: #{@R}, G: #{@G}, B: #{@B}}"
end
end
def get_colors(image_input, need_num)
regions = [image_input.flatten]
while regions.size < need_num
new_regions = []
regions.each do |region|
max_color = [:R, :G, :B].map do |color|
colors = region.map(&color)
next [colors.max - colors.min, color]
end.max[1]
new_order = region.sort_by(&max_color).reverse
middle = new_order.size / 2
new_regions.push(new_order[0, middle], new_order[middle, middle + 1])
end
regions = new_regions
end
return regions.map do |region|
Color.new(*[:R, :G, :B].map{|color| (region.map(&color).inject(&:+) / region.size.to_f).round })
end
end
get_colors(Array.new(10){ Array.new(10){ Color.new } }, 16)
# => [{ R: 187, G: 226, B: 184 }, { R: 185, G: 169, B: 189 }, ...]