Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.cluster import KMeans
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import io
|
| 8 |
+
import base64
|
| 9 |
+
|
| 10 |
+
def extract_colors(image, num_colors=5):
|
| 11 |
+
image = image.resize((200, 200)) # Downsize for faster processing
|
| 12 |
+
img_array = np.array(image)
|
| 13 |
+
img_array = img_array.reshape((-1, 3))
|
| 14 |
+
|
| 15 |
+
kmeans = KMeans(n_clusters=num_colors)
|
| 16 |
+
kmeans.fit(img_array)
|
| 17 |
+
colors = kmeans.cluster_centers_.astype(int)
|
| 18 |
+
|
| 19 |
+
hex_colors = ['#{:02x}{:02x}{:02x}'.format(*color) for color in colors]
|
| 20 |
+
return hex_colors
|
| 21 |
+
|
| 22 |
+
def plot_palette(hex_colors):
|
| 23 |
+
fig, ax = plt.subplots(1, figsize=(5, 1))
|
| 24 |
+
for i, color in enumerate(hex_colors):
|
| 25 |
+
ax.add_patch(plt.Rectangle((i, 0), 1, 1, color=color))
|
| 26 |
+
plt.xlim(0, len(hex_colors))
|
| 27 |
+
plt.axis('off')
|
| 28 |
+
|
| 29 |
+
buf = io.BytesIO()
|
| 30 |
+
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
|
| 31 |
+
plt.close(fig)
|
| 32 |
+
buf.seek(0)
|
| 33 |
+
return Image.open(buf)
|
| 34 |
+
|
| 35 |
+
def process_image(image):
|
| 36 |
+
image = Image.fromarray(image)
|
| 37 |
+
colors = extract_colors(image)
|
| 38 |
+
palette_img = plot_palette(colors)
|
| 39 |
+
return palette_img, "\n".join(colors)
|
| 40 |
+
|
| 41 |
+
demo = gr.Interface(
|
| 42 |
+
fn=process_image,
|
| 43 |
+
inputs=gr.Image(type="numpy", label="Upload an Image"),
|
| 44 |
+
outputs=[
|
| 45 |
+
gr.Image(type="pil", label="Generated Palette"),
|
| 46 |
+
gr.Textbox(label="Hex Codes")
|
| 47 |
+
],
|
| 48 |
+
title="AI Color Palette Generator",
|
| 49 |
+
description="Upload an image and extract dominant colors using K-Means. Lightweight & Fast!"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
demo.launch()
|