Skip to content

Instantly share code, notes, and snippets.

@samhenrigold
Created December 8, 2023 15:48
Show Gist options
  • Save samhenrigold/f4d6be67e906f5e50d12753b75673a90 to your computer and use it in GitHub Desktop.
Save samhenrigold/f4d6be67e906f5e50d12753b75673a90 to your computer and use it in GitHub Desktop.
Turn a directory of photos into a grid of dominant colors
import os
from PIL import Image
import numpy as np
from sklearn.cluster import KMeans
def find_dominant_color(image_path):
image = Image.open(image_path)
image = image.resize((100, 100)) # Resize to speed things up
np_image = np.array(image)
np_image = np_image.reshape((np_image.shape[0] * np_image.shape[1], 3))
kmeans = KMeans(n_clusters=1, n_init=10)
kmeans.fit(np_image)
dominant_color = kmeans.cluster_centers_[0]
return dominant_color
def create_color_grid(directory, grid_size):
files = [img for img in os.listdir(directory) if img.endswith(('.png', '.jpg', '.jpeg'))]
grid = Image.new('RGB', (grid_size, grid_size), color = 'white') # Create a white canvas
x = y = 0
for file in files:
dominant_color = find_dominant_color(os.path.join(directory, file))
grid.putpixel((x, y), tuple(int(c) for c in dominant_color))
x += 1
if x == grid_size:
x = 0
y += 1
if y == grid_size:
break # Grid is full
grid.show() # Pops open in Preview.app or whathaveyou
# Usage
directory = '/path/to/photo/folder'
grid_size = 23 # For a 23x23 grid
create_color_grid(directory, grid_size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment