Generate average image using Python and PIL (Python Image Library)


Generate average image using Python and PIL (Python Image Library)

This page shows how to generate an average image of the image arrays using python and PIL (python image library) module.
It is easy to do by converting the image to the numpy.array.


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
Generate the original images
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('%02d.bmp' % i, format='bmp')
Load the original images saved just above
In [3]:
ims = []
for i in range(1, 21):
    ims.append(Image.open('%02d.bmp' % i, mode='r'))
Check the original images
In [4]:
ims[0]
Out[4]:
In [5]:
ims[10]
Out[5]:
In [6]:
ims[-1]
Out[6]:
Convert the loaded images to numpy ndarray
In [7]:
ims = np.array([np.array(im) for im in ims])
Check the shape of the ims array
In [8]:
ims.shape
Out[8]:
(20, 80, 120, 3)
Generate the averaged array
In [9]:
imave = np.average(ims,axis=0)
Check the shape of the ims array
In [10]:
imave.shape
Out[10]:
(80, 120, 3)
Convert the averated image (in float) to PIL image (uint8)
In [11]:
result = Image.fromarray(imave.astype('uint8'))
Save the averated uint8 image
In [12]:
result.save('result.bmp')