The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Auto-sort images by dominant color

Auto-sorting images by dominant color involves analyzing each image to determine its primary color and then organizing the images based on those color values. Here’s a step-by-step outline of how to do this programmatically using Python:


Requirements

Install the necessary libraries:

bash
pip install opencv-python pillow numpy scikit-learn

Python Script to Auto-Sort Images by Dominant Color

python
import os import shutil import numpy as np from PIL import Image from sklearn.cluster import KMeans # Configuration input_folder = 'images' # Folder with unsorted images output_folder = 'sorted_images' # Destination folder def get_dominant_color(image_path, k=4, resize=150): image = Image.open(image_path) image = image.resize((resize, resize)) # Resize for faster processing data = np.array(image).reshape(-1, 3) # Flatten image to RGB pixels kmeans = KMeans(n_clusters=k) kmeans.fit(data) colors = kmeans.cluster_centers_ labels = kmeans.labels_ counts = np.bincount(labels) dominant = colors[np.argmax(counts)] return tuple(map(int, dominant)) def color_to_hex(color): return "#{:02x}{:02x}{:02x}".format(*color) def sort_images_by_color(input_dir, output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir) for filename in os.listdir(input_dir): if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')): file_path = os.path.join(input_dir, filename) try: dominant_color = get_dominant_color(file_path) color_hex = color_to_hex(dominant_color) color_folder = os.path.join(output_dir, color_hex) if not os.path.exists(color_folder): os.makedirs(color_folder) shutil.copy(file_path, os.path.join(color_folder, filename)) print(f"Sorted {filename} -> {color_hex}") except Exception as e: print(f"Failed to process {filename}: {e}") # Run sort_images_by_color(input_folder, output_folder)

What This Script Does

  • Analyzes each image for dominant color using KMeans clustering.

  • Converts that color to a hexadecimal string.

  • Creates folders named by color (like #aabbcc) and copies the images there.


Tips

  • You can group colors further by rounding or mapping to standard color names.

  • Add cv2 for more preprocessing (e.g., color space conversion to HSV if needed).

  • If working with a large dataset, consider optimizing the resizing and clustering for speed.

Let me know if you want this adapted into a GUI app or CLI tool.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About