Curso Gee 2019

You might also like

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

Iluminando o Google Earth Engine

Rafael Kayser
Fev/2019
Course content

• Module I: Introduction to Google Earth Engine


• Module II: Introduction to JavaScript and GEE Objects
• Module III: Working with vectorial data
• Module IV: Working with raster data
• Module V: Exporting data
• Module VI: Special topics in GEE
Module I
Introduction to Google Earth Engine
Componentes
• Banco de dados • Super computador
Infraestrutura
computacional da
Coleção de imagens públicas
Google otimizada por
de sensoriamento remoto
computação paralela
na escala de petabytes

• APIs (Application • Editor de código


Programming Interface)

Ambiente de
desenvolvimento on
Ferramenta que realiza a comunicação line
entre o usuário e o servidor da Google
(JavaScript API ou Python API) Introduction to Google Earth Engine
Tipos de API

• Earth Engine JavaScript API


• Web code editor: code.earthengine.google.com

• Earth Engine Python API


• Hospedado na plataforma GitHub
• Necessita de um compilador para linguagem
Python
• Utiliza as funções do GEE

Introduction to Google Earth Engine


The Earth Engine Public Data Catalog

Landsat 4, 5, 7, 8 MODIS Terrain Land Cover Atmospheric


Raw, TOA, SR, ... Daily, NBAR, LST, ... SRTM, GTOPO, NED, ... GlobCover, NLCD, ... NOAA NCEP, OMI, ...

... and many more, updating daily!

> 200 public datasets > 4000 new images every day
> 5 million images > 5 petabytes of data

Introduction to Google Earth Engine


Landsat collection

Landsat 4 Surface Reflectance


Landsat 5 Tier 1 Top-of-atmosphere (TOA) reflectance
Landsat 7 Tier 2 Raw Scenes
Landsat 8 Raw Scenes Real-Time

BAI
EVI 8-day
Derived NDVI 32-day
datasets NBRT annual
NDSI
NDWI
Introduction to Google Earth Engine
MODIS collection

https://developers.google.com/earth-
engine/datasets/catalog/modis Introduction to Google Earth Engine
Digital Elevation Models
• SRTM Version 3 (30m) - NASA / USGS / JPL-Caltech
• SRTM Version 4 (90m) – NASA/CGIAR
• Derived products from SRTM
• ALOS Global 30m
• HydroSHEDS products
• Conditioned DEM 3/15 arc-sec
• Void-Filed DEM 3/15 arc-sec
• Drainage Direction 3/15 arc-sec
• Flow Accumulation 3/15 arc-sec

Netherlands
• High resolution Australia

Introduction to Google Earth Engine


Weather products

GPM v4/v5 – 0.5 hour (2014-03-12 – present)


TRMM 3B42 – 3 hours (1998-01-01 – present)
• Precipitation
TRMM 3B43 – monthly (1998-01-01 – present)
GSMaP (product of GPM)

GLDAS (version 1, 2, 2.1, reprocessed 2)


• Reanalysis products NCEP/NCAR

Introduction to Google Earth Engine


Derived products

https://global-surface-water.appspot.com/
Derived products

https://earthenginepartners.appspot.com/science-2013-global-forest
Derived products

http://mapbiomas.org/
https://developers.google.com/earth-engine/datasets/
Types of platforms
• Code Editor
• code.earthengine.google.com
• Web-based IDE for Earth Engine API

• Explorer
• explorer.earthengine.google.com
• Simple web interface
• It allows anyone to visualize the data in the public data
catalog
• Signed in Earth Engine users can also import data, run
simple analyses, save, and export the results

• Client library
• provide JavaScript and Python wrapper functions for
the Earth Engine API
• Build custom applications and to develop Earth Engine
code locally using a JavaScript or Python interpreter
Explorer

https://explorer.earthengine.google.com
Referência

https://www.sciencedirect.com/science/article/pii/S0034425717302900 Introduction to Google Earth Engine


Running a computation

Introduction to Google Earth Engine


Benefícios e limitações
• Benefícios: • Limitações:
• Indicado para projetos • Melhor adaptado a análises de
que requerem: imagens em relação à dados
• Cobertura de dados para vetoriais
uma grande extensão • Análises baseadas em relações
• Extensa biblioteca de espaciais de pixels são mais
dados difíceis de se completar
(processamento em múltiplas
• Alta velocidade, CPUs)
capacidade de
processamento intensiva • Opções para modelagem
hidrológica são limitadas ou em
fase de pesquisa (?)
Introduction to Google Earth Engine
Module II
Introduction to JavaScript and GEE Objects
Developers guide

https://developers.google.com/earth-engine/
Code editor

Painel de scripts, Debugging,


documentação, resultados,
exemplos, Code Editor
download
upload de de imagens
arquivos

