def visualize_grad_cam(input_model, original_img, layer_name = "conv3_1"):
img = np.float32(cv2.resize(original_img, (200, 66))) / 255.0
angle = input_model.predict(np.array([img]))
print("The predicted angle is", 180.0 * angle[0][0] / scipy.pi, "degrees")
model = Sequential()
model.add(input_model)
target_layer = lambda x: grad_cam_loss(x, angle)
model.add(Lambda(target_layer,
output_shape = grad_cam_loss_output_shape))
loss = K.sum(model.layers[-1].output)
conv_output = [l for l in model.layers[0].layers if l.name is layer_name][0].output
grads = normalize(K.gradients(loss, conv_output)[0])
gradient_function = K.function([model.layers[0].input], [conv_output, grads])
output, grads_val = gradient_function([[img]])
output, grads_val = output[0, :], grads_val[0, :, :, :]
weights = np.mean(grads_val, axis = (0, 1))
cam = np.ones(output.shape[0 : 2], dtype = np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
#ReLU:
cam = np.maximum(cam, 0)
cam = cam / np.max(cam)
cam = cv2.resize(cam, tuple(original_img.shape[0:2][::-1]))
cam = cv2.applyColorMap(np.uint8(255*cam), cv2.COLORMAP_JET)
cam = 1.0 * np.float32(cam) + np.float32(original_img)
cam = cam / np.max(cam)
return cam
run.py 文件源码
python
阅读 31
收藏 0
点赞 0
评论 0
评论列表
文章目录