robosapiens's picture
Update app.py
c6aac9e
import gradio as gr
from collections import Counter
from sklearn.cluster import KMeans
from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np
import cv2
def rgb_to_hex(rgb_color):
hex_color = "#"
for i in rgb_color:
hex_color += ("{:02x}".format(int(i)))
return hex_color
def preprocess(raw):
image = cv2.resize(raw, (900, 600), interpolation = cv2.INTER_AREA)
image = image.reshape(image.shape[0]*image.shape[1], 3)
return image
def analyze(img,n_cluster ):
modified_image = preprocess(img)
clf = KMeans(n_clusters = n_cluster)
color_labels = clf.fit_predict(modified_image)
center_colors = clf.cluster_centers_
counts = Counter(color_labels)
ordered_colors = [center_colors[i] for i in counts.keys()]
hex_colors = [rgb_to_hex(ordered_colors[i]) for i in counts.keys()]
plot = plt.figure(figsize = (12, 8))
plt.pie(counts.values(), labels = hex_colors, autopct='%1.1f%%', colors = hex_colors)
plt.savefig("color_classifier_pie.png")
print(str(n_cluster) + " the most dominant colors:\n")
for color in hex_colors:
print(color)
return plot
color_picker = gr.Interface(fn=analyze, inputs=["image", gr.inputs.Slider(minimum=2, maximum=10, step=1, label="Number of claster")], outputs="plot")
color_picker.launch()