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()


Image to ASCII Art

 from PIL import Image


# Define ASCII characters for different levels of brightness

ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]


def resize_image(image, new_width=100):

    """Resizes the image while maintaining aspect ratio."""

    width, height = image.size

    aspect_ratio = height / width

    new_height = int(new_width * aspect_ratio * 0.55)  # Adjusting for terminal aspect ratio

    return image.resize((new_width, new_height))


def grayify(image):

    """Converts the image to grayscale."""

    return image.convert("L")


def pixels_to_ascii(image):

    """Maps grayscale pixel values to ASCII characters."""

    pixels = image.getdata()

    ascii_str = "".join(ASCII_CHARS[pixel // 25] for pixel in pixels)

    return ascii_str


def convert_image_to_ascii(image_path, new_width=100):

    """Main function to convert image to ASCII art."""

    try:

        image = Image.open(image_path)

    except Exception as e:

        print(f"Unable to open image file: {image_path}")

        print(e)

        return


    # Resize and process the image

    image = resize_image(image, new_width)

    image = grayify(image)


    # Convert pixels to ASCII

    ascii_str = pixels_to_ascii(image)

    img_width = image.width

    ascii_str_len = len(ascii_str)

    ascii_art = "\n".join(ascii_str[i:i + img_width] for i in range(0, ascii_str_len, img_width))


    return ascii_art


def main():

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

    width = int(input("Enter the desired width of the ASCII art (default is 100): ") or 100)

    ascii_art = convert_image_to_ascii(image_path, width)

    

    if ascii_art:

        print("\nGenerated ASCII Art:\n")

        print(ascii_art)

        

        # Save the ASCII art to a text file

        output_file = "ascii_art.txt"

        with open(output_file, "w") as f:

            f.write(ascii_art)

        print(f"\nASCII art has been saved to {output_file}")


if __name__ == "__main__":

    main()


Image Resizer with a GUI

 import tkinter as tk

from tkinter import filedialog, messagebox

from PIL import Image, ImageTk


def select_image():

    global img, img_path

    img_path = filedialog.askopenfilename(

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

    )

    if not img_path:

        return

    img = Image.open(img_path)

    preview_image(img)


def preview_image(image):

    # Resize for preview

    preview = image.copy()

    preview.thumbnail((300, 300))

    tk_img = ImageTk.PhotoImage(preview)

    img_label.config(image=tk_img)

    img_label.image = tk_img


def resize_image():

    global img, img_path

    if not img_path:

        messagebox.showerror("Error", "No image selected!")

        return


    try:

        new_width = int(width_entry.get())

        new_height = int(height_entry.get())

        resized_img = img.resize((new_width, new_height))

        

        save_path = filedialog.asksaveasfilename(

            defaultextension=".png",

            filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg"), ("All files", "*.*")]

        )

        if save_path:

            resized_img.save(save_path)

            messagebox.showinfo("Success", f"Image saved to {save_path}")

    except ValueError:

        messagebox.showerror("Error", "Please enter valid width and height values!")

    except Exception as e:

        messagebox.showerror("Error", f"An error occurred: {str(e)}")


# GUI Setup

root = tk.Tk()

root.title("Image Resizer")


frame = tk.Frame(root)

frame.pack(pady=10)


# Image Preview

img_label = tk.Label(frame)

img_label.pack()


# Select Image Button

select_btn = tk.Button(root, text="Select Image", command=select_image)

select_btn.pack(pady=5)


# Input Fields for Width and Height

size_frame = tk.Frame(root)

size_frame.pack(pady=5)

tk.Label(size_frame, text="Width: ").grid(row=0, column=0, padx=5)

width_entry = tk.Entry(size_frame, width=10)

width_entry.grid(row=0, column=1, padx=5)

tk.Label(size_frame, text="Height: ").grid(row=0, column=2, padx=5)

height_entry = tk.Entry(size_frame, width=10)

height_entry.grid(row=0, column=3, padx=5)


# Resize Button

resize_btn = tk.Button(root, text="Resize and Save", command=resize_image)

resize_btn.pack(pady=10)


root.mainloop()


Unit Converter

 def convert_temperature(value, from_unit, to_unit):

    if from_unit == "Celsius" and to_unit == "Fahrenheit":

        return (value * 9/5) + 32

    elif from_unit == "Fahrenheit" and to_unit == "Celsius":

        return (value - 32) * 5/9

    elif from_unit == "Celsius" and to_unit == "Kelvin":

        return value + 273.15

    elif from_unit == "Kelvin" and to_unit == "Celsius":

        return value - 273.15

    elif from_unit == "Fahrenheit" and to_unit == "Kelvin":

        return (value - 32) * 5/9 + 273.15

    elif from_unit == "Kelvin" and to_unit == "Fahrenheit":

        return (value - 273.15) * 9/5 + 32

    return value


def convert_length(value, from_unit, to_unit):

    conversion_factors = {

        "meters": 1,

        "kilometers": 0.001,

        "centimeters": 100,

        "millimeters": 1000,

        "inches": 39.3701,

        "feet": 3.28084,

        "miles": 0.000621371,

    }

    return value * conversion_factors[to_unit] / conversion_factors[from_unit]


def convert_weight(value, from_unit, to_unit):

    conversion_factors = {

        "kilograms": 1,

        "grams": 1000,

        "milligrams": 1_000_000,

        "pounds": 2.20462,

        "ounces": 35.274,

    }

    return value * conversion_factors[to_unit] / conversion_factors[from_unit]


def main():

    print("Unit Converter")

    print("1. Temperature")

    print("2. Length")

    print("3. Weight")

    choice = input("Choose a category (1/2/3): ")


    if choice == "1":

        print("\nTemperature Units: Celsius, Fahrenheit, Kelvin")

        value = float(input("Enter the value to convert: "))

        from_unit = input("Convert from: ").capitalize()

        to_unit = input("Convert to: ").capitalize()

        result = convert_temperature(value, from_unit, to_unit)

        print(f"{value} {from_unit} is equal to {result:.2f} {to_unit}")


    elif choice == "2":

        print("\nLength Units: meters, kilometers, centimeters, millimeters, inches, feet, miles")

        value = float(input("Enter the value to convert: "))

        from_unit = input("Convert from: ").lower()

        to_unit = input("Convert to: ").lower()

        result = convert_length(value, from_unit, to_unit)

        print(f"{value} {from_unit} is equal to {result:.2f} {to_unit}")


    elif choice == "3":

        print("\nWeight Units: kilograms, grams, milligrams, pounds, ounces")

        value = float(input("Enter the value to convert: "))

        from_unit = input("Convert from: ").lower()

        to_unit = input("Convert to: ").lower()

        result = convert_weight(value, from_unit, to_unit)

        print(f"{value} {from_unit} is equal to {result:.2f} {to_unit}")


    else:

        print("Invalid choice! Please select 1, 2, or 3.")


if __name__ == "__main__":

    main()


Managing Students

import os

import platform

global listStd 

listStd = ["Amal", "Appu", "Malavika", "Seetha"]

def manageStudent(): 

global bye

bye = "bye!!"

print(""" 

Welcome To Student Management System


Enter 1 : To View Student's List 

Enter 2 : To Add New Student 

Enter 3 : To Search Student 

Enter 4 : To Remove Student 

""")

try: 

userInput = int(input("Please Select An Above Option: "))

except ValueError:

exit("\nThat's Not A Number")

else:

print("\n") 

if(userInput == 1): 

print("List Students\n")  

for students in listStd:

print("=> {}".format(students))

elif(userInput == 2): 

newStd = input("Enter New Student: ")

if(newStd in listStd): 

print("\nThis Student {} Already In The Database".format(newStd))  

else:

listStd.append(newStd)

print("\n=> New Student {} Successfully Add \n".format(newStd))

for students in listStd:

print("=> {}".format(students))

elif(userInput == 3): 

srcStd = input("Enter Student Name To Search: ")

if(srcStd in listStd): 

print("\n=> Record Found Of Student {}".format(srcStd))

else:

print("\n=> No Record Found Of Student {}".format(srcStd)) 

elif(userInput == 4): 

rmStd = input("Enter Student Name To Remove: ")

if(rmStd in listStd): 

listStd.remove(rmStd)

print("\n=> Student {} Successfully Deleted \n".format(rmStd))

for students in listStd:

print("=> {}".format(students))

else:

print("\n=> No Record Found of This Student {}".format(rmStd)) 

 

elif(userInput < 1 or userInput > 4):

print("Please Enter Valid Option")

manageStudent()

def runAgain():

runAgn = input("\nwant To Run Again Y/n: ")

if(runAgn.lower() == 'y'):

if(platform.system() == "Windows"): 

print(os.system('cls')) 

else:

print(os.system('clear'))

manageStudent()

runAgain()

else:

quit(bye) 

runAgain()