基于GEE使用Landsat 8和Landsat 5影像进行分类

2018年Landsat 8 影像分类

//数据集筛选 
var dataset1 = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
     .filterDate('2018-x-x', '2018-x-x')
     .filterBounds(roi)
     .filter(ee.Filter.lte('CLOUD_COVER',5))//云量设置
     .sort('CLOUD_COVER')//按云量排序
print(dataset1) 
var mos=dataset1.mosaic()
var image1 = mos.clip(roi)
print(image1,'lan')
//显示shp边界
Map.addLayer(roi,{color:'yellow',fillColor: "00000000", width: 1},'Naiman Boundary');

//显示ROI影像并且以321合成,后面命名
Map.addLayer(image1, {min: 0.0, max: 0.2, bands: ['SR_B4', 'SR_B3', 'SR_B2'],}, 'image432');

//外部导入的水体数据,去除影像集的水体
var jrc = jrcwater.select('b1')
var image = image1.updateMask(jrc.eq(1))
Map.addLayer(image, {min: 0.0, max: 0.2, bands: ['SR_B4', 'SR_B3', 'SR_B2'],}, 'image');

//index calculate
//var mndwi = image.normalizedDifference(['SR_B3', 'SR_B6']).rename('MNDWI');//计算MNDWI
var ndbi = image.normalizedDifference(['SR_B6', 'SR_B5']).rename('NDBI');//计算NDBI
var ndvi = image.normalizedDifference(['SR_B5', 'SR_B4']).rename('NDVI');//计算NDVI
var ndwi = image.normalizedDifference(['SR_B3', 'SR_B5']).rename('NDWI');//计算NDWI
var lswi = image.normalizedDifference(['SR_B5','SR_B6']).rename('LSWI')//计算冠层植被光曾冠层植被水份
var nbr2 = image.normalizedDifference(["SR_B6", "SR_B7"]).rename("NBR2")
//var baem = image.expression(
//'NDBI-NDVI-MNDWI', {
//'NDBI': ndbi,
//'NDVI': ndvi,
//'MNDWI':mndwi
//}).rename('BAEM')

var evi = image.expression(
'2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
'NIR': image.select('SR_B5'),
'RED': image.select('SR_B4'),
'BLUE': image.select('SR_B2')
}).rename('EVI')

var rri = image.expression(
'BLUE/NIR', {
'NIR': image.select('SR_B5'),
'BLUE': image.select('SR_B2')
}).rename('RRI')

var awei = image.expression(
              '4*(green-SWIR1)-(0.25*NIR+2.75*SWIR2)',{
              green:image.select('SR_B3'),
              NIR:image.select('SR_B5'),
              SWIR1:image.select('SR_B6'),
              SWIR2:image.select('SR_B7'),
            }).float().rename('AWEI')

var dem_roi = dem.select('elevation').clip(roi).rename('DEM');
var nightlight = ee.ImageCollection("NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG")
                  .filterDate('2018-06-01','2018-08-01'); 
print(nightlight)
var nightlights2018 = ee.Image(nightlight.mean()).select("avg_rad").clip(roi).rename('NIGHTLIGHT');

//NDVI glcm纹理特征 
Map.addLayer(ndvi,{min:-1,max:1},'ndvi');

var input = ndvi.add(127.5).multiply(127.5).toUint16()
Map.addLayer(input, {min:16291,max:16300}, 'GLCM input');

print(input.reduceRegion(ee.Reducer.stdDev(), roi, 30).get('NDVI'))

var glcm = input.glcmTexture({size: 4});
print(glcm,'glcm')
var savg = glcm.select('NDVI_savg').rename('SAVG')
var va = glcm.select('NDVI_var').rename('VA')
var con = glcm.select('NDVI_contrast').rename('CON')

//Map.addLayer(glcm.select('NDVI_savg'),{min:32582,max:32591}, 'GLCM output (SAVG)');
//Map.addLayer(glcm.select('NDVI_var'),{min:0,max:20}, 'GLCM output (VAR)');

