在python中平均多个图像

时间:2015-07-23 10:17:20

标签: python python-3.x numpy python-imaging-library

我试图用这段代码平均300个.tif图像:

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")

它给了我类似的TypeError:

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

我知道它并不是真的想把一个TIF图像放在numpy数组中(它也不能用于PNG图像)。我该怎么办 ?将每个图像拆分为R,G和B阵列以进行平均,然后合并所有内容似乎过于耗费内存。

1 个答案:

答案 0 :(得分:1)

它应该按原样运行,现在用PIL(枕头2.9.0)和numpy 1.9.2检查。