Icontest / app.py
TIMBOVILL's picture
Update app.py
b1e3e6e verified
raw
history blame
2.13 kB
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
# Convert image to RGB and get brightness
img = img.convert("RGB")
img_np = np.array(img).astype(np.float32)
brightness = np.dot(img_np[..., :3], [0.299, 0.587, 0.114]) # shape: (H, W)
if invert_opacity:
brightness = 255 - brightness
# Normalize brightness to alpha (0.0–1.0), then scale back to 0–255
alpha = (brightness / 255.0).clip(0, 1)
alpha = (alpha * 255).astype(np.uint8)
# Create pure white RGB
white = np.ones_like(img_np, dtype=np.uint8) * 255 # shape: (H, W, 3)
# Combine white RGB and computed alpha
white_alpha = np.dstack((white, alpha)).astype(np.uint8) # shape: (H, W, 4)
white_img = Image.fromarray(white_alpha, mode="RGBA")
# If background is provided, overlay white on top
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
# Gradio UI
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()