Skip to content

Instantly share code, notes, and snippets.

@pointofpresence
Last active March 31, 2024 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pointofpresence/f03e6b9d1ad607eefb835c64ccded22b to your computer and use it in GitHub Desktop.
Save pointofpresence/f03e6b9d1ad607eefb835c64ccded22b to your computer and use it in GitHub Desktop.
python color functions
import math
# Function to Parse Hexadecimal Value
def parse_hex_color(string):
if string.startswith("#"):
string = string[1:]
r = int(string[0:2], 16) # red color value
g = int(string[2:4], 16) # green color value
b = int(string[4:6], 16) # blue color value
return r, g, b, 255
# Calculate distance btw two color
def color_similarity(base_col_val,oth_col_val):
return math.sqrt(sum((base_col_val[i]-oth_col_val[i])**2 for i in range(3)))
base_color = "#ff0000"
color_list = ["#467829", "#4587ab", "#1628cd", "#278bad"]
# Max intial value
r = 1000
# Code for finding out minimum distance
for x in color_list:
if color_similarity(parse_hex_color(base_color),parse_hex_color(x))<r:
r,rs=color_similarity(parse_hex_color(base_color),parse_hex_color(x)),x
print("Most similar color inside the list is ", rs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment