Reputation: 129
I want to convert a color either in RGB/Hex format to its nearest web-safe color.
Details about a websafe color can be found here: http://en.wikipedia.org/wiki/Web_safe_color
This website(http://www.colortools.net/color_make_web-safe.html) is able to do the way I want to, but I am not sure how to go about it in Python. Can anyone help me out here?
Upvotes: 5
Views: 6616
Reputation: 9418
Despite being somewhat of a misnomer, the web safe color palette is indeed quite useful for color quantization. It's simple, fast, flexible, and ubiquitous. It also allows for RGB hex shorthand such as #369
instead of #336699
. Here's a walkthrough:
00, 33, 66, 99, CC, FF
. So we can divide the max RGB value 255
by five (one less than the total possible values) to get a multiple value, 51
.255
(this makes it a value from 0-1
instead of 0-255
).5
, and round the result to make sure it stays exact.Multiply by 51
to get the final web safe value. All together, this looks something like:
def getNearestWebSafeColor(r, g, b):
r = int(round( ( r / 255.0 ) * 5 ) * 51)
g = int(round( ( g / 255.0 ) * 5 ) * 51)
b = int(round( ( b / 255.0 ) * 5 ) * 51)
return (r, g, b)
print getNearestWebSafeColor(65, 135, 211)
No need to go crazy comparing colors or creating huge lookup tables, as others have suggested. :-)
Upvotes: 9
Reputation: 404
import scipy.spatial as sp
input_color = (100, 50, 25)
websafe_colors = [(200, 100, 50), ...] # list of web-save colors
tree = sp.KDTree(websafe_colors) # creating k-d tree from web-save colors
ditsance, result = tree.query(input_color) # get Euclidean distance and index of web-save color in tree/list
nearest_color = websafe_colors[result]
Or add loop for several input_color
s
About k-dimensional tree
Upvotes: 2