[GIS] Add a ‘cloud’ band to Sentinel 2 images (GEE)

cloud covergoogle-earth-enginesentinel-2

This script is used to mask out cloud in sentinel 2 images using a threshold for band 4:

// Sentinel 2 cloud function 
var cloudfunction_ST2 = function(image) {
  // If band 4 is higher than 2500, the pixel is considered as cloudy.
  var b4 = image.select("B4");
  // Get pixels above the threshold.
  var cloud = b4.gt(2500);      
  // Create a mask from high likelihood pixels.
  var cloudmask = image.mask().and(cloud.not());
  // Mask those pixels from the image.
  return image.updateMask(cloudmask);
};    

My question is, how to add a 'cloud' band to the image collection?

Best Answer

If you want the value of 'cloud' to be 1 (true) do:

// Sentinel 2 cloud function 
var cloudfunction_ST2 = function(image) {
  // If band 4 is higher than 2500, the pixel is considered as cloudy.
  var b4 = image.select("B4");
  // Get pixels above the threshold.
  var cloud = b4.gt(2500).select([0], ["cloud"]);
  // Create a mask from high likelihood pixels.
  var cloudmask = image.mask().and(cloud.not())
  image = image.updateMask(cloudmask);
  // Mask those pixels from the image.
  return image.addBands(cloud)
};

Otherwise:

// Sentinel 2 cloud function 
var cloudfunction_ST2 = function(image) {
  // If band 4 is higher than 2500, the pixel is considered as cloudy.
  var b4 = image.select("B4");
  // Get pixels above the threshold.
  var cloud = b4.gt(2500);
  // Create a mask from high likelihood pixels.
  var cloudmask = image.mask().and(cloud.not()).select([0], ["cloud"])
  image = image.updateMask(cloudmask);
  // Mask those pixels from the image.
  return image.addBands(cloudmask)
};

Then, when you go ImageCollection.map(cloudfunction_ST2) you'll get an extra band called 'cloud' in every image.

Remember you have a band called 'QA60' which is the bit mask band with cloud mask information.