Kanokwan85
commited on
Commit
•
10895ce
1
Parent(s):
fb013d8
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sklearn.cluster import KMeans
|
2 |
+
from collections import Counter
|
3 |
+
import numpy as np
|
4 |
+
import cv2
|
5 |
+
import os
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
def get_image(pil_image):
|
9 |
+
nimg = np.array(pil_image)
|
10 |
+
image = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
|
11 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
12 |
+
return image
|
13 |
+
|
14 |
+
def label_image(rimg):
|
15 |
+
clf = KMeans(n_clusters = 6)
|
16 |
+
labels = clf.fit_predict(rimg)
|
17 |
+
return labels , clf
|
18 |
+
|
19 |
+
def RGB(color):
|
20 |
+
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
|
21 |
+
|
22 |
+
def extract_colors(pimg):
|
23 |
+
img = get_image(pimg)
|
24 |
+
reshaped_img = img.reshape(img.shape[0]*img.shape[1], img.shape[2])
|
25 |
+
labels, clf = label_image(reshaped_img)
|
26 |
+
counts = Counter(labels)
|
27 |
+
center_colors = clf.cluster_centers_
|
28 |
+
ordered_colors = [center_colors[i] for i in counts.keys()]
|
29 |
+
hex_colors = [RGB(ordered_colors[i]) for i in counts.keys()]
|
30 |
+
return hex_colors[0], hex_colors[0], hex_colors[1], hex_colors[1], hex_colors[2],hex_colors[2], hex_colors[3], hex_colors[3], hex_colors[4], hex_colors[4], hex_colors[5], hex_colors[5]
|
31 |
+
|
32 |
+
demo = gr.Blocks(title="Color Extraction")
|
33 |
+
|
34 |
+
with demo:
|
35 |
+
gr.Markdown(
|
36 |
+
"""
|
37 |
+
# Color Extractor from Images
|
38 |
+
"""
|
39 |
+
)
|
40 |
+
with gr.Row():
|
41 |
+
with gr.Column():
|
42 |
+
inputs = [gr.Image(type="pil", label="")]
|
43 |
+
examples = gr.Examples(inputs=inputs, examples=[
|
44 |
+
[os.path.join(os.path.dirname(__file__), "01.jpg")],
|
45 |
+
[os.path.join(os.path.dirname(__file__), "02.jpg")],
|
46 |
+
[os.path.join(os.path.dirname(__file__), "03.png")],
|
47 |
+
])
|
48 |
+
with gr.Column():
|
49 |
+
with gr.Row():
|
50 |
+
outputs = [ gr.ColorPicker(label="color 1"), gr.Label(label="color 1"),
|
51 |
+
gr.ColorPicker(label="color 2"), gr.Label(label="color 2"),
|
52 |
+
gr.ColorPicker(label="color 3"), gr.Label(label="color 3"),
|
53 |
+
gr.ColorPicker(label="color 4"), gr.Label(label="color 4"),
|
54 |
+
gr.ColorPicker(label="color 5"), gr.Label(label="color 5"),
|
55 |
+
gr.ColorPicker(label="color 6"), gr.Label(label="color 6")]
|
56 |
+
|
57 |
+
btn = gr.Button("Extract colors",variant="primary")
|
58 |
+
btn.click(fn=extract_colors, inputs=inputs, outputs=outputs)
|
59 |
+
|
60 |
+
demo.queue()
|
61 |
+
demo.launch()
|
62 |
+
|