I am trying to use image.paste to paste many images onto one background.
My images contain their x,y offset values in their filenames (eg. Image_1000_2000.png is offset 1000,2000).
The code below works, but it's painfully slow. Here's what I've got:
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)
Any suggestions on a speedier alternative?
EDIT: As per the comments below, it is not necessary to save / reload the image with every photo. This makes it considerably faster.
As pointed out by Siyuan and Dan, Image.save does not require you to save the image and re-load it every loop.
Move the Image.open to before the loop, and move the Image.save to after the loop, as shown:
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")
Thus, it goes from ten minutes to ten seconds.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.