File size: 1,952 Bytes
5dbde27
 
 
 
f4454d4
6d001f6
e7b5496
5dbde27
f4454d4
6d001f6
0e61409
6d001f6
5dbde27
f4454d4
6d001f6
 
f4454d4
 
 
5dbde27
f4454d4
 
 
5dbde27
f4454d4
0e61409
e7b5496
f4454d4
 
6d001f6
 
f4454d4
6d001f6
f4454d4
6d001f6
f4454d4
 
e7b5496
 
5dbde27
f4454d4
e7b5496
f4454d4
 
 
e7b5496
f4454d4
 
e7b5496
f4454d4
 
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
import gradio as gr
from PIL import Image
import numpy as np

def white_alpha_overlay(mask_img, bg_img, invert_opacity=False):
    if mask_img is None or bg_img is None:
        return None

    # Convert and resize
    mask = mask_img.convert("RGB")
    bg = bg_img.convert("RGBA")
    mask = mask.resize(bg.size)

    # Convert brightness to alpha
    mask_np = np.array(mask).astype(np.float32)
    brightness = np.dot(mask_np[..., :3], [0.299, 0.587, 0.114])
    if invert_opacity:
        brightness = 255 - brightness
    alpha = brightness.clip(0, 255) / 255.0  # 0-1

    # Create solid white RGBA with computed alpha
    white = np.ones_like(mask_np) / 255.0  # RGB = 1.0 (white)
    white_rgba = np.dstack((white, alpha))  # shape (H, W, 4)

    # Background as float
    bg_np = np.array(bg).astype(np.float32) / 255.0

    # Blend overlay on top of background
    alpha_fg = white_rgba[..., 3:4]
    alpha_bg = bg_np[..., 3:4]
    out_alpha = alpha_fg + alpha_bg * (1 - alpha_fg)
    out_rgb = (white_rgba[..., :3] * alpha_fg + bg_np[..., :3] * alpha_bg * (1 - alpha_fg)) / np.maximum(out_alpha, 1e-6)

    # Final image
    out_img = np.dstack((out_rgb, out_alpha)).clip(0, 1) * 255
    result = Image.fromarray(out_img.astype(np.uint8), mode="RGBA")
    return result

# Gradio UI
iface = gr.Interface(
    fn=white_alpha_overlay,
    inputs=[
        gr.Image(type="pil", label="Mask Image (Used for Brightness β†’ Alpha)"),
        gr.Image(type="pil", label="Background Image (With Alpha OK)"),
        gr.Checkbox(label="Invert Brightness to Alpha", value=False)
    ],
    outputs=gr.Image(type="pil", label="White Overlay Composite"),
    title="πŸ•ŠοΈ Brightness-to-Alpha White Overlay",
    description=(
        "Converts the brightness of the top image into opacity, sets the image color to white, "
        "and overlays it on a background. Works with full transparency."
    )
)

if __name__ == "__main__":
    iface.launch()