Skip to content

Instantly share code, notes, and snippets.

@kulmajaba
Last active September 26, 2022 10:19
Show Gist options
  • Save kulmajaba/e42971afe6248e227d8c243462b12dea to your computer and use it in GitHub Desktop.
Save kulmajaba/e42971afe6248e227d8c243462b12dea to your computer and use it in GitHub Desktop.
Python script to sort and display a list of colors
import numpy as np
from PIL import Image, ImageColor
from colorir import hue_sort_key
with open('colors hexed.txt', 'r') as file:
lines = file.readlines()
colors_sorted = [line.rstrip() for line in lines]
# The alphabetical sort helps grayscale values greatly
colors_sorted.sort()
colors_sorted.sort(key=hue_sort_key())
# Optionally save the sorted list in a file
# with open('colors sorted.txt', 'w') as w:
# w.write('\n'.join(colors_sorted))
# Convert hex codes to rgb values and create a numpy array
# The type needs to be np.uint8 for the plot to work
barColors = [ImageColor.getrgb(hex) for hex in colors_sorted]
barColors = (np.array(barColors)).astype(np.uint8)
# Create color Array
cols = len(barColors)
rows = cols // 32
barFullData = np.tile(barColors, (rows,1)).reshape(rows, cols, 3)
# Create Image from Array and enlarge
barImg = Image.fromarray(barFullData, 'RGB')
barImg = barImg.resize((cols*3, rows*3), Image.Resampling.NEAREST)
barImg.save("eTasku colors sorted.png")
barImg.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment