0

I am new to GEE. I am trying to export a large land cover classification map on GEE, derived using Landsat 5 data through random forest classification. The classified map has 7 classes represented with 7 colours. When I exported the map, I got a grey colour. I also tried to export the image using RGB colour composite, but the RGB composite does not reflect the 7 colours.

How can I export the classified image with 7 colours?

The link to the code is provided in the following code: https://code.earthengine.google.com/c280f727767fa9cd4ed3a3bf7051dcd0.

The code is provided below.

function maskL457sr_1993(image) {
// Bit 0 - Fill
// Bit 1 - Dilated Cloud
// Bit 2 - Unused
// Bit 3 - Cloud
// Bit 4 - Cloud Shadow
// Bit 5 - Snow
// Removing cloud contamination
    var qaMask = 
     image.select('QA_PIXEL').bitwiseAnd(parseInt('111111', 
     2)).eq(0);
     var saturationMask = image.select('QA_RADSAT').eq(0);

     // Apply the scaling factors to the appropriate bands.
     var opticalBands = 
     image.select('SR_B.').multiply(0.0000275).add(-0.2);
     var thermalBand = 
    image.select('ST_B6').multiply(0.00341802).add(149.0);

    // Replace the original bands with the scaled ones and apply 
    the masks.
    return image.addBands(opticalBands, null, true)
        .addBands(thermalBand, null, true)
        .updateMask(qaMask)
        .updateMask(saturationMask);
}

//Adding Spectral Indices
// This function maps spectral indices for Ontario LULC Mapping using Landsat 5 Imagery

  var addIndicesL5 = function(img) {
      // NDVI
      var ndvi = 
      img.normalizedDifference(['SR_B4','SR_B3']).rename('NDVI');
      // NDMI (Normalized Difference Mangrove Index - Shi et al 
     2016 - New spectral metrics for mangrove forest 
     identification)
     var ndmi = 
     img.normalizedDifference(['SR_B4','SR_B5']).rename('NDMI');
     // MNDWI (Modified Normalized Difference Water Index - Hanqiu 
     Xu, 2006)
     var mndwi = 
     img.normalizedDifference(['SR_B2','SR_B5']).rename('MNDWI');
     // SR (Simple Ratio)
     var sr = 
     img.select('SR_B3').divide(img.select('SR_B4')).rename('SR');
     // Band Ratio 54
     var ratio54 = 
     img.select('SR_B5').divide(img.select('SR_B4')).rename('R54');
     // Band Ratio 35
    var ratio35 = 
    img.select('SR_B3').divide(img.select('SR_B5')).rename('R35');
    // GCVI
    var gcvi = img.expression('(NIR/GREEN)-1',{
        'NIR':img.select('SR_B4'),
        'GREEN':img.select('SR_B2')
    }).rename('GCVI');
    return img
        .addBands(ndvi)
        .addBands(ndmi)
        .addBands(mndwi)
        .addBands(sr)
        .addBands(ratio54)
        .addBands(ratio35)
        .addBands(gcvi);
};



// Landsat 5 1993 dataset
// Map the function over one year of data.
var collection_1993 = ee.ImageCollection('LANDSAT/LT05/C02/T1_L2')
                   .filterBounds(ROI)
                   .filterDate('1993-01-01', '1993-12-31')
                   .map(maskL457sr_1993)
                   .map(addIndicesL5);
                   

var image_1993 = collection_1993.median();

// Display the results.
var vis_params_1993 = {
bands: ['SR_B3', 'SR_B2', 'SR_B1'],
min: 0.0,
max: 0.3,
gamma: 1.3,
};

Map.centerObject(ROI);
Map.addLayer(image_1993.clip(ROI), vis_params_1993, 'landcover_1993');

print('Image Projection:',image_1993.projection())

var training_1993 = waterbody.merge(barrenland).merge(wetlands).merge(vegetation).merge(agric_croplands).merge(builtup).merge(forest)
// print(training_1993);

var label_1993 = 'class'
var bands_1993 = ['SR_B1','SR_B2','SR_B3','SR_B4','SR_B5','SR_B7']
var input_image_1993 = image_1993.select(bands_1993);

var train_image_1993 = input_image_1993.sampleRegions({
collection: training_1993,
properties: [label_1993],
scale: 30,
geometries: false // We don't need the geometries here
});
// 6. Split the data into training and test sets
var trainingData_1993 = train_image_1993.randomColumn();
var trainSet_1993 = trainingData_1993.filter(ee.Filter.lessThan('random', 0.8));
var testSet_1993 = trainingData_1993.filter(ee.Filter.greaterThanOrEquals('random', 0.8));

var model_1993 = ee.Classifier.smileRandomForest(50).train(trainSet_1993, label_1993, bands_1993); 


var classified_image_1993 = input_image_1993.classify(model_1993);

