如何使用PIL/Pillow将图像合并到画布中?

51

我不熟悉PIL,但我知道在ImageMagick中将一堆图像放入网格非常容易。

例如,如何将16张图片放入一个4×4的网格中,并指定行和列之间的间隔?

2个回答

96

PIL 中也很容易实现。创建一个空图像,使用 paste 将您想要的图像粘贴到所需的任何位置。以下是一个快速示例:

import Image

#opens an image:
im = Image.open("1_tree.jpg")
#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (400,400))

#Here I resize my opened image, so it is no bigger than 100,100
im.thumbnail((100,100))
#Iterate through a 4 by 4 grid with 100 spacing, to place my image
for i in xrange(0,500,100):
    for j in xrange(0,500,100):
        #I change brightness of the images, just to emphasise they are unique copies.
        im=Image.eval(im,lambda x: x+(i+j)/30)
        #paste the image at location i,j:
        new_im.paste(im, (i,j))

new_im.show()

在这里输入图像描述


17

在fraxel的出色回答的基础上,我编写了一个程序,它接收(.png)图像文件夹、拼贴的宽度像素数以及每行图片数,并为您完成所有计算。

#Evan Russenberger-Rosica
#Create a Grid/Matrix of Images
import PIL, os, glob
from PIL import Image
from math import ceil, floor

PATH = r"C:\Users\path\to\images"

frame_width = 1920
images_per_row = 5
padding = 2

os.chdir(PATH)

images = glob.glob("*.png")
images = images[:30]                #get the first 30 images

img_width, img_height = Image.open(images[0]).size
sf = (frame_width-(images_per_row-1)*padding)/(images_per_row*img_width)       #scaling factor
scaled_img_width = ceil(img_width*sf)                   #s
scaled_img_height = ceil(img_height*sf)

number_of_rows = ceil(len(images)/images_per_row)
frame_height = ceil(sf*img_height*number_of_rows) 

new_im = Image.new('RGB', (frame_width, frame_height))

i,j=0,0
for num, im in enumerate(images):
    if num%images_per_row==0:
        i=0
    im = Image.open(im)
    #Here I resize my opened image, so it is no bigger than 100,100
    im.thumbnail((scaled_img_width,scaled_img_height))
    #Iterate through a 4 by 4 grid with 100 spacing, to place my image
    y_cord = (j//images_per_row)*scaled_img_height
    new_im.paste(im, (i,y_cord))
    print(i, y_cord)
    i=(i+scaled_img_width)+padding
    j+=1

new_im.show()
new_im.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)

模型崩溃拼贴画


嗨。你的回答看起来很棒。你知道如何避免图像边界处出现黑线吗? - Irbin B.
@IrbinB。当我写这个程序时,我希望图像之间的分割线清晰可见,因此我包括了水平和垂直填充(黑线)。垂直填充由代码中的padding参数给出,因此只需将其设置为0即可删除它们。水平填充被意外地硬编码进去了,而我留下了它,因为我想要那种效果。我必须进行实验才能找出如何删除水平填充;每次循环都会有1个像素的偏差。 - Evan Rosica
感谢您的回复。当然,我意识到了填充参数,但将其设置为0对我没有起作用。奇怪的是,只有垂直填充出现在我的最终图像中。也许我应该开一个新问题。 - Irbin B.
@IrbinB。尝试更改:scaled_img_height = ceil(img_height*sf)scaled_img_height = floor(img_height*sf)。这样应该可以消除水平线。例如,我拍了30张相同图片的照片(https://imgur.com/a/AtyrAR5),并将它们输入到更改后的程序中,得到了:https://imgur.com/a/kbdga0G。 - Evan Rosica
它没有起作用。但我已经解决了我的问题。我发现问题与我的图像文件有关。所以,这不是你的代码的问题。谢谢。 - Irbin B.
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接