Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
from PIL import Image
|
4 |
+
from keras.models import load_model
|
5 |
+
import tensorflow as tf
|
6 |
+
|
7 |
+
# Load the trained model
|
8 |
+
model = load_model('brain_tumor_model.h5')
|
9 |
+
|
10 |
+
# Define the prediction function
|
11 |
+
def predict_image(image):
|
12 |
+
# Resize the image to match training input
|
13 |
+
img = image.resize((128, 128))
|
14 |
+
|
15 |
+
# Convert the image to a NumPy array
|
16 |
+
img_array = np.array(img)
|
17 |
+
|
18 |
+
# Handle grayscale images
|
19 |
+
if img_array.ndim == 2:
|
20 |
+
img_array = np.stack((img_array,) * 3, axis=-1)
|
21 |
+
elif img_array.shape[2] == 4:
|
22 |
+
# Convert RGBA to RGB
|
23 |
+
img_array = img_array[..., :3]
|
24 |
+
|
25 |
+
# Normalize the image
|
26 |
+
img_array = img_array / 255.0
|
27 |
+
|
28 |
+
# Expand dimensions to match model input
|
29 |
+
img_array = np.expand_dims(img_array, axis=0)
|
30 |
+
|
31 |
+
# Make prediction
|
32 |
+
prediction = model.predict(img_array)
|
33 |
+
|
34 |
+
# Interpret the prediction
|
35 |
+
predicted_class = np.argmax(prediction, axis=1)[0]
|
36 |
+
confidence = prediction[0][predicted_class]
|
37 |
+
|
38 |
+
if predicted_class == 0:
|
39 |
+
result = f'No tumor detected with confidence {confidence:.2%}.'
|
40 |
+
else:
|
41 |
+
result = f'Tumor detected with confidence {confidence:.2%}.'
|
42 |
+
|
43 |
+
return result
|
44 |
+
|
45 |
+
# Create Gradio interface
|
46 |
+
interface = gr.Interface(
|
47 |
+
fn=predict_image,
|
48 |
+
inputs=gr.inputs.Image(type="pil"),
|
49 |
+
outputs="text",
|
50 |
+
title="Brain Tumor Detection AI App",
|
51 |
+
description="Upload a brain MRI image to detect the presence of a tumor.",
|
52 |
+
examples=[
|
53 |
+
["example_images/no_tumor_example.jpg"],
|
54 |
+
["example_images/yes_tumor_example.jpg"],
|
55 |
+
],
|
56 |
+
)
|
57 |
+
|
58 |
+
if __name__ == "__main__":
|
59 |
+
interface.launch()
|