Skip to content

Instantly share code, notes, and snippets.

@calebrob6
Created November 13, 2024 23:42
Show Gist options
  • Save calebrob6/125a349f11972ff1e36d1a976aa601d4 to your computer and use it in GitHub Desktop.
Save calebrob6/125a349f11972ff1e36d1a976aa601d4 to your computer and use it in GitHub Desktop.
Method for checking whether a bbox in a Sentinel 2 scene from the Planetary Computer is cloudy or not
def check_if_scene_is_cloudy_at_box(item: pystac.Item, box: shapely.geometry.Polygon):
"""Uses the S2 Scene Classification Layer (SCL) to determine if a S2 L2A scene is cloudy at a given bbox.
Args:
item (pystac.Item): The S2 L2A item to check
box (shapely.geometry.Polygon): The geometry to check (should be EPSG:4326)
Returns:
float: The fraction of the box that is classified as "Cloud medium probability" + "Cloud high probability"
"""
scl_url = item.assets["SCL"].href
with rasterio.open(scl_url) as f:
geom = shapely.geometry.mapping(box)
warped_geom = rasterio.warp.transform_geom("EPSG:4326", f.crs, geom)
out_mask, _ = rasterio.mask.mask(f, [warped_geom], crop=True)
out_mask = out_mask.squeeze()
out_mask_pixels = out_mask[out_mask != 0]
vals, counts = np.unique(out_mask_pixels, return_counts=True)
N = counts.sum()
val_counts = dict(zip(vals, counts))
# Number of "Cloud medium probability" + "Cloud high probability"
num_cloudy = val_counts.get(8, 0) + val_counts.get(9, 0)
if N == 0:
raise WindowEmpty()
else:
fraction_bad = num_cloudy / N
return fraction_bad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment