0

In the next code there are:

  • Creation of variables such as: Slope, DEM, NDVI magnitude, NDVI average, etc.

  • All those variables merged with two LANDSAT scenes

  • Unsupervised classification with all the variables.

I would like to do a supervised classification using the unsupervised classification as an image classified and MODIS LandCover image as a sample regions.

It is giving me an error when I run the code.

//______________________________________NDVI HARMONIC_________________________________________________________


var coll = ee.ImageCollection("MODIS/006/MOD13Q1")

var merged = ee.ImageCollection(coll.merge("MODIS/006/MYD13Q1"))

var recent = merged.sort('system:time_start')
.filterDate('2000-01-01','2015-02-02');

var scale = recent.map(function(image){
  return image.select('NDVI').multiply(0.0001).set('system:time_start', image.get('system:time_start'));
});

// Set the region of interest to a point.
var roi = ee.Geometry.Point([-121.14, 37.98]);

// The dependent variable we are modeling.
var dependent = 'NDVI';

// The number of cycles per year to model.
var harmonics = 1;

// Make a list of harmonic frequencies to model.
// These also serve as band name suffixes.
var harmonicFrequencies = ee.List.sequence(1, harmonics);

// Function to get a sequence of band names for harmonic terms.
var constructBandNames = function(base, list) {
  return ee.List(list).map(function(i) {
    return ee.String(base).cat(ee.Number(i).int());
  });
};

// Construct lists of names for the harmonic terms.
var cosNames = constructBandNames('cos_', harmonicFrequencies);
var sinNames = constructBandNames('sin_', harmonicFrequencies);

// Independent variables.
var independents = ee.List(['constant', 't'])
  .cat(cosNames).cat(sinNames);


// Function to add a time band.
var addDependents = function(image) {
  // Compute time in fractional years since the epoch.
  var years = image.date().difference('2000-01-01', 'year');
  var timeRadians = ee.Image(years.multiply(2 * Math.PI)).rename('t');
  var constant = ee.Image(1);
  return image.addBands(constant).addBands(timeRadians.float());
};

// Function to compute the specified number of harmonics
// and add them as bands.  Assumes the time band is present.
var addHarmonics = function(freqs) {
  return function(image) {
    // Make an image of frequencies.
    var frequencies = ee.Image.constant(freqs);
    // This band should represent time in radians.
    var time = ee.Image(image).select('t');
    // Get the cosine terms.
    var cosines = time.multiply(frequencies).cos().rename(cosNames);
    // Get the sin terms.
    var sines = time.multiply(frequencies).sin().rename(sinNames);
    return image.addBands(cosines).addBands(sines);
  };
};

// Filter to the area of interest, mask clouds, add variables.
var harmonicLandsat = scale
  .filterBounds(roi)
  .map(addDependents)
  .map(addHarmonics(harmonicFrequencies));

// The output of the regression reduction is a 4x1 array image.
var harmonicTrend = harmonicLandsat
  .select(independents.add(dependent))
  .reduce(ee.Reducer.linearRegression(independents.length(), 1));

// Turn the array image into a multi-band image of coefficients.
var harmonicTrendCoefficients = harmonicTrend.select('coefficients')
  .arrayProject([0])
  .arrayFlatten([independents]);

// Compute fitted values.
var fittedHarmonic = harmonicLandsat.map(function(image) {
  return image.addBands(
    image.select(independents)
      .multiply(harmonicTrendCoefficients)
      .reduce('sum')
      .rename('fitted'));
});


// Pull out the three bands we're going to visualize.
var sin = harmonicTrendCoefficients.select('sin_1');
var cos = harmonicTrendCoefficients.select('cos_1');


// Do some math to turn the first-order Fourier model into
// hue, saturation, and value in the range[0,1].
var magnitude = cos.hypot(sin).multiply(5);
var phase = sin.atan2(cos).unitScale(-Math.PI, Math.PI);
var val = harmonicLandsat.select('NDVI').reduce('mean');

// Turn the HSV data into an RGB image and add it to the map.
var seasonality = ee.Image.cat(phase, magnitude, val).hsvToRgb();


// Normalize the image and add it to the map.
var rescaled = magnitude.unitScale(0,1);
var visParams = {min: -1, max: 1};


var reprojected_magn = magnitude
    .unitScale(0, 1)
    .reproject('EPSG:4326', null, 250);

// Normalize the image and add it to the map.
var rescaled = val.unitScale(0,1);
var visParams = {min: -1, max: 1};

