100% found this document useful (1 vote)
184 views47 pages

Introduction To Google Earth Engine (GEE) - CENG688

The document provides an overview of Google Earth Engine (GEE), a cloud-based platform for geospatial processing that allows users to analyze environmental data and monitor land use changes. It details the platform's extensive data catalog, computation engine, and interactive development capabilities, as well as various data types and geospatial processing functions available for users. Additionally, it includes instructions for uploading shapefiles, filtering datasets, and creating composite images using Landsat and Sentinel-2 data.

Uploaded by

fadi.shamtia21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
184 views47 pages

Introduction To Google Earth Engine (GEE) - CENG688

The document provides an overview of Google Earth Engine (GEE), a cloud-based platform for geospatial processing that allows users to analyze environmental data and monitor land use changes. It details the platform's extensive data catalog, computation engine, and interactive development capabilities, as well as various data types and geospatial processing functions available for users. Additionally, it includes instructions for uploading shapefiles, filtering datasets, and creating composite images using Landsat and Sentinel-2 data.

Uploaded by

fadi.shamtia21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

CENG688

Wireless Sensor Networks

Introduction to Google Earth Engine (GEE)

Ghaleb Faour & Zaher Merhi & Ahmad Kobeissi


Google Earth Engine
• It is a cloud-based geospatial processing platform for
monitoring land use change, mapping natural resources and
executing environmental data analysis
• GEE was launched in 2010 by Google as a proprietary system.
Currently, it is available to users as a free service for small and
medium workloads
• Three aspects of Earth Engine make it quite powerful as a
geospatial processing tool :
▫ extensive public data catalog
▫ processing power of the computation engine
▫ interactive development platforms.
Earth Engine data library
• This GEE platform provides a data catalog that stores a large repository of
geospatial data, including optical and radar imagery of a variety of
satellites, environmental variables, weather, and climate forecasts, land
cover, socioeconomic and topographic datasets.

• 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

• then the data is stored in


clusters.

• After all the calculation is


done on these clusters it
merges the grid that was
divided
Interactive Development Platforms
• Earth Engine’s geospatial processing algorithms and API interface enables
interactive algorithm development

• Basic spatial analysis operations and more advanced algorithms such as


image classification and time series analysis could be executed

• Results can be reported as charts, maps, tables, or image exports

• Google Earth Engine algorithms and user-submitted sample scripts – are


constantly being added, enhanced, and updated
Application Program Interface (code editor)

• GEE relies on scripts


programing code that
gives the platform its
instruction.
• The interface is made up
of the following
windows and controls

GEE uses four object types to represent data


that can be manipulated by its API
Data Types
Image :
• ee.Image
• An image composed of one or many bands
• Properties: name, data type, scale, mask and projection
• E.g.: a single Landsat scene, a single land cover raster
var l7scene = ee.Image('LANDSAT/LE07/C01/T1_RT/LE07_001004_20000610');

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

String Date Number


// Use single (or double) quotes // Store a number in a variable.
var date = ee.Date('2015-12-31'); var getnumber = 45;
// to make a string.
var getstring = ‘NDVI’; var getnumber = ee.Number(45);
var getstring=ee.String(‘NDVI); print(getnumber);
print(getstring);

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

Over 1000 data types and operators and growing


