【发布时间】:2021-10-18 02:48:59
【问题描述】:
我遇到了一些内存问题,我想知道是否有任何方法可以在下面的代码中释放一些内存。我尝试使用生成器表达式而不是列表推导,但这不会产生唯一的组合,因为内存已被释放。
列表(组合)列表导致我内存不足,程序无法完成。
最终结果将是此列表中的 729 个列表,每个列表包含 6 个指向图像的 WindowsPath 元素。我尝试将列表作为字符串存储在文本文件中,但我无法让它工作,我尝试使用pandas dataframe 但我无法让它工作。想出一个不同的解决方案,我束手无策。现在的输出正是我需要的,但内存是唯一的问题。
from pathlib import Path
from random import choice
from itertools import product
from PIL import Image
import sys
def combine(arr):
return list(product(*arr))
def generate(x):
#set new value for name
name = int(x)
#Turn name into string for file name
img_name = str(name)
#Pick 1 random from each directory, add to list.
a_paths = [choice(k) for k in layers]
#if the length of the list of unique combinations is equal to the number of total combinations, this function stops
if len(combinations) == len(combine(layers)):
print("Done")
sys.exit()
else:
#If combination exists, generate new list
if any(j == a_paths for j in combinations) == True:
print("Redo")
generate(name)
#Else, initialize new image, paste layers + save image, add combination to list, and generate new list
else:
#initialize image
img = Image.new("RGBA", (648, 648))
png_info = img.info
#For each path in the list, paste on top of previous, sets image to be saved
for path in a_paths:
layer = Image.open(str(path), "r")
img.paste(layer, (0, 0), layer)
print(str(name) + ' - Unique')
img.save(img_name + '.png', **png_info)
combinations.append(a_paths)
name = name - 1
generate(name)
'''
Main method
'''
global layers
layers = [list(Path(directory).glob("*.png")) for directory in ("dir1/", "dir2/", "dir3/", "dir4/", "dir5/", "dir6/")]
#name will dictate the name of the file output(.png image) it is equal to the number of combinations of the image layers
global name
name = len(combine(layers))
#combinations is the list of lists that will store all unique combinations of images
global combinations
combinations = []
#calling recursive function
generate(name)
【问题讨论】:
-
看来问题出在您发布的代码之外。
layers和combinations是在哪里生成的?combine是做什么的?这段代码的总体目的是什么?如果您尝试通过所有可能的组合,您可以使用itertools的生成器之一来提供。如果您需要使用随机生成技术,您可能可以通过存储哈希而不是全部内容来避免受骗,但是在不知道您正在使用的值的类型的情况下,很难建议您如何这样做。 -
@Samwise 我添加了其余的代码。抱歉没有指定。我会澄清一些事情。这段代码的总体目的是从每个目录(dir1、dir2、dir3 等)中随机选择 1 张图像,并将每个图像粘贴在一起。每个目录中有 3 个图像可供选择。随机选择图像然后与称为“组合”的列表进行比较,如果选择的图像组合存在,则再次调用该函数。如果没有,它会将组合(这是一个列表)添加到名为“combinations”的列表中并再次调用该函数。
-
@Samwise 另一个更新,我尝试做 b_paths = hash(str(a_paths)), b_paths = str(b_paths),然后比较哈希并将哈希存储在列表中。同样的结果,在我的内存占用了大约 80% 的 RAM 后,功能会自行关闭。我到达那里大约 95% 的路。如果有办法我可以清除一些正在存储的内存或覆盖我的内存使用以在切断之前允许更多的时间,我将能够完成输出。
-
所以看起来你正在迭代,直到你在列表中生成了每个可能的组合。 为什么不直接遍历组合,而不是将它们保存为列表,然后生成随机组合以重新发现它们?
标签: python list memory memory-management