【发布时间】:2015-07-23 10:17:20
【问题描述】:
我正在尝试使用此代码平均 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 数组进行平均然后合并所有内容似乎太消耗内存了。
【问题讨论】:
-
您的问题是您在该行中传递给 numpy 的内容。您正在尝试传递 Image.open(im),它是一种“TiffImageFile”类型,并且不被 float() 接受。我没有与 PIL 合作过,但我在互联网上看到 Image.load(im) 可能是您正在寻找的东西。否则,请尝试查看对象“im”是否可能具有类似 im.data 之类的内容。
-
顺便说一句,如果“Python 图像库”还没有平均图像的方法,我会感到非常惊讶。也许您只是想自己学习如何做?
-
@Jblasco ,PIL 提供了一种混合方法,我在另一个平均程序中使用了该方法。我相信上面的代码(一旦它可以工作)将为大量图片平均提供更好的结果。即使此代码应该有效,我也会调查您的建议(请参阅下面的答案)
标签: python python-3.x numpy python-imaging-library