How to “remove” the clouds in an NDVI image AND return as 1 band

  • 26 April 2024
  • 3 replies
  • 11 views

I am trying to download NDVI as 1 band with a Cloud mask. Esssentially I am trying to combine these two scripts and need some assistance.

Cloud mask

//VERSION=3
function setup() {
  return {
    input: ["B02", "B03", "B04", "CLM"],
    output: { bands: 1 }
  }
}
function evaluatePixel(sample) {
  if (sample.CLM == 1) {
    return [0.75 + sample.B04,
            sample.B03,
            sample.B02]
  }
  return [ 
    2.5*sample.B04, 
    2.5*sample.B03, 
    2.5*sample.B02];
}

1 band NDVI

//VERSION=3
function setup() {
  return {
    input: ["B08", "B04"],
    output: { bands: 1 }
  };
}
function evaluatePixel(sample) {
  var ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04);  
  return [ndvi];
}

It does not have to be these two scripts specifically, but if anyone has any suggestions on how to effectively combine these two i’d appreciate it. Thank you!


3 replies

Hi Momin,

It depends how you want to return the data, but to get a Geotiff with two bands, where the first band is NDVI and the second band is a binary cloud mask (Cloud = 1, No cloud = 0), you could use the following script:

//VERSION=3
function setup() {
  return {
    input: ["B04", "B08", "CLM"],
    output: { bands: 2, sampleType: "FLOAT32" }
  }
}
function evaluatePixel(sample) {
  
  var ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04)

  return [ndvi, sample.CLM]
}

If you want to return a visualisation of the bands and not the values (for a jpeg or png), you could convert to UINT8 for example and use the following script (note that this way you are visualising NDVI values between 0 and 1):

//VERSION=3
function setup() {
  return {
    input: ["B04", "B08", "CLM"],
    output: { bands: 2, sampleType: "UINT8" }
  }
}
function evaluatePixel(sample) {
  
  var ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04)

  // We reverse the value of the cloud band to mask clouds from the resulting image
  return [ndvi * 255, 255 - sample.CLM * 255]
}

Fantastic, thank you Maxim!

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.

Reply