File size: 1,341 Bytes
98e7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aac9e
 
98e7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aac9e
98e7a36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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()