Matrizes e imagens de matriz

As matrizes no Earth Engine são construídas a partir de listas de números e listas de listas. O grau de aninhamento determina o número de dimensões. Para começar com um exemplo simples e motivado, considere o seguinte exemplo de um Array criado com os coeficientes de tasseled cap (TC) do Landsat 8 (Baig et al., 2014):

Editor de código (JavaScript)

// Create an Array of Tasseled Cap coefficients.
var coefficients = ee.Array([
  [0.3029, 0.2786, 0.4733, 0.5599, 0.508, 0.1872],
  [-0.2941, -0.243, -0.5424, 0.7276, 0.0713, -0.1608],
  [0.1511, 0.1973, 0.3283, 0.3407, -0.7117, -0.4559],
  [-0.8239, 0.0849, 0.4396, -0.058, 0.2013, -0.2773],
  [-0.3294, 0.0557, 0.1056, 0.1855, -0.4349, 0.8085],
  [0.1079, -0.9023, 0.4119, 0.0575, -0.0259, 0.0252],
]);

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Create an Array of Tasseled Cap coefficients.
coefficients = ee.Array([
    [0.3029, 0.2786, 0.4733, 0.5599, 0.508, 0.1872],
    [-0.2941, -0.243, -0.5424, 0.7276, 0.0713, -0.1608],
    [0.1511, 0.1973, 0.3283, 0.3407, -0.7117, -0.4559],
    [-0.8239, 0.0849, 0.4396, -0.058, 0.2013, -0.2773],
    [-0.3294, 0.0557, 0.1056, 0.1855, -0.4349, 0.8085],
    [0.1079, -0.9023, 0.4119, 0.0575, -0.0259, 0.0252],
])

Confirme se esta é uma matriz 2D de 6 x 6 usando length(), que vai retornar os comprimentos de cada eixo:

Editor de código (JavaScript)

// Print the dimensions.
print(coefficients.length()); //    [6,6]

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Print the dimensions.
display(coefficients.length())  #    [6,6]

A tabela a seguir ilustra o arranjo das entradas da matriz ao longo do eixo 0 e do eixo 1:

1 eixo ->
012345
00,30290,27860,47330,55990,5080,1872
1-0,2941-0,243-0,54240,72760,0713-0,1608
Eixo 020,15110,19730,32830,3407-0,7117-0,4559
3-0,82390,08490,4396-0,0580,2013-0,2773
4-0,32940,05570,10560,1855-0,43490,8085
50,1079-0,90230,41190,0575-0,02590,0252

Os índices à esquerda da tabela indicam as posições ao longo do eixo 0. O elemento n-ésimo em cada lista no eixo 0 está na posição n-ésima ao longo do eixo 1. Por exemplo, a entrada na coordenada [3,1] da matriz é 0,0849. Suponha que "greenness" seja o componente de TC de interesse. É possível acessar a submatriz de verde usando slice():

Editor de código (JavaScript)

// Get the 1x6 greenness slice, display it.
var greenness = coefficients.slice({axis: 0, start: 1, end: 2, step: 1});
print(greenness);

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Get the 1x6 greenness slice, display it.
greenness = coefficients.slice(axis=0, start=1, end=2, step=1)
display(greenness)

A matriz de verde 2D vai ficar assim:

[[-0.2941,-0.243,-0.5424,0.7276,0.0713,-0.1608]]
    

Os parâmetros start e end de slice() correspondem aos índices do eixo 0 mostrados na tabela (start é inclusivo e end é exclusivo).

Imagens de matriz

Para gerar uma imagem de verde, multiplique as matrizes das bandas de uma imagem do Landsat 8 pela matriz de verde. Para fazer isso, primeiro converta a imagem Landsat multibanda em uma "imagem de matriz", em que cada pixel é um Array de valores de banda. Exemplo:

Editor de código (JavaScript)

// Load a Landsat 8 image, select the bands of interest.
var image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318')
  .select(['B2', 'B3', 'B4', 'B5', 'B6', 'B7']);

