【问题标题】:Translation of Google Earth Engine javascript functions to python functions谷歌地球引擎javascript函数到python函数的翻译
【发布时间】:2021-04-21 01:01:21
【问题描述】:

我正在努力将一个 JavaScript 地球引擎例程转换为来自此材料 here 的 Python

javascript如下我已经包含了上下文的输入集合。

var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
    .filterBounds(roi)
    .filterDate('2016-01-01', '2016-12-31');

// Load an Earth Engine table.
var blocks = ee.FeatureCollection('TIGER/2010/Blocks');
var subset = blocks.filterBounds(roi);
print('Size of Census blocks subset', subset.size()); // 409


var triplets = l8.map(function(image) {
  return image.select('B1').reduceRegions({
    collection: subset.select(['blockid10']), 
    reducer: ee.Reducer.mean(), 
    scale: 30
  }).filter(ee.Filter.neq('mean', null))
    .map(function(f) { 
      return f.set('imageId', image.id());
    });
}).flatten();

我有点卡住的部分是变量triplets的转换,其中包括各种嵌套例程。我的python版本返回错误:

Unrecognized argument type to convert to a FeatureCollection: {'collection': <ee.featurecollection.FeatureCollection object at 0x7f29fb0e2b80>, 'reducer': <ee.Reducer object at 0x7f29fb10e670>, 'scale': 30}

问题似乎出在 map(imfunc) 上,我认为这是因为我把 python 函数弄错了。

def imfunc(image):
  return image.select('B1').reduceRegions({
    'collection': subset.select(['blockid10']),
    'reducer': ee.Reducer.mean(),
    'scale': 30})

def wrapf(f):
    return f.set('imageId', image.id())

triplets = l8.map(imfunc).filter(ee.Filter.neq('mean', {})).map(wrapf).flatten()

任何人都可以阐明我在 python 转换中出错的地方吗?

【问题讨论】:

    标签: javascript python google-earth-engine


    【解决方案1】:

    在原始代码中,.filter(...).map(wrapf) 应用于reduceRegions 的结果。在您翻译的代码中,您将其应用于l8.map() 的结果,即外部集合而不是内部集合,因为您没有将其保留在外部map 函数中。

    这是一个更正的翻译:

    def imfunc(image):
      return (image.select('B1')
        .reduceRegions(
          collection=subset.select(['blockid10']),
          reducer=ee.Reducer.mean(),
          scale=30
        )
        .filter(ee.Filter.neq('mean', None))
        .map(wrapf))
    
    def wrapf(f):
        return f.set('imageId', image.id())
    
    triplets = l8.map(imfunc).flatten()
    

    我还修复了 reduceRegions 的参数,以使用 Python 风格的命名参数而不是字典(这是必要的)。可能还有其他我没有修复的错误——我没有测试过这段代码——但我希望它有助于学习如何翻译。

    请注意,您不需要将每个函数更改为命名函数。而不是.map(wrapf) ,你可以使用.map(lambda f: f.set('imageId', image.id())))

    【讨论】:

    • 非常感谢 - wrapf 不工作,但匿名。 lambda 函数可以 - 我试图编辑你的答案,但它似乎没有工作/被批准。
    • @crEO 它应该与编写的相同,因此您运行的实际代码会发生其他事情。你看到了什么错误? (您的编辑是rejected by reviewers。)
    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 2022-01-09
    • 2022-01-13
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多