2012-02-21 40 views
2

如何从使用image.load()操作的数据保存图像文件?使用PIL后,如何在使用.load()后保存图片的操作?

这是用来当我运行它,我虽然得到这个错误合并大小相同

from PIL import Image 
import random 

image1 = Image.open("me.jpg") 
image2 = Image.open("otherme.jpg") 

im1 = image1.load() 
im2 = image2.load() 

width, height = image1.size 

newimage = Image.new("RGB",image1.size) 
newim = newimage.load() 

xx = 0 
yy = 0 

while xx < width: 
    while yy < height: 
     if random.randint(0,1) == 1: 
      newim[xx,yy] = im1[xx,yy] 
     else: 
      newim[xx,yy] = im2[xx,yy] 
     yy = yy+1 
    xx = xx+1 

newimage.putdata(newim) 
newimage.save("new.jpg") 

的两张照片我的代码。

Traceback (most recent call last): 
File "/home/dave/Desktop/face/squares.py", line 27, in <module> 
newimage.putdata(newim) 
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1215, in putdata 
self.im.putdata(data, scale, offset) 
TypeError: argument must be a sequence 

是不是字典使用.load()序列?我无法在Google上找到有此问题的其他人。

回答

1

dictionary(这不是一本字典)load返回的是图片中的数据。您不必使用putdata重新加载它。只要删除该行。

此外,使用for循环,而不是一个while循环:

for xx in range(0, width): 
    for yy in range(0, height): 
     if random.randint(0,1) == 1: 
      newim[xx,yy] = im1[xx,yy] 
     else: 
      newim[xx,yy] = im2[xx,yy] 

现在有没有需要初始化,并增加xxyy

你甚至可以使用itertools.product

for xx, yy in itertools.product(range(0, width), range(0, height)): 
    if random.randint(0,1) == 1: 
     newim[xx,yy] = im1[xx,yy] 
    else: 
     newim[xx,yy] = im2[xx,yy] 
相关问题