Utilities

Build a grid of administrative units over a raster, and reproject or anonymize rasters.

source

reproject_raster

def reproject_raster(
    src_fname:str, # Path to the source GeoTIFF
    dst_fname:str, # Path of the reprojected GeoTIFF to write
    dst_crs:str='EPSG:4326', # Target coordinate reference system
)->None:

Reproject every band of src_fname to dst_crs and write the result to dst_fname.

Resampling uses the nearest neighbour. Each output cell copies the value of the closest input cell, and no values are interpolated.


source

gridder

def gridder(
    fname_raster:str, # Path to the raster file
    band:int=1, # Band to read. Unused: the grid depends only on the raster's bounds and CRS
    nrows:int=10, # Number of grid rows
    ncols:int=10, # Number of grid columns
)->geopandas.geodataframe.GeoDataFrame: # One polygon per grid cell, indexed by `loc_id`, in the raster's CRS

Split the extent of fname_raster into an nrows by ncols grid of polygons.

gridder simulates administrative units when real boundaries are not available. The default grid has 10 rows and 10 columns:

fname_raster = './files/ground-truth-02-4326-simulated.tif'
grid = gridder(fname_raster)
test_eq(len(grid), 100)
grid.head()
geometry
loc_id
0 POLYGON ((-1.17017 43.02904, -1.17017 42.99324...
1 POLYGON ((-1.17017 43.06483, -1.17017 43.02904...
2 POLYGON ((-1.17017 43.10063, -1.17017 43.06483...
3 POLYGON ((-1.17017 43.13643, -1.17017 43.10063...
4 POLYGON ((-1.17017 43.17222, -1.17017 43.13643...

loc_id numbers the cells column by column. Cell 0 is in the south-west corner, and the numbers increase northwards, then eastwards:

ax = grid.boundary.plot(lw=0.5, color='black')
for loc_id, pt in grid.representative_point().items(): ax.annotate(loc_id, (pt.x, pt.y), ha='center', va='center', fontsize=6)
ax.axis('off');


source

anonymize_raster

def anonymize_raster(
    fname_raster:str, # Path to the raster file
    new_lon_origin:float, # Longitude of the new upper-left corner
    new_lat_origin:float, # Latitude of the new upper-left corner
    band:int=1, # Band to anonymize
)->None:

Move a raster to a new origin and rescale its values to [0, 1].