8

I have a heatmap with some values in it (model_prediction_i). Because I want to later rotate this heatmap before plotting it, I have to save it with plt.imsave. My goal is then, to display reference.jpg as a background of the plot, plot X_test_i over it, and then position the heatmap also on that plot, such that I can see the background, the plotted line and the heatmap, which hs smaller dimensions than the background picture -> it will only occlude a part of the background picture. As reference.jpg: enter image description here Is this possible?

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

model_prediction_i = np.zeros((200,200))
model_prediction_i[160][160] = 1
model_prediction_i[160][161] = 1
model_prediction_i[160][162] = 1
model_prediction_i[160][163] = 1
model_prediction_i[160][164] = 1
model_prediction_i[160][165] = 1
model_prediction_i[160][166] = 1
model_prediction_i[160][167] = 1
model_prediction_i[160][168] = 1
model_prediction_i[160][169] = 1
model_prediction_i[160][170] = 1
model_prediction_i[160][171] = 1

plt.imsave('outfile.jpg', model_prediction_i, cmap='hot')
rotated_img = Image.open('outfile.jpg')
background = Image.open('reference.jpg')


X_test_i = np.zeros((5, 2))
X_test_i[0] = [10 ,10]
X_test_i[1] = [60 ,60]
X_test_i[2] = [90 ,90]
X_test_i[3] = [140 ,140]
X_test_i[4] = [250 ,230]

fig, ax = plt.subplots(figsize=(10, 10))
ax.plot(X_test_i[:, 0], X_test_i[:, 1], marker='o', markersize=7, color="red", label='Current position', antialiased=True)


ax.imshow(rotated_img, cmap='hot', extent=[X_test_i[:, 0][-1]-10, X_test_i[:, 0][-1]+10, X_test_i[:, 1][-1]-10, X_test_i[:, 1][-1]+10])
ax.imshow(background)
plt.show()
Noltibus
  • 1,300
  • 3
  • 12
  • 34
  • Can you create an example `reference.jpg`? – DavidG Apr 24 '18 at 12:37
  • Edited the post – Noltibus Apr 24 '18 at 12:39
  • Would this solution work? https://stackoverflow.com/questions/42481203/heatmap-on-top-of-image/42482371#42482371 – Ed Smith Apr 24 '18 at 12:40
  • No since I need to to open two images from the disk, where as in your example the heatmap is directly plotted onto the image – Noltibus Apr 24 '18 at 12:47
  • When you use an image it will be a an MxNx3 (RGB) or MxNx4 (RGBA) array so saving/loading should not make a difference (although probably better to store in a lossless format or maybe `pickle` or `numpy.save`) – Ed Smith Apr 24 '18 at 13:20

1 Answers1

14

you could overlay two images plotting them with plt.imshow in the same cell.

from matplotlib import pyplot as plt

plt.figure(figsize = (10,10))
plt.imshow(img_1)
plt.imshow(img_2, alpha=0.5)
user3692586
  • 199
  • 1
  • 7