我有幾張影像(PNG 格式),我想將它們組合成一個網格結構的影像檔案(這樣我可以設定每行顯示的影像數量)。另外,我想在影像之間添加小的空白空間。
例如,假設有 7 個影像。我想將每行顯示的影像數量設定為 3。組合影像的一般結構將是:
如果您知道這樣做的好方法(最好使用PIL/Pillow
或matplotlib
庫),請告訴我。謝謝。
uj5u.com熱心網友回復:
您可以在以像素為單位的影像和串列之間傳遞combine_images
預期的函式columns
編號:space
images
from PIL import Image
def combine_images(columns, space, images):
rows = len(images) // columns
if len(images) % columns:
rows = 1
width_max = max([Image.open(image).width for image in images])
height_max = max([Image.open(image).height for image in images])
background_width = width_max*columns (space*columns)-space
background_height = height_max*rows (space*rows)-space
background = Image.new('RGBA', (background_width, background_height), (255, 255, 255, 255))
x = 0
y = 0
for i, image in enumerate(images):
img = Image.open(image)
x_offset = int((width_max-img.width)/2)
y_offset = int((height_max-img.height)/2)
background.paste(img, (x x_offset, y y_offset))
x = width_max space
if (i 1) % columns == 0:
y = height_max space
x = 0
background.save('image.png')
combine_images(columns=3, space=20, images=['apple_PNG12507.png', 'banana_PNG838.png', 'blackberry_PNG45.png', 'cherry_PNG635.png', 'pear_PNG3466.png', 'plum_PNG8670.png', 'strawberry_PNG2595.png'])
7 幅影像和 3 列的結果:
6 張影像和 2 列的結果:
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495101.html