Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an average picture from 100 pictures using PIL?

Tags:

For example, I have 100 pictures whose resolution is the same, and I want to merge them into one picture. For the final picture, the RGB value of each pixel is the average of the 100 pictures' at that position. I know the getdata function can work in this situation, but is there a simpler and faster way to do this in PIL(Python Image Library)?

like image 815
Hanfei Sun Avatar asked Jun 25 '13 07:06

Hanfei Sun


People also ask

How do you find the average pixel value?

Mean value is the sum of pixel values divided by the total number of pixel values. Pixel Values Each of the pixels that represents an image stored inside a computer has a pixel value which describes how bright that pixel is, and/or what color it should be.

How do I load an image into Python PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).


1 Answers

Let's assume that your images are all .png files and they are all stored in the current working directory. The python code below will do what you want. As Ignacio suggests, using numpy along with PIL is the key here. You just need to be a little bit careful about switching between integer and float arrays when building your average pixel intensities.

import os, numpy, PIL from PIL import Image  # Access all PNG files in directory allfiles=os.listdir(os.getcwd()) imlist=[filename for filename in allfiles if  filename[-4:] in [".png",".PNG"]]  # Assuming all images are the same size, get dimensions of first image w,h=Image.open(imlist[0]).size N=len(imlist)  # Create a numpy array of floats to store the average (assume RGB images) arr=numpy.zeros((h,w,3),numpy.float)  # Build up average pixel intensities, casting each image as an array of floats for im in imlist:     imarr=numpy.array(Image.open(im),dtype=numpy.float)     arr=arr+imarr/N  # Round values in array and cast as 8-bit integer arr=numpy.array(numpy.round(arr),dtype=numpy.uint8)  # Generate, save and preview final image out=Image.fromarray(arr,mode="RGB") out.save("Average.png") out.show() 

The image below was generated from a sequence of HD video frames using the code above.

Average of HD video frames

like image 98
CnrL Avatar answered Sep 30 '22 15:09

CnrL