gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:24:43 39 4
gpt4 key购买 nike

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

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

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

enter image description here

这是我正在使用的代码:

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() 进行调试以查看哪里出错了,但是在方法中设置“title”参数在预览中不起作用并且很难获得完整的时间线。

感谢您的帮助!

最佳答案

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

你能试试deepcopy吗?

import copy

# ...

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

来自 python doc , 我们看到

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.

关于python - 为什么在 for 循环中使用 PIL 的 Image.paste 时出现图像重叠问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67797147/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com