Pneumonia / app.py
aqilarsul's picture
Update app.py
c9237e0 verified
Raw
History Blame Contribute Delete
1.41 kB
import numpy as np
import tensorflow as tf
from PIL import Image
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
import gradio as gr
# Load the Keras model
model = load_model('model.keras')
classnames = np.array(['Normal', 'Pneumonia'])
# Define image preprocessing
def transform(img):
img = img.resize((224, 224)) # Resize to match the input size expected by the model
img_array = img_to_array(img) # Convert PIL image to numpy array
img_array = img_array / 255.0 # Normalize pixel values
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
return img_array
# Define the classify function
def classify(path):
img = Image.open(path)
processed_img = transform(img)
result = model.predict(processed_img)[0]
index = np.argmax(result) # Get the index of the highest probability
predict = str(classnames[index])
return predict
# Create the Gradio interface
with gr.Blocks(theme=gr.themes.Default(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.blue, neutral_hue=gr.themes.colors.zinc)) as demo:
img_path = gr.Image(label="Input Image", type="filepath", height=512, width=512)
output = gr.Textbox(label="Output")
clear_btn = gr.ClearButton([img_path, output], variant="stop")
img_path.upload(classify, inputs=img_path, outputs=output)
demo.launch()