|
23 | 23 | predictions = model.predict(x)
|
24 | 24 | print('predicted: ', decode_predictions(predictions, top=3)[0])
|
25 | 25 |
|
26 |
| -print(np.argmax(predictions[0])) |
| 26 | +print(np.argmax(predictions[0])) # output of this needs to be on the next line |
| 27 | + |
| 28 | +cat_output = model.output[:, 285] # this number comes from the output of previous line |
| 29 | + |
| 30 | +last_conv_layer = model.get_layer('block3_conv3') |
| 31 | + |
| 32 | +from keras import backend as K |
| 33 | + |
| 34 | +grads = K.gradients(cat_output, last_conv_layer.output)[0] |
| 35 | + |
| 36 | +pooled_grads = K.mean(grads, axis=(0, 1, 2)) |
| 37 | + |
| 38 | +iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]]) |
| 39 | + |
| 40 | +pooled_grads_value, conv_layer_output_value = iterate([x]) |
| 41 | + |
| 42 | +for i in range (255): |
| 43 | + conv_layer_output_value[:, :, i] *= pooled_grads_value[i] |
| 44 | + |
| 45 | +heatmap = np.mean(conv_layer_output_value, axis=-1) |
| 46 | + |
| 47 | +import matplotlib.pyplot as plt |
| 48 | + |
| 49 | +heatmap = np.maximum(heatmap, 0) |
| 50 | +heatmap /= np.max(heatmap) |
| 51 | +plt.matshow(heatmap) |
| 52 | +plt.show() |
| 53 | + |
| 54 | +import cv2 |
| 55 | + |
| 56 | +img = cv2.imread(img_path) |
| 57 | + |
| 58 | +heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0])) |
| 59 | + |
| 60 | +heatmap = np.uint8(255 * heatmap) |
| 61 | + |
| 62 | +heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) |
| 63 | + |
| 64 | +superimposed_img = heatmap * 0.4 + img |
| 65 | + |
| 66 | +cv2.imwrite('../heatmap.jpg', superimposed_img) |
27 | 67 |
|
0 commit comments