Finding the closest color using hex-codes

Viewed 26

A few days ago, I created a small color comparing program here. Now I'm trying to make it nicer and better, but I can't get it to return anything. It should take in a hex code and compare it to my excising list of hex codes to find the closest value. I'm new to Python, I can't see what I'm doing wrong, it's not crashing eighter. Currently just to get the algorithm working, the input_hex is just hardcoded.

import math

def compare(input_hex: str, colors: str) -> str:    
    colors = [
  '#FFFCF2',
  '#08112C',
  '#646206',
  '#82130D',
  '#674246',
  '#ED5A06',
  '#E28819',
  '#FAE300',
  '#7FB72E',
  '#005D44',
  '#115D78',
  '#005A98',
  '#223D53',
  '#421D10',
  '#B2470E',
  '#88564E',
  '#800919',
  '#D60075',
  '#E59300',
]

    input_hex = '#900919'
    color_distance_list = []

    input_color = tuple(int(input_hex.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))

    for i in range (len(colors)):
        use_color = colors[i]
        my_color = tuple(int(use_color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
        get_distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(my_color, input_color)])) 
        colors.append(get_distance)

    sorted_color_distance_list = min(color_distance_list)
    closest_hex = color_distance_list.index(sorted_color_distance_list)

   
    return print("closest color hex is: ", closest_hex)
1 Answers

Got it working.

import math

def compare(input_hex: str) -> str:    
    colors = [
  '#FFFCF2',
  '#08112C',
  '#646206',
  '#82130D',
  '#674246',
  '#ED5A06',
  '#E28819',
  '#FAE300',
  '#7FB72E',
  '#005D44',
  '#115D78',
  '#005A98',
  '#223D53',
  '#421D10',
  '#B2470E',
  '#88564E',
  '#800919',
  '#D60075',
  '#E59300',
]

    color_distance_list = []

    input_color = tuple(int(input_hex.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))

    for i in range (len(colors)):
        use_color = colors[i]
        my_color = tuple(int(use_color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
        get_distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(my_color, input_color)])) 
        color_distance_list.append(get_distance)

    sorted_color_distance_list = min(color_distance_list)
    closest_hex = color_distance_list.index(sorted_color_distance_list)

   
    return print("closest color hex is: ", colors[closest_hex])

compare('#905919')
Related