Color Palette Generator

 from PIL import Image

from sklearn.cluster import KMeans

import numpy as np

import matplotlib.pyplot as plt


def extract_colors(image_path, num_colors=5):

    """

    Extracts dominant colors from an image.


    Args:

        image_path (str): Path to the image file.

        num_colors (int): Number of dominant colors to extract.


    Returns:

        List of RGB tuples representing the dominant colors.

    """

    try:

        # Open the image and resize it for faster processing

        image = Image.open(image_path)

        image = image.resize((200, 200))  # Resize for faster processing

        image_array = np.array(image)


        # Reshape the image array to a 2D array of pixels

        pixels = image_array.reshape(-1, 3)


        # Apply KMeans clustering to find dominant colors

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

        kmeans.fit(pixels)


        # Extract cluster centers (dominant colors)

        colors = kmeans.cluster_centers_.astype(int)

        return colors

    except Exception as e:

        print(f"Error: {e}")

        return []


def display_palette(colors):

    """

    Displays the color palette using matplotlib.


    Args:

        colors (list): List of RGB tuples representing colors.

    """

    if colors is None or len(colors) == 0:

        print("No colors to display.")

        return


    # Create a palette image

    palette = np.zeros((50, len(colors) * 50, 3), dtype=np.uint8)

    for i, color in enumerate(colors):

        palette[:, i * 50:(i + 1) * 50, :] = color


    # Display the palette

    plt.imshow(palette)

    plt.axis("off")

    plt.show()



def main():

    print("Welcome to the Color Palette Generator!")

    image_path = input("Enter the path to the image file: ")

    num_colors = input("Enter the number of colors to extract (default is 5): ")

    num_colors = int(num_colors) if num_colors.isdigit() else 5


    print("\nExtracting colors...")

    colors = extract_colors(image_path, num_colors)


    if len(colors) > 0:

        print("Dominant colors (RGB):")

        for i, color in enumerate(colors, 1):

            print(f"{i}: {tuple(color)}")

        display_palette(colors)


if __name__ == "__main__":

    main()


No comments: