I have an array of RGBA values that looks something like this:
# Not all elements are [0, 0, 0, 0]
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
...,
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
I also have a function which returns one of 5 values that a certain RGBA value is closest to (green, red, orange, brown, white).
def closest_colour(requested_colour):
min_colours = {}
for key, name in webcolors.CSS3_HEX_TO_NAMES.items():
if name in ['green', 'red', 'orange', 'brown', 'white']:
r_c, g_c, b_c = webcolors.hex_to_rgb(key)
rd = (r_c - requested_colour[0]) ** 2
gd = (g_c - requested_colour[1]) ** 2
bd = (b_c - requested_colour[2]) ** 2
min_colours[(rd + gd + bd)] = name
return min_colours[min(min_colours.keys())]
I'd like to apply this function to each element of my numpy array and change those elements. I tried doing it this way:
img_array[closest_colour(img_array) == 'green'] = (0, 255, 0, 1)
img_array[closest_colour(img_array) == 'red'] = (255, 0, 0, 1)
img_array[closest_colour(img_array) == 'brown'] = (92, 64, 51, 1)
img_array[closest_colour(img_array) == 'orange'] = (255, 165, 0, 1)
img_array[closest_colour(img_array) == 'white'] = (255, 255, 255, 0)
but I get an error:
TypeError: unhashable type: 'numpy.ndarray'
I am aware of why this error occurs but I also don't know a different way to do this efficiently.
Is there a way to do this efficiently as I'm working with a fairly large array (image)?