Last active
March 31, 2024 19:05
-
-
Save pointofpresence/f03e6b9d1ad607eefb835c64ccded22b to your computer and use it in GitHub Desktop.
python color functions
This file contains hidden or 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
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