Spaces:
Runtime error
Runtime error
bear-zd commited on
Commit ·
8f9daf9
1
Parent(s): 04bdac2
Feature: Trial of color extractor
Browse files- app.py +47 -4
- requirements.txt +2 -0
app.py
CHANGED
|
@@ -1,7 +1,50 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
def
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from colorthief import ColorThief
|
| 3 |
+
import numpy as np
|
| 4 |
+
from io import BytesIO
|
| 5 |
|
| 6 |
+
def extract_colors(image, num_colors):
|
| 7 |
+
img = BytesIO()
|
| 8 |
+
img.seek(0)
|
| 9 |
+
color_thief = ColorThief(img)
|
| 10 |
+
palette = color_thief.get_palette(color_count=num_colors)
|
| 11 |
+
colors = np.array(palette)
|
| 12 |
|
| 13 |
+
return colors
|
| 14 |
+
|
| 15 |
+
def plot_colors(colors):
|
| 16 |
+
palette = np.zeros((50, len(colors) * 50, 3), dtype=int)
|
| 17 |
+
step = 50
|
| 18 |
+
for idx, color in enumerate(colors):
|
| 19 |
+
palette[:, idx*step:(idx+1)*step, :] = color
|
| 20 |
+
return palette
|
| 21 |
+
|
| 22 |
+
def colors_to_hex(colors):
|
| 23 |
+
hex_colors = ['#%02x%02x%02x' % tuple(color) for color in colors]
|
| 24 |
+
return hex_colors
|
| 25 |
+
|
| 26 |
+
def process_image(image, num_colors):
|
| 27 |
+
colors = extract_colors(image, num_colors)
|
| 28 |
+
palette = plot_colors(colors)
|
| 29 |
+
palette_str = "palette=" + str(colors.tolist())
|
| 30 |
+
hex_colors = colors_to_hex(colors)
|
| 31 |
+
hex_palette_str = 'palette=' + str(hex_colors)
|
| 32 |
+
|
| 33 |
+
return palette, palette_str, hex_palette_str
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
iface = gr.Interface(fn=process_image,
|
| 37 |
+
inputs=[
|
| 38 |
+
gr.Image(type="pil", label="上传图片"),
|
| 39 |
+
gr.Slider(minimum=1, maximum=20, value=5, step=1, label="调色板颜色数量")
|
| 40 |
+
],
|
| 41 |
+
outputs=[
|
| 42 |
+
gr.Image(type="numpy", label="生成的调色板"),
|
| 43 |
+
gr.Textbox(label="调色板RGB值"),
|
| 44 |
+
gr.Textbox(label="调色板16进制值")
|
| 45 |
+
])
|
| 46 |
+
|
| 47 |
+
iface.launch()
|
| 48 |
+
|
| 49 |
+
if __name__ == '__main__':
|
| 50 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
colorthief
|