Untitled
Anonymous
Plain Text
10/14/2025 6:56 AM
1.4 KB
14
Indexable
Never
import matplotlib.pyplot as plt
num_test_images = 4 # how many test images to display
for idx in range(num_test_images):
img = x_test[idx]
img_patched = patch_extract(np.expand_dims(img, 0))
true_class = np.argmax(y_test[idx])
preds, _ = model.predict(img_patched)
pred_class = np.argmax(preds[0])
cam = compute_gradcam_swin(img, model, pred_class)
# Grad-CAM Heatmap with colormap
cam_img = cam[...,0]
# Overlay
overlay_img_uint8 = (img*255).astype(np.uint8)
overlay_pil = Image.fromarray(overlay_img_uint8)
heatmap_pil = Image.fromarray((cam_img*255).astype(np.uint8)).convert("L").resize((img.shape[1], img.shape[0]))
overlay_combined = Image.blend(overlay_pil, heatmap_pil.convert("RGB"), alpha=0.5)
# Prediction text
pred_text = f"True: {true_class}, Pred: {pred_class}"
# --- Plot all 4 images in a row ---
fig, axes = plt.subplots(1, 4, figsize=(16,4))
axes[0].imshow(img)
axes[0].set_title("Original Image")
axes[0].axis('off')
axes[1].imshow(cam_img, cmap='jet')
axes[1].set_title("Grad-CAM Heatmap")
axes[1].axis('off')
axes[2].imshow(overlay_combined)
axes[2].set_title("Overlay")
axes[2].axis('off')
axes[3].imshow(img)
axes[3].set_title(pred_text)
axes[3].axis('off')
plt.tight_layout()
plt.show()
Editor is loading...
Leave a Comment