Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import keras
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from keras.preprocessing import image as keras_image
|
| 7 |
+
|
| 8 |
+
# load the model
|
| 9 |
+
def load_model(model_path):
|
| 10 |
+
model = keras.models.load_model(model_path)
|
| 11 |
+
return model
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Function to preprocess the input image
|
| 15 |
+
def preprocess_image(image):
|
| 16 |
+
# Convert image to grayscale
|
| 17 |
+
image = np.array(image)
|
| 18 |
+
image = Image.fromarray(image).convert('L')
|
| 19 |
+
|
| 20 |
+
# Resize the image
|
| 21 |
+
image = image.resize((128, 128))
|
| 22 |
+
|
| 23 |
+
# Convert to numpy array and normalize
|
| 24 |
+
image = np.array(image)
|
| 25 |
+
image = image / 255.0
|
| 26 |
+
|
| 27 |
+
# Add batch dimension
|
| 28 |
+
image = np.expand_dims(image, axis=-1)
|
| 29 |
+
|
| 30 |
+
# Stack the grayscale image to make it a 2-channel image
|
| 31 |
+
image = np.repeat(image, 2, axis=-1)
|
| 32 |
+
|
| 33 |
+
# Add batch dimension
|
| 34 |
+
image = np.expand_dims(image, axis=0)
|
| 35 |
+
|
| 36 |
+
return image
|
| 37 |
+
|
| 38 |
+
# Function to perform segmentation prediction
|
| 39 |
+
def predict_segmentation(model, image):
|
| 40 |
+
segmentation_map = model.predict(image)[0]
|
| 41 |
+
threshold = 0.5
|
| 42 |
+
segmented_image = (segmentation_map > threshold).astype(np.uint8)
|
| 43 |
+
segmented_image = Image.fromarray(segmented_image * 255)
|
| 44 |
+
return segmented_image
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Define Gradio interface
|
| 48 |
+
def gradio_interface(model_path):
|
| 49 |
+
# Load the model
|
| 50 |
+
model = load_model(model_path)
|
| 51 |
+
|
| 52 |
+
# Define input and output components
|
| 53 |
+
demo = gr.Interface(lambda image: predict_segmentation(model, preprocess_image(image)),
|
| 54 |
+
inputs = "image" ,
|
| 55 |
+
outputs= "image" ,
|
| 56 |
+
title = "Brain Tumor Segmentation",
|
| 57 |
+
description = "Upload an image of a brain scan, and the model will segment the brain tumor.")
|
| 58 |
+
|
| 59 |
+
demo.launch(share=True)
|
| 60 |
+
|
| 61 |
+
gradio_interface("model_x81_dcs65.h5")
|