// 9. Display and export results 
//  '272fd6', waterbody(0)
//  'a29b9a', barrenland(1)
//  '84d9ff', wetlands (2)
//  '16f62e', vegetation (3)
//  'e8ff0b', agric_cropland(4)
//  'ff0f3e', built-up(5)
//  '12710a', forest(6)

var visualization_params = {
  'min': 0,
  'max': 6,
  'palette': ['272fd6', 'a29b9a', '84d9ff', '16f62e', 'e8ff0b', 'ff0f3e', 
  '12710a']}
// Note: min 0 and max 6 represents the number of land cover classes, i.e 7 classes


var ON_classified_1993 = classified_image_1993.clip(ROI) 
Map.addLayer(ON_classified_1993, visualization_params,'LULC_1993')

// Show legend
var class_names = ['Waterbody', 'Barrelands', 'Wetlands', 
                  'Vegetation', 'Agric_croplands','Built-up', 'Forest'];
var palette = ['272fd6', 'a29b9a', '84d9ff', '16f62e', 'e8ff0b', 'ff0f3e', 
  '12710a'];

var legend = ui.Panel({
style: {
  position: 'bottom-left',
  padding: '8px 15px'
}
});

var legendTitle = ui.Label({
value: 'Land Cover',
style: {
  fontWeight: 'bold',
  fontSize: '18px',
  margin: '0 0 4px 0',
  padding: '0'
  }
});
legend.add(legendTitle);

var makeRow = function(color, class_names) {
    var colorBox = ui.Label({
      style: {
        backgroundColor: '#' + color,
        // Use padding to give the box height and width.
        padding: '8px',
        margin: '0 0 4px 0'
      }
    });
    
    var description = ui.Label({
      value: class_names,
      style: {margin: '0 0 4px 6px'}
    });
    
    // return the panel
    return ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    });
};

for (var i = 0; i < 7; i++) {
legend.add(makeRow(palette[i], class_names[i]));
}  
Map.add(legend);  

// Get information about the trained classifier.
print('Results of trained classifier', model_1993.explain());

// Get a confusion matrix and overall accuracy for the training sample.
var trainAccuracy_1993 = model_1993.confusionMatrix();
print('Training error matrix', trainAccuracy_1993);
print('Training overall accuracy', model_1993.confusionMatrix().accuracy());

// Get a confusion matrix and overall accuracy for the validation sample.
var validationSet_1993 = testSet_1993.classify(model_1993);
var testMatrix_1993 = validationSet_1993.errorMatrix(label_1993, 'classification');
print('Validation error matrix', testMatrix_1993);
print('Validation accuracy', testMatrix_1993.accuracy());

// Calculate consumer's accuracy, also known as user's accuracy or
// specificity and the complement of commission error (1 − commission error).
print("Consumer's accuracy", testMatrix_1993.consumersAccuracy());

// Calculate producer's accuracy, also known as sensitivity and the
// compliment of omission error (1 − omission error).
print("Producer's accuracy", testMatrix_1993.producersAccuracy());

// Calculate kappa statistic.
print('Kappa statistic', testMatrix_1993.kappa());


// Calculating area of ROI
var OntarioArea = ROI.geometry().area()
var OntarioArea_Ha = ee.Number(OntarioArea).divide(1e4).round()
print('Ontario Area in Hectare:',OntarioArea_Ha)

// Calculating area of each land cover class
var all_classArea_1993 = ee.Image.pixelArea().addBands(ON_classified_1993)
                   .reduceRegion({
                    reducer: ee.Reducer.sum().group({
                      groupField:1, groupName: 'class'}),
                    geometry: ROI,
                    scale: 30,
                    bestEffort: true,
                   });

print('Area of each landcover class in Hectare:', all_classArea_1993)

var classAreas_1993 = ee.List(all_classArea_1993.get('groups'))

var classAreaLists_1993 = classAreas_1993.map(function(item) {
var areaDict_1993 = ee.Dictionary(item)
var classNumber_1993 = ee.Number(areaDict_1993.get('class')).format()
var area_1993 = ee.Number(
  areaDict_1993.get('sum')).divide(1e4).round()
return ee.List([classNumber_1993, area_1993])
});

var result_1993 = ee.Dictionary(classAreaLists_1993.flatten())
print(result_1993)


var exportRegion = ROI.geometry().bounds()
// 12. Export the image, specifying the CRS, transform, and region.
Export.image.toDrive({
  image: ON_classified.visualize(visualization_params),
  description: 'LULC_1993_map',
  folder: 'LULC_project',  
  region: exportRegion, 
  scale: 100,
  maxPixels: 1e13,
  crs: 'EPSG:4326',
  formatOptions: {
  cloudOptimized: true
}
  }); 

1 Answer 1

0

It is impossible to get the classified map with color palette in google earth engine. You can define color palette in the desktop software such as ArcGIS or QGIS etc. Accordingly, first download your map and then visualize it in ArcGIS or QGIS with legend and etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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