Чтобы применить функцию к каждому Image
в ImageCollection
используйте imageCollection.map()
. Единственным аргументом функции map()
является функция, принимающая один параметр: ee.Image
. Например, следующий код добавляет полосу временных меток к каждому изображению в коллекции.
Редактор кода (JavaScript)
// 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
на основе числового значения свойства. Как обсуждалось в разделах «Сокращение» и «Композиция» , наличие временного диапазона полезно для линейного моделирования изменений и создания композитов.
Сопоставленная функция ограничена в операциях, которые она может выполнять. В частности, он не может изменять переменные вне функции; он не может ничего напечатать; он не может использовать операторы «if» или «for» в JavaScript и Python. Однако вы можете использовать ee.Algorithms.If()
для выполнения условных операций в отображаемой функции. Например:
Редактор кода (JavaScript)
// 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()
, истинно, выходные данные содержат постоянное изображение. Хотя это демонстрирует условную функцию на стороне сервера ( узнайте больше о клиенте и сервере в Earth Engine ), вообще избегайте If()
и вместо этого используйте фильтры.