Skip to content

Instantly share code, notes, and snippets.

@t-kashima
Created September 16, 2013 23:04
Show Gist options
  • Save t-kashima/6587821 to your computer and use it in GitHub Desktop.
Save t-kashima/6587821 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
class Colors
def Colors.getArrayFromString(str, num)
colors = str.unpack(("a" + num.to_s) * (str.length / 2))
colors = colors.collect{|color|
color.hex
}
return colors
end
def Colors.getRGB2HSB(rgb)
# #の削除
rgb = rgb.sub(/#/, "")
# 文字列をRGBのそれぞれに分割
colors = getArrayFromString(rgb, 2)
# RGB => HSB に変換する
# Hへの変換
h = nil
if (colors.max - colors.min) == 0 then
h = 0
else
h = (colors.max - colors[0]) / (colors.max - colors.min).to_f * 60
+ 60
end
# Sへの変換
s = nil
if colors.max == 0 then
s = 0
else
s = (colors.max - colors.min) / colors.max.to_f * 255
end
# Bへの変換
b = colors.max
return [h, s, b]
end
def Colors.distance(color1, color2)
array = []
color1.each_with_index{|v, i|
ratio = (color1[i] - color2[i]).abs / 255.to_f
distance = 1 - ratio
array.push(distance)
}
return array
end
def Colors.distanceForRGB(color1, color2)
return distance(getRGB2HSB(color1), getRGB2HSB(color2))
end
end
# -*- coding: utf-8 -*-
require './Colors'
color1 = "#FF0000"
color2 = "#0000FF"
distances = Colors.distanceForRGB(color1, color2)
p distances
puts "色の類似度:" + distances.inject(:*).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment