繁体   English   中英

是否可以使用PIL的Image.paste更快地替代多个图像?

[英]Is there a faster alternative to PIL's Image.paste for multiple images?

我正在尝试使用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)

关于更快选择的任何建议?

编辑:根据下面的评论,没有必要保存/重新加载每张照片的图像。 这使其速度大大提高。

正如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")

因此,它从十分钟变为十秒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM