Google Earth Engine(GEE) 多点像素值导出到CSV文件

本文以分享GEE知识为目的,感谢原作者的支持:)。转自博客:https://dancingchild.github.io/2022/08/09/%E5%83%8F%E7%B4%A0%E5%80%BC%E5%AF%BC%E5%87%BA%E5%88%B0csv/

前言

对于研究区为点数据时,有时我们只想知道影像在这一点的像素值,比如计算某点的NDVI变化,或者查看多个点的NDVI空间异质性。如果导出图像比较麻烦(毕竟我们只要一个点的数据),因此可以直接将像素值导出到文本文件(csv)中,省得提交多个任务,然后下载csv处理。 这里关键使用的函数就是sampleRegions()

1、单个点的导出

var img_value = img.sampleRegions({
    collection:feature_region,
    properties:ee.List(['name']),
    scale:30
    })

以上代码,可以从给定的 feature_region 中,计算每个像素的值,导出到一个FeatureCollection 中,之后再使用Export.table.toDrive()函数,得到包含每个像素值的csv文件。

2、多个像素点导出

如果是多个点,那么只要使用迭代,将每次得到的FeatureCollection merge 一下,就可以得到多个点的csv文件:

function fill(feature,ini){
    var feature_region = XX // point region
    var img = XX // your image 
    var inift = ee.FeatureCollection(ini) // inital file
    var img_value = img.sampleRegions({ 
    collection:feature_region,
    properties:ee.List(['name']),
    scale:30
    });
    return inift.merge(ft3) 
  };

// 不推荐使用for 循环,推荐使用iterate 遍历,第一个参数为function,第二个参数为the initial state.
  var ft2011 = ee.FeatureCollection(ee.List([]))
  var datalist2011 = table2011.toList(1234);
  var fts_data2011 = ee.FeatureCollection(datalist2011);
  var newft2011 = fts_data2011.iterate(fill,ft2011);
  
  Export.table.toDrive({
    collection: newft2011,
    description: 'BioDiversity_2011_AnnualData',
    fileFormat: 'CSV'
  });

上面的代码,如果点数量较少,一切都好说,但是如果有上千个点,那就遇到一个问题: merge()函数的问题,因为我们没循环一个点,就把新计算得到的featureCollection 与之前的FeatureCollection merge 一下。系统在每次merge的时候会自动在系统index前面加个_1。这就意味着如果多次merge,那么每行数据的index名字会特别长,之后就会报错了:

merge() is too deeply nested.

这个时候就得用列表+.flatten() 函数了 具体代码如下:

function GetData2016(point, collection_date){
  var AApoint = ee.Geometry.Point(point)
  var region_Rec =  AApoint.buffer(40);
  var start_time = collection_date.advance(-20,'day');
  var end_time = collection_date.advance(20,'day');
  var L8DateImg= ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
      .filterBounds(region_Rec)
      .filterDate(start_time, end_time)
      .map(maskL8sr)
      .map(L8imgRename)
      .map(addVariables)
      // .mean().clip(region_Rec);
  return L8DateImg
}

function GetData2011(point, collection_date){
  var AApoint = ee.Geometry.Point(point)
  var region_Rec =  AApoint.buffer(40);
  var start_time = collection_date.advance(-20,'day');
  var end_time = collection_date.advance(20,'day');
  var L7DateImg= Landsat7
      .filterBounds(region_Rec)
      .filterDate(start_time, end_time)
      .map(maskL457sr)
      .map(L7imgRename)
      .map(addVariables)
  return L7DateImg
}

function fill2016(feature,ini){
  var point_1 = feature.get('LON_ANALYS')
  var point_2 = feature.get('LAT_ANALYS')
  var point = ee.List([point_1, point_2])
  var collection_date = feature.get('DATE_COL')
  var ymd = ee.Date.parse('MM/dd/yyyy',collection_date)
  var UID = feature.get('UID')
  var AApoint = ee.Geometry.Point(point);
  var region_Rec =  AApoint.buffer(40);
  var feature_region = ee.FeatureCollection(ee.Feature(region_Rec).set('UID',UID));
  var imgCollection = GetData2016(point, ymd)
  return ee.Algorithms.If({
      condition: imgCollection.size().gt(0),
      trueCase: getValue(imgCollection, feature_region, UID, ini),
      falseCase: returnIni(ini),
    })
  
}

function getValue(imgCollection, feature_region, UID, ini){
var img = imgCollection.mean().clip(feature_region);
  var ft2 = img.sampleRegions({
      collection:feature_region,
      properties:ee.List(['UID']),
      scale:30})
  var ft3 = ft2.map(function(f){return f.set("UID", UID)})
  var newlist = ee.List(ini).add(ee.Feature(ft3))
  return newlist
}

function returnIni(ini){
  return  ee.List(ini)
}

