File size: 1,822 Bytes
1177d0b
c89c5ca
 
aaa7a88
c89c5ca
aaa7a88
81e2520
fa16b96
aaa7a88
 
 
 
 
c89c5ca
aaa7a88
 
 
 
fa16b96
aaa7a88
 
 
fa16b96
aaa7a88
 
1177d0b
aaa7a88
 
 
1177d0b
 
aaa7a88
 
 
 
 
 
1177d0b
aaa7a88
 
 
1177d0b
aaa7a88
1177d0b
aaa7a88
1177d0b
 
aaa7a88
 
 
 
1177d0b
 
aaa7a88
 
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
import gradio as gr
import numpy as np
import tensorflow as tf
import cv2

# Load your trained Keras model
model = tf.keras.models.load_model("unet_mask_segmentation.h5")

# Image preprocessing function (same as used during training)
def preprocess_image(img):
    img_resized = cv2.resize(img, (256, 256))
    img_normalized = img_resized / 255.0  # Normalize to 0-1
    return img_normalized

# Prediction and overlay function
def predict(input_img):
    # Ensure image is RGB and numpy array
    img = np.array(input_img.convert("RGB"))

    # Preprocess
    preprocessed_img = preprocess_image(img)
    input_tensor = np.expand_dims(preprocessed_img, axis=0)  # Add batch dimension

    # Model prediction
    prediction = model.predict(input_tensor)[0]  # Remove batch dim

    # Post-processing mask
    mask = (prediction > 0.5).astype(np.uint8)  # Binary mask
    mask_resized = cv2.resize(mask, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_NEAREST)

    # Create overlay
    overlay = img.astype(np.float32) / 255.0  # Normalize input image
    alpha = 0.5  # Transparency of overlay

    # Create red mask in RGB format
    red_mask = np.zeros_like(overlay)
    red_mask[:, :, 0] = mask_resized  # Red channel

    # Alpha blend original image with red mask
    blended = (1 - alpha) * overlay + alpha * red_mask
    blended = np.clip(blended * 255, 0, 255).astype(np.uint8)

    return blended

# Gradio interface
interface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil", label="Upload Image"),
    outputs=gr.Image(type="numpy", label="Segmented Image"),
    title="Image Segmentation App",
    description="Upload an image and get the segmentation mask overlay using your trained model."
)

# Launch Gradio app (enable public link for Hugging Face Spaces)
interface.launch(share=True)