Introduction To Google Earth Engine (GEE) - CENG688
Introduction To Google Earth Engine (GEE) - CENG688
• Before being made available, these data sets are preprocessed and cleaned
• In the data catalog, there is over 40 years of current and historical imagery
and data.
• Users are also able to load in their own data – both imagery and vector
files to use for analysis.
Computation Engine
• The Google earth engine
platform divides the data
into independent grids
Image Collection :
• ee.ImageCollection
• A stack or sequence of images
• E.g. All the Landsat 7 imagery
var l7 = ee.ImageCollection('LANDSAT/LE07/C01/T1_RT');
Data Types
Feature :
• ee.Feature
• A feature composed of a Geometry object and properties
• Features can be created in Earth Engine or uploaded
• E.g. points, lines and polygons, a study area polygon
// Create an ee.Geometry.
var polygon = ee.Geometry.Polygon([[ [-35, -10], [35, -10], [35, 10], [-35, 10], [-35, -10] ]]);
// Create a Feature from the Geometry.
var polyFeature = ee.Feature(polygon, {code: 42, lc: ‘sea'});
Data Types
Feature Collection
• ee.FeatureCollection
• Groups of related Features
• Do not need to have the same geometries or properties to be in a Feature
Collection
• E.g. Relocation points for all animals in a study
var fc = ee.FeatureCollection('TIGER/2016/Roads');
Data Types
List Dictionary
// Use curly brackets {} to make a
// Use square brackets [] to
// dictionary of key:value pairs.
// make a list.
var object = {bands:[‘B1’,’B2’,B3’], min : 10, max: 160};
var listofbands = [‘band1’, ‘band2’,’band3’];
var object = ee.Dictionary({bands:[‘B1’,’B2’,B3’], min :
var listofbands = ee.List([‘band1’, ‘band2’,’band3’]);
10, max: 160});
Geospatial Processing Functions
• Image : band math, clip, convolution, neighborhood, selection
• Image Collection: map, aggregate, filter, mosaic, sort,..
• Feature: buffer, centroid, intersection, union, transform,…
• Feature Collection: aggregate, filter, flatten, merge, sort, …
• Filter : by bounds, within distance, date, day of year, metadata,..
• Reducer: mean, linear regression, percentile, histogram, …
• Join: simple, inner, outer, inverted, …
• Kernel: square, circle, gaussian, sobel, kirsh,…
• Export: to geotiff, to video, to TensorFlow, to map tiles,…
• Machine learning: CART, random forests, bayes, SVM, kmeans, cobweb,…
• Projection: transform, translate, scale
// Get scale (in meters) information from band 1. // Get the timestamp and convert it to a date.
var b1scale = var date = ee.Date(image.get('system:time_start'));
image.select('B1').projection().nominalScale();
print('Timestamp:', date);
print('Band 1 scale:', b1scale); // ee.Number
// ee.Date
Visualization of image : Map.addLayer()
• RGB composites :
// Define the visualization
parameters.
var vizParams = {
bands: ['B5', 'B4', 'B3'],
min: 0,
max: 0.5,
gamma: [0.95, 1.1, 1]
};
Map.addLayer(image,
vizParams, ‘RGB color
composite');
• Color Palette : • Mask :
var ndwiViz = {min: 0.5, You can use image.updateMask() to set
max: 1, palette: ['00FFFF', the opacity of individual pixels based on
'0000FF']}; where pixels in a mask image are non-
Map.addLayer(ndwi, zero.
ndwiViz, ‘NDWI', false); // Mask the non-water parts of the
image, where NDWI < 0.4.
var ndwiMasked =
ndwi.updateMask(ndwi.gte(0.4));
Map.addLayer(ndwiMasked, ndwiViz,
'NDWI masked');
Functions and mapping
A function is a set of instructions to Mapping a function over a collection
perform a specific task: applies the function to every
element in the collection
Var functionName = function (Arguments) {
statements;
}; var result = input.map(functionName);
Calling a function
//For Landsat 8
var addNDVI_8 = function(image) {
var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
return image.addBands(ndvi);
}
var l8_NDVI = l8_Collection.map(addNDVI_8);
Common operations on geometries
Finding the area of a geometry
var geoArea = geometry.area(maxError);
• Creating masks
var mask = image.eq(value);
or .neq or .gt or .gte or .lt or .lte
To get the first (or only) value for a property, use ee.Reducer.first().
Reducers
var l9 = ee.ImageCollection("LANDSAT/LC09/C02/T1_TOA");
var img = l9.filterDate('2022-01-01','2022-03-01').filterBounds(study);
var outputImage = img.reduce(ee.Reducer.median());
Map.addLayer(outputImage, {bands:['B5_median','B4_median','B3_median']});
Defining Study Area in GEE
• Geometry tools :
You can create geometries interactively using the Code Editor Geometry
tools :
Defining Study Area in GEE (Shapefile)
• Uploading a shapefile to google earth engine :
1. In code editor, shapefiles can be uploaded to the assets. In the code editor, on the left side
panel, go to assets.
3. In the popup screen. Make sure you have the correct path for the asset. Click SELECT. Point
to the directory that has your shapefile. Earth Engine takes these extensions to be valid
shapefile.
4. Click OK and let it finish upload the shapefile. You can check the status of the file upload on
the Tasks tab on the right-side panel on the GEE playground. Once it finishes uploading, on the
code editor, locate your assets. It will be the same name that was given while uploading.
5. Click on the import icon. Now on the editor, you will see it as named default. You can
rename it as you want. Use .geometry() function to get the geometry of the uploaded table.
Defining Study Area in GEE (Shapefile)
• Uploading shapefile boundaries level 1 var tunisia = ee.FeatureCollection("projects/ee-
of Tunisia. faourghaleb2022/assets/TUN_adm1");
var filtergov = ee.Filter.eq('NAME_1', 'Zaghouan');
Source :
var wilaya = tunisia.filter(filtergov);
https://data.humdata.org/dataset/cod-
Map.addLayer(wilaya);
ab-tun?
Map.centerObject(wilaya, 6);
// This is the Sentinel-2 collection (all the possible available Sentinel 2 imagery in 2021)
var S2_collection = ee.ImageCollection("COPERNICUS/S2").filterBounds(wilaya).filterDate(startDate,endDate);
// These are the bands that we want to be displayed
var S2_bands = ['B4', 'B3', 'B2'];
// This turns the whole S2 collection into one image, finding the middle value for each pixel
var S2_mosaic = S2_collection.median().select(S2_bands).clip(wilaya);
// This controls how we want the S2 image to be displayed
var S2_display = {bands: S2_bands, min: 0, max: 3000};
// This adds the S2_mosaic to the map, using the S2_display visual parameters, and giving it the name
//"S2_Image"
Map.addLayer(S2_mosaic, S2_display, "S2_Image");
// This automatically pans the map to the middle of our Sentinel-2 image
Map.centerObject(wilaya);
Exporting Image to Google Drive
1. Draw a geometry polygon in Tunis
2. Select the image the least cloudiness, so we have the clearest possible image in 2020.
Var S2 = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(wilay)
.filterDate('2020-01-01', '2020-12-31')
.sort('CLOUDY_PIXEL_PERCENTAGE')
.first()
3. Export the image, specifying the name, spatial resolution, and region.
Export.image.toDrive({
image: S2,
description: 'imageToDriveExample_transform',
scale: 20,
region: wilaya
});
4. When this code is run, an export task will be created in the Code Editor Tasks tab. Click the Run button next to
the task to start it.
Image Transformation: Mapping Vegetation Density
//Define a point of interest. Use the User Interface Drawing Tools to import a point geometry and
name it “location”:
var location = ee.Geometry.Point([20.595753972611735, 32.33333835205989]);
//Import the Landsat 8 TOA image collection:
var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA');
//Get the least cloudy image in 2020:
var image = ee.Image(l8.filterBounds(location) .filterDate('2015-01-01', '2015-12-31')
.sort('CLOUD_COVER').first() );
// Compute the Normalized Difference Vegetation Index (NDVI).
var nir = image.select('B5');
var red = image.select('B4');
var ndvi = nir.subtract(red).divide(nir.add(red)).rename('NDVI');
//Display the result:
Map.centerObject(image, 9);
var ndviParams = {min: -1, max: 1, palette: ['blue', 'white', 'green']};
Map.addLayer(ndvi, ndviParams, 'NDVI image');
Change Detection: Mapping Vegetation Change
//Import the Landsat 8 TOA image collection: //Get composite image in spring 2021
var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA');
var image2021 = l8.filterBounds(wilaya) .filterDate('2021-03-21', '2021-06-
//Get composite image in spring 2014 21').median();
var l8filt = l8.filterBounds(wilaya).filterDate('2014-03-21', var image2021c = image2021.clip(wilaya);
'2014-06-21').median();
var spring2014 = l8filt.clip(wilaya); // Compute the Normalized Difference Vegetation Index (NDVI) spring
//2021
// Compute the Normalized Difference Vegetation Index var ndvi2021 = image2021c.normalizedDifference(['B5', 'B4']);
//(NDVI).
var nir = spring2014.select('B5'); //Display the result:
var red = spring2014.select('B4'); Map.addLayer(ndvi2021, ndviParams, 'NDVI image Spring 2021');
var ndvi2014 =
nir.subtract(red).divide(nir.add(red)).rename('NDVI 2013'); // Vegetation Change Between 2014 and 2021
var ndviParams1 = {min: -0.2, max: 0.2, palette: ['red','yellow', 'cyan',
//Display the result: 'green']};
var ndviParams = {min: -0.4, max: 0.6, palette: var ndvidiff = ndvi2021.subtract(ndvi2014);
['blue','white','green']}; Map.addLayer(ndvidiff, ndviParams1, 'NDVI Change Detection');
Map.addLayer(ndvi2014, ndviParams, 'NDVI image Spring
2014');
NDVI Spring 2014 NDVI Spring 2021 Vegetation Change
Degraded Vegetation Cover
• Criteria Ndvi2014 > 0.2 And Intensity of Change decrease 50% :
// Pixel is vegetation if NDVI is greater than 0.2
var ndvip = ndvidiff.divide(ndvi2014);
var threshold = 0.2;
var changes = ndvi2014.gte(threshold).and(ndvip.lte(-50)).selfMask();
Map.addLayer(changes,{palette:['red']},'mask');
var pixel_area = changes.multiply(ee.Image.pixelArea());
var area = pixel_area.reduceRegion ({reducer:ee.Reducer.sum(),
geometry:wilaya, scale:30})
print(area); Degraded Vegetation Area : 81.6 km2
Changes ee.Image.pixelArea
0 900 900 0
var area = pixel_area.reduceRegion
({reducer:ee.Reducer.sum(), geometry:wilaya, scale:30})
0 900 900 0
0+0+0+900+0+900+900+0+0+900+900+0+900+900+0+0 =
900 900 0 0
6300
Improved Vegetation Cover
• Criteria Ndvi2021 > 0.2 And Intensity of Change increase 50% :
// Pixel is vegetation if ndvi is greater than 0.2
var ndvip = ndvidiff.multiply(100).divide(ndvi2014);
var threshold = 0.2;
var changes =
ndvi2021.gte(threshold).and(ndvip.gte(50)).selfMask().rename('ChangeAream2
');
Map.addLayer(changes,{palette:['green']},'mask');
var pixel_area = changes.multiply(ee.Image.pixelArea());
var area = pixel_area.reduceRegion ({reducer:ee.Reducer.sum(),
geometry:wilaya, scale:30})
print(area);
Improved Vegetation Area : 120 km2
Mapping Surface Water Using MS satellite images
Mapping Water Surface in Zaghouan
var ndwi2021 = ee.ImageCollection('LANDSAT/LC08/C01/T1_ANNUAL_NDWI')
.filterBounds(wilaya)
.filterDate('2021-01-01', '2021-12-31')
.select('NDWI');