Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def getHeatmapGradCAM(img, eps=1e-8, alpha = .3):
- # load up graph and session
- # global graph
- # global sess
- # load image
- originalImage = img.convert('RGB') # load up image
- resizedImage = originalImage.resize((224, 224)) # resize image
- # preprocess and save rbg img arr
- rgbArr = np.array(resizedImage) # arrayfy
- rgbArr = rgbArr[np.newaxis, :, :, :] # batchify
- rgbArrPreproc = tf.keras.applications.densenet.preprocess_input(rgbArr) # preproc densenet
- # save gray img arr
- grayArr = np.array(resizedImage.convert('L')) # convert to gray arr
- # get final conv layer
- finalLayerName = 'relu'
- with tf.device('cpu:0'):
- with graph.as_default():
- tf.compat.v1.keras.backend.set_session(sess)
- # get gradients
- grads = tf.keras.backend.gradients(model.output[:, 0], model.get_layer(finalLayerName).output)[0]
- # make grad func
- gradient_function = tf.keras.backend.function([model.input], [model.get_layer(finalLayerName).output, grads])
- # compute grads
- output, grads_val = gradient_function([rgbArrPreproc])
- output, grads_val = output[0, :], grads_val[0, :, :, :]
- weights = np.mean(grads_val, axis=(0, 1))
- cam = np.dot(output, weights)
- # resize and normalize
- heatmap = cv2.resize(np.array(cam), (224, 224))
- numer = heatmap - np.min(heatmap)
- denom = (heatmap.max() - heatmap.min()) + eps
- heatmap = numer / denom
- heatmap = np.uint8(heatmap * 255)
- # visualize findings
- # original image arr = grayArr
- # heatmap image arr = heatmap
- plt.figure(figsize = (8, 8))
- plt.imshow(grayArr, cmap = 'gray')
- plt.imshow(heatmap, cmap = 'jet', alpha = alpha)
- plt.savefig('heatmap.png')
Add Comment
Please, Sign In to add comment