import streamlit as st import numpy as np import cv2 from PIL import Image from lime import lime_image from tensorflow.keras.models import load_model from tensorflow.keras.applications.xception import Xception, preprocess_input, decode_predictions from tensorflow.keras.preprocessing import image import tensorflow as tf import matplotlib.pyplot as plt # Load Xception model model = Xception(weights='imagenet') # Function to preprocess input image for the model def preprocess_image(img_path): img = image.load_img(img_path, target_size=(299, 299)) # Resize to Xception input size img_array = image.img_to_array(img) img_array = np.expand_dims(img_array, axis=0) img_array = preprocess_input(img_array) return img, img_array # Function to get GradCAM heatmap def get_gradcam(img_array, model, layer_name): grad_model = tf.keras.models.Model([model.inputs], [model.get_layer(layer_name).output, model.output]) with tf.GradientTape() as tape: conv_output, predictions = grad_model(img_array) class_idx = np.argmax(predictions[0]) loss = predictions[:, class_idx] output = conv_output[0] grads = tape.gradient(loss, conv_output)[0] guided_grads = tf.cast(output > 0, 'float32') * tf.cast(grads > 0, 'float32') * grads weights = tf.reduce_mean(guided_grads, axis=(0, 1)) cam = np.dot(output, weights) cam = cv2.resize(cam, (299, 299), cv2.INTER_LINEAR) # Xception input size cam = np.maximum(cam, 0) cam = cam / cam.max() return cam # Function to apply LIME to the image def lime_explanation(img_path, model): explainer = lime_image.LimeImageExplainer() img, img_array = preprocess_image(img_path) def predict_fn(images): return model.predict(preprocess_input(images)) explanation = explainer.explain_instance(np.array(img), predict_fn, top_labels=1, hide_color=0, num_samples=100) lime_img, mask = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=False, hide_rest=False) return lime_img,mask # Streamlit app st.title('Brain Tumor Identification') uploaded_file = st.file_uploader("Choose a brain MRI image (JPEG format)", type="jpeg") if uploaded_file is not None: # Display the uploaded image st.image(uploaded_file, caption="Uploaded Image", use_column_width=True) # Preprocess the image img, img_array = preprocess_image(uploaded_file) # Get GradCAM heatmap (fill in the layer name) #layer_name = 'block14_sepconv2_act' # Replace with the appropriate layer name for Xception #gradcam = get_gradcam(img_array, model, layer_name) # Apply LIME explanation lime_img,mask = lime_explanation(uploaded_file, model) # Display GradCAM and LIME outputs #st.subheader("GradCAM Output") #st.image(gradcam, caption="GradCAM Heatmap", use_column_width=True) st.subheader("LIME Output") st.image(lime_img, caption="LIME Explanation", use_column_width=True)