gdo commited on
Commit
612fb1c
·
verified ·
1 Parent(s): 9ad575c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -0
app.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from sklearn.cluster import KMeans
4
+ from PIL import Image
5
+
6
+ def flatten_colors(input_img, num_colors):
7
+ if input_img is None:
8
+ return None
9
+
10
+ # Convert PIL image to numpy array
11
+ img_array = np.array(input_img)
12
+ original_shape = img_array.shape
13
+
14
+ # Reshape to a list of pixels (R, G, B)
15
+ pixels = img_array.reshape(-1, 3)
16
+
17
+ # Apply K-Means to find dominant colors
18
+ kmeans = KMeans(n_clusters=int(num_colors), random_state=42, n_init=10)
19
+ labels = kmeans.fit_predict(pixels)
20
+ colors = kmeans.cluster_centers_.astype('uint8')
21
+
22
+ # Map each pixel to its corresponding cluster center (the flat color)
23
+ flattened_pixels = colors[labels]
24
+
25
+ # Reshape back to original image dimensions
26
+ flattened_img = flattened_pixels.reshape(original_shape)
27
+
28
+ return Image.fromarray(flattened_img)
29
+
30
+ # Define the Gradio Interface
31
+ demo = gr.Interface(
32
+ fn=flatten_colors,
33
+ inputs=[
34
+ gr.Image(type="pil", label="Upload Image"),
35
+ gr.Slider(minimum=2, maximum=20, value=8, step=1, label="Number of Colors")
36
+ ],
37
+ outputs=gr.Image(type="pil", label="Flat Color Result"),
38
+ title="🎨 Image Color Flattener",
39
+ description="Upload an image and reduce it to a flat color palette using K-Means clustering."
40
+ )
41
+
42
+ if __name__ == "__main__":
43
+ demo.launch()