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(''' ''') 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('
\n') for h in hue: sb.append('
#{:02x}{:02x}{:02x}
\n'.format(h.r, h.g, h.b, h.r, h.g, h.b)) sb.append('
\n') sb.append(''' ''') 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', 0.0, 0.0], ['examples/example2.jpg', 0.0, 0.0]], #cache_examples=False, concurrency_limit=20, ) app.launch()