var reprojected_val = val
    .unitScale(0, 1)
    .reproject('EPSG:4326', null, 250);

// __________________________________________________________________________________________________________
var l8_may = ee.ImageCollection('LANDSAT/LC08/C01/T1')
.filterBounds(geometry);
var composite = ee.Algorithms.Landsat.simpleComposite({
  collection: l8_may.filterDate('2015-05-01', '2015-05-28'),
  asFloat: true
});

var rename = composite.select('B1','B2','B3','B4','B5','B6','B7').rename('B10','B11','B12','B13','B14','B15','B16')

// Load single Landsat 8 scene
// Note that the input to simpleComposite is raw data.
var l8_oct = ee.ImageCollection('LANDSAT/LC08/C01/T1')
.filterBounds(geometry);
var composite1 = ee.Algorithms.Landsat.simpleComposite({
  collection: l8_oct.filterDate('2015-10-01', '2015-10-28'),
  asFloat: true
});



var MDE = ee.Image('USGS/SRTMGL1_003')

var slope = ee.Terrain.slope(MDE);

var demed_image = composite.addBands(MDE.select('elevation'));


var demed_slope = demed_image.addBands(slope.select('slope'))


var composite_scenes = demed_slope.addBands(composite1).addBands(reprojected_magn).addBands(reprojected_val)


// use the bounding box of a Landsat-8 image
var region = demed_slope.geometry()


// training region is the full image
var training = demed_slope.sample({
  region: geometry,
  scale: 30,
  numPixels: 5000
});

// train cluster on image
var clusterer = ee.Clusterer.wekaKMeans(200).train(training);

// cluster the complete image
var result = demed_slope.cluster(clusterer);

// Display the clusters with random colors.
Map.addLayer(result.randomVisualizer().clip(geometry), {}, 'clusters');

var input = result.byte()


// Export the image, specifying scale and region.
Export.image.toDrive({
  image: input,
  description: 'ISO_unsupervised_class_200',
  scale: 30,
  maxPixels: 1e9,
  region: geometry
});



//___________________________supervised_class____________________________________________________________________

// Define a region of interest as a point.  Change the coordinates
// to get a classification of any place where there is imagery.
var roi = geometry;

// Sample the input imagery to get a FeatureCollection of training data.
var training = input.addBands(modis).sample({
  numPixels: 5000,
  seed: 0
});

// Make a Random Forest classifier and train it.
var classifier = ee.Classifier.randomForest(10)
    .train(training, 'Land_Cover_Type_1');

// Classify the input imagery.
var classified = input.classify(classifier);

// Get a confusion matrix representing resubstitution accuracy.
var trainAccuracy = classifier.confusionMatrix();
print('Resubstitution error matrix: ', trainAccuracy);
print('Training overall accuracy: ', trainAccuracy.accuracy());

// Use MODIS land cover, IGBP classification, for training.
var modis = ee.Image('MODIS/051/MCD12Q1/2013_01_01')
    .select('Land_Cover_Type_1');

// Sample the input with a different random seed to get validation data.
var validation = input.addBands(modis).sample({
  numPixels: 5000,
  seed: 1
  // Filter the result to get rid of any null pixels.
}).filter(ee.Filter.neq('B1', null));

// Classify the validation data.
var validated = validation.classify(classifier);

// Get a confusion matrix representing expected accuracy.
var testAccuracy = validated.errorMatrix('Land_Cover_Type_1', 'classification');
print('Validation error matrix: ', testAccuracy);
print('Validation overall accuracy: ', testAccuracy.accuracy());

// Define a palette for the IGBP classification.
var igbpPalette = [
  'aec3d4', // water
  '152106', '225129', '369b47', '30eb5b', '387242', // forest
  '6a2325', 'c3aa69', 'b76031', 'd9903d', '91af40',  // shrub, grass
  '111149', // wetlands
  'cdb33b', // croplands
  'cc0013', // urban
  '33280d', // crop mosaic
  'd7cdcc', // snow and ice
  'f7e084', // barren
  '6f6f6f'  // tundra
];

// Display the input and the classification.
Map.centerObject(roi, 10);
Map.addLayer(input, {bands: ['B3', 'B2', 'B1'], max: 0.4}, 'landsat');
Map.addLayer(classified, {palette: igbpPalette, min: 0, max: 17}, 'classification');
  • 2
    Please include the error message. – Kersten Jul 6 '18 at 10:53
  • as it is, the error comes from var training = input.addBands(modis) because var modis is not defined at that point, but afterwards – Rodrigo E. Principe Jul 8 '18 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.