seungpyo-hong commited on
Commit
8b1da5c
1 Parent(s): 41afbdf
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gradio as gr
3
+ from PIL import Image
4
+ import cv2
5
+ from skimage import color
6
+ from sklearn.cluster import KMeans
7
+ from typing import Tuple
8
+
9
+ f = "view.png"
10
+ img = Image.open(f)
11
+ img = np.array(img)[..., :3]
12
+
13
+
14
+ def proc(img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
15
+ assert img.shape[-1] == 3
16
+ k_size = 11
17
+ sigma = 11
18
+ blurred = cv2.GaussianBlur(img, (k_size, k_size), sigma)
19
+ blurred_small = cv2.resize(blurred, (80, 80))
20
+ labs = color.rgb2lab(blurred_small)
21
+ lab_vectors = labs.reshape(-1, 3)
22
+
23
+ num_colors = 5
24
+ num_bins = 10
25
+ km = KMeans(n_clusters=num_colors)
26
+ km.fit(lab_vectors)
27
+ centroid_labs = km.cluster_centers_ # N x (L, a, b)
28
+ centroid_labs = np.array(
29
+ sorted(centroid_labs, key=lambda x: x[1] ** 2 + x[2] ** 2)
30
+ ) # sort by L
31
+ centroid_ls = (
32
+ np.arange(0, 100, num_bins).reshape(1, num_bins, 1).repeat(num_colors, axis=0)
33
+ )
34
+ centroid_abs = centroid_labs[:, np.newaxis, 1:].repeat(num_bins, axis=1)
35
+ centroid_labs = np.concatenate([centroid_ls, centroid_abs], axis=-1).reshape(
36
+ num_colors, num_bins, 3
37
+ )
38
+
39
+ unique_indices = [0] + [
40
+ i
41
+ for i in range(1, num_colors)
42
+ if np.linalg.norm(centroid_labs[i] - centroid_labs[i - 1]) > 10
43
+ ]
44
+ centroid_labs = centroid_labs[unique_indices, :, :]
45
+
46
+ centroid_rgbs = (color.lab2rgb(centroid_labs) * 255).astype(np.uint8)
47
+ centroid_rgb_vis = cv2.resize(
48
+ centroid_rgbs,
49
+ (int(img.shape[0] / num_colors * num_bins), img.shape[0]),
50
+ interpolation=cv2.INTER_NEAREST,
51
+ )
52
+ return centroid_rgb_vis
53
+
54
+
55
+ demo = gr.Interface(fn=proc, inputs="image", outputs="image")
56
+
57
+ if __name__ == "__main__":
58
+ demo.launch()