تکرار روی ImageCollection

اگرچه map() تابعی را برای هر تصویر در مجموعه اعمال می‌کند، اما تابع به‌طور مستقل از هر تصویر در مجموعه بازدید می‌کند. برای مثال، فرض کنید می‌خواهید ناهنجاری تجمعی (At) را در زمان t از یک سری زمانی محاسبه کنید. برای به‌دست آوردن سری‌های تعریف‌شده بازگشتی از فرم At = f(Imaget, At-1)، نگاشت کار نخواهد کرد زیرا تابع (f) به نتیجه قبلی (At-1) بستگی دارد. برای مثال، فرض کنید می‌خواهید مجموعه‌ای از تصاویر ناهنجاری تجمعی «شاخص پوشش گیاهی تفاضلی نرمال‌شده» (NDVI) را نسبت‌به یک خط مبنا محاسبه کنید. فرض کنید A0 = 0 و f(Imaget, At-1) = Imaget + At-1 که در آن At-1 ناهنجاری تجمعی تا زمان t-1 و Imaget ناهنجاری در زمان t است. از imageCollection.iterate() برای تعریف بازگشتی این ImageCollection استفاده کنید. در مثال زیر، تابع accumulate() دو پارامتر می‌گیرد: یک تصویر در مجموعه، و فهرستی از همه بروندادهای قبلی. با هر تماس با iterate()، ناهنجاری به مجموع درحال اجرا اضافه می‌شود و نتیجه به فهرست اضافه می‌شود. نتیجه نهایی به سازنده ImageCollection ارسال می‌شود تا توالی جدیدی از تصاویر دریافت شود:

ویرایشگر کد (جاوا اسکریپت)

// Load MODIS EVI imagery.
var collection = ee.ImageCollection('MODIS/061/MYD13A1').select('EVI');

// Define reference conditions from the first 10 years of data.
var reference = collection.filterDate('2001-01-01', '2010-12-31')
  // Sort chronologically in descending order.
  .sort('system:time_start', false);

// Compute the mean of the first 10 years.
var mean = reference.mean();

// Compute anomalies by subtracting the 2001-2010 mean from each image in a
// collection of 2011-2014 images. Copy the date metadata over to the
// computed anomaly images in the new collection.
var series = collection.filterDate('2011-01-01', '2014-12-31').map(function(image) {
    return image.subtract(mean).set('system:time_start', image.get('system:time_start'));
});

// Display cumulative anomalies.
Map.setCenter(-100.811, 40.2, 5);
Map.addLayer(series.sum(),
    {min: -60000, max: 60000, palette: ['FF0000', '000000', '00FF00']}, 'EVI anomaly');

// Get the timestamp from the most recent image in the reference collection.
var time0 = reference.first().get('system:time_start');

// Use imageCollection.iterate() to make a collection of cumulative anomaly over time.
// The initial value for iterate() is a list of anomaly images already processed.
// The first anomaly image in the list is just 0, with the time0 timestamp.
var first = ee.List([
  // Rename the first band 'EVI'.
  ee.Image(0).set('system:time_start', time0).select([0], ['EVI'])
]);

// This is a function to pass to Iterate().
// As anomaly images are computed, add them to the list.
var accumulate = function(image, list) {
  // Get the latest cumulative anomaly image from the end of the list with
  // get(-1).  Since the type of the list argument to the function is unknown,
  // it needs to be cast to a List.  Since the return type of get() is unknown,
  // cast it to Image.
  var previous = ee.Image(ee.List(list).get(-1));
  // Add the current anomaly to make a new cumulative anomaly image.
  var added = image.add(previous)
    // Propagate metadata to the new image.
    .set('system:time_start', image.get('system:time_start'));
  // Return the list with the cumulative anomaly inserted.
  return ee.List(list).add(added);
};

// Create an ImageCollection of cumulative anomaly images by iterating.
// Since the return type of iterate is unknown, it needs to be cast to a List.
var cumulative = ee.ImageCollection(ee.List(series.iterate(accumulate, first)));

// Predefine the chart titles.
var title = {
  title: 'Cumulative EVI anomaly over time',
  hAxis: {title: 'Time'},
  vAxis: {title: 'Cumulative EVI anomaly'},
};

// Chart some interesting locations.
var pt1 = ee.Geometry.Point(-65.544, -4.894);
print('Amazon rainforest:',
    ui.Chart.image.series(
      cumulative, pt1, ee.Reducer.first(), 500).setOptions(title));

var pt2 = ee.Geometry.Point(116.4647, 40.1054);
print('Beijing urbanization:',
    ui.Chart.image.series(
      cumulative, pt2, ee.Reducer.first(), 500).setOptions(title));

var pt3 = ee.Geometry.Point(-110.3412, 34.1982);
print('Arizona forest disturbance and recovery:',
    ui.Chart.image.series(
      cumulative, pt3, ee.Reducer.first(), 500).setOptions(title));

