Rémi Vennereau
Rémi Vennereau

Reputation: 91

Averaging multiple images in python

I'm trying to average 300 .tif images with this code :

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[".tif",".TIF"]]

# 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 16-bit integer
arr = numpy.array(numpy.round(arr),dtype=numpy.uint16)

# Generate, save and preview final image
out = Image.fromarray(arr,mode="RGB")
out.save("Average.tif")

And it gives me a TypeError like that :

imarr = numpy.array(Image.open(im),dtype=numpy.float)
TypeError: float() argument must be a string or a number, not 'TiffImageFile'

I understand that it doesn't really like to put a TIF image in the numpy array (it also doesn't work with PNG images). What should I do ? Splitting each image into R, G and B arrays to average and then merge everything seems too memory consuming.

Upvotes: 2

Views: 6288

Answers (0)

Related Questions