Inserir
Display
geometria

https://code.earthengine.google.com/
Creating a new project
1
2

Repository: folder to
store projects

File: new projects


Strings

// Use single (or double) quotes to make a string.


var testString = 'Hello World!';
// Print the final request.
print(testString);

Importante: Tenga en cuenta que las variables se definen con la


palabra clave var. SIEMPRE!!

Introduction to JavaScript and GEE Objects


Numbers

// Store a number in a variable.


var a = 5;
// Store another number
var b = 2.5;
// Calculates the sum between a and b
var c = a + b;
//Print the final result
print('The answer is:', c);

The type is determined when assigned (like python or R)!

Noções básicas de JavaScript


Numbers: operations and properties
• Basic operators: + - / *
//math operator examples
var rand = Math.random(); // returns a random number
var min = Math.min(0, 150, 30, 20, -8); // returns the minimum
var round1 = Math.round(4.7); // returns the nearest integer
var round2 = Math.round(4.4); // returns the nearest integer
var e = Math.E; // returns Euler's number
var PI = Math.PI; // returns PI
var ln2 = Math.log(2); // returns the natural logarithm of 2

//print the results


print('random number :', rand);
print('minimum :', min);
print('round up: ', round1);
print('round down: ', round2);
print('eulers number: ', e);
print('PI: ', PI);
print('natural log ', ln2);

