Conn Finnegan
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
|
|
|
| 3 |
from torchvision import models, transforms
|
| 4 |
-
from torch.nn import functional as F
|
| 5 |
from PIL import Image
|
| 6 |
import numpy as np
|
| 7 |
import cv2
|
|
@@ -14,82 +14,79 @@ model.eval()
|
|
| 14 |
|
| 15 |
classes = ['benign', 'malignant']
|
| 16 |
|
| 17 |
-
#
|
| 18 |
transform = transforms.Compose([
|
| 19 |
transforms.Resize((224, 224)),
|
| 20 |
transforms.ToTensor()
|
| 21 |
])
|
| 22 |
|
| 23 |
-
# Grad-CAM
|
| 24 |
-
|
| 25 |
-
gradients = []
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
model.zero_grad()
|
| 34 |
output = model(input_tensor)
|
| 35 |
-
class_score = output[0,
|
| 36 |
class_score.backward()
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
for i, w in enumerate(weights):
|
| 45 |
-
cam += w * activations[i]
|
| 46 |
-
|
| 47 |
cam = np.maximum(cam, 0)
|
| 48 |
cam = cv2.resize(cam, (224, 224))
|
| 49 |
-
cam
|
| 50 |
-
cam
|
| 51 |
-
|
| 52 |
return cam
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
def
|
| 56 |
-
global
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
img_rgb = img.convert("RGB")
|
| 65 |
-
input_tensor = transform(img_rgb).unsqueeze(0)
|
| 66 |
-
|
| 67 |
-
with torch.no_grad():
|
| 68 |
-
output = model(input_tensor)
|
| 69 |
-
probs = F.softmax(output[0], dim=0)
|
| 70 |
-
pred_class = torch.argmax(probs).item()
|
| 71 |
|
| 72 |
-
# Grad-CAM
|
| 73 |
cam = generate_gradcam(input_tensor, pred_class)
|
| 74 |
|
| 75 |
-
# Convert
|
| 76 |
-
heatmap = (
|
| 77 |
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
| 78 |
|
| 79 |
-
# Overlay
|
| 80 |
-
img_np = np.array(
|
| 81 |
overlay = cv2.addWeighted(img_np, 0.6, heatmap, 0.4, 0)
|
| 82 |
-
|
| 83 |
-
# Convert back to PIL
|
| 84 |
overlay_img = Image.fromarray(cv2.cvtColor(overlay, cv2.COLOR_BGR2RGB))
|
| 85 |
|
| 86 |
return {classes[i]: float(probs[i]) for i in range(2)}, overlay_img
|
| 87 |
|
| 88 |
-
#
|
| 89 |
-
title = "🧠 Lumen: Skin Cancer Classifier
|
| 90 |
description = """
|
| 91 |
Upload a dermoscopic image of a mole or lesion. The model will classify it as <b>benign</b> or <b>malignant</b> and show a heatmap of what it focused on.<br><br>
|
| 92 |
-
<b>Disclaimer:</b>
|
| 93 |
"""
|
| 94 |
|
| 95 |
demo = gr.Interface(
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
from torchvision import models, transforms
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
import numpy as np
|
| 7 |
import cv2
|
|
|
|
| 14 |
|
| 15 |
classes = ['benign', 'malignant']
|
| 16 |
|
| 17 |
+
# Transform
|
| 18 |
transform = transforms.Compose([
|
| 19 |
transforms.Resize((224, 224)),
|
| 20 |
transforms.ToTensor()
|
| 21 |
])
|
| 22 |
|
| 23 |
+
# Target layer for Grad-CAM
|
| 24 |
+
target_layer = model.layer3[1].conv2
|
|
|
|
| 25 |
|
| 26 |
+
# Store activations & gradients
|
| 27 |
+
activations = None
|
| 28 |
+
gradients = None
|
| 29 |
|
| 30 |
+
def forward_hook(module, input, output):
|
| 31 |
+
global activations
|
| 32 |
+
activations = output.detach()
|
| 33 |
|
| 34 |
+
def backward_hook(module, grad_input, grad_output):
|
| 35 |
+
global gradients
|
| 36 |
+
gradients = grad_output[0].detach()
|
| 37 |
+
|
| 38 |
+
target_layer.register_forward_hook(forward_hook)
|
| 39 |
+
target_layer.register_backward_hook(backward_hook)
|
| 40 |
+
|
| 41 |
+
# Grad-CAM function
|
| 42 |
+
def generate_gradcam(input_tensor, class_idx):
|
| 43 |
model.zero_grad()
|
| 44 |
output = model(input_tensor)
|
| 45 |
+
class_score = output[0, class_idx]
|
| 46 |
class_score.backward()
|
| 47 |
|
| 48 |
+
pooled_gradients = torch.mean(gradients, dim=[0, 2, 3]) # [C]
|
| 49 |
+
weighted_activations = activations[0] * pooled_gradients[:, None, None] # [C, H, W]
|
| 50 |
+
cam = torch.sum(weighted_activations, dim=0).cpu().numpy()
|
| 51 |
+
|
| 52 |
+
# Normalize and resize
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
cam = np.maximum(cam, 0)
|
| 54 |
cam = cv2.resize(cam, (224, 224))
|
| 55 |
+
cam -= cam.min()
|
| 56 |
+
cam /= cam.max()
|
|
|
|
| 57 |
return cam
|
| 58 |
|
| 59 |
+
# Full pipeline
|
| 60 |
+
def predict(img):
|
| 61 |
+
global activations, gradients
|
| 62 |
+
activations = None
|
| 63 |
+
gradients = None
|
| 64 |
|
| 65 |
+
img = img.convert("RGB")
|
| 66 |
+
input_tensor = transform(img).unsqueeze(0)
|
| 67 |
|
| 68 |
+
output = model(input_tensor)
|
| 69 |
+
probs = F.softmax(output[0], dim=0)
|
| 70 |
+
pred_class = torch.argmax(probs).item()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
|
|
|
| 72 |
cam = generate_gradcam(input_tensor, pred_class)
|
| 73 |
|
| 74 |
+
# Convert to heatmap
|
| 75 |
+
heatmap = np.uint8(255 * cam)
|
| 76 |
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
| 77 |
|
| 78 |
+
# Overlay
|
| 79 |
+
img_np = np.array(img.resize((224, 224)))
|
| 80 |
overlay = cv2.addWeighted(img_np, 0.6, heatmap, 0.4, 0)
|
|
|
|
|
|
|
| 81 |
overlay_img = Image.fromarray(cv2.cvtColor(overlay, cv2.COLOR_BGR2RGB))
|
| 82 |
|
| 83 |
return {classes[i]: float(probs[i]) for i in range(2)}, overlay_img
|
| 84 |
|
| 85 |
+
# Gradio interface
|
| 86 |
+
title = "🧠 Lumen: Skin Cancer Classifier + Grad-CAM"
|
| 87 |
description = """
|
| 88 |
Upload a dermoscopic image of a mole or lesion. The model will classify it as <b>benign</b> or <b>malignant</b> and show a heatmap of what it focused on.<br><br>
|
| 89 |
+
<b>Disclaimer:</b> For educational use only.
|
| 90 |
"""
|
| 91 |
|
| 92 |
demo = gr.Interface(
|