如需将函数应用于 ImageCollection
中的每个 Image
,请使用 imageCollection.map()
。map()
的唯一实参是一个接受一个参数(即 ee.Image
)的函数。例如,以下代码会向合集中的每张图片添加时间戳条带。
// Load a Landsat 8 collection for a single path-row, 2021 images only. var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA') .filterDate('2021', '2022') .filter(ee.Filter.eq('WRS_PATH', 44)) .filter(ee.Filter.eq('WRS_ROW', 34)); // This function adds a band representing the image timestamp. var addTime = function(image) { return image.addBands(image.getNumber('system:time_start')); }; // Map the function over the collection and display the result. print(collection.map(addTime));
import ee import geemap.core as geemap
# Load a Landsat 8 collection for a single path-row, 2021 images only. collection = ( ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA') .filterDate('2021', '2022') .filter(ee.Filter.eq('WRS_PATH', 44)) .filter(ee.Filter.eq('WRS_ROW', 34)) ) # This function adds a band representing the image timestamp. def add_time(image): return image.addBands(image.getNumber('system:time_start')) # Map the function over the collection and display the result. display(collection.map(add_time))
请注意,在预定义函数中,getNumber()
方法用于根据属性的数值创建新的 Image
。如缩减和组合部分所述,设置时间段对对变化进行线性建模和制作复合图表非常有用。
映射的函数可以执行的操作有限。具体而言,它无法修改函数外的变量;无法输出任何内容;无法使用 JavaScript 和 Python 的“if”或“for”语句。不过,您可以使用 ee.Algorithms.If()
在映射的函数中执行条件运算。例如:
// Load a Landsat 8 collection for a single path-row, 2021 images only. var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA') .filterDate('2021', '2022') .filter(ee.Filter.eq('WRS_PATH', 44)) .filter(ee.Filter.eq('WRS_ROW', 34)); // This function uses a conditional statement to return the image if // the solar elevation > 40 degrees. Otherwise it returns a "zero image". var conditional = function(image) { return ee.Algorithms.If(ee.Number(image.get('SUN_ELEVATION')).gt(40), image, ee.Image(0)); }; // Map the function over the collection and print the result. Expand the // collection and note that 7 of the 22 images are now "zero images'. print('Expand this to see the result', collection.map(conditional));
import ee import geemap.core as geemap
# Load a Landsat 8 collection for a single path-row, 2021 images only. collection = ( ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA') .filterDate('2021', '2022') .filter(ee.Filter.eq('WRS_PATH', 44)) .filter(ee.Filter.eq('WRS_ROW', 34)) ) # This function uses a conditional statement to return the image if # the solar elevation > 40 degrees. Otherwise it returns a "zero image". def conditional(image): return ee.Algorithms.If( ee.Number(image.get('SUN_ELEVATION')).gt(40), image, ee.Image(0) ) # Map the function over the collection and print the result. Expand the # collection and note that 7 of the 22 images are now "zero images'. display('Expand this to see the result', collection.map(conditional))
检查输出 ImageCollection 中的图片列表,并注意,当 If()
算法评估的条件为 true 时,输出中会包含一个常量图片。虽然这演示了服务器端条件函数(详细了解 Earth Engine 中的客户端与服务器),但一般来说,请避免使用 If()
,改用过滤器。