Adam C
Adam C

Reputation: 334

Google Earth Engine: Flatten a one-band ImageCollection into a multi-band single Image

I want to use supervised classification to classify a pattern that has a clear temporal pattern. For example, identifying stands of deciduous trees in a coniferous forest. NDVI would change overtime in the deciduous stands in a regular pattern that should be easily detectable. I assume there's an easy method to flatten the temporal dataset into a single image so that the bands in that image can be used in a classification algorithm. Maybe using .map(....)?

Here's some code to build the answer from:

var startDate = '2016-05-01';
var endDate = '2016-09-01';

var lng = -122.3424; var lat = 37.9344; //SF
var region = ee.Geometry.Point(lng, lat);

//Image Import
var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
.filterBounds(region)
.filterDate(startDate,endDate);

// NDVI temporal
var ndvi = l8.map(function(image) {
  var ndvi = image.normalizedDifference(['B5', 'B4']).rename("NDVI");
  return ndvi;
  });

Map.addLayer(ndvi,{},"NDVI Temporal"); // 8 images with 1 band

//NDVI FLATTENED??????? I want 1 image with 8 bands. The below code doesn't work...
var ndviFlat = ee.Image().addBands(ndvi.map(function(image){
  var temp = image.select("NDVI");  
  return temp;
  }));

From there, I will pass ndviFlat to .sampleRegions, which only works with Images not ImageCollections:

//Classification Model:
var points = ee.FeatureCollection([trainingPointsPos,trainingPointsNeg]).flatten(); 

var training = ndviFlat.sampleRegions({
  collection: points,
  properties: ['class'],
  scale: 30
});

var trained = ee.Classifier.randomForest(20).train(training, 'class', bands);
classified = regLayers.select(bands).classify(trained);

Upvotes: 0

Views: 2511

Answers (1)

Nicholas Clinton
Nicholas Clinton

Reputation: 893

Here's one way:

var startDate = '2016-05-01';
var endDate = '2016-09-01';

var lng = -122.3424; 
var lat = 37.9344; //SF
var region = ee.Geometry.Point(lng, lat);

//Image Import
var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
  .filterBounds(region)
  .filterDate(startDate, endDate);

var empty = ee.Image();

// NDVI temporal
var ndvi = ee.Image(l8.iterate(function(image, previous) {
  var name = ee.String('NDVI_').cat(image.id());
  var ndvi = image.normalizedDifference(['B5', 'B4']).rename(name);
  return ee.Image(previous).addBands(ndvi);
}, empty));

// Remove the annoying non-band
ndvi = ndvi.select(ndvi.bandNames().remove('constant'));

Map.centerObject(region, 13);
Map.addLayer(ndvi, {}, 'ndvi');

Upvotes: 2

Related Questions