I want to use a imagecollection to calculate NDVI, the following code shows how I did. However, I know some values of surface reflectance of Near-infrared band and Red band are less than 0, or larger than 10000, or is Null, so how to calculate the NDVI by avoiding use the Near-infrared band and Red band with those unusual values?

var collection = ee.ImageCollection('LANDSAT/LE07/C01/T1_SR') 
    .filterDate('2019-01-01', '2019-12-31') // the period of interest
    .filterBounds(fc) // the study area
// B4 is near-infrared band and B3 is red band
var NDVI1 = function(image) {
  return image.expression('float(b("B4") - b("B3")) / (b("B4") + b("B3"))');
var NDVI = collection.map(NDVI1)
Map.addLayer(NDVI, {}, 'ndvi')

this is the code link: https://code.earthengine.google.com/202776c3d784fed6c7a04947f6b769f6

1 Answer 1


You can mask those values first, and then use your expression to calculate the NDVI:

var NDVI_maskedVals = function(image) {
  var B3_B4_masked = image.select(['B3', 'B4'])
                          .updateMask(image.select(['B3', 'B4']).gt(0))
                          .updateMask(image.select(['B3', 'B4']).lt(10000)) 
  return image.addBands(
               B3_B4_masked.expression('float(b("B4") - b("B3")) / (b("B4") + b("B3"))')

Or use the normalizedDifference function, which automatically forces negatives values to zero:

var NDVI_normDiff = function(image) {
  return image.addBands(image.normalizedDifference(['B4','B3']).rename('NDVI_normDiff'));

link code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.