import streamlit as st import numpy as np import cv2 import matplotlib.pyplot as plt from sklearn.cluster import KMeans from io import BytesIO # Function to extract dominant colors def extract_colors(image, num_colors): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pixels = image.reshape(-1, 3) # Reshape to 2D array kmeans = KMeans(n_clusters=num_colors, n_init=10, random_state=42) kmeans.fit(pixels) colors = kmeans.cluster_centers_.astype(int) return colors # Function to display the color palette def display_palette(colors): fig, ax = plt.subplots(figsize=(8, 2)) ax.imshow([colors], aspect='auto') ax.set_xticks([]) ax.set_yticks([]) st.pyplot(fig) # Streamlit UI Design st.set_page_config(page_title="Color Palette Generator", page_icon="🎨", layout="centered") # Custom CSS for aesthetics st.markdown( """ """, unsafe_allow_html=True, ) # Header Design st.markdown("
🎨 K-Means Color Palette Generator
", unsafe_allow_html=True) st.markdown("
Upload an image and extract its dominant colors!
", unsafe_allow_html=True) uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"]) num_colors = st.slider("Select Number of Colors", 2, 10, 5) if uploaded_file is not None: file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8) image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) st.markdown("
", unsafe_allow_html=True) st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), caption="Uploaded Image", use_column_width=True) st.markdown("
", unsafe_allow_html=True) colors = extract_colors(image, num_colors) st.write("## 🎨 Extracted Color Palette") display_palette(colors) # Show color RGB values st.write("## 🌈 RGB Values of Extracted Colors") color_columns = st.columns(num_colors) for i, color in enumerate(colors): with color_columns[i]: st.markdown(f"""
""", unsafe_allow_html=True) st.write(f"RGB({color[0]}, {color[1]}, {color[2]})")