Spaces:
Runtime error
Runtime error
import gradio as gr | |
import numpy as np | |
from tensorflow.keras.models import load_model | |
from tensorflow.keras.preprocessing import image | |
from PIL import Image | |
# Load your custom model | |
model = load_model("lung_cancer_detection_model.h5", compile=False) | |
# Compile your model using the optimizer | |
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]) | |
# Function to preprocess the uploaded image | |
def predict_single_image(img, model, target_size=(128, 128)): | |
# Convert the PIL image to grayscale and resize | |
img = img.convert("L") # Convert to grayscale | |
img = img.resize(target_size) # Resize to target size | |
# Convert image to array | |
img_array = np.array(img) | |
img_array = np.expand_dims(img_array, axis=0) # Expand dimensions for batch | |
img_array = img_array / 255.0 # Normalize the image | |
# Predict the class probabilities | |
probabilities = model.predict(img_array) | |
# Determine the predicted class label | |
predicted_class = "positive" if probabilities[0][0] > 0.5 else "negative" | |
return predicted_class, probabilities[0][0] | |
# Function to classify the uploaded image | |
def classify_lung_cancer(img): | |
# Call the function to predict the class label for the single image | |
predicted_label, confidence = predict_single_image(img, model, target_size=(128, 128)) | |
# Return the formatted prediction | |
return f"Prediction: {predicted_label}\n(Confidence: {confidence:.2f})" | |
# Define the Gradio interface | |
iface = gr.Interface( | |
fn=classify_lung_cancer, | |
inputs=gr.Image(type="pil"), # Pass the PIL image directly | |
outputs=gr.Textbox(), | |
live=True, | |
title="Lung Cancer Classification", | |
description="Upload an image and the model will classify it as positive or negative for lung cancer.", | |
) | |
# Create a Gradio interface | |
iface.launch(share=True) | |