I would like to set to NaN or Null all clouds to a cut section of a Sentinel-2 MSI level 2, for one band only if possible (not all RGB) I have used the following code:
/**
* Function to mask clouds using the Sentinel-2 QA band
* @param {ee.Image} image Sentinel-2 image
* @return {ee.Image} cloud masked Sentinel-2 image
*/
function maskS2clouds(image) {
var qa = image.select('QA60');
// Bits 10 and 11 are clouds and cirrus, respectively.
var cloudBitMask = 1 << 10;
var cirrusBitMask = 1 << 11;
// Both flags should be set to zero, indicating clear conditions.
var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
.and(qa.bitwiseAnd(cirrusBitMask).eq(0));
return image.updateMask(mask).divide(10000);
}
var dataset = ee.ImageCollection('COPERNICUS/S2_SR')
.filterDate('2020-01-01', '2020-01-30')
// Pre-filter to get less cloudy granules.
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))
.map(maskS2clouds);
var visualization = {
min: 0.0,
max: 0.3,
bands: ['B4', 'B3', 'B2'],
};
Map.setCenter(83.277, 17.7009, 12);
Map.addLayer(dataset.mean(), visualization, 'RGB');
the code used does not completely eliminate the clouds as is seen in the figure:
when I do the same for Landsat I have found out the clouds are well masked with the code:
/**
* Function to mask clouds based on the pixel_qa band of Landsat SR data.
* @param {ee.Image} image Input Landsat SR image
* @return {ee.Image} Cloudmasked Landsat image
*/
var cloudMaskL457 = function(image) {
var qa = image.select('pixel_qa');
// If the cloud bit (5) is set and the cloud confidence (7) is high
// or the cloud shadow bit is set (3), then it's a bad pixel.
var cloud = qa.bitwiseAnd(1 << 5)
.and(qa.bitwiseAnd(1 << 7))
.or(qa.bitwiseAnd(1 << 3));
// Remove edge pixels that don't occur in all bands
var mask2 = image.mask().reduce(ee.Reducer.min());
return image.updateMask(cloud.not()).updateMask(mask2);
};
var dataset = ee.ImageCollection('LANDSAT/LT05/C01/T1_SR')
.filterDate('2011-01-01', '2011-12-31')
.map(cloudMaskL457);
var visParams = {
bands: ['B3', 'B2', 'B1'],
min: 0,
max: 3000,
gamma: 1.4,
};
Map.setCenter(34.9774, 32.4916, 8);
Map.addLayer(dataset.median(), visParams);