// Make an Array Image, with a 1-D Array per pixel.
var arrayImage1D = image.toArray();

// Make an Array Image with a 2-D Array per pixel, 6x1.
var arrayImage2D = arrayImage1D.toArray(1);

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Load a Landsat 8 image, select the bands of interest.
image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318').select(
    ['B2', 'B3', 'B4', 'B5', 'B6', 'B7']
)

# Make an Array Image, with a 1-D Array per pixel.
array_image_1d = image.toArray()

# Make an Array Image with a 2-D Array per pixel, 6x1.
array_image_2d = array_image_1d.toArray(1)

Neste exemplo, toArray() converte image em uma imagem de matriz em que cada pixel é um vetor de 1D, e as entradas correspondem aos 6 valores nas posições correspondentes nas bandas de image. Uma imagem de matriz de vetores unidimensionais criada dessa maneira não tem o conceito de forma bidimensional. Para realizar operações apenas 2D, como multiplicação de matriz, converta-as em uma matriz 2D por pixel com toArray(1). Em cada pixel da imagem de matriz 2D, há uma matriz de 6 x 1 de valores de faixa. Para entender isso, considere o seguinte exemplo de brinquedo:

Editor de código (JavaScript)

var array1D = ee.Array([1, 2, 3]);              // [1,2,3]
var array2D = ee.Array.cat([array1D], 1);     // [[1],[2],[3]]

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

array_1d = ee.Array([1, 2, 3])  # [1,2,3]
array_2d = ee.Array.cat([array_1d], 1)  # [[1],[2],[3]]

Observe que o vetor array1D varia ao longo do eixo 0. A matriz array2D também faz isso, mas tem uma dimensão extra. Chamar toArray(1) na imagem do array é como chamar cat(bandVector, 1) em cada pixel. Usando a imagem da matriz 2D, a multiplicação à esquerda por uma imagem em que cada pixel contém uma matriz 2D de coeficientes de verde:

Editor de código (JavaScript)

// Do a matrix multiplication: 1x6 times 6x1.
// Cast the greenness Array to an Image prior to multiplication.
var greennessArrayImage = ee.Image(greenness).matrixMultiply(arrayImage2D);

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Do a matrix multiplication: 1x6 times 6x1.
# Cast the greenness Array to an Image prior to multiplication.
greenness_array_image = ee.Image(greenness).matrixMultiply(array_image_2d)

O resultado é uma nova imagem de matriz em que cada pixel é a matriz 1x1 resultante da multiplicação da matriz de verde 1x6 (à esquerda) e da matriz de banda 6x1 (à direita). Para fins de exibição, converta em uma imagem regular de uma banda com arrayGet():

Editor de código (JavaScript)

// Get the result from the 1x1 array in each pixel of the 2-D array image.
var greennessImage = greennessArrayImage.arrayGet([0, 0]);

// Display the input imagery with the greenness result.
Map.setCenter(-122.3, 37.562, 10);
Map.addLayer(image, {bands: ['B5', 'B4', 'B3'], min: 0, max: 0.5}, 'image');
Map.addLayer(greennessImage, {min: -0.1, max: 0.13}, 'greenness');

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Get the result from the 1x1 array in each pixel of the 2-D array image.
greenness_image = greenness_array_image.arrayGet([0, 0])

# Display the input imagery with the greenness result.
m = geemap.Map()
m.set_center(-122.3, 37.562, 10)
m.add_layer(image, {'bands': ['B5', 'B4', 'B3'], 'min': 0, 'max': 0.5}, 'image')
m.add_layer(greenness_image, {'min': -0.1, 'max': 0.13}, 'greenness')
m

Confira um exemplo completo que usa a matriz de coeficientes inteira para calcular vários componentes de cap com borla de uma vez e mostrar o resultado:

Editor de código (JavaScript)

