对于多个图像,PIL的Image.paste有更快的替代方案吗?

时间:2018-05-01 02:51:59

标签: python python-imaging-library

我正在尝试使用image.paste将许多图像粘贴到一个背景上。

我的图片在其文件名中包含x,y偏移值(例如,Image_1000_2000.png偏移量为1000,2000)。

下面的代码有效,但速度很慢。这就是我所拥有的:

import re
import glob
from PIL import Image

# Disable Decompression Bomb Protection
Image.MAX_IMAGE_PIXELS = None

# Set the dimensions of the blank canvas
newheight = 13000
newwidth = 13000

# Glob all the PNG images in the folder and create the blank canvas
photos = glob.glob("*.png")
blankbackground = Image.new('RGB', (newheight, newwidth), (0, 0, 0))
blankbackground.save(r'..\bg999.png', "PNG")

for photo in photos:
  blankbackground = Image.open(r'..\bg999.png')
  photog = Image.open(photo)

  # Get the x , y offsets from the filenames using re
  y_value = re.findall(r"0_(\d*).", photo)[0]
  y = int(y_value)
  x_value = re.findall(r'_(\d*).', photo)[0]
  x = int(x_value)

  # The actual paste operation, and save the image to be re-opened later
  blankbackground.paste(photog,(x,y))
  blankbackground.save(r"..\bg999.png")
  print(photo)

有关更快速替代方案的任何建议吗?

编辑:根据以下评论,无需为每张照片保存/重新加载图片。这使它更快。

1 个答案:

答案 0 :(得分:0)

正如Siyuan和Dan所指出的,Image.save不要求你保存图像并在每个循环中重新加载它。

将Image.open移动到循环之前,并将Image.save移动到循环之后,如图所示:

import re
import glob
from PIL import Image

# Disable Decompression Bomb Protection
Image.MAX_IMAGE_PIXELS = None

# Set the dimensions of the blank canvas
newheight = 13000
newwidth = 13000

# Glob all the PNG images in the folder and create the blank canvas
photos = glob.glob("*.png")
blankbackground = Image.new('RGB', (newheight, newwidth), (0, 0, 0))
blankbackground.save(r'..\bg999.png', "PNG")

# MOVE THE IMAGE.OPEN BEFORE THE LOOP
blankbackground = Image.open(r'..\bg999.png')
for photo in photos:
  photog = Image.open(photo)

  # Get the x , y offsets from the filenames using re
  y_value = re.findall(r"0_(\d*).", photo)[0]
  y = int(y_value)
  x_value = re.findall(r'_(\d*).', photo)[0]
  x = int(x_value)

  # The actual paste operation
  blankbackground.paste(photog,(x,y))
  print(photo)
# MOVE THE IMAGE.SAVE AFTER THE LOOP
blankbackground.save(r"..\bg999.png")

因此,它从十分钟到十秒钟。