Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Last active February 7, 2026 11:52
Show Gist options
  • Select an option

  • Save mdsumner/c20d965c5e975ec2aad2f4656030ddd2 to your computer and use it in GitHub Desktop.

Select an option

Save mdsumner/c20d965c5e975ec2aad2f4656030ddd2 to your computer and use it in GitHub Desktop.

https://fosstodon.org/@hughagraham/116005729038262380

## generate a tif with a nodata collar
dsn <- "/vsicurl/https://projects.pawsey.org.au/idea-gebco-tif/GEBCO_2024.tif"
library(terra)
#> terra 1.8.96
pr <- rast(ext(c(-1, 1, -1, 1)) * 1e7, res = 4000, crs = "+proj=laea")
pr
#> class       : SpatRaster 
#> size        : 5000, 5000, 1  (nrow, ncol, nlyr)
#> resolution  : 4000, 4000  (x, y)
#> extent      : -1e+07, 1e+07, -1e+07, 1e+07  (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=laea +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
r <- mask(project(rast(dsn), pr, by_util = TRUE, filename = tempfile(fileext = ".tif")), ext(c(-1, 1, -1, 1) * 5e6), inverse = FALSE, filename = "collar.tif", overwrite = TRUE)
plot(r, main  = "original data")

## run footprint (could be a more complex collar)
system("gdal raster footprint collar.tif nodata.parquet --overwrite")

plot(v <- vect("nodata.parquet"), add = TRUE, lwd = 2, border = "firebrick")

## get the extent of the collar 
ex <- as.vector(ext(v))
## use vrt:// to invoke VRT crop of the original tif
dsn_crop <- sprintf("vrt://collar.tif?projwin=%s", paste0(ex[c(1, 4, 2, 3)], collapse = ","))
plot(rast(dsn_crop), main = "the virtual crop we will warp")

gdalraster::warp(dsn_crop, "warp.tif", t_srs = "EPSG:4326")
plot(w <- rast("warp.tif"), main = "warp result")

w
#> class       : SpatRaster 
#> size        : 2271, 2913, 1  (nrow, ncol, nlyr)
#> resolution  : 0.04085825, 0.04085825  (x, y)
#> extent      : -59.504, 59.51609, -46.39806, 46.39104  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#> source      : warp.tif 
#> name        : GEBCO_2024

Created on 2026-02-07 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment