Skip to content

Instantly share code, notes, and snippets.

@kadyb
Last active February 12, 2024 20:22
Show Gist options
  • Save kadyb/31799be3a639910efac6095ef9d4c665 to your computer and use it in GitHub Desktop.
Save kadyb/31799be3a639910efac6095ef9d4c665 to your computer and use it in GitHub Desktop.
Search and acquire satellite data in R
library("rstac")
library("stars")

catalog = stac("https://earth-search.aws.element84.com/v1")
collection = "sentinel-2-l2a"
bbox = c(16, 52, 17, 53) # xmin, ymin, xmax, ymax (WGS84)
datetime = "2023-01-01T00:00:00Z/2023-12-31T00:00:00Z" # RFC 3339

catalog |>
  stac_search(
    collections = collection,
    bbox = bbox,
    datetime = datetime,
    limit = 1) |>
  ext_query(`eo:cloud_cover` < 10) |>
  post_request() -> items

items |>
  assets_select(asset_names = c("blue", "green", "red")) |>
  assets_url(append_gdalvsi = TRUE) -> urls

r = read_stars(urls, proxy = TRUE, along = 3)
plot(st_rgb(r[,,,3:1]), main = "Sentinel 2")
write_stars(r, "sentinel.tif") # save multilayer raster to disk

sentinel

@abdelkrim-bsr
Copy link

How to write stars object to drive as tif images?

@kadyb
Copy link
Author

kadyb commented Feb 12, 2024

@abdelkrim-bsr, you can use the write_stars() function like this:

r = read_stars(urls, proxy = TRUE, along = 3)
r = st_set_dimensions(r, 3, values = c("Blue", "Green", "Red"), names = "band") # change band names
write_stars(r, "sentinel.tif", type = "UInt16", NA_value = 0, options = "COMPRESS=DEFLATE")

But this is not the only way. You can also use download.file() or GDAL translate from sf::gdal_utils(). See also this question on StackOverflow.

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