|
import gradio as gr |
|
from PIL import Image |
|
import numpy as np |
|
|
|
def brightness_to_white_alpha(img, bg=None, invert_opacity=False): |
|
if img is None: |
|
return None |
|
|
|
|
|
img = img.convert("RGB") |
|
img_np = np.array(img).astype(np.float32) |
|
brightness = np.dot(img_np[..., :3], [0.299, 0.587, 0.114]) |
|
|
|
if invert_opacity: |
|
brightness = 255 - brightness |
|
|
|
|
|
alpha = (brightness / 255.0).clip(0, 1) |
|
alpha = (alpha * 255).astype(np.uint8) |
|
|
|
|
|
white = np.ones_like(img_np, dtype=np.uint8) * 255 |
|
|
|
|
|
white_alpha = np.dstack((white, alpha)).astype(np.uint8) |
|
|
|
white_img = Image.fromarray(white_alpha, mode="RGBA") |
|
|
|
|
|
if bg: |
|
bg = bg.convert("RGBA").resize(white_img.size) |
|
white_np = np.array(white_img).astype(np.float32) / 255.0 |
|
bg_np = np.array(bg).astype(np.float32) / 255.0 |
|
|
|
fg_a = white_np[..., 3:4] |
|
bg_a = bg_np[..., 3:4] |
|
out_a = fg_a + bg_a * (1 - fg_a) |
|
out_rgb = (white_np[..., :3] * fg_a + bg_np[..., :3] * bg_a * (1 - fg_a)) / np.maximum(out_a, 1e-6) |
|
|
|
result = np.dstack((out_rgb, out_a)).clip(0, 1) * 255 |
|
return Image.fromarray(result.astype(np.uint8), mode="RGBA") |
|
|
|
return white_img |
|
|
|
|
|
iface = gr.Interface( |
|
fn=brightness_to_white_alpha, |
|
inputs=[ |
|
gr.Image(type="pil", label="Input Image"), |
|
gr.Image(type="pil", label="Optional Background Image"), |
|
gr.Checkbox(label="Invert Brightness β Alpha", value=False) |
|
], |
|
outputs=gr.Image(type="pil", label="White with Alpha"), |
|
title="ποΈ Brightness to White Alpha Image", |
|
description=( |
|
"Generates a pure white image where opacity = brightness of input. " |
|
"Darker = more transparent, lighter = more opaque. Optional overlay on background." |
|
) |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |