Displaying Colormap over Image

Hey everyone,

I tried to display a heatmap over an image both using matplotlib - which I was able to get done now. This is the result:
Screenshot 2021-05-13 at 13.30.40

More particularly, I have:

  • a tensor of shape (7, 7) with floats between 0 and 1 - let’s call it the activation_map
  • the image tensor of shape (3, 224, 224)

I now upsampled the activation_map to (224, 224) and overlayed it with a custom colormap that is based on the gray colormap, just making high values transparent instead of white.

However, when I plot multiple of these pictures with activation_map, I always want them to show the same amount of pixels of the picture. Basically, I always want the highest 10.000 values of the activation_map to be ‘1’ and the other ones to be ‘0’. How can I achieve that?

I know I need to squeeze the activation_map to an array, sort it, then make the biggest values to ‘1’, the smallest ones to ‘0’. But how do I get the values back in the same order as they were in the original activation_map? I need to work with the indices but I am struggling to do so…

I would be happy to receive any help, overall it is for research as this will be used in an experiment.
BR, David

Well, sometimes it helps to just approach the problem again after you explained it to others… Here is the solution I got the problem solved with:

# make a copy of the original activation_map
nact = act.copy()

#Reshape the activation map to a 1D Matrix / Array
nact = nact.reshape(-1)

#Get the indices that would sort the array from low to high
sort_ind = np.argsort(nact)

# indices of the values I want to set to 0
sort_zero = sort_ind[:47175]

#indices of the values I want to set to 1
sort_ones = sort_ind[47176:]

#set values to zero
nact[sort_zero] = 0.0
# set values to one
nact[sort_ones] = 1.0

#Reshape activation_map back to original size
d_act = nact.reshape(224, 224)

#Visualize it over the image
plt.imshow(img)
plt.imshow(d_act, alpha=1.0, cmap=my_cmap)
plt.axis('off'); plt.tight_layout(); plt.show()

Result:
Screenshot 2021-05-13 at 14.36.28