Arrange multiple images in one large image using Python PIL.Image


The results are:

Arrange multiple images in one large image using Python PIL.Image -1-

and

Arrange multiple images in one large image using Python PIL.Image -2-

This page shows how to arrange the images in one figure using Python & PIL.Image.
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
Firstly, generate the image to arrange.
In [2]:
for i in range(1,21):
    col = int(255*i/20)
    img = Image.new('RGB',(120,80),color=(col,col,col))
    img.save('%2d.png'%i,format='png')
    
    # check the generated image
    plt.imshow(np.asarray(img))
    plt.show()
Secondly, load the generated data.
In [3]:
fs = []
for i in range(1,21):
    im = Image.open('%2d.png'%i,'r')
    fs.append(im)
    
# get the image size
x,y = fs[0].size
Tertiary, generate the new large image to arrange all images just loaded.
In [4]:
ncol = 4
nrow = 5
cvs = Image.new('RGB',(x*ncol,y*nrow))
Finaly, arrange the images on the new large image.
Case 1: if you want to arrange image like
1, 6,11,16
2, 7,12,17
3, 8,13,18
4, 9,14,19
5,10,15,20 then you can use the following code:
In [5]:
for i in range(len(fs)):
    px, py = x*int(i/nrow), y*(i%nrow)
    cvs.paste(fs[i],(px,py))
In [6]:
cvs
Out[6]:
In [7]:
cvs.save('arranged_img_1.png',format='png')
Case 2: if you want to arrange image like
1, 2, 3, 4
5, 6, 7, 8
9,10,11,12
13,14,15,16
17,18,19,20 then you can use the following code:
In [8]:
for i in range(len(fs)):
    px, py = x*(i%ncol), y*int(i/ncol)
    cvs.paste(fs[i],(px,py))
In [9]:
cvs
Out[9]:
In [10]:
cvs.save('arranged_img_2.png',format='png')