Operations on image collections
// Select collection of images
var dataset = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR’);
// Filter by Date (Temporal Filtering)
var dataset2020 = dataset.filterDate(‘2020-01-01’,’2020-12-31’);
// Filter by Location (Spatial Filtering)
var tunisia2020 = dataset2020.filterBounds(location);
// Filter by Properties (Attribute Filtering)
var tunisiaNC= tunisia2020.filter(ee.Filter.eq('CLOUD_COVER’, 0));
// Sorting image collection by cloud percentage.
var scene = tunisia2020.sort(‘CLOUD_COVER’).first ();
//Mosaic and Clip Image by study area
var study = TunisiaNC.mosaic().clip(location)
Image Properties
// Display all metadata.
print('All metadata:', image); // Get a list of all metadata properties.
var properties = image.propertyNames();
// Get information about the bands as a list. print('Metadata properties:', properties);
var bandNames = image.bandNames(); // ee.List of metadata properties
print('Band names:', bandNames); // ee.List of band
names
// Get a specific metadata property.
// Get projection information from band 1. var cloudiness = image.get('CLOUD_COVER');
var b1proj = image.select('B1').projection(); print('CLOUD_COVER:', cloudiness);
print('Band 1 projection:', b1proj); // ee.Projection // ee.Number
object

// 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

var result = functionName(input);


Example : Calculating all NDVI in 2020 using Map function
var l8_Collection = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR")
.filterDate("2020-01-01", "2020-12-30")
.filterBounds(studyArea).
filter(ee.Filter.lte('CLOUD_COVER', 25));

//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 buffer around a geometry


var buffGeo = geometry.buffer(radius, maxError);

Creating a feature from an existing feature, renaming a property


var country = worldcountries.filter('country_na', 'Tunisia’);

// (By default, all units in Earth Engine are in meters)


Common operations on Raster image
• Selecting the bands of an image
var band = image.select(bandName);

• Creating masks
var mask = image.eq(value);
or .neq or .gt or .gte or .lt or .lte

• Applying image masks


var masked = image.updateMask(mask);

• Performing pixelwise calculations


var results = image.add(value);
or .subtract , .multiply , .divide , .max , .min , .abs , .round , .floor , .ceil , .sqrt , .exp, .log, .log10, .sin , .cos , .tan ,
.sinh , .cosh , .tanh , .acos, .asin
Reducers
Reducers are objects in Earth Engine for data aggregation. They can be used for aggregating
across time, space, bands, properties, etc.
• Basic statistical indices :
- like ee.Reducer.mean(), ee.Reducer.stdDev(), ee.Reducer.max(), …
• Standard measures of covariance :
- like ee.Reducer.linearFit(), ee.Reducer.spearmansCorrelation(),
ee.Reducer.spearmansCorrelation(), …
Descriptors of variable distributions :
- ee.Reducer.skew(), ee.Reducer.frequencyHistogram(), ee.Reducer.kurtosis(), ….

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.

2. Click new and table upload

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);

To upload a Shapefile click the button


Assets/New, then select Shape files under
the Table Upload section. An upload
dialog will be presented. Click the SELECT
button and navigate to a Shapefile or Zip
archive containing a Shapefile on your
local file system.
Defining Study Area in GEE (Data Catalog)
• Importing administrative boundaries
from Data Catalog
var worldcountries = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017');
▫ We can obtain the boundaries of the
var filterCountry = ee.Filter.eq('country_na', 'Tunisia');
world countries from the Large Scale
var country = worldcountries.filter(filterCountry);
International Boundary (LSIB) dataset
Map.addLayer(country);
which has collection ID
Map.centerObject(country, 6);
"USDOS/LSIB_SIMPLE/2017".

▫ The FeatureCollection worldcountries


has a field called country_na with the
names of the countries and we can
use ee.Filter.eq() to select the
boundaries of Tunisia.
Landsat 8 - Bands
Loading Landsat Images
• Load USGS Landsat 8 Surface Reflectance Tier 1 product in GEE. This
dataset is the atmospherically corrected surface reflectance from the
Landsat 8 OLI/TIRS sensors.
var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR');
• Filter by Date :
var startDate = '2021-01-01';
var endDate = '2021-12-31';
var l8date = l8. filterDate(startDate,endDate);
Filter by location : Area of interest (Zaghouan, var wilaya). We will use the
filterBounds function.
var l8Filt = l8date.filterBounds(wilaya);
Extraction of Landsat False Color Composite Image

With your filtered collection, create a


composite using a median reducer. We will use
the median() function for ee.ImageCollection
and the clip() function to clip the composite to
the area of interest.

var composite = l8Filt.median().clip(wilaya);


Map.addLayer(composite,{bands:['B5','B4','B3'],min:300,max:5000}, 'L8 Composite 2021');
False Color Composite Image : Zaghouan
Extraction of Landsat True Color Composite Image
• It incorporates new
spectral bands in the red-
edge region, these are
particularly suitable for
deriving estimates of
canopy chlorophyll, green
leaf area index (LAI)and
nitrogen (N) content
• Coastal Aerosol band can
be used to express certain
spectral signatures of
underwater life such as
algae.
• Water vapor band is one
of the main parameters for
atmospheric correction of
Sentinel-2 imagery
Loading Sentinel-2 image in GEE
Imports the Sentinel-2 collection ("COPERNICUS/S2") from the data catalog of GEE engine.
Select three bands to reduce time processing. Then create the composite image of Jabal Al
Akhdar in Lybia using the reducer Median. At the end display the image on the Map Window.

// 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 0 0 1 900 900 900 900


0 1 1 0
0 1 1 0 900 900 900 900
1 1 0 0
900 900 900 900
Pixel_area
900 900 900 900
0 0 0 900

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');

var colorized = ndwi2021.max().clip(wilaya);


var colorizedVis = {
min: 0.5,
max: 1.0,
palette: ['00FFFF', '0000FF']
};
Map.centerObject(wilaya, 6);
Map.addLayer(colorized, colorizedVis, 'Colorized');

var water = colorized.gte(0.5).selfMask();


Map.addLayer(water,{palette:('blue')});
var pixel_area = water.multiply(ee.Image.pixelArea());
Area : 22.2 Km2
var area = pixel_area.reduceRegion ({reducer:ee.Reducer.sum(), geometry:wilaya, scale:30})
print(area);
Land Cover Mapping : Image Classification
Step 1 :Loading up the image :
var image =
ee.Image(ee.ImageCollection('LANDSAT/LC08/
C01/T1_SR')
.filterBounds(roi)
.filterDate('2016-05-01', '2016-06-30')
.sort('CLOUD_COVER')
.first());
var image1 = image.clip(roi);
Map.addLayer(image1, {bands: ['B5', 'B4',
'B3'],min:0, max: 3000}, 'True colour image');
Land Cover Mapping : Image Classification
Step 2 : Gathering training data
The first step in classifying our image is to collect some
training data to teach the classifier.
• Go to the 'Geometry Imports' box next to the
geometry drawing tools and click '+ new layer.'
• Each new layer represents one class within the training
data, for example 'urban.'
• Locate points in the new layer for each class and click
to collect them adding points in the geometry layer.
• Collect at least 25 representative points and rename
the 'geometry' as ‘class’.
• Click the cog-wheel icon to configure it, change 'Import
as' from 'Geometry' to 'FeatureCollection'. Use 'Add
property' landcover and set its value to 0. (Subsequent
classes will be 1, 2, 3 etc.) when finished, click 'OK’.
• Repeat for each land cover class in that you wish to
include in your classification
Land Cover Mapping : Script Image Classification
// Merge the training data them into a single // Train the classifier and run the classification
collection, called a Feature Collection var classifier = ee.Classifier.minimumDistance().train({
var classNames = features: training,
urban.merge(water).merge(forest).merge(agri classProperty: 'type',
culture);
inputProperties: bands
});
// Create the training data
var bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
//Run the classification
var training =
var classified = image1.select(bands).classify(classifier);
image1.select(bands).sampleRegions({
collection: classNames,
//Display classification
properties: ['type'],
Map.centerObject(classNames, 11);
scale: 30
Map.addLayer(classified,
});
{min: 1, max: 4, palette: ['red', 'blue', 'green','yellow']},
'classification');

You might also like