使用PIL,如何在使用.load()之后保存来自操纵的图像?

2024-09-27 23:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从使用操作的数据中保存图像文件图像.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")

当我运行它时,我得到了这个错误。在

^{pr2}$

使用.load()得到的字典不是一个序列吗?我在谷歌上找不到其他人有这个问题。在


Tags: imageimportloadrandomopenwidthjpgxx
1条回答
网友
1楼 · 发布于 2024-09-27 23:23:19

load返回的dictionary(实际上不是字典)是图像中的数据。您不必使用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

^{pr2}$

相关问题 更多 >

    热门问题