image=image
      //.addBands(ndvi)
      .addBands(ndbi)
      //.addBands(mndwi)
      .addBands(ndwi)
     // .addBands(baem)
      .addBands(evi)
      .addBands(rri)
      //.addBands(awei)
      .addBands(lswi)
      .addBands(nbr2)
      .addBands(dem_roi)
      .addBands(nightlights2018)
      .addBands(savg)
      //.addBands(water_index)
      .addBands(va)
      .addBands(con)

image=image.clip(roi)

//融合外部导入的样本数据

var classNames = cao.merge(geng).merge(jian).merge(lin).merge(qita)
var bands = ['SR_B2', 'SR_B3','SR_B4','SR_B5', 'SR_B6','EVI','RRI','LSWI','NBR2','DEM','NIGHTLIGHT','SAVG','VA','CON'];
var training = image.select(bands).sampleRegions({
  collection: classNames,
  properties: ['L1'],
  scale: 30
});
print(training,'training');


// random uniforms to the training dataset.
var withRandom = training.randomColumn('random');//样本点随机的排列
// 我们想保留一些数据进行测试,以避免模型过度拟合。
var split = 0.7; 
var trainingPartition = withRandom.filter(ee.Filter.lt('random', split));//筛选70%的样本作为训练样本
var testingPartition = withRandom.filter(ee.Filter.gte('random', split));//筛选30%的样本作为测试样本

// 选择分类的属性
var classProperty = 'L1';

//分类方法选择smileCart() randomForest() minimumDistance libsvm
var classifier = ee.Classifier.smileRandomForest(35).train({
  features: trainingPartition,
  classProperty: 'L1',
  inputProperties: bands
});
//分类
var classified = image.select(bands).classify(classifier);
//Display the classification map
Map.centerObject(classNames, 11);
// Map.addLayer(classified,
// {min: 0, max: 4, visParams: imageVisParam},
// 'classification');

Map.addLayer(classified, {min:100, max:700, palette:['#f1ea13','#f59d19','#0ba617','#39f12d', '#d63809']}, 'classified')
print(classified,'classified')

//决策树数量选择
var numTrees = ee.List.sequence(10, 100, 10); 
var accuracies = numTrees.map(function(t)

  var classifier = ee.Classifier.smileRandomForest(t)
                    .train({
                features: trainingPartition,
  classProperty: 'L1',
  inputProperties: bands
                    });
  return testingPartition
      .classify(classifier)
      .errorMatrix('L1', 'classification')
      .accuracy();
}); 
print(ui.Chart.array.values({
  array: ee.Array(accuracies),
  axis: 0,
  xLabels: numTrees
}));
//随机森林特征重要性
var dict = classifier.explain();
print('Explain:',dict);
 
var variable_importance = ee.Feature(null, ee.Dictionary(dict).get('importance'));
var chart =
ui.Chart.feature.byProperty(variable_importance)
.setChartType('ColumnChart')
.setOptions({
title: 'Random Forest Variable Importance',
legend: {position: 'none'},
hAxis: {title: 'Bands'},
vAxis: {title: 'Importance'}
});
 
print(chart);


var test = testingPartition.classify(classifier);//运用测试样本分类,确定要进行函数运算的数据集以及函数

var confusionMatrix = test.errorMatrix('L1', 'classification');//计算混淆矩阵
print('confusionMatrix',confusionMatrix);//面板上显示混淆矩阵
print('overall accuracy', confusionMatrix.accuracy());//面板上显示总体精度
print('kappa accuracy', confusionMatrix.kappa());//面板上显示kappa值

Export.image.toDrive({
        image:  classified,//分类结果
        description: 'classified',//文件名
        folder: 'test',
        scale: 30,//分辨率
        region: roi,//区域
        maxPixels:34e10//此处值设置大一些,防止溢出
      });

2000年Landsat 5 影像分类

