//sentinel2 NDVI Demo
//方法一:普通方式,通过将数学公式翻译为代码直接计算
function NDVI_V1(img) {
var nir = img.select("B8");
var red = img.select("B4");
var ndvi = nir.subtract(red).divide(nir.add(red));
return ndvi;
}
//方法二:将计算公式直接带入,通过解析字符串实现计算。这种方式更加灵活,在某些特殊情况下非常好用,而且非常直观。
function NDVI_V2(img) {
var nir = img.select("B8");
var red = img.select("B4");
var ndvi = img.expression(
"(B5 - B4)/(B5 + B4)",
{
"B5": nir,
"B4": red
}
);
return ndvi;
}
//方法三:GEE将计算公式封装为一个方法可以直接调用
function NDVI_V3(img) {
var ndvi = img.normalizedDifference(["B8","B4"]);
return ndvi;
}
//sentinel2 and roi
var s2_col = ee.ImageCollection("COPERNICUS/S2");
var roi = ee.Geometry.Point([117.0703125,38.09133660751176]);
var img = ee.Image(s2_col.filterBounds(roi)
.filterDate("2017-01-01", "2017-09-24")
.first());
var ndvi1 = NDVI_V1(img);
var ndvi2 = NDVI_V2(img);
var ndvi3 = NDVI_V3(img);
var visParam = {
min: -0.2,
max: 0.8,
palette: 'FFFFFF, CE7E45, DF923D, F1B555, FCD163, 99B718, 74A901, 66A000, 529400,' +
'3E8601, 207401, 056201, 004C00, 023B01, 012E01, 011D01, 011301'
};
Map.addLayer(img, {bands:["B8", "B4", "B3"], max:3048}, "raw_img");
Map.addLayer(ndvi1, visParam, "ndvi_1");
Map.addLayer(ndvi2, visParam, "ndvi_2");
Map.addLayer(ndvi3, visParam, "ndvi_3");
Map.centerObject(roi, 9);
//show charts
var ndvi_list = s2_col.filterDate("2017-01-01", "2017-09-24")
.map(function(image) {
var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI');
return image.addBands(ndvi);
});
//展示每一张影像NDVI值
var chart1 = ui.Chart.image.series({
//影像集合
imageCollection: ndvi_list.select('NDVI'),
//关心区域
region: roi,
//关心区域计算方式,这里采用的是均值。也就是比如roi是一个矩形,
//那么在图表中这个点的值就是矩形内所有像素值求平均。
reducer: ee.Reducer.mean(),
//分辨率
scale: 30
}).setOptions({title: 'NDVI IMAGE SERIES'});
print(chart1);
//展示每一天所关心区域的NDVI值
var chart2 = ui.Chart.image.doySeries({
imageCollection: ndvi_list.select('NDVI'),
region:roi,
regionReducer: ee.Reducer.mean(),
scale:30
}).setOptions({title: "ROI NDVI EACH DAY SERIES"})
print(chart2)