K-Means / app.py
Tzetha's picture
added app
8188cd9
raw
history blame
2.68 kB
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(
"""
<style>
.title {
text-align: center;
font-size: 36px;
font-weight: bold;
color: #4A90E2;
}
.subtitle {
text-align: center;
font-size: 20px;
color: #7F8C8D;
}
.uploaded-img {
display: flex;
justify-content: center;
}
</style>
""",
unsafe_allow_html=True,
)
# Header Design
st.markdown("<div class='title'>🎨 K-Means Color Palette Generator</div>", unsafe_allow_html=True)
st.markdown("<div class='subtitle'>Upload an image and extract its dominant colors!</div>", 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("<div class='uploaded-img'>", unsafe_allow_html=True)
st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), caption="Uploaded Image", use_column_width=True)
st.markdown("</div>", 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"""<div style='background-color: rgb({color[0]}, {color[1]}, {color[2]});
height: 50px; border-radius: 10px;'></div>""", unsafe_allow_html=True)
st.write(f"RGB({color[0]}, {color[1]}, {color[2]})")