OverMind0 commited on
Commit
bf5ebd3
·
verified ·
1 Parent(s): b6ddce3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -12
app.py CHANGED
@@ -88,29 +88,44 @@ transform = transforms.Compose([
88
  def predict_with_gradcam(image):
89
  image = image.convert("RGB")
90
  input_tensor = transform(image).unsqueeze(0).to(device)
 
 
91
  output = model(input_tensor)
92
  pred_idx = output.argmax(dim=1).item()
93
  pred_label = class_names[pred_idx]
94
 
95
- gradcam = GradCAM(model, model.conv4)
96
- cam = gradcam.generate(input_tensor)
97
- cam_resized = cv2.resize(cam, (224, 224))
98
-
99
  img_np = np.array(image.resize((224, 224))) / 255.0
100
- cam_overlay = cv2.applyColorMap(np.uint8(255 * cam_resized), cv2.COLORMAP_JET)
101
- cam_overlay = cv2.cvtColor(cam_overlay, cv2.COLOR_BGR2RGB)
102
- overlay = (0.5 * img_np + 0.5 * cam_overlay / 255.0)
103
- overlay = np.clip(overlay, 0, 1)
104
 
105
- return pred_label, overlay
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- # Gradio interface
108
  interface = gr.Interface(
109
  fn=predict_with_gradcam,
110
  inputs=gr.Image(type="pil"),
111
- outputs=["label", "image"],
 
 
 
 
 
112
  title="🦷 Teeth Disease Classifier with Grad-CAM",
113
- description="Upload an image of teeth and the model will predict the disease with Grad-CAM visualization."
114
  )
115
 
 
116
  interface.launch()
 
88
  def predict_with_gradcam(image):
89
  image = image.convert("RGB")
90
  input_tensor = transform(image).unsqueeze(0).to(device)
91
+
92
+ # Prediction
93
  output = model(input_tensor)
94
  pred_idx = output.argmax(dim=1).item()
95
  pred_label = class_names[pred_idx]
96
 
97
+ # Prepare base image
 
 
 
98
  img_np = np.array(image.resize((224, 224))) / 255.0
 
 
 
 
99
 
100
+ # Multiple layer Grad-CAMs
101
+ target_layers = [model.conv2, model.conv3, model.conv4]
102
+ visualizations = []
103
+
104
+ for layer in target_layers:
105
+ gradcam = GradCAM(model, layer)
106
+ cam = gradcam.generate(input_tensor)
107
+ cam_resized = cv2.resize(cam, (224, 224))
108
+ cam_overlay = cv2.applyColorMap(np.uint8(255 * cam_resized), cv2.COLORMAP_JET)
109
+ cam_overlay = cv2.cvtColor(cam_overlay, cv2.COLOR_BGR2RGB)
110
+ overlay = (0.5 * img_np + 0.5 * cam_overlay / 255.0)
111
+ overlay = np.clip(overlay, 0, 1)
112
+ visualizations.append(overlay)
113
+
114
+ return pred_label, *visualizations
115
+
116
 
 
117
  interface = gr.Interface(
118
  fn=predict_with_gradcam,
119
  inputs=gr.Image(type="pil"),
120
+ outputs=[
121
+ gr.Label(label="Predicted Class"),
122
+ gr.Image(label="Grad-CAM: Conv2"),
123
+ gr.Image(label="Grad-CAM: Conv3"),
124
+ gr.Image(label="Grad-CAM: Conv4")
125
+ ],
126
  title="🦷 Teeth Disease Classifier with Grad-CAM",
127
+ description="Upload a teeth image. The model predicts the class and shows Grad-CAM visualizations for multiple convolutional layers."
128
  )
129
 
130
+
131
  interface.launch()