Python 是否有比PIL'更快的替代方案;是否为多个图像粘贴?
我正在尝试使用image.paste将多个图像粘贴到一个背景上 “我的图像”的文件名中包含其x、y偏移值(例如,Image_1000_2000.png的偏移量为10002000) 下面的代码可以工作,但速度非常慢。以下是我得到的:Python 是否有比PIL'更快的替代方案;是否为多个图像粘贴?,python,python-imaging-library,Python,Python Imaging Library,我正在尝试使用image.paste将多个图像粘贴到一个背景上 “我的图像”的文件名中包含其x、y偏移值(例如,Image_1000_2000.png的偏移量为10002000) 下面的代码可以工作,但速度非常慢。以下是我得到的: import re import glob from PIL import Image # Disable Decompression Bomb Protection Image.MAX_IMAGE_PIXELS = None # Set the dimensio
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)
有没有关于更快的替代方案的建议
编辑:根据下面的评论,无需在每张照片中保存/重新加载图像。这使它的速度大大加快。正如思源和丹所指出的,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")
因此,它从10分钟变为10秒 为什么每次迭代都要保存结果?为什么不能只在最后保存?跳过每个图像的保存和重新加载。粘贴每个图像,然后保存。你说得对。不必为每个图像保存和重新加载。谢谢现在够快了吗?如果是这样的话,也许值得发布你自己的答案。在短期内,它可能不会获得很多选票,但随着时间的推移,它可能会积累一些。肯定会快得多。谢谢你,保罗,我就是这么做的。