import cv2 import streamlit as st st.set_page_config(layout="wide") import streamlit.components.v1 as components import time import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.cm as cm from PIL import Image from tf_keras_vis.gradcam import Gradcam from io import BytesIO if "model" not in st.session_state: st.session_state.model = tf_model = tf.keras.models.load_model('best_model.h5') import base64 import os #****************************************/ # GRAD CAM #*********************************************# gradcam = Gradcam(st.session_state.model, model_modifier=None, clone=False) def generate_gradcam(pil_image, target_class): # Convert PIL to array and preprocess img_array = np.array(pil_image) img_preprocessed = tf.keras.applications.vgg16.preprocess_input(img_array.copy()) img_tensor = tf.expand_dims(img_preprocessed, axis=0) # Generate heatmap loss = lambda output: tf.reduce_mean(output[:, target_class]) cam = gradcam(loss, img_tensor, penultimate_layer=-1) # Process heatmap cam = cam if cam.ndim > 2: cam = cam.squeeze() cam = np.maximum(cam, 0) cam = cv2.resize(cam, (224, 224)) cam = cam / cam.max() if cam.max() > 0 else cam return cam def convert_image_to_base64(pil_image): buffered = BytesIO() pil_image.save(buffered, format="PNG") return base64.b64encode(buffered.getvalue()).decode() #--------------------------------------------------# class_labels=[ 'Cyst', 'Normal','Stone', 'Tumor'] def load_tensorflow_model(): tf_model = tf.keras.models.load_model('best_model.h5') return tf_model def predict_image(image): time.sleep(2) image = image.resize((224, 224)) image = np.expand_dims(image, axis=0) predictions = st.session_state.model.predict(image) return predictions logo_path = "tensorflow.png" main_bg_ext = 'png' main_bg = 'bg1.jpg' # Read and encode the logo image with open(logo_path, "rb") as image_file: encoded_logo = base64.b64encode(image_file.read()).decode() # Custom CSS to style the logo above the sidebar st.markdown( f"""
Logo

KidneyScan AI

Empowering Early Diagnosis with AI
""", unsafe_allow_html=True ) loading_html = """
""" page = "Home" # Display content based on the selected page # Define the page content dynamically if page == "Home": #components.html(html_string) # JavaScript works #st.markdown(html_string, unsafe_allow_html=True) image_path = "image.jpg" st.container() st.markdown(f"""

Kidney Disease Classfication
Using Transfer learning

This web application utilizes deep learning to classify kidney ultrasound images
into four categories: Normal, Cyst, Tumor, and Stone Class. Built with Streamlit and powered by
a TensorFlow transfer learning model based on VGG16 the app provides a simple and efficient way for users
to upload kidney scans and receive instant predictions. The model analyzes the image and classifies it based
on learned patterns, offering a confidence score for better interpretation.
""", unsafe_allow_html=True, ) uploaded_file = st.file_uploader("Choose a file", type=["png", "jpg", "jpeg"],key="upload-btn") if uploaded_file is not None: images = Image.open(uploaded_file) # Rewind file pointer to the beginning uploaded_file.seek(0) file_content = uploaded_file.read() # Read file once # Convert to base64 for HTML display encoded_image = base64.b64encode(file_content).decode() # Read and process image pil_image = Image.open(uploaded_file).convert('RGB').resize((224, 224)) img_array = np.array(pil_image) prediction = predict_image(images) max_index = int(np.argmax(prediction[0])) print(f"max index:{max_index}") max_score = prediction[0][max_index] predicted_class = np.argmax(prediction[0]) highlight_class = "highlight" # Special class for the highest confidence score # Generate Grad-CAM cam = generate_gradcam(pil_image, predicted_class) # Create overlay heatmap = cm.jet(cam)[..., :3] heatmap = (heatmap * 255).astype(np.uint8) overlayed_image = cv2.addWeighted(img_array, 0.6, heatmap, 0.4, 0) # Convert to PIL overlayed_pil = Image.fromarray(overlayed_image) # Convert to base64 orig_b64 = convert_image_to_base64(pil_image) overlay_b64 = convert_image_to_base64(overlayed_pil) content = f"""
Uploaded Image

{class_labels[0]}

T Score: {prediction[0][0]:.2f}

{class_labels[1]}

T Score: {prediction[0][1]:.2f}

{class_labels[2]}

T Score: {prediction[0][2]:.2f}

{class_labels[3]}

T Score: {prediction[0][3]:.2f}

""" # Close the gallery and content div # Render the content placeholder = st.empty() # Create a placeholder placeholder.markdown(loading_html,unsafe_allow_html=True) time.sleep(5) # Wait for 5 seconds placeholder.empty() st.markdown(content, unsafe_allow_html=True) else: default_image_path = "image.jpg" with open(image_path, "rb") as image_file: encoded_image = base64.b64encode(image_file.read()).decode() st.markdown(f"""
Default Image
""", unsafe_allow_html=True, )