Creating and combining numerous images in Python - Error: Too many open files:

Creating and combining numerous images in Python - Error: Too many open files:

所以基本上我有 2 个代码:

  1. 创建多个具有 1 像素尺寸的不同颜色的图像

  2. 另一个将所有创建的图像合并为一个

第一个完美运行,但在第二个代码中出现错误:IOError: [Errno 24] Too many open files: 'Test 3161.png'

问题是我不一定要创建文件。我真正想要的是最后的组合图像。我不确定如何处理这个问题。任何帮助将不胜感激。

代码 1 - 创建图像

from PIL import Image
import sys

im = Image.new("RGB", (1, 1))
pix = im.load()

j=0

for r in range(65,130):
    for g in range(65,130):
        for b in range(65,130):
            for x in range(1):
                for y in range(1):
                    axis = (r,g,b)
                    pix[x,y] = axis
                print axis
                j+=1
                im.save('Test {}.png'.format(j), "PNG")

代码2:合并图片

from PIL import Image
import sys
import glob

imgfiles = []
for file in glob.glob("*.png"):
    imgfiles.append(file)
print imgfiles

#stitching images together
images = map(Image.open, imgfiles)
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
    new_im.paste(im, (x_offset,0))
    x_offset += im.size[0]

new_im.save('test.png')

这在某种程度上是我试图获得的最终图像,但没有像图中显示的那样多的颜色:

从代码 1 创建的彩色图像是宽度和直径为 1 像素的图像。例如像这样:

很难看到它旁边的一个像素。它看起来像一个句号,但却是有问题的 1 像素图像。

要解决打开文件过多的错误,可以做一个小函数:

def getImageDetails(imgfile):
    im = Image.open(imgfile)
    size = im.size
    im.load() # closes the pointer after it loads the image

    return size[0], size[1], im

widths, heights, images = zip(*(getImageDetails(i) for i in imgfiles))

用上面的代码替换这些行:

images = map(Image.open, imgfiles)
widths, heights = zip(*(i.size for i in images))

我仍然不明白你期望产生什么,但这应该很接近,而且更快更容易:

#!/usr/local/bin/python3
from PIL import Image
import numpy as np

# Create array to hold output image
result=np.zeros([1,13*13*13,3],dtype=np.uint8)

j=0
for r in range(65,130,5):
    for g in range(65,130,5):
        for b in range(65,130,5):
            result[0,j]= (r,g,b)
            j+=1

# Convert output array to image and save
im=Image.fromarray(result)
im.save("result.jpg")

请注意,上面的脚本旨在一次性完成 两个 脚本的工作。

请注意,我将结果图像做得更高(更胖)所以您可以看到它,实际上它只有 1 个像素高。

请注意,我添加了 5 的步长以使输出图像更小,因为它超出了大小限制 - 至少对于 JPEG 是这样。

注意我是在(130-65)/5的基础上粗略的猜到了数组宽度(13*13*13),因为我不是很懂你的要求