راه‌اندازی Python

برای اطلاعات درباره Python API و استفاده از geemap برای توسعه تعاملی، به صفحه محیط Python مراجعه کنید.

import ee
import geemap.core as geemap

Colab (Python)

import altair as alt
# Load MODIS EVI imagery.
collection = ee.ImageCollection('MODIS/061/MYD13A1').select('EVI')

# Define reference conditions from the first 10 years of data.
reference = collection.filterDate('2001-01-01', '2010-12-31').sort(
    # Sort chronologically in descending order.
    'system:time_start',
    False,
)

# Compute the mean of the first 10 years.
mean = reference.mean()

# Compute anomalies by subtracting the 2001-2010 mean from each image in a
# collection of 2011-2014 images. Copy the date metadata over to the
# computed anomaly images in the new collection.
series = collection.filterDate('2011-01-01', '2014-12-31').map(
    lambda image: image.subtract(mean).set(
        'system:time_start', image.get('system:time_start')
    )
)

# Display cumulative anomalies.
m = geemap.Map()
m.set_center(-100.811, 40.2, 5)
m.add_layer(
    series.sum(),
    {'min': -60000, 'max': 60000, 'palette': ['FF0000', '000000', '00FF00']},
    'EVI anomaly',
)
display(m)

# Get the timestamp from the most recent image in the reference collection.
time_0 = reference.first().get('system:time_start')

# Use imageCollection.iterate() to make a collection of cumulative anomaly over time.
# The initial value for iterate() is a list of anomaly images already processed.
# The first anomaly image in the list is just 0, with the time_0 timestamp.
first = ee.List([
    # Rename the first band 'EVI'.
    ee.Image(0)
    .set('system:time_start', time_0)
    .select([0], ['EVI'])
])

# This is a function to pass to Iterate().
# As anomaly images are computed, add them to the list.
def accumulate(image, list):
  # Get the latest cumulative anomaly image from the end of the list with
  # get(-1).  Since the type of the list argument to the function is unknown,
  # it needs to be cast to a List.  Since the return type of get() is unknown,
  # cast it to Image.
  previous = ee.Image(ee.List(list).get(-1))
  # Add the current anomaly to make a new cumulative anomaly image.
  added = image.add(previous).set(
      # Propagate metadata to the new image.
      'system:time_start',
      image.get('system:time_start'),
  )
  # Return the list with the cumulative anomaly inserted.
  return ee.List(list).add(added)

# Create an ImageCollection of cumulative anomaly images by iterating.
# Since the return type of iterate is unknown, it needs to be cast to a List.
cumulative = ee.ImageCollection(ee.List(series.iterate(accumulate, first)))

# Predefine the chart titles.
title = 'Cumulative EVI anomaly over time'

# Chart some interesting locations.
def display_chart(region, collection):
  reduced = (
      collection.filterBounds(region)
      .sort('system:time_start')
      .map(
          lambda image: ee.Feature(
              None,
              image.reduceRegion(ee.Reducer.first(), region, 500).set(
                  'time', image.get('system:time_start')
              ),
          )
      )
  )
  reduced_dataframe = ee.data.computeFeatures(
      {'expression': reduced, 'fileFormat': 'PANDAS_DATAFRAME'}
  )
  alt.Chart(reduced_dataframe).mark_line().encode(
      alt.X('time:T').title('Time'),
      alt.Y('EVI:Q').title('Cumulative EVI anomaly'),
  ).properties(title=title).display()

pt_1 = ee.Geometry.Point(-65.544, -4.894)
display('Amazon rainforest:')
display_chart(pt_1, cumulative)

pt_2 = ee.Geometry.Point(116.4647, 40.1054)
display('Beijing urbanization:')
display_chart(pt_2, cumulative)

pt_3 = ee.Geometry.Point(-110.3412, 34.1982)
display('Arizona forest disturbance and recovery:')
display_chart(pt_3, cumulative)

ترسیم این توالی‌ها نشان می‌دهد که آیا NDVI نسبت‌به اختلالات قبلی درحال تثبیت است یا اینکه NDVI به حالت جدیدی گرایش دارد. درباره نمودارها در Earth Engine در بخش «نمودارها» بیشتر بدانید.

تابع تکرارشده در عملیاتی که می‌تواند انجام دهد محدود است. به‌طور مشخص، نمی‌تواند متغیرهای خارج از تابع را اصلاح کند؛ نمی‌تواند چیزی را چاپ کند؛ نمی‌تواند از عبارت‌های «if» یا «for» جاوا اسکریپت استفاده کند. هر نتیجه‌ای که می‌خواهید جمع‌آوری کنید یا اطلاعات واسطه‌ای که می‌خواهید به تکرار بعدی منتقل کنید باید در مقدار برگشتی تابع باشد. می‌توانید از `ee.Algorithms.If()` برای انجام عملیات شرطی استفاده کنید.