Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

// Lab: Unsupervised Classification (Clustering)

// Create region
var region = ee.Geometry.Rectangle(31.56, -26.24, 31.78, -26.09);
Map.addLayer(region, {}, "Region");
Map.centerObject(region, 10);

/*******************************************
Proccess Landsat 8 data
/*******************************************/
// Function to mask clouds based on the pixel_qa band of Landsat 8 SR data.
function maskL8sr(image) {
// Bits 3 and 5 are cloud shadow and cloud, respectively.
var cloudShadowBitMask = (1 << 3);
var cloudsBitMask = (1 << 5);
// Get the pixel QA band.
var qa = image.select('pixel_qa');
// Both flags should be set to zero, indicating clear conditions.
var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
.and(qa.bitwiseAnd(cloudsBitMask).eq(0));
return image.updateMask(mask);
}

// Load 2016 Landsat 8 annual composites.


var landsat2016 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
.filterDate('2016-01-01', '2016-12-31')
.map(maskL8sr)
.filterBounds(region)
.median();

//Display Landsat data


var visParams = {
bands: ['B4', 'B3', 'B2'],
min: 0,
max: 3000,
gamma: 1.4,
};
Map.centerObject(region, 9);
Map.addLayer(landsat2016, visParams, "Landsat 8 (2016)");

/*******************************************
Run supervised classification (clustering)
/*******************************************/
// Create training dataset.
var training = landsat2016.sample({
region: region,
scale: 30,
numPixels: 5000
});

// Instantiate the clusterer and train it.


var clusterer = ee.Clusterer.wekaKMeans(15).train(training);

// Cluster the input using the trained clusterer.


var result = landsat2016.cluster(clusterer);
print("result", result.getInfo());

// Display the clusters with random colors.


Map.addLayer(result.randomVisualizer(), {}, 'Unsupervised Classification');

You might also like