Python -L oop: загрузите файл .png с opentopomap.org и объедините отдельные файлы png в одно большое изображение - PullRequest
0 голосов
/ 08 апреля 2020

Я хочу создать большую картину местности, где я сейчас живу, и распечатать ее на бумаге. Мне очень нравятся карты из opentopomap.org.

Я уже закончил код для извлечения отдельных изображений в определенном порядке c. См. Код ниже:

import multiprocessing
import pprint
import time


print("The pictures will be saved all what is east-south from Mannheim Quadrate")
x2 = int(input("North-South (latitude) (start: 22369, Mannheim) Type in more than 22369: "))
x3 = int(input("East-West (longitude) (start: 34309, Mannheim) Type in more than 34309: "))

urls = [
    f"https://c.tile.opentopomap.org/16/{j}/{i}.png" for i in range(22369, x2 + 1) for j in range(34309, x3 + 1)]

def download_image(url):
    response = requests.get(url)
    print(f"Downloading from {url}...")
    url = url.replace("/", "_").replace(":", "_")
    with open(f"{url}", "wb") as file:
        file.write(response.content)

if __name__ == "__main__":
    start = time.perf_counter()
    p = multiprocessing.Pool(processes=4)
    p.map(download_image, urls)
    p.close()
    stop = time.perf_counter()


    print(f"It took {round(stop - start, 2)} seconds in total")```

Все изображения сохраняются на моем рабочем столе в таком порядке:

     https___c.tile.opentopomap.org_16_{j}_{i}
e.g. https___c.tile.opentopomap.org_16_34309_22370 (Mannheim, Germany)

Теперь мне нужен хороший код для объединения всех изображений в правильном порядке, используя имена файлов. Кто-нибудь знает некоторые строки кода, чтобы сделать? Я нашел и изменил это: Как объединить изображения в холст, используя PIL / Pillow?

import PIL, os, glob
from PIL import Image
from math import ceil, floor

PATH = r"C:\Users\micha\Desktop\test"

frame_width = 3072
images_per_row = 12
padding = 0

os.chdir(PATH)

images = glob.glob("*.png")
images = images[:30]

img_width, img_height = Image.open(images[0]).size

scaled_img_width = ceil(img_width)
scaled_img_height = ceil(img_height)

number_of_rows = ceil(len(images)/images_per_row)
frame_height = ceil(img_height*number_of_rows)

new_im = Image.new('RGB', (frame_width, frame_height))

i,j=0,0
for num, im in enumerate(images):
    if num%images_per_row==0:
        i=0
    im = Image.open(im)
    #Here I resize my opened image, so it is no bigger than 100,100
    im.thumbnail((scaled_img_width,scaled_img_height))
    #Iterate through a 4 by 4 grid with 100 spacing, to place my image
    y_cord = (j//images_per_row)*scaled_img_height
    new_im.paste(im, (i,y_cord))
    print(i, y_cord)
    i=(i+scaled_img_width)+padding
    j+=1

new_im.show()
new_im.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)

new_im.save()

Проблема здесь в том, что имя файла в настоящее время, например:

https___c.tile.opentopomap.org_16_34309_22370 

Для объединения имя файла должно выглядеть следующим образом: например,

https___c.tile.opentopomap.org_16_222370_34309 

Последние два блока должны быть переключены ...

Есть ли у кого-то идеи, как решить эту проблему с переименованием?

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 11 апреля 2020

Возможно, вы можете использовать pygame

Если вы добавите import pygame и используете pygame.Surface

import pygame

image1 = pygame.image.load("image1") # First image
image2 = pygame.image.load("image2") # Second image
image3 = pygame.Surface(total width of images, height of an image) #  Free surface
image3.blit(image1, (0, 0)) # Drawing images on image3
image3.blit(image2, (image1s width, 0))
pygame.image.save(image3, "name of image.png") # Saving total of them to harddisk

Это не лучшая идея, но она может помочь

...