Created
September 23, 2025 19:19
-
-
Save scottstanie/7f339a391e58947bee8e52a490448443 to your computer and use it in GitHub Desktop.
Create a water mask in EPSG:4326 using `esa_world_cover_2021` imagery
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
| # /// script | |
| # requires-python = ">=3.12" | |
| # dependencies = [ | |
| # "tile-mate", | |
| # "tyro", | |
| # ] | |
| # /// | |
| """Create a water mask in EPSG:4326 using `esa_world_cover_2021` imagery. | |
| Examples | |
| -------- | |
| uv run --script create-water-mask.py --output water_mask.tif -120.9 34.85 -120.25 35.15 | |
| """ | |
| from pathlib import Path | |
| import rasterio as rio | |
| import tile_mate | |
| import tyro | |
| def download_water_mask( | |
| bounds: tuple[float, float, float, float], /, output: Path | |
| ) -> None: | |
| """Download a water mask for the given DISP dataset. | |
| Retrieves a water mask corresponding to the provided DISP dataset and saves it | |
| in the specified output directory. | |
| Parameters | |
| ---------- | |
| bounds : tuple[int, int, int, int] | |
| (west, south, east, north) in degrees longitude/latitude of requested area. | |
| output_dir : str | Path | |
| Directory where the downloaded water mask file will be saved. | |
| """ | |
| # Create output directory if does not exist | |
| if output.exists(): | |
| print(f"{output} exists, exiting.") | |
| return | |
| print(f"Saving Water Mask: {output}") | |
| output_dir = output.parent | |
| output_dir.mkdir(exist_ok=True) | |
| mask_data, mask_attr = tile_mate.get_raster_from_tiles( | |
| bounds, tile_shortname="esa_world_cover_2021" | |
| ) | |
| # Make byte mask | |
| # class 80 is water | |
| water_pixels = mask_data == 80 | |
| # 0 was the old nodata | |
| nodata_pixels = mask_data == 0 | |
| mask_data[:] = 1 | |
| mask_data[water_pixels] = 0 | |
| mask_data[nodata_pixels] = 255 | |
| mask_data = mask_data.astype("byte") | |
| mask_attr["nodata"] = 255 | |
| with rio.open(output, "w", **mask_attr) as dst: | |
| dst.write(mask_data) | |
| if __name__ == "__main__": | |
| tyro.cli(download_water_mask) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment