Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import tensorflow as tf
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
# Load the TensorFlow Lite model
|
7 |
+
interpreter = tf.lite.Interpreter(model_path="pneumonia_classifier.tflite")
|
8 |
+
interpreter.allocate_tensors()
|
9 |
+
|
10 |
+
# Get input and output tensors
|
11 |
+
input_details = interpreter.get_input_details()
|
12 |
+
output_details = interpreter.get_output_details()
|
13 |
+
|
14 |
+
# Define a function to resize the input image
|
15 |
+
def resize_image(image):
|
16 |
+
image_resized = tf.image.resize(image, [224, 224])
|
17 |
+
return image_resized.numpy()
|
18 |
+
|
19 |
+
# Define a function to perform inference on the TensorFlow Lite model
|
20 |
+
def classify_image(image):
|
21 |
+
image_resized = resize_image(image)
|
22 |
+
input_data = np.expand_dims(image_resized, axis=0).astype(np.float32)
|
23 |
+
interpreter.set_tensor(input_details[0]['index'], input_data)
|
24 |
+
interpreter.invoke()
|
25 |
+
output_data = interpreter.get_tensor(output_details[0]['index'])
|
26 |
+
return output_data[0]
|
27 |
+
|
28 |
+
# Define the labels for pneumonia classes
|
29 |
+
labels = ['0: Normal', '1: Pneumonia']
|
30 |
+
|
31 |
+
# Define the main Gradio app
|
32 |
+
def pneumonia_classification(image):
|
33 |
+
pil_image = Image.fromarray(image.astype('uint8'), 'RGB')
|
34 |
+
probabilities = classify_image(pil_image)
|
35 |
+
prediction = labels[np.argmax(probabilities)]
|
36 |
+
return {
|
37 |
+
"Prediction": prediction,
|
38 |
+
"Probability": f"{probabilities.max() * 100:.2f}%"
|
39 |
+
}
|
40 |
+
|
41 |
+
# Create the Gradio interface
|
42 |
+
gr.Interface(
|
43 |
+
fn=pneumonia_classification,
|
44 |
+
inputs="image",
|
45 |
+
outputs="json",
|
46 |
+
title="Pneumonia Classification",
|
47 |
+
examples=["normal.jpg", "pneumonia.jpg"],
|
48 |
+
description="""The app provides users with the ability to classify chest X-ray images as 'Normal' or 'Pneumonia'. Please upload an image of a chest X-ray to classify it and provide information about the prediction.""",
|
49 |
+
).launch()
|