我想做类似这篇文章的事情: sample code
如何更改给定的代码以适用于" tiff" - 格式的浮动图像?
这是我试过的:
import os, numpy, PIL
from PIL import Image
# Access all PNG files in directory
os.chdir("c://users//Student///Desktop//bilder//" )
print "Current working dir : %s" % os.getcwd()
allfiles=os.listdir(os.getcwd())
imlist=[filename for filename in allfiles if filename[-5:] in [".tiff",".tiff"]]
#imlist=[filename for filename in allfiles]
# 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,1),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+=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="F")
out.save("Average.tiff")
out.show()
产生此错误:
File "C:\Users\Student\im_average.py", line 25, in <module>
arr+=imarr/N
ValueError: non-broadcastable output operand with shape (250,250,1) doesn't match the broadcast shape (250,250,250)
我不熟悉numpy数组,所以欢迎任何帮助。
答案 0 :(得分:0)
做imarr / N会在原地进行,并将dtype转换为数组的整数。所以,使用N = float(N)
请参阅http://docs.scipy.org/doc/numpy/user/basics.indexing.html#assigning-values-to-indexed-arrays
请注意,如果将较高类型分配给较低类型(如浮点数到整数)或甚至例外(将复数分配给浮点数或整数),则分配可能会导致更改。