function fill2011(feature,ini){
  var point_1 = feature.get('AA_CENTER_LON')
  var point_2 = feature.get('AA_CENTER_LAT')
  var point = ee.List([point_1, point_2])
  var UID = feature.get('UID')
  var collection_date = feature.get('DATE_COL')
  var ymd = ee.Date.parse('MM/dd/yyyy',collection_date)
  var AApoint = ee.Geometry.Point(point);
  var region_Rec =  AApoint.buffer(40);
  var feature_region = ee.FeatureCollection(ee.Feature(region_Rec).set('UID',UID));
  var imgCollection = GetData2011(point, ymd)
  return ee.Algorithms.If({
          condition: imgCollection.size().gt(0),
          trueCase: getValue(imgCollection, feature_region, UID, ini),
          falseCase: returnIni(ini),
        })
}

function L8imgRename(img){
  return img.select(
                      ['SR_B1','SR_B2','SR_B3','SR_B4','SR_B5','SR_B6','SR_B7']
                      ,['aerosol', 'blue', 'green', 'red','nir','swir1','swir2']
                    );
};

function L7imgRename(img){
  return img.select(
                      ['SR_B1','SR_B2','SR_B3','SR_B4','SR_B5','SR_B7']
                      ,['blue', 'green', 'red','nir','swir1','swir2']
                    );
};

function addVariables(image) {
  return image
    // Add a NDVI band.
    .addBands(image.normalizedDifference(['nir', 'red']).toDouble().rename('NDVI'))
    // Add a EVI band.
    .addBands(image.expression('2.5*((nir-red)/(nir+6*red-7.5*blue+1))', {
      'nir':image.select('nir'),
      'red':image.select('red'),
      'blue':image.select('blue')
    }).toDouble().rename('EVI'))
// Add a GCVI: Green Chlorophyll Vegetation Index (Guan Kaiyu, Wang Sherrie)
    .addBands(image.expression('nir/green-1',{
      'nir': image.select('nir'),
      'green': image.select('green'),
    }).toDouble().rename('GCVI'))
    // Add a MSAVI2: Modified Soil-adjusted Vegetation Index (Qi et al. (1994b))
    .addBands(image.expression('1/2 * (2*nir + 1 - ((2*nir+1)**2 - 8*(nir-red))**(1/2))',{
      'nir': image.select('nir'),
      'red': image.select('red'),
    }).toDouble().rename('MSAVI2'))  
    // Add a LSWI band.
    .addBands(image.normalizedDifference(['nir','swir1']).toDouble().rename('LSWI'))
    // Add a NDWI band.
    .addBands(image.normalizedDifference(['green','nir']).toDouble().rename('NDWI'))
    // Add a NDSI band.
    .addBands(image.normalizedDifference(['green','swir1']).toDouble().rename('NDSI'))
    
    // Add NDSVI: normalized differential senescent vegetation index (Zhong,2014)
    .addBands(image.normalizedDifference(['swir1','red']).toDouble().rename('NDSVI'))
    // Add NDTI: normalized differential tillage index, relates to residue cover (Zhong,2014)
    .addBands(image.normalizedDifference(['swir1','swir2']).toDouble().rename('NDTI'))

};

function maskL8sr(image) {
  // Bit 0 - Fill
  // Bit 1 - Dilated Cloud
  // Bit 2 - Cirrus
  // Bit 3 - Cloud
  // Bit 4 - Cloud Shadow
  var qaMask = image.select('QA_PIXEL').bitwiseAnd(parseInt('11111', 2)).eq(0);
  var saturationMask = image.select('QA_RADSAT').eq(0);

  // Apply the scaling factors to the appropriate bands.
  var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
  var thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0);

  // Replace the original bands with the scaled ones and apply the masks.
  return image.addBands(opticalBands, null, true)
      .addBands(thermalBands, null, true)
      .updateMask(qaMask)
      .updateMask(saturationMask);
}

function maskL457sr(image) {
  // Bit 0 - Fill
  // Bit 1 - Dilated Cloud
  // Bit 2 - Unused
  // Bit 3 - Cloud
  // Bit 4 - Cloud Shadow
  var qaMask = image.select('QA_PIXEL').bitwiseAnd(parseInt('11111', 2)).eq(0);
  var saturationMask = image.select('QA_RADSAT').eq(0);

  // Apply the scaling factors to the appropriate bands.
  var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
  var thermalBand = image.select('ST_B6').multiply(0.00341802).add(149.0);

  // Replace the original bands with the scaled ones and apply the masks.
  return image.addBands(opticalBands, null, true)
      .addBands(thermalBand, null, true)
      .updateMask(qaMask)
      .updateMask(saturationMask);
}


// 主函数开始:

var ft = ee.List([])
var datalist = table.toList(table.size());//table.size()
var fts_data = ee.FeatureCollection(datalist);
var newft = fts_data.iterate(fill2016,ft);
var newftnew = ee.List(newft)
var totabel_ite = ee.FeatureCollection(newftnew).flatten();

Export.table.toDrive({
collection: totabel_ite,
description: 'BioDiversity_2016_CollectionDate',
fileFormat: 'CSV'
});
  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值