|
import gradio as gr
|
|
from PIL import ImageEnhance
|
|
from color import Color
|
|
from color_wheel import ColorWheel
|
|
|
|
def create_color_table(color):
|
|
sb = []
|
|
sb.append('''<!DOCTYPE html>
|
|
<html lang="ja" xmlns="http://www.w3.org/1999/xhtml">
|
|
<head>
|
|
<meta charset="utf-8" />
|
|
<title></title>
|
|
<style>
|
|
.container {display:grid;grid-template-columns:64px 64px 64px 64px 64px 64px 64px 64px 64px 64px 64px 64px}
|
|
.container > div {padding:3px; color:white; font-size:9pt; height: 32px}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
''')
|
|
cwt = ColorWheel(color)
|
|
colors = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
|
|
for h in cwt.hue:
|
|
cw = ColorWheel(Color.from_rgb(h.r, h.g, h.b))
|
|
for i, t in enumerate(cw.tone15):
|
|
colors[i].append(t)
|
|
|
|
for hue in colors:
|
|
sb.append(' <div class="container">\n')
|
|
for h in hue:
|
|
sb.append(' <div style="background-color:rgb({},{},{})">#{:02x}{:02x}{:02x}</div>\n'.format(h.r, h.g, h.b, h.r, h.g, h.b))
|
|
sb.append(' </div>\n')
|
|
sb.append(''' </body >
|
|
</html>''')
|
|
html = ''.join(sb)
|
|
return html
|
|
|
|
def chunks(list, n):
|
|
c = []
|
|
for i in range(0, len(list), n):
|
|
c.append(list[i:i + n])
|
|
return c
|
|
|
|
def calc_score(colors, colorset):
|
|
s = []
|
|
srccolors = colors.copy()[0:32]
|
|
for c in colorset:
|
|
cd = []
|
|
for color in srccolors:
|
|
cd.append((color.r - c.r) ** 2 + (color.g - c.g) ** 2 + (color.b - c.b) ** 2)
|
|
i = min(range(len(cd)), key=cd.__getitem__)
|
|
s.append(cd[i])
|
|
srccolors.pop(i)
|
|
return sum(s)
|
|
|
|
def handv(c):
|
|
cw = ColorWheel.rgb_to_hsv(c.r / 255.0, c.g / 255.0, c.b / 255.0)
|
|
return cw[1] + cw[2]
|
|
|
|
def process_image(image, sf=0.0, cf=0.0):
|
|
if image is None:
|
|
return None
|
|
|
|
e = ImageEnhance.Color(image)
|
|
img = e.enhance(cf + 1.0)
|
|
|
|
imglim = img.quantize(256)
|
|
palette = list(chunks(imglim.getpalette(), 3))
|
|
colors = []
|
|
for p in palette:
|
|
r, g, b = p
|
|
color = Color(255, r, g, b)
|
|
colors.append(color)
|
|
colors.sort(key=handv, reverse=True)
|
|
|
|
scores = []
|
|
for c in colors[0:32 + int(sf * 96)]:
|
|
cw = ColorWheel(c)
|
|
scores.append(calc_score(colors, cw.hue))
|
|
i = min(range(len(scores)), key=scores.__getitem__)
|
|
return create_color_table(colors[i])
|
|
|
|
app = gr.Interface(
|
|
title='Image To Color Wheel',
|
|
fn=process_image,
|
|
inputs=[
|
|
gr.Image(type='pil'),
|
|
gr.Slider(maximum=1.0, step=0.1, label='sampling factor', value=0.0),
|
|
gr.Slider(maximum=1.0, step=0.1, label='color factor', value=0.0),
|
|
],
|
|
outputs=gr.HTML(),
|
|
allow_flagging='never',
|
|
examples=[['examples/example1.jpg'], ['examples/example2.jpg']],
|
|
|
|
concurrency_limit=20,
|
|
)
|
|
app.launch()
|
|
|