Update app.py
Browse files
app.py
CHANGED
@@ -1,36 +1,48 @@
|
|
1 |
import gradio as gr
|
2 |
from PIL import Image
|
3 |
import numpy as np
|
4 |
-
import io
|
5 |
|
6 |
-
def
|
7 |
-
|
8 |
-
|
9 |
-
img_array = np.array(img)
|
10 |
|
11 |
-
#
|
12 |
-
|
|
|
13 |
|
14 |
-
#
|
15 |
-
|
|
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
rgba_array = np.dstack((white_rgb, alpha))
|
20 |
|
21 |
-
#
|
22 |
-
|
23 |
-
|
|
|
24 |
|
25 |
-
#
|
|
|
|
|
|
|
|
|
|
|
26 |
iface = gr.Interface(
|
27 |
-
fn=
|
28 |
-
inputs=
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
)
|
33 |
|
34 |
-
#
|
35 |
if __name__ == "__main__":
|
36 |
iface.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from PIL import Image
|
3 |
import numpy as np
|
|
|
4 |
|
5 |
+
def brightness_to_opacity_overlay(foreground_img, background_img, invert_opacity=False):
|
6 |
+
if foreground_img is None or background_img is None:
|
7 |
+
return None
|
|
|
8 |
|
9 |
+
# Resize foreground to match background
|
10 |
+
bg = background_img.convert("RGBA")
|
11 |
+
fg = foreground_img.convert("RGB").resize(bg.size)
|
12 |
|
13 |
+
# Convert foreground to grayscale (luminance)
|
14 |
+
fg_array = np.array(fg)
|
15 |
+
luminance = np.dot(fg_array[...,:3], [0.299, 0.587, 0.114]).astype(np.uint8)
|
16 |
|
17 |
+
# Optionally invert the opacity
|
18 |
+
alpha = 255 - luminance if invert_opacity else luminance
|
|
|
19 |
|
20 |
+
# Set RGB to white, combine with alpha
|
21 |
+
white_rgb = np.ones_like(fg_array) * 255
|
22 |
+
rgba_array = np.dstack((white_rgb, alpha)).astype(np.uint8)
|
23 |
+
mask_image = Image.fromarray(rgba_array, mode="RGBA")
|
24 |
|
25 |
+
# Overlay mask_image on background
|
26 |
+
combined = Image.alpha_composite(bg, mask_image)
|
27 |
+
|
28 |
+
return combined
|
29 |
+
|
30 |
+
# Gradio UI
|
31 |
iface = gr.Interface(
|
32 |
+
fn=brightness_to_opacity_overlay,
|
33 |
+
inputs=[
|
34 |
+
gr.Image(type="pil", label="Mask Source (Brightness to Alpha)"),
|
35 |
+
gr.Image(type="pil", label="Background Image"),
|
36 |
+
gr.Checkbox(label="Invert Opacity", value=False)
|
37 |
+
],
|
38 |
+
outputs=gr.Image(type="pil", label="Final Composite"),
|
39 |
+
title="Brightness-to-Alpha Overlay Tool",
|
40 |
+
description=(
|
41 |
+
"This tool uses the brightness of the first image as its opacity mask, "
|
42 |
+
"optionally inverts it, resizes it to match the second image, and overlays the result."
|
43 |
+
)
|
44 |
)
|
45 |
|
46 |
+
# Run the app
|
47 |
if __name__ == "__main__":
|
48 |
iface.launch()
|