Last active
November 15, 2025 14:05
-
-
Save zabop/8ad594138fccfd473af9fac4bdbeedc4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| from osgeo import gdal | |
| from PIL import Image | |
| import numpy as np | |
| import shapely.ops | |
| import shapely | |
| import pyproj | |
| import sys | |
| from typing import Callable | |
| z, x, y = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) # 6, 36, 16 | |
| # prepare jpeg | |
| w, h = 512, 512 | |
| data = np.dstack([255*np.ones((h,w),dtype=np.uint8),np.ones((h,w,2),dtype=np.uint8)]) | |
| im = Image.fromarray(data,"RGB") | |
| im.save("example.jpeg") | |
| # utils | |
| maxc = 20037508.342789244 | |
| sidelength: Callable[[int], float] = lambda z: 2 * maxc / (2**z) | |
| def get_tile_centres(z: int, x: int, y: int) -> tuple[float, float]: | |
| # return coordinates of tile centres in EPSG:3857 | |
| x = -maxc + maxc / (2**z) + sidelength(z) * x | |
| y = maxc - maxc / (2**z) - sidelength(z) * y | |
| return x, y | |
| def get_tile_corners(z: int, x: int, y: int): | |
| tc = get_tile_centres(z, x, y) | |
| s = sidelength(z) | |
| corners = [] | |
| for each in [[1, 1], [1, -1], [-1, -1], [-1, 1], [1, 1]]: | |
| v = 0.5 * np.array([each]) * np.array([s, s]) | |
| corner = tc + v | |
| corners.append(corner) | |
| corners = np.squeeze(corners) | |
| p = shapely.geometry.Polygon(corners) | |
| return p | |
| # georef jpeg | |
| minx, miny, maxx, maxy = get_tile_corners(z, x, y).bounds | |
| dataset = gdal.Open("example.jpeg") | |
| translate_options = gdal.TranslateOptions( | |
| format="JPEG", outputSRS="epsg:3857", outputBounds=[minx, maxy, maxx, miny], | |
| ) | |
| gdal.Translate("georeferenced-example.jpeg", dataset, options=translate_options, dstAlpha=True) | |
| # prepare cutline | |
| trans = pyproj.Transformer.from_crs( | |
| crs_from="EPSG:3857", crs_to="EPSG:25835", always_xy=True | |
| ).transform | |
| transformed_tile = shapely.ops.transform(trans, get_tile_corners(z, x, y)) | |
| xys = [p for p in transformed_tile.exterior.coords] | |
| xs = sorted([x for x, _ in xys]) | |
| ys = sorted([y for _, y in xys]) | |
| inner_rectangle = shapely.geometry.box(xs[1],ys[1],xs[2],ys[2]) | |
| print(inner_rectangle.wkt) | |
| # reproject & cut | |
| input_ds = gdal.Open("georeferenced-example.jpeg") | |
| warp_options = gdal.WarpOptions( | |
| format="JPEG", | |
| cropToCutline=True, | |
| dstSRS="EPSG:25835", | |
| cutlineWKT=inner_rectangle.wkt, | |
| cutlineSRS="EPSG:25835", | |
| resampleAlg="cubic", | |
| warpOptions={"CUTLINE_ALL_TOUCHED": True}, | |
| ) | |
| gdal.Warp(f"warped-{z}-{x}-{y}.jpeg", input_ds, options=warp_options) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment