-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.py
143 lines (114 loc) · 4.31 KB
/
check.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import os.path as osp
import cv2
import matplotlib.cm as cm
import numpy as np
import torch.hub
import os
import model
from PIL import Image
from torchvision import transforms
from torchsummary import summary
from visualize.grad_cam import BackPropagation, GradCAM,GuidedBackPropagation
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
faceCascade = cv2.CascadeClassifier('./visualize/haarcascade_frontalface_default.xml')
shape = (48,48)
classes = [
'Angry',
'Disgust',
'Fear',
'Happy',
'Sad',
'Surprised',
'Neutral'
]
def preprocess(image_path):
transform_test = transforms.Compose([
transforms.ToTensor()
])
image = cv2.imread(image_path)
faces = faceCascade.detectMultiScale(
image,
scaleFactor=1.1,
minNeighbors=5,
minSize=(1, 1),
flags=cv2.CASCADE_SCALE_IMAGE
)
if len(faces) == 0:
print('no face found')
face = cv2.resize(image, shape)
else:
(x, y, w, h) = faces[0]
face = image[y:y + h, x:x + w]
face = cv2.resize(face, shape)
img = Image.fromarray(face).convert('L')
inputs = transform_test(img)
return inputs, face
def get_gradient_image(gradient):
gradient = gradient.cpu().numpy().transpose(1, 2, 0)
gradient -= gradient.min()
gradient /= gradient.max()
gradient *= 255.0
return np.uint8(gradient)
def get_gradcam_image(gcam, raw_image, paper_cmap=False):
gcam = gcam.cpu().numpy()
cmap = cm.jet_r(gcam)[..., :3] * 255.0
if paper_cmap:
alpha = gcam[..., None]
gcam = alpha * cmap + (1 - alpha) * raw_image
else:
gcam = (cmap.astype(np.float) + raw_image.astype(np.float)) / 2
return np.uint8(gcam)
def guided_backprop(images, model_name):
for i, image in enumerate(images):
target, raw_image = preprocess(image['path'])
target = target.to(device)
image['image'] = target
image['raw_image'] = raw_image
net = model.Model(num_classes=len(classes))
checkpoint = torch.load(os.path.join('../trained', model_name), map_location=torch.device('cpu'))
net.load_state_dict(checkpoint['net'])
net.to(device)
net.eval()
summary(net, (1, shape[0], shape[1]))
result_images = []
for index, image in enumerate(images):
img = torch.stack([image['image']])
bp = BackPropagation(model=net)
probs, ids = bp.forward(img)
gcam = GradCAM(model=net)
_ = gcam.forward(img)
gbp = GuidedBackPropagation(model=net)
_ = gbp.forward(img)
# Guided Backpropagation
actual_emotion = ids[:,0]
gbp.backward(ids=actual_emotion.reshape(1,1))
gradients = gbp.generate()
# Grad-CAM
gcam.backward(ids=actual_emotion.reshape(1,1))
regions = gcam.generate(target_layer='conv3')
# Get Images
label_image = np.zeros((shape[0],65, 3), np.uint8)
cv2.putText(label_image, classes[actual_emotion.data], (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
prob_image = np.zeros((shape[0],60,3), np.uint8)
cv2.putText(prob_image, '%.1f%%' % (probs.data[:,0] * 100), (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
guided_bpg_image = get_gradient_image(gradients[0])
guided_bpg_image = cv2.merge((guided_bpg_image, guided_bpg_image, guided_bpg_image))
grad_cam_image = get_gradcam_image(gcam=regions[0, 0],raw_image=image['raw_image'])
guided_gradcam_image = get_gradient_image(torch.mul(regions, gradients)[0])
guided_gradcam_image = cv2.merge((guided_gradcam_image, guided_gradcam_image, guided_gradcam_image))
img = cv2.hconcat([image['raw_image'],label_image,prob_image,guided_bpg_image,grad_cam_image,guided_gradcam_image])
result_images.append(img)
print(image['path'],classes[actual_emotion.data], probs.data[:,0] * 100)
cv2.imwrite('../test/guided_gradcam.jpg',cv2.resize(cv2.vconcat(result_images), None, fx=2,fy=2))
def main():
guided_backprop(
images=[
{'path': '../test/angry.jpg'},
{'path': '../test/happy.jpg'},
{'path': '../test/sad.jpg'},
{'path': '../test/surprised.jpg'},
],
model_name='private_model_20_53.t7'
)
if __name__ == "__main__":
main()