//数据集筛选 
var dataset1 = ee.ImageCollection('LANDSAT/LT05/C02/T1_L2')
     .filterDate('2000-7-1', '2000-8-1')
     .filterBounds(roi)
     .filter(ee.Filter.lte('CLOUD_COVER',5))//云量设置
     .sort('CLOUD_COVER')//按云量排序
print(dataset1) 
var mos=dataset1.mosaic()
var image1 = mos.clip(roi)
print(image1,'lan')
//显示shp边界
Map.addLayer(roi,{color:'yellow',fillColor: "00000000", width: 1},'Naiman Boundary');

//显示ROI影像并且以321合成,后面命名
Map.addLayer(image1, {min: 0.0, max: 0.2, bands: ['SR_B3', 'SR_B2', 'SR_B1'],}, 'image321');

//外部导入水体,去除影像中的水体数据
var jrc = jrcwater.select('b1')
var image = image1.updateMask(jrc.eq(1))
Map.addLayer(image, {min: 0.0, max: 0.2, bands: ['SR_B3', 'SR_B2', 'SR_B1'],}, 'image');

//index calculate
//var mndwi = image.normalizedDifference(['SR_B3', 'SR_B6']).rename('MNDWI');//计算MNDWI
var ndbi = image.normalizedDifference(['SR_B5', 'SR_B4']).rename('NDBI');//计算NDBI
var ndvi = image.normalizedDifference(['SR_B4', 'SR_B3']).rename('NDVI');//计算NDVI
var ndwi = image.normalizedDifference(['SR_B2', 'SR_B4']).rename('NDWI');//计算NDWI
var lswi = image.normalizedDifference(['SR_B4','SR_B5']).rename('LSWI')//计算冠层植被光曾冠层植被水份
var nbr2 = image.normalizedDifference(["SR_B5", "SR_B7"]).rename("NBR2")
//var baem = image.expression(
//'NDBI-NDVI-MNDWI', {
//'NDBI': ndbi,
//'NDVI': ndvi,
//'MNDWI':mndwi
//}).rename('BAEM')

var evi = image.expression(
'2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
'NIR': image.select('SR_B4'),
'RED': image.select('SR_B3'),
'BLUE': image.select('SR_B1')
}).rename('EVI')

var rri = image.expression(
'BLUE/NIR', {
'NIR': image.select('SR_B4'),
'BLUE': image.select('SR_B1')
}).rename('RRI')

var awei = image.expression(
              '4*(green-SWIR1)-(0.25*NIR+2.75*SWIR2)',{
              green:image.select('SR_B2'),
              NIR:image.select('SR_B4'),
              SWIR1:image.select('SR_B5'),
              SWIR2:image.select('SR_B7'),
            }).float().rename('AWEI')
var dem_roi = dem.select('elevation').clip(roi).rename('DEM');
var nightlight = ee.ImageCollection("NOAA/DMSP-OLS/NIGHTTIME_LIGHTS")
                  .filterDate('2000-01-01','2000-12-1');
print(nightlight)
var nightlights2018 = ee.Image(nightlight.mean()).select("stable_lights").clip(roi).rename('NIGHTLIGHT');

//NDVI glcm纹理特征 

Map.addLayer(ndvi,{min:-1,max:1},'ndvi');

var input = ndvi.add(127.5).multiply(127.5).toUint16()
Map.addLayer(input, {min:16291,max:16300}, 'GLCM input');

print(input.reduceRegion(ee.Reducer.stdDev(), roi, 30).get('NDVI'))

var glcm = input.glcmTexture({size: 4});
print(glcm,'glcm')
var savg = glcm.select('NDVI_savg').rename('SAVG')
var va = glcm.select('NDVI_var').rename('VA')
var con = glcm.select('NDVI_contrast').rename('CON')

//Map.addLayer(glcm.select('NDVI_savg'),{min:32582,max:32591}, 'GLCM output (SAVG)');
//Map.addLayer(glcm.select('NDVI_var'),{min:0,max:20}, 'GLCM output (VAR)');

