Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import gradio as grimport numpy as npfrom PIL import Imagefrom sklearn.cluster import KMeans
def extract_colors(img, num_colors): if img is None: return "<p>No image uploaded.</p>" # Resize image for faster processing img_resized = img.resize((150, 150)) data = np.array(img_resized) data = data.reshape(-1, 3) # Remove any grayscale or alpha if present if data.shape[1] == 4: data = data[:, :3] # Fit KMeans kmeans = KMeans(n_clusters=num_colors, random_state=42) kmeans.fit(data) # Get cluster centers colors = kmeans.cluster_centers_.round().astype(int) # Convert to hex hex_colors = ['#' + ''.join(f'{c:02x}' for c in color) for color in colors] # Generate HTML for palette html = '<div style="text-align: center;"><h2>Color Palette</h2><div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">' for hex_color in hex_colors: html += f''' <div style="background-color: {hex_color}; width: 80px; height: 80px; border: 2px solid #333; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: {hex_color};"> <span style="background: white; padding: 2px 5px; border-radius: 3px; font-size: 12px; font-weight: bold;">{hex_color}</span> </div> ''' html += '</div></div>' return html
with gr.Blocks(title="Image Color Palette Extractor") as demo: gr.Markdown("# Image Color Palette Extractor") gr.Markdown("Upload an image to extract the main colors and generate a palette.") with gr.Row(): with gr.Column(scale=1): input_img = gr.Image(type="pil", label="Upload Image") num_colors = gr.Slider(2, 12, value=6, step=1, label="Number of Colors") extract_btn = gr.Button("Extract Colors", variant="primary") with gr.Column(scale=2): palette_output = gr.HTML() extract_btn.click( extract_colors, inputs=[input_img, num_colors], outputs=palette_output ) input_img.change( extract_colors, inputs=[input_img, num_colors], outputs=palette_output )
demo.queue()demo.launch()app.pyAdded+66