Spaces:
Sleeping
Sleeping
File size: 2,361 Bytes
c1596ac 2729151 c1596ac | 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 | import os
import cv2
import torch
import torch.nn as nn
import numpy as np
from PIL import Image
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.image import (
show_cam_on_image
)
from src.transforms.image_transform import (
get_classification_valid_transform
)
class SwinClassifierWrapper(nn.Module):
def __init__(self, model):
super().__init__()
self.model = model
def forward(self, images):
features = self.model.backbone(images)
features = features.view(
features.size(0),
-1
)
logits = self.model.classifier(features)
return logits
def reshape_transform(tensor):
# Swin-T feature output: B, H, W, C
# Grad-CAM expects: B, C, H, W
if tensor.ndim == 4:
tensor = tensor.permute(
0,
3,
1,
2
)
return tensor
def save_gradcam(
model,
image_path,
save_path,
device
):
model.eval()
for param in model.backbone.parameters():
param.requires_grad = True
for param in model.classifier.parameters():
param.requires_grad = True
gradcam_model = SwinClassifierWrapper(
model
).to(device)
gradcam_model.eval()
transform = (
get_classification_valid_transform()
)
image = Image.open(
image_path
).convert("RGB")
image = image.resize(
(224, 224)
)
image_np = (
np.array(image)
.astype(np.float32)
/ 255.0
)
tensor = transform(
image
).unsqueeze(0).to(device)
target_layer = (
model.backbone.features[-1][-1].norm2
)
cam = GradCAM(
model=gradcam_model,
target_layers=[target_layer],
reshape_transform=reshape_transform
)
grayscale_cam = cam(
input_tensor=tensor
)[0]
visualization = show_cam_on_image(
image_np,
grayscale_cam,
use_rgb=True
)
os.makedirs(
os.path.dirname(save_path),
exist_ok=True
)
cv2.imwrite(
save_path,
cv2.cvtColor(
visualization,
cv2.COLOR_RGB2BGR
)
) |