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
| from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM from pytorch_grad_cam.utils.image import show_cam_on_image from torchvision.models import resnet50 import torchvision.transforms as transforms import cv2 as cv import numpy as np
model = resnet50(pretrained=True)
target_layer = model.layer4[-1]
image = cv.imread("C:/Users/doris/Desktop/image.jpg").astype(np.float32)/255 transf= transforms.ToTensor() input_tensor = transf(image).unsqueeze(0)
cam = GradCAM(model=model, target_layer=target_layer, use_cuda=False)
target_category = 1
grayscale_cam = cam(input_tensor=input_tensor, target_category=target_category)
grayscale_cam = grayscale_cam[0, :]
visualization = show_cam_on_image(image, grayscale_cam)
cv.imwrite("C:/Users/doris/Desktop/result.jpg",visualization)
|