File size: 2,127 Bytes
5dbde27 b1e3e6e e7b5496 5dbde27 b1e3e6e 5dbde27 f4454d4 5dbde27 b1e3e6e 1a346bf e7b5496 b1e3e6e 6d001f6 b1e3e6e e7b5496 5dbde27 b1e3e6e e7b5496 b1e3e6e e7b5496 b1e3e6e e7b5496 b1e3e6e e7b5496 5dbde27 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
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() |