天天看點

GEE(Google Earth Engine)——JavaScript 入門(3)

波段計算

使用Image方法對圖像進行數學運算。這可能包括波段重組(光譜指數)、圖像差分或數學運算,例如乘以常數。例如,計算相隔 20 年的歸一化差異植被指數 (NDVI) 圖像之間的差異:

​​代碼編輯器 (JavaScript)​​

// This function gets NDVI from Landsat 5 imagery.
var getNDVI = function(image) {
  return image.normalizedDifference(['B4', 'B3']);
};

// Load two Landsat 5 images, 20 years apart.
var image1 = ee.Image('LANDSAT/LT05/C01/T1_TOA/LT05_044034_19900604');
var image2 = ee.Image('LANDSAT/LT05/C01/T1_TOA/LT05_044034_20100611');

// Compute NDVI from the scenes.
var ndvi1 = getNDVI(image1);
var ndvi2 = getNDVI(image2);

// Compute the difference in NDVI.
var ndviDifference = ndvi2.subtract(ndvi1);      

請注意function本示例中定義的使用者的使用。更多關于下一節的功能。

映射(做什麼而不是 for 循環)

使用map()以周遊集合中的項目。(For 循環不是在 Earth Engine 中執行此操作的正确方法,應避免使用)。該map() 函數可以應用于 an ImageCollection、 a FeatureCollection或 aList并接受 afunction 作為其參數。函數的參數是它所映射的集合的一個元素。這對于以相同的方式修改集合的每個元素很有用,例如添加。例如,以下代碼向 中的每個圖像添加 NDVI 波段ImageCollection:

​​代碼編輯器 (JavaScript)​​

// This function gets NDVI from Landsat 8 imagery.
var addNDVI = function(image) {
  return image.addBands(image.normalizedDifference(['B5', 'B4']));
};

// Load the Landsat 8 raw data, filter by location and date.
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1')
  .filterBounds(ee.Geometry.Point(-122.262, 37.8719))
  .filterDate('2014-06-01', '2014-10-01');

// Map the function over the collection.
var ndviCollection = collection.map(addNDVI);      

另一個常見任務是向 .csv 檔案中的要素添加新屬性(或“屬性”或“字段”) FeatureCollection。在以下示例中,新屬性是涉及兩個現有屬性的計算:

​​代碼編輯器 (JavaScript)​​

// This function creates a new property that is the sum of two existing properties.
var addField = function(feature) {
  var sum = ee.Number(feature.get('property1')).add(feature.get('property2'));
  return feature.set({'sum': sum});
};

// Create a FeatureCollection from a list of Features.
var features = ee.FeatureCollection([
  ee.Feature(ee.Geometry.Point(-122.4536, 37.7403),
    {property1: 100, property2: 100}),
    ee.Feature(ee.Geometry.Point(-118.2294, 34.039),
    {property1: 200, property2: 300}),
]);

// Map the function over the collection.
var featureCollection = features.map(addField);

// Print a selected property of one Feature.
print(featureCollection.first().get('sum'));

// Print the entire FeatureCollection.
print(featureCollection);      

請注意将ee.Number屬性值識别為數字以使用該add()方法所需的強制轉換)。可以通過 更改集合的類型map()。例如:

// This function returns the image centroid as a new Feature.
var getGeom = function(image) {
  return ee.Feature(image.geometry().centroid(), {foo: 1});
};

// Load a Landsat 8 collection.
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1')
  .filterBounds(ee.Geometry.Point(-122.262, 37.8719))
  .filterDate('2014-06-01', '2014-10-01');

// Map the function over the ImageCollection.
var featureCollection = ee.FeatureCollection(collection.map(getGeom));

// Print the collection.
print(featureCollection);      

以上所有例子都可以在科學上網的情況下,完成直達,具體圖像我就不展示了,希望對大家有幫助,更多資源可以點選資源檢視。

繼續閱讀