madboi commited on
Commit
4e0c33e
·
verified ·
1 Parent(s): d1f1d28

Upload 3 files

Browse files
Files changed (3) hide show
  1. dic.py +112 -0
  2. requirements.txt +5 -0
  3. tb_classification_model.h5 +3 -0
dic.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import cv2
4
+ import tensorflow as tf
5
+ from tensorflow.keras.preprocessing import image
6
+ import matplotlib.pyplot as plt
7
+ from PIL import Image
8
+ import gdown
9
+
10
+ # Load trained model
11
+ # model_path = "tb_classification_model.h5" # Ensure this file exists
12
+ # model = tf.keras.models.load_model(model_path)
13
+
14
+ file_id = "1S6Keu4Qmaj6NrtX3lF3s9tbUFlyYhDhL"
15
+ output_path = "tb_classification_model.h5"
16
+
17
+ # Download the model
18
+ gdown.download(f"https://drive.google.com/uc?id={file_id}", output_path, quiet=False)
19
+
20
+ # Load the model
21
+ model = tf.keras.models.load_model(output_path)
22
+
23
+
24
+ def preprocess_image(img):
25
+ img = img.resize((224, 224)) # Resize to model input size
26
+ img_array = image.img_to_array(img)
27
+
28
+ # Convert grayscale images to 3-channel RGB
29
+ if img_array.shape[-1] == 1:
30
+ img_array = np.repeat(img_array, 3, axis=-1) # (224, 224, 1) → (224, 224, 3)
31
+
32
+ img_array = img_array / 255.0 # Normalize
33
+ img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
34
+
35
+ return img_array # ✅ Return processed image
36
+
37
+
38
+ # Function to compute Grad-CAM
39
+ def compute_gradcam(model, img_array, layer_name="conv4_block5_out"):
40
+ grad_model = tf.keras.models.Model(inputs=model.input,
41
+ outputs=[model.get_layer(layer_name).output, model.output])
42
+
43
+ with tf.GradientTape() as tape:
44
+ conv_outputs, predictions = grad_model(img_array)
45
+ class_idx = tf.argmax(predictions[0])
46
+ loss = predictions[:, class_idx]
47
+
48
+ grads = tape.gradient(loss, conv_outputs)
49
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
50
+
51
+ conv_outputs = conv_outputs.numpy()[0]
52
+ heatmap = np.dot(conv_outputs, pooled_grads.numpy())
53
+
54
+ heatmap = np.maximum(heatmap, 0) # ReLU
55
+ heatmap /= np.max(heatmap) + 1e-10 # Normalize
56
+ return heatmap
57
+
58
+ # Function to overlay Grad-CAM heatmap
59
+ def overlay_gradcam(img, heatmap, alpha=0.4):
60
+ """Overlay Grad-CAM heatmap on the original image."""
61
+
62
+ # Ensure heatmap is the same size as the image
63
+ heatmap = cv2.resize(heatmap, (img.width, img.height)) # Resize to match original image
64
+
65
+ # Normalize heatmap to [0,255] and apply color mapping
66
+ heatmap = np.uint8(255 * heatmap)
67
+ heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
68
+
69
+ # Convert PIL image to NumPy array
70
+ original = np.array(img)
71
+
72
+ # If original image is grayscale, convert to RGB
73
+ if len(original.shape) == 2 or original.shape[-1] == 1:
74
+ original = cv2.cvtColor(original, cv2.COLOR_GRAY2RGB)
75
+
76
+ # Ensure both images have the same shape (H, W, 3)
77
+ if heatmap.shape != original.shape:
78
+ heatmap = cv2.resize(heatmap, (original.shape[1], original.shape[0]))
79
+
80
+ # Blend original image with heatmap
81
+ superimposed = cv2.addWeighted(original, 1 - alpha, heatmap, alpha, 0)
82
+
83
+ return superimposed
84
+
85
+ # Streamlit UI
86
+ st.title("Tuberculosis Detection using ResNet50")
87
+ st.write("Upload a Chest X-ray image to classify as **Normal** or **TB**.")
88
+
89
+ uploaded_file = st.file_uploader("Choose a Chest X-ray Image...", type=["jpg", "png", "jpeg"])
90
+
91
+ if uploaded_file is not None:
92
+ image_pil = Image.open(uploaded_file)
93
+ st.image(image_pil, caption="Uploaded Image", use_container_width=True)
94
+
95
+ # Preprocess image
96
+ img_array = preprocess_image(image_pil)
97
+
98
+ # Get model prediction
99
+ prediction = model.predict(img_array)[0][0]
100
+ result = "Tuberculosis Detected" if prediction > 0.5 else "Normal"
101
+ confidence = prediction if prediction > 0.5 else 1 - prediction
102
+
103
+ st.subheader(f"Prediction: **{result}**")
104
+ st.write(f"Confidence: **{confidence:.2%}**")
105
+
106
+ # Generate Grad-CAM
107
+ heatmap = compute_gradcam(model, img_array)
108
+ gradcam_output = overlay_gradcam(image_pil, heatmap)
109
+
110
+ # Show Grad-CAM
111
+ st.subheader("Grad-CAM Visualization")
112
+ st.image(gradcam_output, caption="Grad-CAM Heatmap", use_container_width=True)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ opencv-python-headless
2
+ streamlit
3
+ numpy
4
+ Pillow
5
+ tensorflow
tb_classification_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e31385eb92710b2e75ce67989885b32fbcadf88b4667dcabdcd613c5e927be3
3
+ size 828735528