Reputation: 165
I am doing some image processing in Python and I would like to plot 4 images (they are all 224x224x3 np arrays) in one figure, add some titles and save the whole figure as png.
Obviously, I can do this using plt and subplot:
f, axs = plt.subplots(2, 2)
ax = axs[0, 0]
ax.imshow(img1)
ax.axis('off')
ax.set_title('original')
ax = axs[1, 0]
ax.imshow(img2)
ax.axis('off')
ax.set_title('blur + noise')
ax = axs[0, 1]
ax.imshow(img3)
ax.axis('off')
ax.set_title('restored a')
ax = axs[1, 1]
ax.imshow(img4)
ax.axis('off')
ax.set_title('restored b')
However this will apply scaling to the different images and I would like to display the images in their original resolution without any interpolation being applied. Is there any way to achieve this behaviour in plt? I found some other thread that asked a similar question, however it only answers how to display one single image without scaling.
Thanks for your help, Max
Upvotes: 1
Views: 1957
Reputation: 339560
The procedure is essentially the same as in the linked question, Show image without scaling.
In addition to the margin and the image size(s) you need to take into account the spacing between the subplots.
The size of the figure in pixels is then
size_image_A + size_image_B + 2* margin + spacing
This needs to be converted to the size in inched by dividing by the figure dpi
.
The subplots_adjust parameters need to be extended by the spacing in relative axes units.
import matplotlib.pyplot as plt
import numpy as np
images = [np.random.rayleigh((i+1)/8., size=(180, 200, 3)) for i in range(4)]
margin=50 # pixels
spacing =35 # pixels
dpi=100. # dots per inch
width = (200+200+2*margin+spacing)/dpi # inches
height= (180+180+2*margin+spacing)/dpi
left = margin/dpi/width #axes ratio
bottom = margin/dpi/height
wspace = spacing/float(200)
fig, axes = plt.subplots(2,2, figsize=(width,height), dpi=dpi)
fig.subplots_adjust(left=left, bottom=bottom, right=1.-left, top=1.-bottom,
wspace=wspace, hspace=wspace)
for ax, im, name in zip(axes.flatten(),images, list("ABCD")):
ax.axis('off')
ax.set_title('restored {}'.format(name))
ax.imshow(im)
plt.show()
Upvotes: 3