Cloud Masking for Sentinel-2 images

If there are clouds or cloud shadows on your sentinel-2 scene, they can be mask out using the quality scene classification band of your scene.

Sentinel-2 scene (true color) with clouds and cloud shadows

Image quality band and the classes we want to delete for our mask (Values): 3 (cloud shadows), 7 (unclassified), 8 (cloud medium probability), 9 (cloud high probability), 10 (thin cirrus) and 11 (snow or ice). For other scenes, you have to adjust the classes if necessary.

Sentinel-2 scene with quality scene classification

Here you can download a Sentinel-2 image for executing this pre-processing step. For the scene which we used in the pre-processing before is no cloud correction necessary.

Processing steps in RStudio:

Open R-Studio and install, open the required packages and set your working directory:

install.packages("raster")
install.packages("rgdal")

library(raster)
library(rgdal)

setwd("D:\\elearning\\exchange\\R")

 

Open and plot the image:

sen2 <- stack("subset_0_of_S2A_MSIL2A_20190626T102031_N0212_R065_T32UQD_20190626T125319_resampled.tif")
plot(sen2)
plotRGB(sen2, 4,3,2, stretch="lin")

 

Seperate spectral bands and classification (band 1 to 12 is the mulispectral Senitnel- 2 scene, band 13 is the quality classification band):

sen2_bands <- sen2[[-13]]
sen2_mask <- sen2[[13]]
plot(sen2_mask)

 

Which pixels do we want to mask?

plot(sen2_mask)
sen2_mask_combi <- sen2_mask
sen2_mask_combi[sen2_mask == 3 |sen2_mask == 7 |sen2_mask == 8 | sen2_mask == 9 |sen2_mask == 10 |sen2_mask == 11 ] <- NA

plot(sen2_mask_combi)
writeRaster(sen2_mask_combi, "sen2_mask.tif")

Mask without the classes: 3,7,8,9,10,11

 

Apply mask:

sen2_bands_masked <- raster::mask(sen2_bands,sen2_mask_combi)
plotRGB(sen2_bands_masked, 4,3,2,stretch="lin")
writeRaster(sen2_bands_masked, "sen2_masked.tif")

Applied mask

 

…or the whole part in short:

sen2_bands_masked_a <- sen2_bands
sen2_bands_masked_a [sen2_mask == 3 |sen2_mask == 7 |sen2_mask == 8 | sen2_mask == 9 |sen2_mask == 10 |sen2_mask == 11 ] <- NA
writeRaster(sen2_bands_masked_a, "sen2_masked_alternativ.tif")