求在GEE上用SAM提取赣南果园面积的代码,包括验证,导出数据,时间紧迫
下面是SAM提取赣南果园面积的代码示例,其中我使用的是Sentinel-2影像。你根据自己的实际情况进行调整和修改。
// 导入SAM和GEE库
var sam = require('users/sofiaermida/landsat_smoothing:modules/SAM');
var ee = require('users/fitoprincipe/geetools:cloud_masks').ee;
// 设置区域和时间范围
var roi = ee.Geometry.Polygon([[113.441, 24.932], [116.510, 25.013], [116.572, 28.215], [113.503, 28.143]]);
var startDate = '2019-01-01';
var endDate = '2019-12-31';
// 加载Sentinel-2影像
var s2Collection = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(roi)
.filterDate(startDate, endDate)
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 10))
.map(function(img) {
var cloudMask = ee.Algorithms.Landsat.simpleCloudScore(img).select('cloud').gte(50);
var clearImg = img.updateMask(cloudMask.not());
return clearImg;
})
.select(['B4', 'B3', 'B2', 'B8']);
// 提取样本点
var samplePoints = ee.FeatureCollection('users/your_username/sample_points');
// 为每个样本点提取相应的像素值和类别
var trainingData = s2Collection.map(function(img) {
var bands = ["B2","B3","B4","B8"];
var classField = "class";
var pointData = img.sampleRegions({
collection: samplePoints,
properties: [classField],
scale: 10
});
return pointData;
}).flatten();
// 拆分训练和测试数据集
var [training, testing] = trainingData.randomColumn('random').split(0.8);
// 训练模型
var classifier = sam.trainClassifier({
trainingData: training,
bands: ["B2","B3","B4","B8"],
classProperty: "class",
eeBatchSize: 5000,
nTrees: 200,
bagFraction: 0.5,
randomSeed: 0
});
// 验证模型
var confusionMatrix = sam.testClassifier({
classifier: classifier,
testData: testing,
classProperty: "class"
});
// 输出混淆矩阵
print("Confusion matrix", confusionMatrix);
// 导出影像面积
var s2Image = s2Collection.median();
var area = s2Image.multiply(ee.Image.pixelArea()).reduceRegion({
reducer: ee.Reducer.sum(),
geometry: roi,
});
print('Area of region (m^2):', area.get('B2'));
// 导出训练数据集
Export.table.toDrive({
collection: trainingData,
description: 'training_data',
fileFormat: 'CSV'
});
// 导出模型
Export.table.toAsset({
collection: ee.FeatureCollection(classifier),
description: 'sam_model',
assetId: 'sam_model'
});
还有就是,代码中的样本点需要根据实际情况进行提取和调整,同时也需要更新训练集和验证集的比例。最后,在导出数据之前请确保有足够的存储空间。
引用chatGPT作答,以下是在Google Earth Engine (GEE)上使用不同的算法提取果园面积并进行验证的代码示例:
1.支持向量机 (SVM):
// 定义 AOI (感兴趣区域)
var aoi = ee.Geometry.Rectangle([xmin, ymin, xmax, ymax]);
// 加载 Landsat 8 遥感影像
var l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
.filterBounds(aoi)
.filterDate('2018-01-01', '2018-12-31');
// 加载水果园地物分类样本点
var orchardSamples = ee.FeatureCollection('users/your_username/orchard_samples');
// 选择要素属性和分类标签
var bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
var label = 'class';
// 将样本数据集拆分为训练和测试数据集
var split = 0.7;
var training = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 0,
geometries: true
}).filterMetadata('random', 'less_than', split);
var testing = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 1,
geometries: true
}).filterMetadata('random', 'not_less_than', split);
// 训练分类器
var classifier = ee.Classifier.libsvm({
kernelType: 'RBF',
gamma: 0.5,
cost: 10
}).train({
features: training,
classProperty: label,
inputProperties: bands
});
// 对测试数据进行分类
var classified = l8.select(bands).classify(classifier);
// 将分类结果可视化
Map.addLayer(classified, {min: 0, max: 1, palette: ['green', 'red']}, 'SVM Classification');
// 计算混淆矩阵和精度
var testAccuracy = testing
.classify(classifier)
.errorMatrix(label, 'classification')
.accuracy();
print('SVM Test Accuracy: ', testAccuracy);
// 提取果园面积
var orchardArea = classified.eq(1).multiply(ee.Image.pixelArea()).divide(1e4)
.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: aoi,
scale: 30,
maxPixels: 1e9
});
print('Orchard Area (ha): ', orchardArea);
2.谱角匹配 (SAM):
// 定义 AOI (感兴趣区域)
var aoi = ee.Geometry.Rectangle([xmin, ymin, xmax, ymax]);
// 加载 Landsat 8 遥感影像
var l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
.filterBounds(aoi)
.filterDate('2018-01-01', '2018-12-31');
// 加载水果园地物分类样本点
var orchardSamples = ee.FeatureCollection('users/your_username/orchard_samples');
// 选择要素属性和分类标签
var bands = ['B2','B3', 'B4', 'B5', 'B6', 'B7'];
var label = 'class';
// 将样本数据集拆分为训练和测试数据集
var split = 0.7;
var training = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 0,
geometries: true
}).filterMetadata('random', 'less_than', split);
var testing = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 1,
geometries: true
}).filterMetadata('random', 'not_less_than', split);
// 训练分类器
var classifier = ee.Classifier.sam({
kernelType: 'linear',
nSamplings: 10,
scale: 100
}).train({
features: training,
classProperty: label,
inputProperties: bands
});
// 对测试数据进行分类
var classified = l8.select(bands).classify(classifier);
// 将分类结果可视化
Map.addLayer(classified, {min: 0, max: 1, palette: ['green', 'red']}, 'SAM Classification');
// 计算混淆矩阵和精度
var testAccuracy = testing
.classify(classifier)
.errorMatrix(label, 'classification')
.accuracy();
print('SAM Test Accuracy: ', testAccuracy);
// 提取果园面积
var orchardArea = classified.eq(1).multiply(ee.Image.pixelArea()).divide(1e4)
.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: aoi,
scale: 30,
maxPixels: 1e9
});
print('Orchard Area (ha): ', orchardArea);
3.随机森林 (RF):
// 定义 AOI (感兴趣区域)
var aoi = ee.Geometry.Rectangle([xmin, ymin, xmax, ymax]);
// 加载 Landsat 8 遥感影像
var l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
.filterBounds(aoi)
.filterDate('2018-01-01', '2018-12-31');
// 加载水果园地物分类样本点
var orchardSamples = ee.FeatureCollection('users/your_username/orchard_samples');
// 选择要素属性和分类标签
var bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
var label = 'class';
// 将样本数据集拆分为训练和测试数据集
var split = 0.7;
var training = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 0,
geometries: true
}).filterMetadata('random', 'less_than', split);
var testing = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 1,
geometries: true
}).filterMetadata('random', 'not_less_than', split);
// 训练分类器
var classifier = ee.Classifier.randomForest({
numberOfTrees: 100,
variablesPerSplit: 6,
minLeafPopulation
var classified = l8.select(bands).classify(classifier);
// 将分类结果可视化
Map.addLayer(classified, {min: 0, max: 1, palette: ['green', 'red']}, 'RF Classification');
// 计算混淆矩阵和精度
var testAccuracy = testing
.classify(classifier)
.errorMatrix(label, 'classification')
.accuracy();
print('RF Test Accuracy: ', testAccuracy);
// 提取果园面积
var orchardArea = classified.eq(1).multiply(ee.Image.pixelArea()).divide(1e4)
.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: aoi,
scale: 30,
maxPixels: 1e9
});
print('Orchard Area (ha): ', orchardArea);
// 定义 AOI (感兴趣区域)
var aoi = ee.Geometry.Rectangle([xmin, ymin, xmax, ymax]);
// 加载 Landsat 8 遥感影像
var l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
.filterBounds(aoi)
.filterDate('2018-01-01', '2018-12-31');
// 加载水果园地物分类样本点
var orchardSamples = ee.FeatureCollection('users/your_username/orchard_samples');
// 选择要素属性和分类标签
var bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
var label = 'class';
// 将样本数据集拆分为训练和测试数据集
var split = 0.7;
var training = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 0,
geometries: true
}).filterMetadata('random', 'less_than', split);
var testing = orchardSamples.sample({
region: aoi,
scale: 30,
numPixels: 500,
seed: 1,
geometries: true
}).filterMetadata('random', 'not_less_than', split);
// 定义卷积神经网络模型
var model = ee.Model.fromSavedModel({
modelUrl: 'users/your_username/cnn_model',
inputNames: ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'],
outputNames: ['class'],
})
.setOutputType('class');
// 训练分类器
var classifier = ee.Classifier.constant({
'class': model
}).train({
features: training,
classProperty: label,
inputProperties: bands
});
// 对测试数据进行分类
var classified = l8.select(bands).classify(classifier);
// 将分类结果可视化
Map.addLayer(classified, {min: 0, max: 1, palette: ['green', 'red']}, 'CNN Classification');
// 计算混淆矩阵和精度
var testAccuracy = testing
.classify(classifier)
.errorMatrix(label, 'classification')
.accuracy();
print('CNN Test Accuracy: ', testAccuracy);
// 提取果园面积
var orchardArea = classified.eq(1).multiply(ee.Image.pixelArea()).divide(1e4)
.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: aoi,
scale: 30,
maxPixels: 1e9
});
print('Orchard Area (ha): ', orchardArea);
注意:在上述代码中,需要将 your_username
替换为您的用户名,并确保您已经将分类器和模型保存在您的 Google Drive 中,并将其添加到 GEE 中。
此外,需要注意的是,每种分类算法的超参数设置和模型架构都可能有所不同,需要根据实际情况进行调整和优化。这些代码只是给出了一个基本的示例,希望能够帮助您入门。
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
使用SAM提取果园面积,需要进行以下步骤:
// 选择区域
var roi = ee.Geometry.Polygon([
[[114.05, 25.4], [114.05, 24.9], [114.6, 24.9], [114.6, 25.4]]
]);
// 获取训练样本
var training = ee.FeatureCollection("users/用户名/样本数据集");
// 训练SAM分类器
var classifier = ee.Classifier.SAM().train(training, "class");
// 应用分类器到区域
var classified = ee.Image("COPERNICUS/S2_SR/20181107T032251_20181107T033249_T49QEF").classify(classifier);
Map.addLayer(classified, {min: 0, max: 3, palette: ['white', 'red', 'green', 'blue']}, 'Classification');
// 对 NDVI 进行阈值处理
var ndvi = ee.Image("COPERNICUS/S2_SR/20181107T032251_20181107T033249_T49QEF").normalizedDifference(['B8', 'B4']).rename('ndvi');
var mask = ndvi.gt(0.5);
// 裁剪分类结果
var roiImage = ee.Image(0).updateMask(mask).clip(roi);
var classifiedMasked = classified.updateMask(roiImage);
// 创建蒙版
var mask = classifiedMasked.eq(1).or(classifiedMasked.eq(2));
Map.addLayer(mask, {}, 'Mask');
// 计算果园面积
var area_m2 = mask.multiply(ee.Image.pixelArea()).reduceRegion({
reducer: ee.Reducer.sum(),
geometry: roi,
scale: 10,
maxPixels: 1e13,
}).get('classification');
print('果园面积:', area_m2);
// 验证结果
var validation = classifiedMasked.sample({
region: roi,
scale: 10,
numPixels: 500,
geometries: true
});
var errorMatrix = validation.errorMatrix({
referenceColumn: 'class',
predictionColumn: 'classification'
});
var acc = errorMatrix.accuracy();
var kappa = errorMatrix.kappa();
print('Accuracy: ', acc);
print('Kappa: ', kappa);
print('Error Matrix: ', errorMatrix);
// 导出数据
Export.image.toDrive({
image: mask,
description: 'FruitOrchardMask',
scale: 10,
region: roi,
maxPixels: 1e13
});
注意:代码中的训练样本和光学遥感影像需要根据实际需求进行更改。另外,代码中使用了Sentinel-2的影像数据,如果需要使用其他卫星数据,需要进行更改。
如果我的回答解决了您的问题,请采纳!