image=image
      //.addBands(ndvi)
      .addBands(ndbi)
      //.addBands(mndwi)
      .addBands(ndwi)
     // .addBands(baem)
      .addBands(evi)
      .addBands(rri)
      //.addBands(awei)
      .addBands(lswi)
      .addBands(nbr2)
      .addBands(dem_roi)
      .addBands(nightlights2018)
      .addBands(savg)
      //.addBands(water_index)
      .addBands(va)
      .addBands(con)

image=image.clip(roi)

//融合外部导入的样本数据

var classNames = cao.merge(geng).merge(jian).merge(lin).merge(qita)
var bands = ['SR_B1', 'SR_B2','SR_B3','SR_B4', 'SR_B5','EVI','RRI','LSWI','NBR2','DEM','NIGHTLIGHT','SAVG','VA','CON'];
var training = image.select(bands).sampleRegions({
  collection: classNames,
  properties: ['L1'],
  scale: 30
});
print(training,'training');


// random uniforms to the training dataset.
var withRandom = training.randomColumn('random');//样本点随机的排列
// 我们想保留一些数据进行测试,以避免模型过度拟合。
var split = 0.7; 
var trainingPartition = withRandom.filter(ee.Filter.lt('random', split));//筛选70%的样本作为训练样本
var testingPartition = withRandom.filter(ee.Filter.gte('random', split));//筛选30%的样本作为测试样本

// 选择分类的属性
var classProperty = 'L1';

//分类方法选择smileCart() randomForest() minimumDistance libsvm
var classifier = ee.Classifier.smileRandomForest(35).train({
  features: trainingPartition,
  classProperty: 'L1',
  inputProperties: bands
});
//分类
var classified = image.select(bands).classify(classifier);
//Display the classification map
Map.centerObject(classNames, 11);
// Map.addLayer(classified,
// {min: 0, max: 4, visParams: imageVisParam},
// 'classification');

Map.addLayer(classified, {min:100, max:700, palette:['#f1ea13','#f59d19','#0ba617','#39f12d', '#d63809']}, 'classified')
print(classified,'classified')

//决策树数量选择
var numTrees = ee.List.sequence(10, 100, 10); 
var accuracies = numTrees.map(function(t)

  var classifier = ee.Classifier.smileRandomForest(t)
                    .train({
                features: trainingPartition,
  classProperty: 'L1',
  inputProperties: bands
                    });
  return testingPartition
      .classify(classifier)
      .errorMatrix('L1', 'classification')
      .accuracy();
}); 
print(ui.Chart.array.values({
  array: ee.Array(accuracies),
  axis: 0,
  xLabels: numTrees
}));
//随机森林特征重要性
var dict = classifier.explain();
print('Explain:',dict);
 
var variable_importance = ee.Feature(null, ee.Dictionary(dict).get('importance'));
var chart =
ui.Chart.feature.byProperty(variable_importance)
.setChartType('ColumnChart')
.setOptions({
title: 'Random Forest Variable Importance',
legend: {position: 'none'},
hAxis: {title: 'Bands'},
vAxis: {title: 'Importance'}
});
 
print(chart);


var test = testingPartition.classify(classifier);//运用测试样本分类,确定要进行函数运算的数据集以及函数

var confusionMatrix = test.errorMatrix('L1', 'classification');//计算混淆矩阵
print('confusionMatrix',confusionMatrix);//面板上显示混淆矩阵
print('overall accuracy', confusionMatrix.accuracy());//面板上显示总体精度
print('kappa accuracy', confusionMatrix.kappa());//面板上显示kappa值

Export.image.toDrive({
        image:  classified,//分类结果
        description: 'classified',//文件名
        folder: 'test',
        scale: 10,//分辨率
        region: roi,//区域
        maxPixels:34e10//此处值设置大一些,防止溢出
      })

你可能感兴趣的:(分类,googlecloud)