## // Import boundaries from asset ## var aoi = ee.FeatureCollection('users/juliusadewopo/MzeTargetRegion_alt_dslv2'); ## ## 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); ## } ## ## //general collection ## var l8collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR') ## .filterBounds(aoi) ## .map(maskL8sr) ## ## // Function to add an NDVI band, the dependent variable. ## // More details: https://landsat.usgs.gov/sites/default/files/documents/si_product_guide.pdf ## var addVI = function(image) { ## var ndvi = image.normalizedDifference(['nir', 'red']).rename('NDVI').float(); ## var gndvi = image.normalizedDifference(['nir', 'green']).rename('GNDVI').float(); ## var grvi = image.normalizedDifference(['green', 'red']).rename('GRVI').float(); ## var gbvi = image.normalizedDifference(['blue', 'green']).rename('GBVI').float(); ## var ndmi = image.normalizedDifference(['nir', 'swir1']).rename('NDMI').float(); ## var nbr2 = image.normalizedDifference(['swir1', 'swir2']).rename('NBR2').float(); ## // Compute the EVI using an expression. ## var evi = image.expression( ## '2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', { ## 'NIR': image.select('nir'), ## 'RED': image.select('red'), ## 'BLUE': image.select('blue') ## }).rename('EVI').float(); ## // Compute VI using expressions ## ## var gcvi = image.expression( ## '(NIR/GREEN) - 1', { ## 'NIR': image.select('nir'), ## 'GREEN': image.select('green'), ## }).rename('GCVI').float(); ## ## // Return the masked image, with additional bands for predictors. ## return image ## // Add the response variables last. ## .addBands([ndvi,gndvi, grvi,gbvi,ndmi, nbr2, evi, gcvi]) ## // Retain this metadata property for use in the chart. ## .copyProperties(image, ['system:time_start']); ## }; ## // Which bands to select:L8 ## var bandNumbers = [1,2,3,4,5,6]; ## var bandNames = ee.List(['blue','green','red','nir','swir1','swir2']); ## ## // apply over the image collection ## var l8collection = l8collection.select(bandNumbers, bandNames).map(addVI); ## // Use the combined reducer - here just 25-75th ## var reducersCol = ee.Reducer.percentile({percentiles:[25]}) ## .combine(ee.Reducer.percentile({percentiles:[50]}), null, true) ## .combine(ee.Reducer.percentile({percentiles:[75]}), null, true); ## var getNames = function(base, list) { ## return ee.List(list).map(function(i) { ## return ee.String(base).cat(i); ## }); ## }; ## ## //SEASON 1: ## var startDate = '2016-12-01'; ## var endDate = '2017-3-31'; ## var s1 = l8collection ## .filterDate(startDate, endDate) ## .reduce({ ## reducer: reducersCol ## }); ## ## var s1New = s1.select(s1.bandNames(), ## getNames('season1_', s1.bandNames())); ## ## //season 2: ## var startDate = '2017-04-01'; ## var endDate = '2017-7-31'; ## // Use the combined reducer - here just 25-75th ## var s2 = l8collection ## .filterDate(startDate, endDate) ## .reduce({ ## reducer: reducersCol ## }); ## ## var s2New = s2.select(s2.bandNames(), ## getNames('season2_', s2.bandNames())); ## ## //combine ## var TwoSeason = s1New.addBands(s2New); ## print(TwoSeason); ## var vizParams = {bands: ['nir', 'red', 'green'], min: 0, max: 3000}; ## // to be added ## var samples = crop.merge(water).merge(soil).merge(vegetation); ## //add export ## // name of the bands ## var bands = TwoSeason.bandNames(); ## ## // extract band values from the input image ## var samplevals = TwoSeason.sampleRegions({ ## collection: samples, ## properties: ['landcover'] ## scale: 30 ## }); ## ## // define the random forest classier ## var classifier = ee.Classifier.randomForest({ ## numberOfTrees: 500, ## variablesPerSplit: 8, ## minLeafPopulation: 2, ## seed: 1}); ## ## // Train the classifier ## var trained = classifier.train(samplevals, "landcover", bands); ## ## // Classify the image with the same bands used for training. ## var classified = TwoSeason.select(bands).classify(trained); ## ## // Display the inputs and the results. ## Map.centerObject(samples, 11); ## Map.addLayer(TwoSeason, {bands: ['B4', 'B3', 'B2'], max: 0.4}, 'image'); ## Map.addLayer(classified, ## {min: 0, max: 3, palette: ['red', 'green', 'blue']}, ## 'classification'); ## ## // Export the classification result to Google drive for additional analysis ## ## Export.image.toDrive({ ## image: classified, ## description: "export_landsat_classification", ## fileNamePrefix: 'landsat8_classified', ## folder: 'GEE_export', ## scale: 30, ## region: aoi, ## maxPixels: 1e13 ## }); ## // Step 1: Assign random numbers in preparation for a test/train split ## var seed = 100; ## samples = samples.randomColumn('random', seed); ## ## // Join the landcover & random values with all pixels in each polygon in the training datasets. ## var samplevals = TwoSeaosn.sampleRegions({ ## collection: samples, ## properties: ['landcover', 'random'], ## scale: 30 ## }); ## ## ## //Step 2: Perform a 30/70 test/train split using the random numbers generated in Step 1 to assess model performance. ## ## var training = samplevals.filterMetadata('random', 'less_than', 0.7); ## var testing = samplevals.filterMetadata('random', 'not_less_than', 0.7); ## ## // Step 3: Train the classifier ## ## // define the random forest classier ## var classifier = ee.Classifier.randomForest({ ## numberOfTrees: 500, ## variablesPerSplit: 8, ## minLeafPopulation: 2, ## seed: 1}); ## ## // Train the classifier. ## var trained = classifier.train(training, "cropland", bands); ## ## // Confusion matrix with independent samples ## var validation = testing.classify(trained); ## ## // Generate accuracy metrics ## var errorMatrix = validation.errorMatrix('landcover', 'classification'); ## ## // print results ## ## // Calculate fallowed area by pixel (0 if pixel was not fallowed) ## var areaImageSqM = ee.Image.pixelArea() ## .clip(roi); ## var areaImageSqKm = areaImageSqM.multiply(0.000001); ## var cropArea = cropBinary.multiply(areaImageSqKm); ## // Calculate total fallowed area in square kilometers. ## var totalCroppedArea = cropArea.reduceRegion({reducer: ee.Reducer.sum(), ## geometry: roi, ## scale: 1000}); ## print('Total cropped area, sq km:', totalCroppedArea);