4
4
import numpy as np
5
5
import torch
6
6
from torchvision import models
7
+ from torchvision .models import ResNet50_Weights
7
8
from pytorch_grad_cam import (
8
9
GradCAM , HiResCAM , ScoreCAM , GradCAMPlusPlus ,
9
10
AblationCAM , XGradCAM , EigenCAM , EigenGradCAM ,
18
19
19
20
def get_args ():
20
21
parser = argparse .ArgumentParser ()
21
- parser .add_argument ('--use-cuda ' , action = 'store_true' , default = False ,
22
- help = 'Use NVIDIA GPU acceleration ' )
22
+ parser .add_argument ('--device ' , type = str , default = None ,
23
+ help = 'Torch device to use ' )
23
24
parser .add_argument (
24
25
'--image-path' ,
25
26
type = str ,
@@ -44,9 +45,9 @@ def get_args():
44
45
parser .add_argument ('--output-dir' , type = str , default = 'output' ,
45
46
help = 'Output directory to save the images' )
46
47
args = parser .parse_args ()
47
- args . use_cuda = args . use_cuda and torch . cuda . is_available ()
48
- if args .use_cuda :
49
- print ('Using GPU for acceleration' )
48
+
49
+ if args .device :
50
+ print (f 'Using device " { args . device } " for acceleration' )
50
51
else :
51
52
print ('Using CPU for computation' )
52
53
@@ -76,7 +77,7 @@ def get_args():
76
77
"gradcamelementwise" : GradCAMElementWise
77
78
}
78
79
79
- model = models .resnet50 (pretrained = True )
80
+ model = models .resnet50 (weights = ResNet50_Weights . DEFAULT ). to ( args . device ). eval ( )
80
81
81
82
# Choose the target layer you want to compute the visualization for.
82
83
# Usually this will be the last convolutional layer in the model.
@@ -97,7 +98,7 @@ def get_args():
97
98
rgb_img = np .float32 (rgb_img ) / 255
98
99
input_tensor = preprocess_image (rgb_img ,
99
100
mean = [0.485 , 0.456 , 0.406 ],
100
- std = [0.229 , 0.224 , 0.225 ])
101
+ std = [0.229 , 0.224 , 0.225 ]). to ( args . device )
101
102
102
103
# We have to specify the target we want to generate
103
104
# the Class Activation Maps for.
@@ -111,7 +112,7 @@ def get_args():
111
112
cam_algorithm = methods [args .method ]
112
113
with cam_algorithm (model = model ,
113
114
target_layers = target_layers ,
114
- use_cuda = args .use_cuda ) as cam :
115
+ device = args .device ) as cam :
115
116
116
117
117
118
# AblationCAM and ScoreCAM have batched implementations.
@@ -127,7 +128,7 @@ def get_args():
127
128
cam_image = show_cam_on_image (rgb_img , grayscale_cam , use_rgb = True )
128
129
cam_image = cv2 .cvtColor (cam_image , cv2 .COLOR_RGB2BGR )
129
130
130
- gb_model = GuidedBackpropReLUModel (model = model , use_cuda = args .use_cuda )
131
+ gb_model = GuidedBackpropReLUModel (model = model , device = args .device )
131
132
gb = gb_model (input_tensor , target_category = None )
132
133
133
134
cam_mask = cv2 .merge ([grayscale_cam , grayscale_cam , grayscale_cam ])
0 commit comments