import streamlit as st import tensorflow as tf import numpy as np from PIL import Image import cv2 import os from tensorflow.keras.applications.resnet50 import preprocess_input # Load the saved models model_vgg = tf.keras.models.load_model("brain_tumor_model_26.h5") classes_vgg = ["No Tumor detected", "Tumor detected"] model_resnet = tf.keras.models.load_model("Tumor_GliMeninPitu_model.h5") # model_resnet = tf.keras.models.load_model("model.h5") classes_resnet = ["Glioma", "Meningioma", "No Tumor", "Pituitary"] # Function to preprocess image def preprocess_image_old(uploaded_image, target_size): img = Image.open(uploaded_image) # Check if the image is grayscale if img.mode == 'L': # Convert grayscale to RGB by repeating the single channel img = img.convert('RGB') st.info("Gray scale image has been converted to three channels.") # Resize the image img = img.resize(target_size) # Convert image to numpy array and preprocess img_array = np.array(img) # Ensure the image has three channels if img_array.shape[-1] == 4: img_array = img_array[:, :, :3] img_array = tf.keras.applications.vgg16.preprocess_input(img_array) # Add batch dimension img_array = np.expand_dims(img_array, axis=0) return img_array def preprocess_image_mc(uploaded_image, target_size=(224,224)): # Read the image from the uploaded file img = Image.open(uploaded_image) # Convert the image to RGB format (ResNet50 expects RGB) img = img.convert("RGB") # Resize the image to match the target size used during training img = img.resize(target_size) # Convert the image to a numpy array img_array = np.array(img) # Preprocess the image using ResNet50 preprocessing img_array = preprocess_input(img_array) # Expand the dimensions to match the model's input shape (batch size of 1) img_array = np.expand_dims(img_array, axis=0) return img_array def preprocess_image_mcb(image_path, target_size=(224, 224)): # Read the image from the given path using cv2.imread img = cv2.imread(image_path) # Use COLOR mode # Resize the image to match the target size img = cv2.resize(img, target_size) # Convert the image to a numpy array img_array = np.array(img) # Preprocess the image using ResNet50 preprocessing (if needed) # img_array = preprocess_input(img_array) # Expand the dimensions to match the model's input shape (batch size of 1) img_array = np.expand_dims(img_array, axis=0) return img_array def preprocess_image(uploaded_image, target_size=(224, 224)): if uploaded_image is not None: # Read the image from BytesIO object file_bytes = np.asarray(bytearray(uploaded_image.read()), dtype=np.uint8) img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) # Resize the image img = cv2.resize(img, target_size) # Convert image to RGB if it's not already (OpenCV uses BGR by default) if img.shape[2] == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Normalize the pixel values (the model expects values in [0, 1]) img_array = img.astype('float32') / 255.0 # Add batch dimension img_array = np.expand_dims(img_array, axis=0) return img_array return None # Function to analyze binary classification def analyze_binary(uploaded_image, model, classes): if uploaded_image is not None: # Preprocess the uploaded image img_array = preprocess_image(uploaded_image, (224, 224)) if img_array is not None: # Make predictions using the loaded model predictions = model.predict(img_array) # Get the class label with the highest probability class_label = np.argmax(predictions) pred_class = classes[class_label] confidence = predictions[0][class_label] # Display prediction and confidence with stylish colors st.markdown( f"
Prediction: {pred_class}
", unsafe_allow_html=True, ) st.markdown( f"
Confidence Level: {confidence:.2%}
", unsafe_allow_html=True, ) else: st.warning("Please upload an image before clicking 'Analyze Binary'.") # Function to analyze multiclass classification def analyze_multiclass(uploaded_image, model, classes): if uploaded_image is not None: # Preprocess the uploaded image img_array = preprocess_image_mcb(uploaded_image, (224, 224)) if img_array is not None: # Make predictions using the loaded model predictions = model.predict(img_array) # Get the class label with the highest probability class_label = np.argmax(predictions) pred_class = classes[class_label] confidence = predictions[0][class_label] # Display prediction and confidence with stylish colors st.markdown( f"
Prediction: {pred_class}
", unsafe_allow_html=True, ) st.markdown( f"
Confidence Level: {confidence:.2%}
", unsafe_allow_html=True, ) else: st.warning("Please upload an image before clicking 'Analyze Multiclass'.") # Set page configuration and layout st.set_page_config( page_title="Image Classification App", page_icon=":camera:", layout="wide", ) # Header logo with a colorful border st.markdown( """ """, unsafe_allow_html=True, ) st.markdown("
", unsafe_allow_html=True) st.image("RCAIoT_logo.png", use_column_width=False) st.markdown("
", unsafe_allow_html=True) def open_google_maps(): st.markdown("## Nearest Hospital Location") st.markdown("Here is the nearest hospital's location on Google Maps:") # You can replace the following URL with the actual Google Maps URL google_maps_url = "https://www.google.com/maps" st.write(f"[Open Google Maps]({google_maps_url})") # Main content col1, col2 = st.columns([1, 1]) with col1: st.header("Upload Image") uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"], key="upload_image") if uploaded_image is not None: # Create an 'uploads' directory if it doesn't exist if not os.path.exists('uploads'): os.makedirs('uploads') # Construct the path to save the uploaded file file_path = os.path.join('uploads', uploaded_image.name) # Save the uploaded file to the 'uploads' directory with open(file_path, "wb") as f: f.write(uploaded_image.getbuffer()) st.image(uploaded_image, caption="Uploaded Image", use_column_width=False, width=300) st.markdown( """ """, unsafe_allow_html=True, ) with col2: st.header("Results") # Stylish Analyze and Reset buttons in a horizontal row st.markdown( """ """, unsafe_allow_html=True, ) st.markdown("
", unsafe_allow_html=True) if st.button("Detect Tumor", key="analyze_binary_button"): analyze_binary(uploaded_image, model_vgg, classes_vgg) if st.button("Help"): open_google_maps() if st.button("Classify cancer", key="analyze_multiclass_button"): analyze_multiclass(file_path, model_resnet, classes_resnet) if st.button("Help"): open_google_maps()