1

I'm new to using Google Earth Engine and I obtained the following code from Medium and tried to update it with the AOI and training data for my specific area. I am trying to classify landcover for an AOI and then export this to csv using CORINE landuse categories

The issue seems to be with the classification as when I run the code it just hangs while the other maps seem to be produced correctly. I've been trying to spot the problem but so far I haven't made any progress.


var train_points = Peat_Bogs
        .merge(Coniferous_Forest) 
        .merge(ContinuousUrban) 
        .merge(DiscontinuousUrban)
        .merge(DumpSites)
        .merge(IndustrialAreas)
        .merge(InlandMarshes)
        .merge(MineralExtraction)
        .merge(MixedForest)
        .merge(MoorsandHeathlands)
        .merge(NaturalGrasslands)
        .merge(RoadandRail)
        .merge(Marine)
        .merge(Waterbody)
        .merge(Sports_Facilities)
        .merge(SaltMarshes)
        .merge(Sparsely_Vegetated_Area)
        .merge(BurntAreas)
        .merge(Traditional_Woodland_Schrub)
        .merge(Pastureland)
        .merge(BroadLeaf_Forest)
        .merge(Beaches_Dunes_and_Sand)
        .merge(Ports_Areas)
        .merge(ConstructionSites)
        .merge(Non_irrigated_arable_land)
        .merge(LandOccupiedbyAgricultural)
        .merge(CoastalLagoons)



var dataset = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA').filter(ee.Filter.date('2011-01-01', '2011-12-31'))
                  .filterBounds(AOI).sort('CLOUD_COVER').first();
                  // Sort by scene cloudiness, ascending.
                  
                  // Get the first (least cloudy) scene.
                 
  

// Compute cloud score.
var cloudScore = ee.Algorithms.Landsat.simpleCloudScore(dataset).select('cloud');


// Mask the input for clouds.  Compute the min of the input mask to mask
// pixels where any band is masked.  Combine that with the cloud mask.
var Training_Image1 = dataset.updateMask(dataset.mask().reduce('min').and(cloudScore.lte(50)));
                  
                  
var img = Training_Image1.clip(AOI);
var trueColorVis = {
  min: 0.0,
  max: 255.0, 
  bands:"B3,B2,B1"
};
Map.centerObject(AOI);
Map.addLayer(img);

var ndvi = img.normalizedDifference(["B4", "B3"]).rename('NDVI')

Map.addLayer(ndvi, {min:-1, max:0.8, palette: ["red", "orange", "yellow", "green"]}, "NDVI")
//Map.addLayer(ndvi.gt([0.03, 0.06, 0.09, 0.12, 0.15,0.18,0.21,0.24,0.27,0.30,0.33,0.35,0.38,0.41,0.44,0.47,0.50,0.53,0.56,0.59,0.62,0.]).reduce('sum'), {min:0, max: 4, palette: ["red", "orange", "yellow", "green", "darkgreen"]}, "NDVI steps")
//Map.addLayer(ndvi.gt().reduce('sum'), {min:0, max: 26, palette: palette}, "NDVI steps")

var ndviGradient = ndvi.gradient().pow(2).reduce('sum').sqrt().rename('NDVI_GRAD')
Map.addLayer(ndviGradient, {min:0, max:0.01}, "NDVI gradient")

// Compute entropy and display.
var square = ee.Kernel.square({radius: 4});


var entropy = img.select('B4').toByte().entropy(square);
Map.addLayer(entropy);

var glcm = img.select('B4').toByte().glcmTexture({size: 4});
print(glcm)
var contrast = glcm.select('B4_contrast');
//Map.addLayer(contrast, {min: 0, max: 1500, palette: ['0000CC', 'CC0000']}, 'contrast');
var asm = glcm.select('B4_asm');
//Map.addLayer(asm, {}, 'asm');


var bands = ['B3', 'B2', 'B1', 'B4'];
var FullImage = img.select(bands).float().divide(255);


// Segmentation -----------------------------------------------------------------------------

var seeds = ee.Algorithms.Image.Segmentation.seedGrid(35);

var snic = ee.Algorithms.Image.Segmentation.SNIC({
  image: FullImage, 
  compactness: 0,
  connectivity: 4,
  neighborhoodSize: 128,
  size: 20,
  seeds: seeds
})



var clusters_snic = snic.select("clusters")

var vectors = clusters_snic.reduceToVectors({
  geometryType: 'polygon',
  reducer: ee.Reducer.countEvery(),
  scale: 30,
  maxPixels: 1e13,
  geometry: AOI,
});


