Skip to main content

This is probably something simple to answer: I am working with eo-learn and trying to apply an AOI mask (defined in mask_timeless) and set masked areas to NaN across all images in a temporal stack within an eo-patch.


I am using the code below from How To: Land-Use-Land-Cover Prediction for Slovenia — eo-learn 0.9.2 documentation


ndvi_cleana~aoi_mask] = np.nan


where ndvi_clean is the multitemporal NDVI from the eo-patch and aoi_mask is a single band mask.

Issue is how I apply the single band mask across the temporal stack. Appreciate any guidance on this as I am still learning python and numpy.

You should broadcast the mask shape to the data shape.


broadcasted_mask = np.broadcast_to(array=aoi_mask, shape=ndvi_clean.shape)
ndvi_clean[~broadcasted_mask] = np.nan

A full example:



import numpy as np
import matplotlib.pyplot as plt

n_timestamps = 10
size = 20

# made up data
ndvi_clean = np.random.random(size=(n_timestamps,size,size))

# made up mask
aoi_mask = np.zeros((size,size))
aoi_mask[5:15,5:15] = 1
aoi_mask = aoi_mask > 0.5

# new mask is broadcasted (in shape) to the array we want to mask
broadcasted_mask = np.broadcast_to(array=aoi_mask, shape=ndvi_clean.shape)

# test that first slice of broadcasted_mask equals to aoi_mask
np.testing.assert_equal(broadcasted_mask[0,...], aoi_mask)

# work on a copy for illustration
aoi_ndvi = ndvi_clean.copy()

# mask the ndvi array
aoi_ndvi[~broadcasted_mask] = 0

fig, ax = plt.subplots(ncols=2, figsize=(11,5))
ax[0].imshow(ndvi_clean[0][...])
ax[1].imshow(aoi_ndvi[0][...])

produces the following image:


Hope that helps!


Great, this is exactly what I was looking for! Thanks so much!


Reply