Created
February 17, 2020 20:34
-
-
Save georgewhewell/e8667236bffabe5b472b36d338f4f71c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from time import sleep | |
from urllib.request import Request, urlopen | |
from PIL import Image | |
ZOOM_SIZE = 16 | |
TILE_SIZE = 256 | |
TILE_URL = "https://a.tile.openstreetmap.org/{}/{}/{}.png" | |
def deg2num(lat_deg, lon_deg, zoom): | |
lat_rad = math.radians(lat_deg) | |
n = 2.0 ** zoom | |
xtile = (lon_deg + 180.0) / 360.0 * n | |
ytile = (1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n | |
return (xtile, ytile) | |
def get_img(x, y): | |
request = Request(TILE_URL.format(ZOOM_SIZE, x, y)) | |
request.add_header('User-Agent', 'Maptthing') | |
return urlopen(request) | |
def stitch(lat, lng): | |
xtile, ytile = deg2num(lat, lng, ZOOM_SIZE) | |
print(f"{xtile}, {ytile}") | |
stitched = Image.new('RGB', (TILE_SIZE * 3, TILE_SIZE * 3)) | |
for i, x in enumerate(range(int(xtile-1), int(xtile+2))): | |
for j, y in enumerate(range(int(ytile-1), int(ytile+2))): | |
sleep(1) | |
img = Image.open(get_img(x, y)) | |
print(f"saving at {x} at {i*TILE_SIZE}, {y} at {j*TILE_SIZE}") | |
stitched.paste(img, box=(i*TILE_SIZE, j*TILE_SIZE)) | |
xoffset = xtile - (x - (TILE_SIZE * 2)) + (xtile % 1) | |
yoffset = ytile - (y - (TILE_SIZE * 2)) + (ytile % 1) | |
print(f"cropping: from {xoffset} {yoffset}") | |
box = (xoffset - TILE_SIZE / 2, yoffset - TILE_SIZE / 2, xoffset + TILE_SIZE / 2, yoffset + TILE_SIZE /2) | |
print(f"box: {box}") | |
cropped = stitched.crop(box) | |
cropped.save('out.png') | |
stitch(51.471539,-0.0931495) |
tmellan
commented
Feb 17, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment