milorable commited on
Commit
c3e5542
·
verified ·
1 Parent(s): ae773cf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -0
app.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from collections import Counter
3
+ from sklearn.cluster import KMeans
4
+ from matplotlib import colors
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import cv2
8
+
9
+ def rgb_to_hex(rgb_color):
10
+ hex_color = "#"
11
+ for i in rgb_color:
12
+ hex_color += ("{:02x}".format(int(i)))
13
+ return hex_color
14
+
15
+ def preprocess(raw):
16
+ image = cv2.resize(raw, (900, 600), interpolation = cv2.INTER_AREA)
17
+ image = image.reshape(image.shape[0]*image.shape[1], 3)
18
+ return image
19
+
20
+ def analyze(img,n_cluster ):
21
+ modified_image = preprocess(img)
22
+ clf = KMeans(n_clusters = n_cluster)
23
+ color_labels = clf.fit_predict(modified_image)
24
+ center_colors = clf.cluster_centers_
25
+ counts = Counter(color_labels)
26
+ ordered_colors = [center_colors[i] for i in counts.keys()]
27
+ hex_colors = [rgb_to_hex(ordered_colors[i]) for i in counts.keys()]
28
+
29
+ plot = plt.figure(figsize = (12, 8))
30
+ plt.pie(counts.values(), labels = hex_colors, autopct='%1.1f%%', colors = hex_colors)
31
+
32
+ plt.savefig("color_classifier_pie.png")
33
+ print(str(n_cluster) + " the most dominant colors:\n")
34
+ for color in hex_colors:
35
+ print(color)
36
+
37
+ return plot
38
+
39
+ color_picker = gr.Interface(fn=analyze, inputs=["image", gr.inputs.Slider(minimum=2, maximum=10, step=1, label="Number of claster")], outputs="plot")
40
+ color_picker.launch()