// Define an Array of Tasseled Cap coefficients.
var coefficients = ee.Array([
  [0.3029, 0.2786, 0.4733, 0.5599, 0.508, 0.1872],
  [-0.2941, -0.243, -0.5424, 0.7276, 0.0713, -0.1608],
  [0.1511, 0.1973, 0.3283, 0.3407, -0.7117, -0.4559],
  [-0.8239, 0.0849, 0.4396, -0.058, 0.2013, -0.2773],
  [-0.3294, 0.0557, 0.1056, 0.1855, -0.4349, 0.8085],
  [0.1079, -0.9023, 0.4119, 0.0575, -0.0259, 0.0252],
]);

// Load a Landsat 8 image, select the bands of interest.
var image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318')
  .select(['B2', 'B3', 'B4', 'B5', 'B6', 'B7']);

// Make an Array Image, with a 1-D Array per pixel.
var arrayImage1D = image.toArray();

// Make an Array Image with a 2-D Array per pixel, 6x1.
var arrayImage2D = arrayImage1D.toArray(1);

// Do a matrix multiplication: 6x6 times 6x1.
var componentsImage = ee.Image(coefficients)
  .matrixMultiply(arrayImage2D)
  // Get rid of the extra dimensions.
  .arrayProject([0])
  .arrayFlatten(
    [['brightness', 'greenness', 'wetness', 'fourth', 'fifth', 'sixth']]);

// Display the first three bands of the result and the input imagery.
var vizParams = {
  bands: ['brightness', 'greenness', 'wetness'],
  min: -0.1, max: [0.5, 0.1, 0.1]
};
Map.setCenter(-122.3, 37.562, 10);
Map.addLayer(image, {bands: ['B5', 'B4', 'B3'], min: 0, max: 0.5}, 'image');
Map.addLayer(componentsImage, vizParams, 'components');

Configuração do Python

Consulte a página Ambiente Python para informações sobre a API Python e o uso de geemap para desenvolvimento interativo.

import ee
import geemap.core as geemap

Colab (Python)

# Define an Array of Tasseled Cap coefficients.
coefficients = ee.Array([
    [0.3029, 0.2786, 0.4733, 0.5599, 0.508, 0.1872],
    [-0.2941, -0.243, -0.5424, 0.7276, 0.0713, -0.1608],
    [0.1511, 0.1973, 0.3283, 0.3407, -0.7117, -0.4559],
    [-0.8239, 0.0849, 0.4396, -0.058, 0.2013, -0.2773],
    [-0.3294, 0.0557, 0.1056, 0.1855, -0.4349, 0.8085],
    [0.1079, -0.9023, 0.4119, 0.0575, -0.0259, 0.0252],
])

# Load a Landsat 8 image, select the bands of interest.
image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318').select(
    ['B2', 'B3', 'B4', 'B5', 'B6', 'B7']
)

# Make an Array Image, with a 1-D Array per pixel.
array_image_1d = image.toArray()

# Make an Array Image with a 2-D Array per pixel, 6x1.
array_image_2d = array_image_1d.toArray(1)

# Do a matrix multiplication: 6x6 times 6x1.
components_image = (
    ee.Image(coefficients)
    .matrixMultiply(array_image_2d)
    # Get rid of the extra dimensions.
    .arrayProject([0])
    .arrayFlatten(
        [['brightness', 'greenness', 'wetness', 'fourth', 'fifth', 'sixth']]
    )
)

# Display the first three bands of the result and the input imagery.
viz_params = {
    'bands': ['brightness', 'greenness', 'wetness'],
    'min': -0.1,
    'max': [0.5, 0.1, 0.1],
}
m = geemap.Map()
m.set_center(-122.3, 37.562, 10)
m.add_layer(image, {'bands': ['B5', 'B4', 'B3'], 'min': 0, 'max': 0.5}, 'image')
m.add_layer(components_image, viz_params, 'components')
m

Ao extrair bandas de uma imagem de matriz, primeiro se livre das dimensões extras com project() e, em seguida, converta-a de volta em uma imagem normal com arrayFlatten(). A saída será semelhante a esta:

imagem de boné com borla
Figura 1. Componentes de tampa com franjas "brilho" (vermelho), "verde" (verde) e "umidade" (azul).