为什么在 for 循环中使用 PIL 的 Image.paste 时出现图像重叠问题?

Why am I having image overlap issues while using PIL's Image.paste in a for loop?

我正在尝试从一组形状或属性中生成 50 张随机的个人资料图片。有不同颜色背景的分组、矩形(body 的占位符)、圆形(头部)、椭圆形(手臂),然后是一组数字。每个图像都有一个透明的背景,除了纯色的背景图像。所有图片均为 PNG。

目前,我正在 运行 设置一个 for 循环,生成一个随机数,并将该数字用于 运行 函数,以检索随机分类的属性图像。然后我使用 Image.paste 链将随机属性图像集放在一起并保存到外部文件夹。

问题是,一些生成的图像共享先前生成的图像的重叠属性。几乎就像没有重新分配变量一样。这是一个例子 -

这是我正在使用的代码:

body1 = Image.open("test-images/body1.png")

# example of array of images
bodyArr = (body1, body2, body3, body4, body5, body6, body7, body8)

# example of function to select a position in above array
def getBody(num):
    result = int(num[2:4])

    if result < 12:
        return 0
    elif result >= 12 and result < 24:
        return 1
    elif result >= 24 and result < 36:
        return 2
    elif result >= 36 and result < 48:
        return 3
    elif result >= 48 and result < 60:
        return 4
    elif result >= 60 and result < 72:
        return 5
    elif result >= 72 and result < 84:
        return 6
    else:
        return 7

for x in range(0, 50):

    # generate random, 10 digit number
    randomStr = str(randint(100000000000, 999999999999))[1:11]

    # assigning images 
    backgroundImage = bgArr[getBg(randomStr)]
    bodyImage = bodyArr[getBody(randomStr)]
    headImage = headArr[getHead(randomStr)]
    armsImage = armsArr[getArms(randomStr)]
    numImage = numArr[getNum(randomStr)]

    backgroundImage.paste(bodyImage, (0,0), bodyImage)
    backgroundImage.paste(headImage, (0,0), headImage)
    backgroundImage.paste(armsImage, (0,0), armsImage)
    backgroundImage.paste(numImage, (0,0), numImage)

    imgname = f'{dirname}/profile_images/profile{x}.png'
    backgroundImage.save(imgname)

知道是什么原因造成的吗?我尝试使用多个 Image.show() 进行调试以查看问题出在哪里,但是在方法中设置“标题”参数在预览中不起作用并且很难获得完整的时间表。

感谢您的帮助!

在 for 循环中,您正在从 bgArr[getBg(randomStr)] 获取 backgroundImage 的浅拷贝。这意味着,您使用的是同一对象,该对象之前可能已被修改。

你能试试吗deepcopy

import copy

# ...

for x in range(0, 50):
    #...
    # assigning images 
    backgroundImage = copy.deepcopy(bgArr[getBg(randomStr)])

从pythondoc,我们看到

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.