2012-02-21 17 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] 
相關問題