Python3.4 PIL
我将100多个16x16图块组合在一起,为测试应用程序随机生成地形,并保存为.png文件进行存储。
我在测试时的担心是我收到了以下完成时间:
对于移动/桌面应用,这太长了。是否有更优化的创建这些地图?
注意:我不打算使用16x16瓷砖以外的任何东西。不过我对其他Python模块持开放态度。
from datetime import datetime
from os import listdir, chdir
from random import randint
from time import strftime
from PIL import Image
x_size = 4800
y_size = 4800
x_tile_size = 16
y_tile_size = 16
x_tile_amount = int(x_size/x_tile_size)
y_tile_amount = int(y_size/y_tile_size)
new_im = Image.new('RGB', (x_size, y_size))
file_path = './assets/terrain/plains/'
print("Generating map.")
start_time = strftime("%H:%M:%S")
for i in range(x_tile_amount):
for j in range(y_tile_amount):
dice_roll = randint(1,7)
if dice_roll == 1:
terrain_file_path = 'grass_1.png'
elif dice_roll == 2:
terrain_file_path = 'grass_2.png'
elif dice_roll == 3:
terrain_file_path = 'grass_3.png'
elif dice_roll == 4:
terrain_file_path = 'grass_4.png'
elif dice_roll == 5:
terrain_file_path = 'white_flower.png'
elif dice_roll == 6:
terrain_file_path = 'red_flower.png'
elif dice_roll == 7:
terrain_file_path = 'blue_flower.png'
old_im = Image.open(file_path + terrain_file_path)
new_im.paste(old_im, (i*x_tile_size,j*y_tile_size))
end_time = strftime("%H:%M:%S")
t_format = "%H:%M:%S"
t_delta = datetime.strptime(end_time, t_format) - datetime.strptime(start_time, t_format)
print('Time to generate map = ' + str(t_delta))
new_im.save('pillow_test.png', 'PNG')
答案 0 :(得分:3)
您正在打开新图像n ^ 2次。这使它非常慢。
在进行for循环之前,您应该预先加载这些图像
grass_1 = Image.open(file_path + 'grass_1.png')
grass_2 = Image.open(file_path + 'grass_2.png')
...
for i in range(x_tile_amount):
for j in range(y_tile_amount):
dice_roll = random.randint(1, 7)
if dice_roll == 1:
etc.
您可以做的另一个补充是将图片设为字典。
my_dict = {
1: 'grass_1',
2: 'grass_2',
...
}
然后你可以做
dice_roll = random.randint(1,7)
new_im.paste(my_dict[dice_roll], (i*x_tile_size,j*y_tile_size))
尝试一下,看看这是否有助于你的时间。
主要问题是,当您生成100x100地图时,您将加载图像10,000次。没有理由将相同的7个图像文件加载10k次,因此您只需预加载它们并根据需要添加。
答案 1 :(得分:3)
您正在为每个随机选择加载每个地形图像。最好预加载所有图像,然后只需使用random.choice()
为您选择其中一个,如下所示:
from datetime import datetime
import random
from time import strftime
from PIL import Image
x_size = 4800
y_size = 4800
x_tile_size = 16
y_tile_size = 16
x_tile_amount = int(x_size/x_tile_size)
y_tile_amount = int(y_size/y_tile_size)
new_im = Image.new('RGB', (x_size, y_size))
file_path = './assets/terrain/plains/'
images = ['grass_1.png', 'grass_2.png', 'grass_3.png', 'grass_4.png', 'white_flower.png', 'red_flower.png', 'blue_flower.png']
terrain = [Image.open(os.path.join(file_path, image)) for image in images]
print("Generating map.")
start_time = strftime("%H:%M:%S")
for i in range(x_tile_amount):
for j in range(y_tile_amount):
old_im = random.choice(terrain)
new_im.paste(old_im, (i*x_tile_size,j*y_tile_size))
end_time = strftime("%H:%M:%S")
t_format = "%H:%M:%S"
t_delta = datetime.strptime(end_time, t_format) - datetime.strptime(start_time, t_format)
print('Time to generate map = ' + str(t_delta))
new_im.save('pillow_test.png', 'PNG')
这种方法可以让你加快速度。