Dora Kuflu
Dora Kuflu

Reputation: 61

Sort RGB Colors Uniformly in Python

I have a piece of code that finds the most dominant colors in an image and returns them as RGB values. I try to sort them so I can create a gradient image but they don't sort properly.

img = Image.open(r'C:\Users\Dora\Projects\Python\Album-Gradient\{}'.format(filename))
palette = dominant_colors(img) #getting dominant rgb values
palette.sort(key=lambda rgb: colorsys.rgb_to_hsb(*rgb))
print(palette) #printing sorted rgb values as a list
#then I convert them into a gradient image

Here's the gradient image I get.

As you can see there's dark yellow before black.

As you can see there's dark yellow before black. The colors don't sort uniformly and there are noise in the gradient. How can I sort the RGB values so it goes from black to the colors of the rainbow to white, or white to the colors of the rainbow to black?

(Something like black=>grey=>dark colors=>light colors=>white)

EDIT1: Here's the link to the full code: GitHub Repo Also, the gradient always consists of 5 colors if that helps.

Upvotes: 2

Views: 1358

Answers (1)

Dora Kuflu
Dora Kuflu

Reputation: 61

Sorting them according to their "lightness" value after converting them to HSL solved the problem.

Upvotes: 3

Related Questions