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

Context

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

Example:

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 = rasterio.open(file1)
msk = rasterio.open(file2)

r= img.read(1)
g= img.read(2)
b= img.read(3)

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

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),
dtype=rasterio.int8,)
outstackmask = "water_body_nowater_1.jpg"

with rasterio.open(outstackmask, '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 = rasterio.open("/kaggle/working/water_body_nowater_1.jpg")
show(img)

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

GeoSense ✅

🌏 Remote sensing | 🛰️ Geographic Information Systems (GIS) | ℹ️ https://www.tnmthai.com/medium