【问题标题】:Tiling images by batch using python PIL, fill background image repeatedly by folder使用python PIL批量平铺图像,按文件夹重复填充背景图像
【发布时间】:2021-12-16 14:46:16
【问题描述】:
from PIL import Image
Image.MAX_IMAGE_PIXELS = None

# Opens an image
bg = Image.open('./images/1.jpg')

# The width and height of the background tile
bg_w, bg_h = bg.size

# Creates a new empty image, RGB mode, and size 1000 by 1000
new_im = Image.new('RGB', (7000,9240))

# The width and height of the new image
w, h = new_im.size

# Iterate through a grid, to place the background tile
for i in range(0, w, bg_w):
    for j in range(0, h, bg_h):
        # Change brightness of the images, just to emphasise they are unique copies
        # bg = Image.eval(bg, lambda x: x+(i+j)/1000)

        #paste the image at location i, j:
        new_im.paste(bg, (i, j))

new_im.save('./tiled/tiled-image1.png')

一直在使用上面的代码: PIL fill background image repeatedly

现在我尝试按文件夹制作它,而不是一张一张地制作图像。 但不能让我的代码(如下)工作。有人可以帮忙吗?

from PIL import Image


path = "./images/"

# Opens an image
bg = Image.open(path)

# The width and height of the background tile
bg_w, bg_h = bg.size

# Creates a new empty image, RGB mode, and size 1000 by 1000
new_im = Image.new('RGB', (7000,9240))



# The width and height of the new image
w, h = new_im.size

# Iterate through a grid, to place the background tile
for i in range(0, w, bg_w):
    for j in range(0, h, bg_h):
        # Change brightness of the images, just to emphasise they are unique copies
        # bg = Image.eval(bg, lambda x: x+(i+j)/1000)

        #paste the image at location i, j:
        new_im.paste(bg, (i, j))

new_im.save("./tiled/" + new_im + ".png")
new_im.show()

当然,我缺少一些东西来运行代码并在文件夹中获取图像,但无法弄清楚。

【问题讨论】:

    标签: python concatenation python-imaging-library batch-processing


    【解决方案1】:

    您可以使用os.walk 来遍历您的文件夹和子文件夹:

    import os
    from PIL import Image
    Image.MAX_IMAGE_PIXELS = None
    
    INPUT_DIR = r'c:\so\69804229\images'
    OUTPUT_DIR = r'c:\so\69804229\results'
    IMAGE_EXT = ('.jpg', '.jpeg', '.png', '.gif')
    
    
    for subdir, dirs, files in os.walk(INPUT_DIR):
        for file in files:
            if file.endswith(IMAGE_EXT):
                image_path = os.path.join(subdir, file)
                bg = Image.open(image_path)
                bg_w, bg_h = bg.size
                new_im = Image.new('RGB', (7000, 9240))
                w, h = new_im.size
                for i in range(0, w, bg_w):
                    for j in range(0, h, bg_h):
                        new_im.paste(bg, (i, j))
                new_im.save(os.path.join(OUTPUT_DIR, file))
    

    【讨论】:

    • 它有效,谢谢!
    猜你喜欢
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多