This project uses Google Earth Engine to perform land cover classification on Sentinel-2 imagery for the year 2023.
var image = imageCollection.filterDate('2023-01-01', '2023-12-31').filterBounds(ddn).median()
var bands = ['B2', 'B3', 'B4', 'B8'] var image = image.select(bands).addBands(image.normalizedDifference(['B8', 'B4']).rename('NDVI'))
The code selects specific bands (B2, B3, B4, and B8) and adds the Normalized Difference Vegetation Index (NDVI) as an additional band.
var displayparameters = { min: 1000, max: 4500, bands: ['B8', 'B4', 'B3'] } Map.addLayer(image, displayparameters, "Image")
var label = "Class" var training = Water.merge(Forest).merge(Urban)
The script combines different land cover classes (Water, Forest, Urban) into a single training dataset and assigns them a label "Class".
var trainingimage = image.sampleRegions({ collection: training, properties: [label], scale: 10 })
Features are extracted from the image for each training region. The sampling is done at a 10-meter scale.
var traingData = trainingimage.randomColumn() var trainSet = traingData.filter(ee.Filter.lessThan('random',0.8')) var testSet = traingData.filter(ee.Filter.greaterThanOrEquals('random',0.8'))
var classifier = ee.Classifier.smileRandomForest({numberOfTrees:100, variablesPerSplit: 2, minLeafPopulation: 1, bagFraction: 0.5, seed: 0}) var classifier = ee.Classifier.smileRandomForest(100).train(trainSet, label, bands)
The script trains a Random Forest classifier using the training set. The classifier uses 100 trees and the specified parameters
var classified = image.classify(classifier)
Map.centerObject(ddn, 10) Map.addLayer(classified, {min: 1, max: 3, palette: ['green', 'blue', 'red']}, 'LandCover')
var trainAccuracy = classifier.confusionMatrix() print('Training error matrix', trainAccuracy) print('Training overall accuracy', trainAccuracy.accuracy())
testSet = testSet.classify(classifier) var validationAccuracy = testSet.errorMatrix(label, 'classification') print('Validation error matrix', validationAccuracy) print('Validation accuracy', validationAccuracy.accuracy())
The script evaluates the classifier's performance on the test set and prints the validation confusion matrix and accuracy.
Export.table.toAsset({ collection: training, description: 'LCsample2023', assetId: 'LCsample2023' })