Update app.py
Browse files
app.py
CHANGED
@@ -2,45 +2,49 @@ import gradio as gr
|
|
2 |
from PIL import Image
|
3 |
import numpy as np
|
4 |
|
5 |
-
def
|
6 |
-
if
|
7 |
return None
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
|
|
|
|
|
14 |
if invert_opacity:
|
15 |
brightness = 255 - brightness
|
|
|
16 |
|
17 |
-
alpha
|
|
|
|
|
18 |
|
19 |
-
#
|
20 |
-
|
21 |
-
white_rgb = np.full((height, width, 3), 255, dtype=np.uint8)
|
22 |
-
white_rgba = np.dstack((white_rgb, alpha)) # shape (H, W, 4)
|
23 |
-
white_img = Image.fromarray(white_rgba, mode="RGBA")
|
24 |
|
25 |
-
#
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
return white_img
|
32 |
|
33 |
# Gradio UI
|
34 |
iface = gr.Interface(
|
35 |
-
fn=
|
36 |
inputs=[
|
37 |
-
gr.Image(type="pil", label="
|
38 |
-
gr.Image(type="pil", label="
|
39 |
-
gr.Checkbox(label="Invert Brightness
|
40 |
],
|
41 |
-
outputs=gr.Image(type="pil", label="
|
42 |
-
title="
|
43 |
-
description=
|
|
|
|
|
|
|
44 |
)
|
45 |
|
46 |
if __name__ == "__main__":
|
|
|
2 |
from PIL import Image
|
3 |
import numpy as np
|
4 |
|
5 |
+
def combine_opacity_layers(top_img, bg_img, invert_opacity=False):
|
6 |
+
if top_img is None or bg_img is None:
|
7 |
return None
|
8 |
|
9 |
+
# Convert both to RGB and resize
|
10 |
+
top = top_img.convert("RGB")
|
11 |
+
bg = bg_img.convert("RGBA").resize(top.size)
|
12 |
+
top_np = np.array(top).astype(np.float32)
|
13 |
|
14 |
+
# Compute brightness from top image
|
15 |
+
brightness = np.dot(top_np[..., :3], [0.299, 0.587, 0.114])
|
16 |
if invert_opacity:
|
17 |
brightness = 255 - brightness
|
18 |
+
alpha_top = (brightness / 255.0).clip(0, 1) # shape (H, W)
|
19 |
|
20 |
+
# Get alpha from background image
|
21 |
+
bg_np = np.array(bg).astype(np.float32) / 255.0
|
22 |
+
alpha_bg = bg_np[..., 3] # shape (H, W)
|
23 |
|
24 |
+
# Multiply alpha channels
|
25 |
+
combined_alpha = (alpha_top * alpha_bg).clip(0, 1)
|
|
|
|
|
|
|
26 |
|
27 |
+
# Create output RGBA: white RGB + combined alpha
|
28 |
+
height, width = combined_alpha.shape
|
29 |
+
white_rgb = np.ones((height, width, 3), dtype=np.float32) # all white
|
30 |
+
out_rgba = np.dstack((white_rgb, combined_alpha)) * 255
|
31 |
+
out_img = Image.fromarray(out_rgba.astype(np.uint8), mode="RGBA")
|
32 |
+
return out_img
|
|
|
33 |
|
34 |
# Gradio UI
|
35 |
iface = gr.Interface(
|
36 |
+
fn=combine_opacity_layers,
|
37 |
inputs=[
|
38 |
+
gr.Image(type="pil", label="Top Brightness-Based Image"),
|
39 |
+
gr.Image(type="pil", label="Base Opacity Image (with alpha)"),
|
40 |
+
gr.Checkbox(label="Invert Top Brightness", value=False)
|
41 |
],
|
42 |
+
outputs=gr.Image(type="pil", label="Combined Opacity Image"),
|
43 |
+
title="π Combine Two Opacity Images (Multiply Alphas)",
|
44 |
+
description=(
|
45 |
+
"Takes two images and multiplies their opacity (alpha). Output is solid white "
|
46 |
+
"with combined alpha values. Useful for stacking brightness masks."
|
47 |
+
)
|
48 |
)
|
49 |
|
50 |
if __name__ == "__main__":
|