Spaces:
Runtime error
Runtime error
add application file
Browse files
app.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""Copy of extract_colors_from_image.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1Zx45R30-L2sIBh8VU_Fnbv9G6v4445TD
|
8 |
+
"""
|
9 |
+
|
10 |
+
# Commented out IPython magic to ensure Python compatibility.
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import cv2
|
14 |
+
from sklearn.cluster import KMeans
|
15 |
+
from collections import Counter
|
16 |
+
|
17 |
+
import gradio as gr
|
18 |
+
|
19 |
+
|
20 |
+
def get_image(pil_image):
|
21 |
+
#image = cv2.imread(image_path)
|
22 |
+
nimg = np.array(pil_image)
|
23 |
+
image = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
|
24 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
25 |
+
return image
|
26 |
+
|
27 |
+
def get_labels(rimg):
|
28 |
+
clf = KMeans(n_clusters = 5)
|
29 |
+
labels = clf.fit_predict(rimg)
|
30 |
+
return labels , clf
|
31 |
+
|
32 |
+
def RGB2HEX(color):
|
33 |
+
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
|
34 |
+
|
35 |
+
def get_colors(pimg):
|
36 |
+
img = get_image(pimg)
|
37 |
+
reshaped_img = img.reshape(img.shape[0]*img.shape[1], img.shape[2])
|
38 |
+
labels, clf = get_labels(reshaped_img)
|
39 |
+
counts = Counter(labels)
|
40 |
+
center_colors = clf.cluster_centers_
|
41 |
+
# We get ordered colors by iterating through the keys
|
42 |
+
ordered_colors = [center_colors[i] for i in counts.keys()]
|
43 |
+
hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
|
44 |
+
#rgb_colors = [ordered_colors[i] for i in counts.keys()]
|
45 |
+
return hex_colors
|
46 |
+
|
47 |
+
demo = gr.Blocks()
|
48 |
+
|
49 |
+
with demo:
|
50 |
+
gr.Markdown(
|
51 |
+
"""
|
52 |
+
# Extract Colors from an image using KMeans clustering
|
53 |
+
"""
|
54 |
+
)
|
55 |
+
inputs = [gr.Image(type="pil", label="Image to extract colors from")]
|
56 |
+
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")]
|
57 |
+
|
58 |
+
btn = gr.Button("Extract colors")
|
59 |
+
btn.click(fn=get_colors, inputs=inputs, outputs=outputs)
|
60 |
+
demo.queue()
|
61 |
+
demo.launch()
|
62 |
+
|