forked from tanjimin/grad-cam-pytorch-light
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.py
64 lines (59 loc) · 2.02 KB
/
example.py
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
import torchvision
import matplotlib.pyplot as plt
from PIL import Image
from torchvision import transforms
from grad_cam import grad_cam
def main():
boxer_example()
tiger_cat_example()
elephant_example()
def boxer_example():
model = torchvision.models.resnet34(pretrained=True)
model.eval()
transform = transforms.Compose([
transforms.Resize(240),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
heatmap_layer = model.layer4[2].conv2
image = Image.open("./images/cat_dog.png")
input_tensor = transform(image)
boxer_label = 242
image = grad_cam(model, input_tensor, heatmap_layer, boxer_label)
plt.imshow(image)
plt.savefig('./images/boxer_grad-cam')
def tiger_cat_example():
model = torchvision.models.resnet34(pretrained=True)
model.eval()
transform = transforms.Compose([
transforms.Resize(240),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
heatmap_layer = model.layer4[2].conv2
image = Image.open("./images/cat_dog.png")
input_tensor = transform(image)
tiger_cat_label = 282
image = grad_cam(model, input_tensor, heatmap_layer, tiger_cat_label)
plt.imshow(image)
plt.savefig('./images/tiger_cat_grad-cam')
def elephant_example():
model = torchvision.models.resnet34(pretrained=True)
model.eval()
transform = transforms.Compose([
transforms.Resize(240),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
heatmap_layer = model.layer4[2].conv2
image = Image.open("./images/elephant.jpg")
input_tensor = transform(image)
elephant_label = 386
image = grad_cam(model, input_tensor, heatmap_layer, elephant_label)
plt.imshow(image)
plt.savefig('./images/elephant_grad-cam')
if __name__== "__main__":
main()