mapbox/mercantile

Utility function for NumPy Array Representation of Tile Coordinates

Closed this issue ยท 2 comments

Hi, Mapbox - thanks for this utility! It's been quite useful for me on a few projects.

One use case that I've had for it has been to generate rastered tilesets for variations on nearest-neighbor type algorithms with 2 dimensional geographic datasets. For these, it's been quite useful to be able to generate a 3D numpy array of shape (WIDTH, HEIGHT, 2) for representation of each pixel location in the tile. With this array I can then generate predictions from a K-NearestNeighbors model, mask the results of predictions for tile using rasterio tooling, etc.

I thought it might be a useful functionality for other people in their projects, and would be happy to contribute to the codebase if you felt it was within scope of the mercantile. Code logic below. It does introduce a numpy dependency which may not be ok.

import mercantile
import numpy as np

def tile_to_matrix(tile: mercantile.Tile, WIDTH=256, HEIGHT=256) -> np.ndarray:
    bounds = mercantile.bounds(tile)
    x_domain = np.linspace(bounds.west, bounds.east, WIDTH)
    y_domain = np.linspace(bounds.north, bounds.south, HEIGHT)
    matrix = np.transpose(
        [np.tile(x_domain, len(y_domain)), np.repeat(y_domain, len(x_domain))]
    ).reshape((HEIGHT, WIDTH, 2))
    return matrix

another similarly useful function might be get_affine_transform(tile: mercantile.Tile) ... etc. for building the affine transforms for each tile from rasterio or affine packages.

@jtbaker have you seen our https://github.com/mapbox/supermercado project? That's where we've been developing our numpy-based extensions of mercantile.

Mercantile needs to remain as minimal as possible.

I hadn't seen that - thanks for the reference, I'll go try and peddle my wares over there. ๐Ÿ˜‰