Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display two images on top of another with matplotlib?

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()
like image 966
Noltibus Avatar asked Jan 28 '23 05:01

Noltibus


1 Answers

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)
like image 146
user3692586 Avatar answered Jan 31 '23 09:01

user3692586