Ask Your Question

Revision history [back]

How to store these values?

Just store the raw HSV values of each colour. This would make it easier especially on finding the closest match.

In general, you have a distance minimisation problem. When the user selects their colour from the dialog box, you want to search through your database looking for a colour whose Euclidean distance is the smallest.

If we assume that a database does not exist, then your function would look something like this,

import sys

all_colours_in_hsv = [colour1, colour2, colour3, colour4, colour5]

def closest_colour(selected_colour):
    # set the distance to be a reallly big number
    # initialise closest_colour to empty
    shortest_distance, closest_colour = sys.max(), None

    # iterate through all the colours
    # for each colour in the list, find the Euclidean distance to the one selected by the user
    for colour in all_colours_in_hsv:
        # since your colours are in 3D space, perform the calculation in each respective space
        current_distance = sqrt(pow(colour.H - selected_colour.H, 2) + pow(colour.S - selected_colour.S, 2) + pow(colour.V - selected_colour.V, 2))

        # unless you truly care about the exact length, then you don't need to perform the sqrt() operation.
        # it is a rather expensive one so you can just do this instead
        # current_distance = pow(colour.H - selected_colour.H, 2) + pow(colour.S - selected_colour.S, 2) + pow(colour.V - selected_colour.V, 2)

        # update the distance along with the corresponding colour
        if current_distance < shortest_distance:
            shortest_distance = current_distance
            closest_colour = colour

    return shortest_distance, closest_colour

Since you have a database and have not told us what kind it is (MySQL, MS. Access, NoSQL etc), then it is hard to tell you exactly what you need to do but the general query would be something like

Select top 3 from table colours order by Euclidean Distance calculation