[GIS] Iterate Add Band Google Earth Engine

google-earth-engine

I would like to add a band to each image in an image collection ('median_ndvi' in the linked code). The band should be a sequence of ee.Image() constants from 1 to 12.

https://code.earthengine.google.com/e6f22ac8bc6763aa795a14272c89ce6f

Best Answer

You can make your image collection way more convenient by looping over the years you are interested in. While doing so, you can also add a constant band to each of the images.

// get image composite for years between: 
var startyear = 1983
var endyear   = 2018
// composite of how many years (1 = one composite per year, 2 = one composite every 2 years etc.)
var step = 3

// make image composites
var loopsteps = ee.List.sequence(startyear,endyear,step)
var composites = ee.ImageCollection.fromImages(loopsteps.map(function(x){
  var endYear = ee.Number(x).add(ee.Number(step)).subtract(1);
  var sdate = ee.Date.fromYMD(x,1,1);                // startdate of current loop
  var edate = ee.Date.fromYMD(endYear,12,31);        // enddate of current loop
  var index = loopsteps.indexOf(x).add(1);
  var constant = ee.Image.constant(index);
  var comp = overall_collection.filterDate(sdate,edate).reduce(reducer).addBands(constant)
                                    .set('system:time_start', sdate).set('system:time_end', edate)
                                    .set("system:id", index);
  return comp;
}));

print(composites);

Note that for further calculations you might have to cast the different types of bands to a similar bandtype. Most likely, you will have to cast the constant image to a floating number using

image.select('constant').toFloat();

You can then get only the bands you are interested in using:

var median_ndvi = composites.select(["ndvi_median", "constant"]);
print(median_ndvi);

Link

Related Question