How to stack bands in Google Earth Engine?
Here is an example of creating a stacked image, using the ee.ImageCollection.iterate() method.
I also included code to define to define an example region and image collection, so that it is a working example.
// Define a sample Region-of-Interest
var roi = ee.Geometry.Polygon(
[[[-109.1, 37.0],
[-109.1, 36.9],
[-108.9, 36.9],
[-108.9, 37.0]]]);
// Define an example collection.
var collection = ee.ImageCollection('COPERNICUS/S2')
.filterDate('2016', '2017')
.filterBounds(roi);
print('collection', collection);
print('Number of images in collection:', collection.size());
// Calculate NDVI.
var calculateNDVI = function(scene) {
// get a string representation of the date.
var dateString = ee.Date(scene.get('system:time_start')).format('yyyy-MM-dd');
var ndvi = scene.normalizedDifference(['B8', 'B4']);
return ndvi.rename(dateString);
};
var NDVIcollection = collection.map(calculateNDVI);
var stackCollection = function(collection) {
// Create an initial image.
var first = ee.Image(collection.first()).select([]);
// Write a function that appends a band to an image.
var appendBands = function(image, previous) {
return ee.Image(previous).addBands(image);
};
return ee.Image(collection.iterate(appendBands, first));
};
var stacked = stackCollection(NDVIcollection);
print('stacked image', stacked);
// Display the first band of the stacked image.
Map.addLayer(stacked.select(0).clip(roi), {min:0, max:0.3}, 'stacked');
Note that the new, better way to do this is with imageCollection.toBands()
.