Commit
·
98e7a36
1
Parent(s):
991bfd5
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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):
|
| 21 |
+
modified_image = preprocess(img)
|
| 22 |
+
n_cluster = 6
|
| 23 |
+
|
| 24 |
+
clf = KMeans(n_clusters = n_cluster)
|
| 25 |
+
color_labels = clf.fit_predict(modified_image)
|
| 26 |
+
center_colors = clf.cluster_centers_
|
| 27 |
+
counts = Counter(color_labels)
|
| 28 |
+
ordered_colors = [center_colors[i] for i in counts.keys()]
|
| 29 |
+
hex_colors = [rgb_to_hex(ordered_colors[i]) for i in counts.keys()]
|
| 30 |
+
|
| 31 |
+
plot = plt.figure(figsize = (12, 8))
|
| 32 |
+
plt.pie(counts.values(), labels = hex_colors, autopct='%1.1f%%', colors = hex_colors)
|
| 33 |
+
|
| 34 |
+
plt.savefig("color_classifier_pie.png")
|
| 35 |
+
print(str(n_cluster) + " the most dominant colors:\n")
|
| 36 |
+
for color in hex_colors:
|
| 37 |
+
print(color)
|
| 38 |
+
|
| 39 |
+
return plot
|
| 40 |
+
|
| 41 |
+
color_picker = gr.Interface(fn=analyze, inputs="image", outputs="plot")
|
| 42 |
+
color_picker.launch()
|