Apply masks on Satellite Images

GeoSense ✅
2 min readDec 23, 2022

When we use Satellite Imagery, they usually provide masks for clouds, water, etc. I will show you how to apply masks to remove water pixels from satellite images.

About Dataset


A collection of water bodies images captured by the Sentinel-2 Satellite. Each image comes with a black and white mask where white represents water and black represents something else but water. The masks were generated by calculating the NWDI (Normalized Water Difference Index) which is frequently used to detect and measure vegetation in satellite images, but a greater threshold was used to detect water bodies.

Link: Satellite Images of Water Bodies


Original image
Mask for the above image

Desired output like this:

Water pixels were removed

Now, we start:

1. Load Libraries:

import numpy as np
import os
import matplotlib.pyplot as plt
from scipy import stats
import rasterio
from rasterio.plot import show
%matplotlib inline

2. Load images using Rasterio. I keep the metadata in the variable name out_meta:

file1 = "/kaggle/input/satellite-images-of-water-bodies/Water Bodies Dataset/Images/water_body_1.jpg"
file2 = "/kaggle/input/satellite-images-of-water-bodies/Water Bodies Dataset/Masks/water_body_1.jpg"
img =
msk =


mask =
show(img), show(msk)
out_meta = img.meta.copy()

3. Create a mask boolean from the mask file and apply the mask boolean to the original image:

# create mask
maskby = mask == 0
# apply to 3 bands
rm = r * maskby
gm = g * maskby
bm = b * maskby
all_bands_mask = [rm,gm,bm]

out_meta.update(count = len(all_bands_mask),
outstackmask = "water_body_nowater_1.jpg"

with, 'w', **out_meta) as dst:

for id, layer in enumerate(all_bands_mask, start=1):
dst.write_band(id, layer)
print(outstackmask + ": Stacking successfully!")

img ="/kaggle/working/water_body_nowater_1.jpg")

Here is my code on Kaggle and GitHub. Thanks for reading.

GeoSense ✅

🌏 Remote sensing | 🛰️ Geographic Information Systems (GIS) | ℹ️

Recommended from Medium


See more recommendations