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.
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.
Desired output like this:
Now, we start:
1. Load Libraries:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from rasterio.plot import show
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)
mask = msk.read(1)
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 rasterio.open(outstackmask, 'w', **out_meta) as dst:
for id, layer in enumerate(all_bands_mask, start=1):
print(outstackmask + ": Stacking successfully!")
img = rasterio.open("/kaggle/working/water_body_nowater_1.jpg")