Created
October 20, 2025 07:28
-
-
Save Inobtenio/bd6c1c20e1af3dbafeafb4dc781d0144 to your computer and use it in GitHub Desktop.
Takes a look at an image and returns the most dominant/eye-catching color trying to mimic Spotify's way of picking a color for the lyrics background and whatnot. More info at https://inobtenio.com/posts/spotify-song-colors/.
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 | |
| import numpy as np | |
| from PIL import Image | |
| from sklearn.cluster import KMeans | |
| qC = 4.9226 | |
| qD = 1.4060 | |
| qR = 0.7932 | |
| def calculate_dark_colorfulness(rgb): | |
| red, green, blue = [x / 255.0 for x in rgb] | |
| red_greenness = red - green # or the a component | |
| yellow_blueness = (red + green)/2 - blue # or the b component. red + green output yellow in additive color (light) | |
| chroma = math.sqrt(red_greenness ** 2 + yellow_blueness ** 2) | |
| """ | |
| Choose any of these three, bascially according to preference, the output is not going to change | |
| significantly. If you care about accuracy, you're free to do some research to determine the best | |
| option for your use case. Keep in mind that the overall formula coefficients might need to change too. | |
| They're as follows: | |
| First option: the standard way of obtaining luminance from RGB coordinates but without linearizing | |
| Second option: same as the previous, but linear (removing gamma correction) | |
| Third option: Independent HSP color space "percieved brightness" (https://alienryderflex.com/hsp.html) | |
| """ | |
| # luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue # Relative luminance | |
| # luminance = 0.2126 * (red ** (1/2.2)) + 0.7152 * (green ** (1/2.2)) + 0.0722 * (blue ** (1/2.2))# Relative luminance without gamma correction | |
| luminance = math.sqrt(0.299 * (red ** 2) + 0.587 * (green ** 2) + 0.114 * (blue ** 2)) # Percieved brightness (HSP) | |
| darkness = 1 - luminance | |
| return (chroma, darkness) | |
| ### TO-DO: Implement improving picked color contrast with white, as lyrics are always white, to better match Spotify's choice | |
| def improve_white_contrast(rgb, brightness_factor=0.85, saturation_boost=1.1): | |
| red, green, blue = [x / 255 for x in rgb] | |
| hue, sat, value = colorsys.rgb_to_hsv(red, green, blue) | |
| sat = min(sat * saturation_boost, 1.0) | |
| value = max(value * brightness_factor, 0.0) # darken | |
| red, green, blue = colorsys.hsv_to_rgb(hue, sat, value) | |
| return tuple(int(x * 255) for x in (red, green, blue)) | |
| def extract_color_clusters(num_clusters): | |
| image = Image.open("./cover.jpg").convert("RGB") | |
| width, height = image.size | |
| try: | |
| pixels = np.array(image).reshape(-1, 3) # Turn a RGB matrix into an RGB 2D array | |
| # Cluster colors using K-Means | |
| kmeans = KMeans(n_clusters=num_clusters, random_state=0, n_init="auto") | |
| kmeans.fit(pixels) | |
| labels = kmeans.labels_ | |
| colors = [] | |
| # Group colors by cluster and calculate average for each | |
| clusters = [[] for _ in range(num_clusters)] | |
| for i, label in enumerate(labels): | |
| clusters[label].append(pixels[i]) | |
| for group in clusters: | |
| color = np.mean(group, axis=0) | |
| chroma, darkness = calculate_dark_colorfulness(color) | |
| dominance = len(group)/(width * height) | |
| score = chroma * qC + darkness * qD + dominance * qR | |
| colors.append({ | |
| 'color': tuple(int(c) for c in color), | |
| 'score': score, | |
| }) | |
| return colors | |
| except Exception as e: | |
| print(e) | |
| print("Black and white image?") | |
| return [{ | |
| 'color': (128,128,128), | |
| 'score': 10.0, | |
| }] | |
| def get_best_color(): | |
| return max(extract_color_clusters(20), key=lambda c: c['score']) | |
| if __name__ == '__main__': | |
| print(get_best_color()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment