Blog Pages

Smart Image Color Palette Extractor

import cv2

import numpy as np

from sklearn.cluster import KMeans

from tkinter import Tk, filedialog

from PIL import Image

import matplotlib.pyplot as plt


def rgb_to_hex(rgb):

    """Convert RGB tuple to HEX string."""

    return "#{:02x}{:02x}{:02x}".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))


def extract_colors(image_path, num_colors=6):

    """Extract dominant colors from an image using KMeans clustering."""

    # Read and convert image

    image = cv2.imread(image_path)

    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    

    # Reshape image data for clustering

    pixels = image.reshape((-1, 3))

    pixels = np.float32(pixels)


    # Apply K-Means

    kmeans = KMeans(n_clusters=num_colors, random_state=42)

    kmeans.fit(pixels)

    

    colors = np.round(kmeans.cluster_centers_).astype(int)

    return colors


def display_palette(colors):

    """Display color palette using matplotlib."""

    plt.figure(figsize=(10, 2))

    plt.axis("off")


    # Create palette blocks

    for i, color in enumerate(colors):

        plt.subplot(1, len(colors), i + 1)

        plt.imshow(np.ones((100, 100, 3), dtype=np.uint8) * np.uint8(color))

        plt.title(rgb_to_hex(color), fontsize=10)

        plt.axis("off")


    plt.tight_layout()

    plt.show()


def main():

    # GUI File Picker

    root = Tk()

    root.withdraw()

    image_path = filedialog.askopenfilename(title="Select an Image",

                                            filetypes=[("Image Files", "*.jpg *.jpeg *.png *.bmp")])

    if not image_path:

        print("❌ No file selected.")

        return


    print(f"šŸ“ø Analyzing: {image_path}")

    colors = extract_colors(image_path, num_colors=6)

    

    print("\nšŸŽØ Dominant Colors:")

    for color in colors:

        print(f"RGB: {tuple(color)} | HEX: {rgb_to_hex(color)}")


    # Show palette visually

    display_palette(colors)


if __name__ == "__main__":

    main()


No comments:

Post a Comment