使用PIL,如何在使用.load()后保存图像?

时间:2012-02-21 18:30:57

标签: python python-imaging-library

如何使用image.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()的序列吗?我在谷歌找不到其他人有这个问题。

1 个答案:

答案 0 :(得分: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]
相关问题