[GIS] Google Earth Engine API: How to select an image from an image collection based on NDVI value

google-earth-enginejavascriptndvisentinel-2

I want to select the image with lowest median NDVI to represent bare ground cover from Sentinel-2 image collection for my region of interest (<5% cloud).

I have a boundary file pre-loaded on Asset called boundary.

I started with:

var start = ee.Date('2017-05-01'); //Dates of interest
var finish = ee.Date('2018-10-31'); 
var sentinel = ee.ImageCollection('COPERNICUS/S2')
.filterBounds(boundary)
.filterDate(start, finish)
.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE', 5)); 
//to get imagery with cloud coverage below 5%

//compute NDVI for each image
var NDVI = sentinel.map(
    function(img) {
        return img.normalizedDifference(['B8','B4'])
              .rename('NDVI');
    });
print(NDVI)

// now compute median for each NDVI image
var Dict = NDVI.map(
  function(img){
   return img.set('NDVI', 
    img.reduceRegion({
     reducer: ee.Reducer.median(),
     geometry: boundary,
     scale: 10})
   );
   }); 
print(Dict);

var best = ee.Image(Dict.sort('NDVI').first()); 
print(best); 

It turns out Image (Error) Collection.first: Cannot compare values '{NDVI=0.254702177047319}' (Type<Dictionary<Object>>) and '{NDVI=0.18543783789000937}' (Type<Dictionary<Object>>).

Ideally, I want it to return the index of that image from the sentinel image collection in response to the lower NDVI median so I can select it automatically.

Best Answer

To compute normalized difference in Google Earth Engine over an ImageCollection you have to map a function over it:

var NDVI = sentinel.map(
    function(img) {
        return img.normalizedDifference(['B8','B4'])
                  .rename('medianNDVI')
    }

// now compute median of the collection
var median_NDVI = NDVI.median()
Related Question