var empty = ee.Image().byte();


var outline = empty.paint({
  featureCollection: vectors,
  color: 1,
  width: 1
});
Map.addLayer(outline, {palette: 'FF0000'}, 'segments');



// Select train polygons from points -------------------------------------------------------

//var FullImage = FullImage.addBands(ndvi).addBands(ndviGradient)
                         //.addBands(glcm.select(['B4_contrast','B4_asm',"B4_corr"]).float())
                         //.addBands(entropy);
                         

var FullImage = FullImage.addBands(ndvi).addBands(ndviGradient);

var train_polys = vectors.map(function(feat){
  feat = ee.Feature(feat);
  var point = feat.geometry();
  


  var mappedPolys = train_points.map(function(poly){
    var cls = poly.get("LC")
    var intersects = poly.intersects(point, ee.ErrorMargin(1));
    var property = ee.String(ee.Algorithms.If(intersects, 'TRUE', 'FALSE'));
    return feat.set('belongsTo',  property).set('LC', cls);
  });
  return mappedPolys;
}).flatten().filter(ee.Filter.neq('belongsTo', 'FALSE'));




//extract features from train polygons --------------------------------------------- 

var train_areas = train_polys
  .reduceToImage({
    properties: ['LC'],
    reducer: ee.Reducer.first()
}).rename('LC').toInt();



// Extract features from image ------------------------------------------------------------------------------------------
var predict_image = vectors
  .reduceToImage({
    properties: ['label'],
    reducer: ee.Reducer.first()
}).rename('id').toInt();


FullImage = FullImage.addBands(predict_image)


var FullImage_mean = FullImage.reduceConnectedComponents({
  reducer: ee.Reducer.mean(),
  labelBand: 'id'
});


var FullImage_std = FullImage.reduceConnectedComponents({
  reducer: ee.Reducer.stdDev(),
  labelBand: 'id'
});



var FullImage_median = FullImage.reduceConnectedComponents({
  reducer: ee.Reducer.median(),
  labelBand: 'id'
});


var FullImage_area = ee.Image.pixelArea().addBands(FullImage.select('id')).reduceConnectedComponents(ee.Reducer.sum(), 'id')
var FullImage_sizes = ee.Image.pixelLonLat().addBands(FullImage.select('id')).reduceConnectedComponents(ee.Reducer.minMax(), 'id')
var FullImage_width = FullImage_sizes.select('longitude_max').subtract(FullImage_sizes.select('longitude_min')).rename('width')
var FullImage_height = FullImage_sizes.select('latitude_max').subtract(FullImage_sizes.select('latitude_min')).rename('height')


// join features in an image

var Pred_bands = ee.Image.cat([
  FullImage_mean,
  FullImage_std,
  FullImage_median,
  FullImage_area,
  FullImage_width,
  FullImage_height
]).float();



var clip_Image = Pred_bands.clip(train_polys)



train_areas = train_areas.addBands(clip_Image)

var predictionBands = Pred_bands.bandNames();


var classifierTraining = train_areas.select(predictionBands).sampleRegions({collection: train_polys, properties: ['LC'], scale: 30 });

var RF = ee.Classifier.randomForest(30).train({features:classifierTraining, classProperty:'LC', inputProperties: predictionBands});


var classified_RF = Pred_bands.select(predictionBands).classify(RF);



//var vis_RF = {min: 0, max: 4,
//palette: [ 'blue' //0
//,'red' //1
//,'orange' //2
//,'green' //3
//,'yellow']//4
//}
//Map.addLayer(classified_RF,vis_RF,"OBIA_RF");

Map.addLayer(classified_RF);

Please see link to code: https://code.earthengine.google.com/?scriptPath=users%2F454262%2FTest%3APixel_Based%2FTest_OBI

4
  • Do you get thrown an error message or does your runtime time-out? If the latter, might need to export the classified image out of the cloud or to your assets (will receive longer runtime). Could not access your script. – korndog Feb 20 at 8:39
  • Thanks! I've added code above. I get an error code saying "Layer 6: Layer error: User memory limit exceeded". I'll try export the output as you suggested – Stephen Feb 20 at 14:42
  • Exporting the image didn't work. I got an error code saying "Error: Image.classify: Classification request exceeds size limit". I'd appreciate any further suggestions? – Stephen Feb 20 at 15:10
  • Unfortunately I don't have an answer, but judging by the error message, you have too many training points or a similar issue. – korndog Feb 20 at 17:45
1

After removing the training points and adding a new, much smaller training dataset the script worked.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.