Noções básicas de JavaScript


Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x (x is in radians)
x
exp(x) Returns the value of E
floor(x) Returns the value of x rounded down to its nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x, y, z, ..., n) Returns the number with the highest value
min(x, y, z, ..., n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

https://www.w3schools.com/jsref/jsref_obj_math.asp
Noções básicas de JavaScript
Lists (arrays)
Define lists with square brackets [ ]. A list of numbers or strings, for example:

// Use square brackets [] to make a list.


var listOfNumbers = [0, 1, 1, 2, 3, 5];
print('List of numbers:', listOfNumbers);

// Make a list of strings.


var listOfStrings = ['a', 'b', 'c', 'd'];
print('List of strings:', listOfStrings);

//Create an empty array


var mayArray = new Array(5);
print('empty array:', mayArray);

Noções básicas de JavaScript


Objects
Objects in JavaScript are dictionaries of key: value pairs. Make an object (or dictionary)
using curly brackets {}, for example:

// Use curly brackets {} to make a dictionary of key:value pairs.


var object = {
foo: 'bar',
baz: 13,
stuff: ['this', 'that', 'the other thing']
};

print('Dictionary:', object);
// Access dictionary items using dot notation.
print('Print foo:', object.foo);

Noções básicas de JavaScript


Functions
• Uma função é definida com a palavra-chave function
• As funções geralmente usam parâmetros que informam à função o que fazer. Esses parâmetros
vão dentro de parênteses().
• O conjunto de instruções que compõem a função vão dentro de chaves{ }
• A palavra-chave return indica qual é a saída da função.

// Function example
var function_hello = function( name ) {
var message = 'Hi ' + name + '! How are you?';
return message;
};

// invoking the function with its parameter.


print( function_hello( 'Fulano' ) );

Noções básicas de JavaScript


Conditionals
var a = 3;
var b = 9;

var ans;

if (a>b){
ans = "a greater than b";
} else if (a<b){
ans = "b greater than a";
} else {
ans = "a equals b";
}

print(ans);

Noções básicas de JavaScript


Loops

var List = [];


for(var i = 0; i < 8; i++) {
List.push(i + 1);
}
print(List);

Noções básicas de JavaScript


Earth Engine Objects

ee.String
ee.Number
ee.List
ee.Dictionary
var name = ee.Object(value) ee.Date
ee.Geometry
ee.Image
ee.ImageCollection
....

Earth Engine Objects


JavaScript Objects vs. GEE Objects

var number = 1; var number = ee.Number(1);

JavaScript object (client-side) Earth Engine object (server-side)

Earth Engine Objects


GEE Objects: Strings

// Define a string, then put it into an EE container.


var aString = 'To the cloud!';
var eeString = ee.String(aString);
print('Where to?', eeString);

Earth Engine Objects


GEE Objects: Methods of an object
var name = ee.Object(value).method ( argument1, argument2, ...)
.add()
.subtract()
.multiply() List of methods:
.divide()
https://developers.google.com/earth-engine/api_docs
.pow()
.log()
ee.Number .log10()
.abs()
.sin()
.eq()
.gt()
.lt()
.max()
.min()
.... Earth Engine Objects
GEE Objects: Numbers
// Define the euler's number.
var e = ee.Number(Math.E);
print('e=', e);

// Define another number


var a = ee.Number(1);
print('a=', a);

// Calculates the sum between two server numbers (wrong way)


var wrong_sum = e + a;
print('wrong sum=', wrong_sum);

// Calculates the sum between two server numbers (right way)


var right_sum = e.add(a);
print('right sum=', right_sum);

Earth Engine Objects


GEE Objects: Lists and casting
// Make a sequence the hard way.
var eeList = ee.List([1, 2, 3, 4, 5]);

// Make a sequence the easy way!


var sequence = ee.List.sequence(1, 5);
print('Sequence:', sequence);

// Use a method on an ee.List to extract a value.


var value = sequence.get(2);
print('Value at index 2:', value);

// Cast the return value of get() to a number.


var sum = ee.Number(value).add(3);
print(sum);
Earth Engine Objects
GEE Objects: Dates
// Define a date in Earth Engine.
var date = ee.Date('2015-12-31');
print('Date:', date);

// Get the current time using the JavaScript Date.now() method.


var now = Date.now();
print('Milliseconds since January 1, 1970', now);

// Initialize an ee.Date object.


var eeNow = ee.Date(now);
print('Now:', eeNow);

// Define a date with arguments


var aDate = ee.Date.fromYMD(2017, 1, 13);
print('Date:', aDate);

Earth Engine Objects


GEE Objects: geographic data structures
• Geometry: ponto, polígono..
• Image: estrutura fundamental de
uma imagem raster (bandas,
metatadata)

• Feature: estrutura vetorial associada


com propriedades aos objetos
• ImageCollection: coleção de imagens
(séries temporais, mosaicos)
• FeatureCollection: coleção de
features (propriedades diferentes)

Earth Engine Objects


GEE Objects: geographic data structures

Image
ImageCollection
var name = ee. Geometry .( value)
Feature
FeatureCollection

Earth Engine Objects


GEE Objects: Other objects

ee.Algorithms()
ee.Array()
ee.Classifier()
ee.Filter()
ee.Join()
ee.Projection()
ee.Reducer()
ee.Terrain()
ee.Kernel()
....

Earth Engine Objects


Module III
Working with vectorial data
Geometry Overview
Simple geometries:
• ee.Geometry.Point
• ee.Geometry.LinearString
• ee.Geometry.LinearRing
• ee.Geometry.Rectangle
• ee.Geometry.Polygon
• ee.Geometry.Rectangle
Multiple geometries:
• ee.Geometry.MultiPoint
• ee.Geometry.MultiLineString
• ee.Geometry.MultiPolygon
Working with vectorial data
Creating a geometry

//create a point geometry


var point = ee.Geometry.Point([-51.113192, -30.076435]);
//display the point on the map
Map.addLayer(point, {},'Point');
//zoom to layer
Map.setCenter(-51.113192, -30.076435, 10);

ee.Geometry.Point is a Earth Engine API call that receives one parameter: ee.List ([])

Working with vectorial data


Geometric Operations
// Create a geodesic polygon.
var polygon = geometry;

// Compute a buffer of the polygon.


var buffer = polygon.buffer(1000);

// Area in km²
print('Area (km²): ', polygon.area().divide(1000 * 1000));

//perimeter in km
print('Perimeter (km): ', polygon.perimeter().divide(1000));

// Compute the centroid of the polygon.


var centroid = polygon.centroid();
Map.addLayer(buffer, {}, 'buffer');
Map.addLayer(centroid, {}, 'centroid');

Working with vectorial data


Feature / FeatureCollection Overview

Feature is an object with a geometry property storing a Geometry object (or null)
and a properties property storing a dictionary of other properties.
// Create an ee.Geometry.
var polygon = ee.Geometry.Polygon([
[[-35, -10], [35, -10], [35, 10], [-35, 10], [-35, -10]]
]);

//crete a dictionary with properties


var dictionary = ee.Dictionary({id: 1, type: 'polygon'});

// Create a Feature from the Geometry.


var polyFeature = ee.Feature(polygon, dictionary);

print(polyFeature);
Map.addLayer(polyFeature, {}, 'feature');
Working with vectorial data
Inserting vectorial data
• Code / map • Assets • Fusion Table

Working with vectorial data


Inserting FeatureCollection from Assets
• Es posible instanciar un FC utilizando tablas que tenemos almacenadas en un Assets.
• Para crear esta nueva tabla podemos utilizar un Shapefile o un .zip que contenga todos los
archivos que componen el Shapefile. El tamaño máximo permitido es 10GB.
• Los pasos para subir un Shapefile son seleccionar desde Assets NEW > Table Upload.

Excluir formato .sbx

Working with vectorial data


Upload/Task Panel

Upload is not instant and may take a few minutes


depending on the congestion of the platform and the size have the file.
You can check the progress from the TASK tab:

Working with vectorial data


Getting the TableID

2 3

Working with vectorial data


Creating a FeatureCollection from Assets
// define a feature collection from assets
var south_america_basins = ee.FeatureCollection('users/rafaelkayser/South_America_Basins');

//print properties on console


print(south_america_basins);

//display on map
Map.addLayer(south_america_basins, {}, 'South America Basins');

Working with vectorial data


Inserting FeatureCollection from Fusion Table
É possível editar tabelas após inserir no GEE! 
A Google vai descontinuar até dezembro 

3. Verificar tabela importada e > Next


1. Google Drive > NOVO > Mais > 2. Escolher arquivo (.csv, .txt ou .kml) e > Finish
Google Fusion Tables indicar caractere de separação

Working with vectorial data


Inserting FeatureCollection from Fusion Table

4. Buscar o Table ID
File > About this table
> Get ID

Working with vectorial data


Feature / FeatureCollection properties

.area() .aggregate()
.buffer() .filter()
.centroid() .filterBounds()
.dissolve() .first()
ee.Feature() .distance() ee.FeatureCollection()
.map()
.perimeter() .merge()
.union() .sort()
... .reducetoImage()
...

https://developers.google.com/earth-engine/api_docs

Working with vectorial data


Filtering a FeatureCollection
// define a feature collection drom assets
var south_america_basins = ee.FeatureCollection('users/rafaelkayser/South_America_Basins');

// filter basins by name


var amazon_basin = south_america_basins.filter(ee.Filter.eq('MAJ_NAME', 'Amazon Basin' ));
var la_plata_basin = south_america_basins.filter(ee.Filter.eq('MAJ_NAME', 'La Plata Basin' ));

//display on map
Map.addLayer(amazon_basin, {color: 'green'}, 'Amazon Basin');
Map.addLayer(la_plata_basin, {color: 'blue'}, 'La Plata Basin');

Working with vectorial data


Mapping over a FeatureCollection
Apply a function to each element of a collection
A "For Each" operation

var function_name = function(feature) { function function_name (feature) {


do something do something
return output; return output;
} }

collection_name.map( function_name)

Working with vectorial data


Mapping over a FeatureCollection
// define a feature collection from assets
var fc_south_america_basins = ee.FeatureCollection('users/rafaelkayser/South_America_Basins');

//select basin by filter


var fc_selected_basin = fc_south_america_basins.filter(ee.Filter.eq('SUB_NAME', 'Taquari' ));

// function to apply buffer method in each featureCollection


var function_buffer = function(feature) {
return feature.buffer(2000); //distance in meters
};

// apply buffer
var fc_selected_basin_buff = fc_selected_basin.map(function_buffer);

//display basin limits


Map.addLayer(fc_selected_basin, {}, 'Taquari Basin');
Map.addLayer(fc_selected_basin_buff, {}, 'Taquari Basin - buffer');

Working with vectorial data


Module IV
Working with raster data
Image vs. ImageCollection

Image ImageCollection

• Image are composed of one or more • An ImageCollection is a stack or time


bands series of images
• Each band has its own name, data type,
scale, mask and projection.
• Examples: SRTM, Landsat, MODIS (one
scene)

Working with raster data


Importing to project

Working with raster data


Importing to project

Working with raster data


Image visualization
Map.addLayer( image, visParams, ‘layer name’ )
Parameter Description Type
bands Comma-delimited list of three band list
var visParams = {
names to be mapped to RGB
bands: ['B5', 'B4', 'B3'],
min Value(s) to map to 0 number or list of three numbers,
min: 0,
one for each band
max: 0.5,
max Value(s) to map to 255 number or list of three numbers,
gamma: [0.95, 1.1, 1]
one for each band
};
gain Value(s) by which to multiply each number or list of three numbers,
pixel value one for each band
bias Value(s) to add to each DN number or list of three numbers,
one for each band
gamma Gamma correction factor(s) number or list of three numbers,
one for each band Table of colors:
palette List of CSS-style color strings comma-separated list of hex strings
https://en.wikipedia.org/wiki/Web_colors
(single-band images only)
opacity The opacity of the layer (0.0 is fully number
transparent and 1.0 is fully opaque)
format Either "jpg" or "png" string
Working with raster data
Image visualization
// Load an image.
var srtm = ee.Image('USGS/SRTMGL1_003');

// Define the visualization parameters


var par_vis = {
min: 0,
max: 3000,
palette: ['00FFFF','00FF7F','7CFC00','2E8B57','FFD700','F4A460','A0522D', 'FFFFFF'] //HTML colors (or name)
};
// Display the image.
Map.addLayer(srtm, par_vis, 'Digital Elevation Model');

Working with raster data


Methods for Image and ImageCollection
.clip(geometry) .filterBounds(geometry)
.expression(‘expression’) .filterDate(start, end)
.select(‘band name’) .filterMetadata(name, operator,
.reduce(reducer) value)
.reduceRegion(reducer) .first()
.get(‘property’) .merge(collection2)
.add(image2) .reduce(reducer)
ee.Image .subtract(image2) ee.ImageColection .select(list of bands)
.multiply(image2) .median()
.divide(image2) .max()
.lte(image2) .aggregate_min(property)
.gte(image2) .....
.max(image2)
.min(image2)
.....
Working with raster data
Example: applying clip method
//get RS shapefile
var RS =
ee.FeatureCollection('users/rafaelkayser/UF').filter(ee.Filter.eq('UFD_NM',
'Rio Grande do Sul'));

// clip SRTM with RS contour


var srtm = ee.Image('USGS/SRTMGL1_003').clip(RS);

// Define the visualization parameters


var par_vis = {
min: 0,
max: 1000,
palette: ['00FFFF','00FF7F','7CFC00','2E8B57','FFD700','F4A460','A0522D',
'FFFFFF']
};

// Display the image.


Map.addLayer(srtm, par_vis, 'Digital Elevation Model');

Working with raster data


Filtering an ImageCollection
// Load Landsat 8 TOA Reflectance Collection, filter by date, bounds and cloud cover
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
.filterDate('2014-01-01', '2014-03-01')
.filterBounds(geometry)
.filterMetadata('CLOUD_COVER', 'less_than', 20);

//select image with the lowest cloud cover


var image = collection.sort('CLOUD_COVER').first();

// Display the image.


Map.addLayer(image, {min: 0, max: 0.3, bands: ['B4', 'B3', 'B2'], gamma: 1.5}, 'LANDSAT 8’);

// Print the resultant collection


print(image);

Working with raster data


Landsat collections

Collection ImageCollection ID
Landsat 5 Surface Reflectance Tier 1 LANDSAT/LT05/C01/T1_SR
Landsat 5 TM Collection 1 Tier 1 TOA Reflectance LANDSAT/LT05/C01/T1_TOA
Landsat 5 TM Collection 1 Tier 1 Raw Scenes LANDSAT/LT05/C01/T1
Landsat 7 Surface Reflectance Tier 1 LANDSAT/LE07/C01/T1_SR
Landsat 7 Collection 1 Tier 1 TOA Reflectance LANDSAT/LE07/C01/T1_TOA
Landsat 7 Collection 1 Tier 1 Raw Scenes LANDSAT/LE07/C01/T1
Landsat 8 Surface Reflectance Tier 1 LANDSAT/LC08/C01/T1_SR
Landsat 8 Collection 1 Tier 1 TOA Reflectance LANDSAT/LC08/C01/T1_TOA
Landsat 8 Collection 1 Tier 1 Raw Scenes LANDSAT/LC08/C01/T1

Working with raster data


Mathematical operations with images
ee.Image.expression ( ‘A + B * C’, {‘A’: image.select(‘B1’),
‘B’: image.select(‘B2’),
‘C’: image.select(‘B3’) } )

1 − 2
ee.Image.normalizedDifference( [‘B1’, ‘B2’] ) =
1+ 2

.add()
.subtract()
.multiply() image.select(‘B1’).add( image.select(‘B2’).multiply(image.select(‘B3’)) )
.divide()
.pow()
ee.Image .sin()
.cos()
.tan()
.log()
.log10()
... Working with raster data
Mathematical operations with images
// Load Landsat 8 TOA Reflectance Collection, filter by date, bounds and cloud cover
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
.filterDate('2014-01-01', '2014-03-01')
.filterBounds(geometry)
.filterMetadata('CLOUD_COVER', 'less_than', 20);

//select image with the lowest cloud cover


var image = collection.sort('CLOUD_COVER').first();

// Compute NDVI by normalized difference method


var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
image.normalizedDifference
// Compute the EVI using an expression.
var evi = image.expression( image.expression
'2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
'NIR': image.select('B5'),
'RED': image.select('B4'),
'BLUE': image.select('B2')
}).rename('EVI');

//add bands to original image


image = image.addBands([ndvi, evi]);

// Display the images.


Map.addLayer(image.select('NDVI'), {min: 0, max: 1, palette: ['SandyBrown', 'DarkKhaki', 'Gold',
'Yellow', 'GreenYellow', 'Lime', 'LimeGreen', 'Green']}, 'NDVI');

Map.addLayer(image.select('EVI'), {min: 0, max: 1, palette: ['SandyBrown', 'DarkKhaki', 'Gold',


'Yellow', 'GreenYellow', 'Lime', 'LimeGreen', 'Green']}, 'EVI');

// Print the resultant collection Working with raster data


print(image);
Conditional and boolean operations
.eq(image2) 1: first image
.neq(image2) with condition
.gt(image2) 0: second image
.gte(image2) with condition
.lt(image2)
.lte(image2)

ee.Image replace pixels


from image1 to
(image1) .where( condition, image2) image1 if
condition is true

Keep pixels from image1


.updateMask(condition) if condition is true

Working with raster data


Conditional and boolean operations
var image = ee.Image("CGIAR/SRTM90_V4");

//create an empty image


var basic = ee.Image(0);

//create elevation categories


basic = basic.where(image.lt(50),1);
basic = basic.where(image.gte(50).and(image.lt(100)),2);
basic = basic.where(image.gte(100).and(image.lt(500)),3);
basic = basic.where(image.gte(500).and(image.lt(1000)),4);
basic = basic.where(image.gte(1000).and(image.lt(2000)),5);
basic = basic.where(image.gte(2000).and(image.lt(3000)),6);
basic = basic.where(image.gte(3000),7);

//mask srtm pixels


basic=basic.updateMask(image);

//display on map
Map.addLayer(basic, {palette: ['Cyan',
'GreenYellow','LimeGreen','Yellow','Orange','Red','DarkRed']},
'Elevation');

Working with raster data


Example: create a NDWI and a not-vegetated bands
// Load Landsat 8 TOA Reflectance Collection, filter by date, bounds and cloud cover
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
.filterDate('2014-01-01', '2014-03-01')
.filterBounds(geometry)
.filterMetadata('CLOUD_COVER', 'less_than', 20);

//select image with the lowest cloud cover


var image = collection.sort('CLOUD_COVER').first();

// Compute NDVI by normalized difference method


var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
var ndwi = image.normalizedDifference(['B3', 'B5']).rename('NDWI');

// Create a binary layer using logical operations.


var not_veg = ndvi.lt(0.4).and(ndwi.lt(0));

//create water band


var water = ndwi.updateMask(ndwi.gt(0));

//keep only ndvi < 0.4


var ndvi_not_veg = ndvi.updateMask(not_veg);

// Display the images.


Map.addLayer(ndvi_not_veg.select('NDVI'), {min: 0, max: 1, palette: ['SandyBrown',
'DarkKhaki', 'Gold', 'Yellow', 'GreenYellow', 'Lime', 'LimeGreen', 'Green']}, 'NDVI');

Map.addLayer(water, {min: 0, max: 1, palette: ['Blue']}, 'Water');

Working with raster data


Mapping over an ImageCollection

var function_name = function(image) { function function_name (image) {


do something ou do something
return output; return output;
} }

collection_name.map( function_name)

Working with raster data


Mapping over an ImageCollection
// Load Landsat 8 TOA Reflectance Collection, filter by date, bounds and cloud cover
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
.filterDate('2013-01-01', '2018-01-01')
.filterBounds(geometry)
.filterMetadata('CLOUD_COVER', 'less_than', 20);

//This function adds a band representing the NDVI


var addNDVI = function (image) {
var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
return image.addBands(ndvi);
};

//Map the function over the collection


collection = collection.map(addNDVI);

//create an image with the median of NDVI band


var ndvi_median = collection.select('NDVI').median();

// Create and print a chart with NDVI time series


print(ui.Chart.image.series(collection.select('NDVI'), geometry));

// Display the image.


Map.addLayer(ndvi_median, {min: 0, max: 1, palette: ['SandyBrown', 'DarkKhaki', 'Gold',
'Yellow', 'GreenYellow', 'Lime', 'LimeGreen', 'Green']}, 'NDVI');

// Print the resultant collection


print(collection);

Working with raster data


Function Reduce

Reducers are the way to aggregate data over


time, space, bands, arrays and other data
structures in Earth Engine

Examples:
• Reduction over time
• Reduction over space
• Reduction over bands

Working with raster data


Ways to reduce
Reduce Image Reduce ImageCollection

Reduce Region Reduce Regions


Reducers in Earth Engine
8 ways to reduce 40+ reducers
Reducer.min
Reducer.allNonZero
Reducer.minMax
Image.reduce Reducer.and
Reducer.mode
Image.reduceNeighborhood Reducer.anyNonZero
Reducer.or
Image.reduceRegion Reducer.count
Reducer.percentile
Image.reduceRegions Reducer.countEvery
Reducer.product
Image.reduceToVectors Reducer.histogram
Reducer.sampleStdDev
ImageCollection.reduce Reducer.intervalMean
Reducer.sampleVariance
FeatureCollection.reduceColumns Reducer.linearFit
Reducer.stdDev
FeatureCollection.ReduceToImage Reducer.linearRegressio
n Reducer.sum
Reducer.max Reducer.toCollection
Reducer.mean Reducer.toList
Reducer.median Reducer.variance
Reduce Image/ ImageCollection

mean()
var new_image= image.reduce(ee.Reducer. max() );
etc

mean()
var new_image= collection.select(‘band’).reduce(ee.Reducer. max() );
etc
ReduceRegion

var output = image.reduceRegion(reducer, geometry, scale, crs, crsTransform, bestEffort, maxPixels, tileScale)

dictionary ee.Reducer.median()
optionals
ee.Reducer.max()
ee.Reducer.min()
...

var output = image. reduceRegion({


reducer: ee.Reducer.stat()
geometry: polygon,
scale: value
});
ReduceRegions

var output = image.reduceRegions(collection, reducer, scale, crs, crsTransform, tileScale)

dictionary
optionals

ee.Reducer.median()
ee.Reducer.max()
ee.Reducer.min()
...
Example: extract maximum altitude from a region
//get RS shapefile
var RS = ee.FeatureCollection('users/rafaelkayser/UF').filter(ee.Filter.eq('UFD_NM', 'Rio Grande do
Sul'));

// clip SRTM with RS contour


var srtm = ee.Image('USGS/SRTMGL1_003').clip(RS);

// Apply a reduce region method


var max_alt = srtm.reduceRegion(
{reducer: ee.Reducer.max(),
geometry: RS ,
scale: 30,
maxPixels: 9e9});

// Display the image.


Map.addLayer(srtm, {min: 0,max: 1000,palette:
['00FFFF','00FF7F','7CFC00','2E8B57','FFD700','F4A460','A0522D', 'FFFFFF']}, 'Digital Elevation Model');

// print
print('Maximum altitude (meters):', max_alt);
Example: calculate a reservoir surface area

https://code.earthengine.google.com/49b1e64b31e238ddc4b7c21912086afd
Module V
Exporting data
Making charts
• Histogramas • Séries espectrais por região

• Séries temporais por região • DOY series (dia do ano)


Making charts
var chart = ui.Chart.image.series(imageCollection, region, reducer, scale,
xProperty)

var chart = ui.Chart.image.histogram(image, region, scale, maxBuckets,


minBucketWidth, maxRaw)

var chart = ui.Chart.image.regions(image, regions, reducer, scale,


seriesProperty, xLabels)

var chart = ui.Chart.image.seriesByRegion(imageCollection,


regions, reducer, band, scale, xProperty, seriesProperty)

.setChartType(...)
.setOptions(...)

print(chart)
Making charts

Link to code: https://code.earthengine.google.com/ef377bc2935102c09977a9fcf726a625


Exporting images

Export.image.toDrive(image, description, folder, fileNamePrefix, dimensions,


region, scale, crs, crsTransform, maxPixels, shardSize, fileDimensions,
skipEmptyTiles, fileFormat, formatOptions)

Export.image.toDrive({
image: image_name,
region: feature.geometry(),
description: “image_description”,
folder: “name_folder”,
scale: scale_value, //default: 1000 meters
maxPixels: 1e9 //default: 1e8
});
// define a feature collection from assets
var fc_south_america_basins = ee.FeatureCollection('users/rafaelkayser/South_America_Basins');

Export SRTM image //select basin by filter


var fc_selected_basin = fc_south_america_basins.filter(ee.Filter.eq('SUB_NAME', 'Taquari' ));

// function to apply buffer method in each featureCollection


var function_buffer = function(feature) {
return feature.buffer(1000)};

// apply buffer
var fc_selected_basin_buff = fc_selected_basin.map(function_buffer);

// select srtm and clip basin


var image_srtm = ee.Image('USGS/SRTMGL1_003').clip(fc_selected_basin_buff);

//export image to Google Drive


Export.image.toDrive({
image: image_srtm,
description: 'srtm',
region: fc_selected_basin_buff.geometry(),
folder: 'output_gee',
maxPixels: 1e9 ,
scale: 30
});

//display basin limits


Map.addLayer(fc_selected_basin_buff, {}, 'Taquari Basin');

// Define the visualization parameters


var par_vis = {
min: 0,
max: 1000,
palette: ['00FFFF','00FF7F','7CFC00','2E8B57','FFD700','F4A460','A0522D', 'FFFFFF']
};

// Display the image.


Map.addLayer(image_srtm, par_vis, 'Digital Elevation Model');
Export Landsat images

https://code.earthengine.google.com/3b1001f55f8965cf684946ba09578d4e
Export table with time series data

https://code.earthengine.google.com/78354473a72631e1534b6f78c4b97314
Module VI
Special topics in GEE
Special topics in GEE

• Cloud remotion methods

• Deriving topographic products from elevation data

• Working with precipitation products

• Data visualization on QGIS


Special topics in GEE

• Cloud remotion methods

• Deriving topographic products from elevation data

• Working with precipitation products

• Data visualization on QGIS


Landsat 5/7 Surface Reflectance – pixel_qa band

https://www.usgs.gov/media/files/landsat-4-7-surface-
reflectance-code-ledaps-product-guide
Landsat 8 Surface Reflectance – pixel_qa band

https://www.usgs.gov/media/files/landsat-8-surface-
reflectance-code-lasrc-product-guide
Functions to cloud remotion in SR images
// Function to mask clouds in Landsat 5/7 SR imagery. // Function to mask clouds in Landsat 8 SR imagery.
var f_cloudMaskL457_SR = function(image) { var f_cloudMaskL8_SR = function(image) {
var quality = image.select('pixel_qa'); var quality = image.select('pixel_qa');
var c01 = quality.eq(66); //Clear, low confidence cloud var c01 = quality.eq(322); //Clear, low confidence cloud
var c02 = quality.eq(68); //water, low confidence var c02 = quality.eq(324); //water, low confidence cloud
cloud var c03 = quality.eq(1346); //Clear terrain, terrain occluded
var mask = c01.or(c02); var mask = c01.or(c02).or(c03);
return image.updateMask(mask); return image.updateMask(mask);
}; };

// Function to mask clouds in Landsat 5/7 SR imagery // Function to mask clouds in Landsat 8 SR imagery.
var f_cloudMaskL457_SR_v2 = function(image) { var f_cloudMaskL8_SR_v2 = function (image) {
var qa = image.select('pixel_qa'); // Bits 3 and 5 are cloud shadow and cloud, respectively.
// If the cloud bit (5) is set and the cloud confidence (7) var cloudShadowBitMask = (1 << 3);
// is high or the cloud shadow bit is set (3), then it's a var cloudsBitMask = (1 << 5);
bad pixel. // Get the pixel QA band.
var cloud = qa.bitwiseAnd(1 << 5) var qa = image.select('pixel_qa');
.and(qa.bitwiseAnd(1 << 7)) // Both flags should be set to zero, indicating clear conditions.
.or(qa.bitwiseAnd(1 << 3)); var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0).
// Remove edge pixels that don't occur in all bands and(qa.bitwiseAnd(cloudsBitMask).eq(0));
var mask2 = image.mask().reduce(ee.Reducer.min()); return image.updateMask(mask);
return };
image.updateMask(cloud.not()).updateMask(mask2);
};
Landsat 5/7 TOA – BQA band

https://landsat.usgs.gov/collectionqualityband
Landsat 8 TOA – BQA band

https://landsat.usgs.gov/collectionqualityband
Script to remove cloud pixels

https://code.earthengine.google.com/b18dd1539c6fed43113dd6221a9ce027
Special topics in GEE

• Cloud remotion methods

• Deriving topographic products from elevation data

• Working with precipitation products

• Data visualization on QGIS


Terrain properties
// define a feature collection from assets
var fc_south_america_basins = ee.FeatureCollection('users/rafaelkayser/South_America_Basins');
//select basin by filter
var fc_selected_basin = fc_south_america_basins.filter(ee.Filter.eq('SUB_NAME', 'Taquari' ));
// function to apply buffer method in each featureCollection
var function_buffer = function(feature) {
return feature.buffer(1000)};
// apply buffer
var fc_selected_basin_buff = fc_selected_basin.map(function_buffer); ee.Terrain.slope()
// select srtm and clip basin value in degrees
var image_srtm = ee.Image('USGS/SRTMGL1_003').clip(fc_selected_basin_buff);
//calculate slope
var slope = ee.Terrain.slope(image_srtm);
//calculate aspect
var aspect = ee.Terrain.aspect(image_srtm);

// Define the visualization parameters


var par_vis = {min: 0, max: 1000,
palette: ['00FFFF','00FF7F','7CFC00','2E8B57','FFD700','F4A460','A0522D', 'FFFFFF']};

var par_vis1 = {min: 0,max: 50,


palette: ['00FFFF','00FF7F','7CFC00','2E8B57','FFD700','F4A460','A0522D', 'FFFFFF']};

// Display the image. ee.Terrain.aspect()


Map.addLayer(image_srtm, par_vis, 'Digital Elevation Model');
Map.addLayer(slope, par_vis1, 'Slope'); slope direction (value in
Map.addLayer(aspect, {}, 'Aspect'); degrees)
Special topics in GEE

• Cloud remotion methods

• Deriving topographic products from elevation data

• Working with precipitation products

• Data visualization on QGIS


Script to read TRMM and GPM products and convert to daily step

https://code.earthengine.google.com/202d043bf4a7dcdf1fe012fd5c17a6d3
Special topics in GEE

• Cloud remotion methods

• Deriving topographic products from elevation data

• Working with precipitation products

• Data visualization on QGIS


Referências

https://developers.google.com/earth-engine/
Referências

• Fórum do Google Earth Engine


https://groups.google.com/forum/?hl=pt-BR#!forum/google-earth-engine-
developers

• Grupo do Google Earth Engine no Facebook


Dúvidas?
rafael.hbkayser@gmail.com

You might also like