Spaces:
Running
Running
add palette module
Browse files- myapp/palette.py +30 -0
myapp/palette.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from sklearn.cluster import KMeans
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def join_images(a: Image.Image, b: Image.Image):
|
| 7 |
+
result = Image.new(a.mode, (a.width + b.width, max(a.height, b.height)))
|
| 8 |
+
result.paste(a)
|
| 9 |
+
result.paste(b, (a.width, 0))
|
| 10 |
+
|
| 11 |
+
return result
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_palette_image(model: KMeans, size=40):
|
| 15 |
+
image = Image.new("RGB", (0, size))
|
| 16 |
+
|
| 17 |
+
for cluster_center in model.cluster_centers_:
|
| 18 |
+
color = tuple(map(int, cluster_center))
|
| 19 |
+
part = Image.new("RGB", (40, 40), color)
|
| 20 |
+
image = join_images(image, part)
|
| 21 |
+
|
| 22 |
+
return image
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def extract_color_clusters(image_array: np.ndarray):
|
| 26 |
+
w, h, d = image_array.shape
|
| 27 |
+
pixels = image_array.reshape(w * h, d)
|
| 28 |
+
model = KMeans(n_clusters=4).fit(pixels)
|
| 29 |
+
|
| 30 |
+
return model
|