File size: 1,391 Bytes
b3460e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
from PIL import Image
import tempfile
import os

def generate_binary_mask(image_data):
    if image_data is None or "layers" not in image_data or not image_data["layers"]:
        raise gr.Error("Please draw a mask before generating!")

    mask = image_data["layers"][0]
    mask_array = np.array(mask)

    if np.all(mask_array < 10):
        raise gr.Error("The mask is empty! Please draw something.")

    # Binary mask logic
    is_black = np.all(mask_array < 10, axis=2)
    binary_mask = Image.fromarray(((~is_black) * 255).astype(np.uint8))

    # Save to temporary file
    temp_dir = tempfile.mkdtemp()
    output_path = os.path.join(temp_dir, "binary_mask.png")
    binary_mask.save(output_path)

    return binary_mask, output_path

with gr.Blocks() as app:
    with gr.Row():
        with gr.Column():
            image_input = gr.ImageMask(
                label="Upload or Paste Image, then draw mask",
                type="pil",
                height=None,
                width=None
            )
            generate_btn = gr.Button("Generate Mask")
        
        with gr.Column():
            mask_preview = gr.Image(label="Mask Preview", type="pil")
            output_file = gr.File(label="Download Mask")

    generate_btn.click(fn=generate_binary_mask, inputs=image_input, outputs=[mask_preview, output_file])

app.launch()