File size: 1,855 Bytes
7d99c12
 
 
 
 
 
 
 
 
 
 
02d9a55
7d99c12
 
02d9a55
 
7d99c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51fe0ad
 
7d99c12
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
"""Copy of extract_colors_from_image.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1Zx45R30-L2sIBh8VU_Fnbv9G6v4445TD
"""

# Commented out IPython magic to ensure Python compatibility.


from sklearn.cluster import KMeans
from collections import Counter
import numpy as np
import cv2

import gradio as gr


def get_image(pil_image):
    #image = cv2.imread(image_path)
    nimg = np.array(pil_image)
    image = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return image

def get_labels(rimg):
  clf = KMeans(n_clusters = 5)
  labels = clf.fit_predict(rimg)
  return labels ,  clf

def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

def get_colors(pimg):
  img = get_image(pimg)
  reshaped_img = img.reshape(img.shape[0]*img.shape[1], img.shape[2])
  labels, clf = get_labels(reshaped_img)
  counts = Counter(labels)
  center_colors = clf.cluster_centers_
  # We get ordered colors by iterating through the keys
  ordered_colors = [center_colors[i] for i in counts.keys()]
  hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
  #rgb_colors = [ordered_colors[i] for i in counts.keys()]
  return hex_colors

demo = gr.Blocks()

with demo:
    gr.Markdown(
        """
    # Extract Colors from an image using KMeans clustering
    """
    )
    inputs = [gr.Image(type="pil", label="Image to extract colors from")]
    with gr.Row():
        outputs = [gr.ColorPicker(label="color 1"), gr.ColorPicker(label="color 2"),gr.ColorPicker(label="color 3"),gr.ColorPicker(label="color 4"),gr.ColorPicker(label="color 5")]

    btn = gr.Button("Extract colors")
    btn.click(fn=get_colors, inputs=inputs, outputs=outputs)
demo.queue()
demo.launch()