縮減函式是一種方法,可在 Earth Engine 中匯總時間、空間、頻帶、陣列和其他資料結構的資料。ee.Reducer
類別會指定資料的匯總方式。這個類別中的縮減器可指定用於匯總的簡單統計資料 (例如最小值、最大值、平均值、中位數、標準差等),或輸入資料的較複雜摘要 (例如直方圖、線性迴歸、清單)。縮減可能發生在時間 (imageCollection.reduce()
)、空間 (image.reduceRegion()
、image.reduceNeighborhood()
)、頻帶 (image.reduce()
) 或 FeatureCollection
的屬性空間 (featureCollection.reduceColumns()
或以 aggregate_
開頭的 FeatureCollection
方法)。
Reducer 有輸入和輸出
算術運算器會擷取輸入資料集,並產生單一輸出內容。當單一輸入縮減器套用至多頻帶影像時,Earth Engine 會自動複製縮減器,並分別套用至各個頻帶。因此,輸出圖片的頻帶數量與輸入圖片相同;輸出圖片中的每個頻帶,都是輸入資料中對應頻帶的像素減少量。部分縮減器會使用輸入資料集的元組。這些縮減器不會自動複製到每個頻帶。舉例來說,ee.Reducer.LinearRegression()
會以特定順序 (請參閱「迴歸縮減器」) 取用多個預測資料集 (代表迴歸中的獨立變數)。
某些縮減器會產生多個輸出,例如 ee.Reducer.minMax()
、ee.Reducer.histogram()
或 ee.Reducer.toList()
。例如:
程式碼編輯器 (JavaScript)
// Load and filter the Sentinel-2 image collection. var collection = ee.ImageCollection('COPERNICUS/S2_HARMONIZED') .filterDate('2016-01-01', '2016-12-31') .filterBounds(ee.Geometry.Point([-81.31, 29.90])); // Reduce the collection. var extrema = collection.reduce(ee.Reducer.minMax());
import ee import geemap.core as geemap
Colab (Python)
# Load and filter the Sentinel-2 image collection. collection = ( ee.ImageCollection('COPERNICUS/S2_HARMONIZED') .filterDate('2016-01-01', '2016-12-31') .filterBounds(ee.Geometry.Point([-81.31, 29.90])) ) # Reduce the collection. extrema = collection.reduce(ee.Reducer.minMax())
這會產生輸出內容,其頻帶數量是輸入內容的兩倍,其中輸出內容中的頻帶名稱會在名稱後方加上「_min」或「_max」。
輸出類型應與運算相符。舉例來說,套用至 ImageCollection
的 reducer 有 Image
輸出內容。由於輸出內容會解讀為像素值,因此您必須使用具有數值輸出的縮減器來縮減 ImageCollection
(toList()
或 histogram()
這類縮減器無法運作)。
Reducer 會使用加權輸入
根據預設,系統會根據遮罩為像素值減數加權,但這項行為可以變更 (請參閱「加權」一節)。系統不會在縮減作業中使用遮罩值等於 0 的像素。
合併縮減器
如果您想將多個減算器套用至相同的輸入內容,建議您combine()
減算器以提高效率。具體來說,在 sharedInputs
設為 true
的情況下,對 reducer 呼叫 combine()
只會對資料進行一次傳送。舉例來說,如要計算圖片中像素的平均值和標準差,您可以使用以下方式:
程式碼編輯器 (JavaScript)
// Load a Landsat 8 image. var image = ee.Image('LANDSAT/LC08/C02/T1/LC08_044034_20140318'); // Combine the mean and standard deviation reducers. var reducers = ee.Reducer.mean().combine({ reducer2: ee.Reducer.stdDev(), sharedInputs: true }); // Use the combined reducer to get the mean and SD of the image. var stats = image.reduceRegion({ reducer: reducers, bestEffort: true, }); // Display the dictionary of band means and SDs. print(stats);
import ee import geemap.core as geemap
Colab (Python)
# Load a Landsat 8 image. image = ee.Image('LANDSAT/LC08/C02/T1/LC08_044034_20140318') # Combine the mean and standard deviation reducers. reducers = ee.Reducer.mean().combine( reducer2=ee.Reducer.stdDev(), sharedInputs=True ) # Use the combined reducer to get the mean and SD of the image. stats = image.reduceRegion(reducer=reducers, bestEffort=True) # Display the dictionary of band means and SDs. display(stats)
請注意,在輸出內容中,reducer 名稱已附加至輸入名稱,以便區分 reducer 輸出內容。這項行為也適用於圖片輸出,輸出頻帶名稱會加上縮減器名稱。
如果您要結合使用無權重的輸入內容和使用權重輸入內容的 reducer,所有權重輸入內容必須置於所有無權重輸入內容之前。