CAM, Class Activation Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image

# img and cam have already implemented before

im = np.asarray(img.permute(1, 2, 0)+1)
im = 255*((im-im.min())/im.max())

cam = cv2.resize(cam, (224, 224))

cam = np.uint8(255 * cam)
cam = cv2.applyColorMap(cam, cv2.COLORMAP_JET)
print(cam.shape)
plt.matshow(cam)

imgrgb = Image.fromarray(im.astype('uint8')).convert('RGB')
img_add = cv2.addWeighted(np.array(imgrgb), 0.6, np.array(cam), 0.4, 0)
plt.figure(figsize=(8,8))
plt.subplot(121);plt.imshow(imgrgb)
plt.subplot(122);plt.imshow(img_add)