File size: 9,310 Bytes
71648e5 542b6b9 cfea14a 542b6b9 71648e5 8a4c886 542b6b9 8a4c886 cfea14a 8a4c886 542b6b9 8a4c886 542b6b9 cfea14a 542b6b9 8a4c886 cfea14a 8a4c886 71648e5 8a4c886 71648e5 8a4c886 71648e5 821ccd0 71648e5 cfea14a 71648e5 cfea14a 71648e5 8a4c886 71648e5 8a4c886 71648e5 8a4c886 71648e5 8a4c886 21fff94 8a4c886 821ccd0 cfea14a 821ccd0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | 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"<div class='results-text' style='color: #009688;'>Prediction: <span class='results-values'>{pred_class}</span></div>",
unsafe_allow_html=True,
)
st.markdown(
f"<div class='results-text' style='color: #E91E63;'>Confidence Level: <span class='results-values'>{confidence:.2%}</span></div>",
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"<div class='results-text' style='color: #4CAF50;'>Prediction: <span class='results-values'>{pred_class}</span></div>",
unsafe_allow_html=True,
)
st.markdown(
f"<div class='results-text' style='color: #FFC107;'>Confidence Level: <span class='results-values'>{confidence:.2%}</span></div>",
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(
"""
<style>
.header-logo {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
padding: 20px;
background-color: #2196F3;
border-radius: 10px;
color: white;
}
</style>
""",
unsafe_allow_html=True,
)
st.markdown("<div class='header-logos'>", unsafe_allow_html=True)
st.image("RCAIoT_logo.png", use_column_width=False)
st.markdown("</div>", 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(
"""
<style>
img {
max-height: 300px;
}
</style>
""",
unsafe_allow_html=True,
)
with col2:
st.header("Results")
# Stylish Analyze and Reset buttons in a horizontal row
st.markdown(
"""
<style>
.analyze-reset-buttons {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 20px;
}
.analyze-reset-buttons button {
flex: 1;
margin: 10px;
padding: 10px;
background-color: #2196F3;
color: white;
font-size: 16px;
text-align: center;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.analyze-reset-buttons button:hover {
background-color: #1565C0;
}
.results-text {
font-size: 24px;
font-weight: bold;
margin-top: 20px;
}
.results-values {
font-size: 18px;
font-weight: bold;
margin-top: 10px;
}
</style>
""",
unsafe_allow_html=True,
)
st.markdown("<div class='analyze-reset-buttons'>", 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() |