From 50e32cca3b66b7db3265488c105b10a22829d9d2 Mon Sep 17 00:00:00 2001 From: Justin Braaten Date: Fri, 6 Oct 2023 09:09:12 -0700 Subject: [PATCH] Convert API code snippets from JS to Py (misc 1) PiperOrigin-RevId: 571353628 --- .../python/apidocs/ee_classifier_explain.py | 99 +++++++++++++++++ .../python/apidocs/ee_classifier_libsvm.py | 100 ++++++++++++++++++ .../python/apidocs/ee_classifier_smilecart.py | 100 ++++++++++++++++++ .../ee_classifier_smilegradienttreeboost.py | 99 +++++++++++++++++ .../apidocs/ee_classifier_smilenaivebayes.py | 99 +++++++++++++++++ .../ee_classifier_smilerandomforest.py | 99 +++++++++++++++++ .../apidocs/ee_featurecollection_distance.py | 30 ++++++ samples/python/apidocs/ee_image.py | 66 ++++++++++++ samples/python/apidocs/ee_image_classify.py | 99 +++++++++++++++++ samples/python/apidocs/ee_image_clip.py | 57 ++++++++++ samples/python/apidocs/ee_image_mask.py | 40 +++++++ .../apidocs/ee_image_normalizeddifference.py | 29 +++++ .../python/apidocs/ee_image_reduceregion.py | 62 +++++++++++ .../python/apidocs/ee_image_reduceregions.py | 67 ++++++++++++ .../python/apidocs/ee_image_sampleregions.py | 64 +++++++++++ samples/python/apidocs/ee_image_updatemask.py | 62 +++++++++++ .../ee_imagecollection_reducetoimage.py | 40 +++++++ samples/python/apidocs/ee_terrain_products.py | 38 +++++++ samples/python/apidocs/ee_terrain_slope.py | 38 +++++++ .../python/apidocs/export_table_todrive.py | 58 ++++++++++ 20 files changed, 1346 insertions(+) create mode 100644 samples/python/apidocs/ee_classifier_explain.py create mode 100644 samples/python/apidocs/ee_classifier_libsvm.py create mode 100644 samples/python/apidocs/ee_classifier_smilecart.py create mode 100644 samples/python/apidocs/ee_classifier_smilegradienttreeboost.py create mode 100644 samples/python/apidocs/ee_classifier_smilenaivebayes.py create mode 100644 samples/python/apidocs/ee_classifier_smilerandomforest.py create mode 100644 samples/python/apidocs/ee_featurecollection_distance.py create mode 100644 samples/python/apidocs/ee_image.py create mode 100644 samples/python/apidocs/ee_image_classify.py create mode 100644 samples/python/apidocs/ee_image_clip.py create mode 100644 samples/python/apidocs/ee_image_mask.py create mode 100644 samples/python/apidocs/ee_image_normalizeddifference.py create mode 100644 samples/python/apidocs/ee_image_reduceregion.py create mode 100644 samples/python/apidocs/ee_image_reduceregions.py create mode 100644 samples/python/apidocs/ee_image_sampleregions.py create mode 100644 samples/python/apidocs/ee_image_updatemask.py create mode 100644 samples/python/apidocs/ee_imagecollection_reducetoimage.py create mode 100644 samples/python/apidocs/ee_terrain_products.py create mode 100644 samples/python/apidocs/ee_terrain_slope.py create mode 100644 samples/python/apidocs/export_table_todrive.py diff --git a/samples/python/apidocs/ee_classifier_explain.py b/samples/python/apidocs/ee_classifier_explain.py new file mode 100644 index 000000000..1d5064443 --- /dev/null +++ b/samples/python/apidocs/ee_classifier_explain.py @@ -0,0 +1,99 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_classifier_explain] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train a 10-tree random forest classifier from the training sample. +trained_classifier = ee.Classifier.smileRandomForest(10).train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_classifier_explain] diff --git a/samples/python/apidocs/ee_classifier_libsvm.py b/samples/python/apidocs/ee_classifier_libsvm.py new file mode 100644 index 000000000..dba661ced --- /dev/null +++ b/samples/python/apidocs/ee_classifier_libsvm.py @@ -0,0 +1,100 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_classifier_libsvm] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train an SVM classifier (C-SVM classification, voting decision procedure, +# linear kernel) from the training sample. +trained_classifier = ee.Classifier.libsvm().train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_classifier_libsvm] diff --git a/samples/python/apidocs/ee_classifier_smilecart.py b/samples/python/apidocs/ee_classifier_smilecart.py new file mode 100644 index 000000000..d15b12a4d --- /dev/null +++ b/samples/python/apidocs/ee_classifier_smilecart.py @@ -0,0 +1,100 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_classifier_smilecart] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train a CART classifier (up to 10 leaf nodes in each tree) from the +# training sample. +trained_classifier = ee.Classifier.smileCart(10).train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_classifier_smilecart] diff --git a/samples/python/apidocs/ee_classifier_smilegradienttreeboost.py b/samples/python/apidocs/ee_classifier_smilegradienttreeboost.py new file mode 100644 index 000000000..0a1a3cd0d --- /dev/null +++ b/samples/python/apidocs/ee_classifier_smilegradienttreeboost.py @@ -0,0 +1,99 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_classifier_smilegradienttreeboost] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train a 10-tree gradient boosting classifier from the training sample. +trained_classifier = ee.Classifier.smileGradientTreeBoost(10).train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_classifier_smilegradienttreeboost] diff --git a/samples/python/apidocs/ee_classifier_smilenaivebayes.py b/samples/python/apidocs/ee_classifier_smilenaivebayes.py new file mode 100644 index 000000000..89afebb76 --- /dev/null +++ b/samples/python/apidocs/ee_classifier_smilenaivebayes.py @@ -0,0 +1,99 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_classifier_smilenaivebayes] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train a Naive Bayes classifier from the training sample. +trained_classifier = ee.Classifier.smileNaiveBayes().train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_classifier_smilenaivebayes] diff --git a/samples/python/apidocs/ee_classifier_smilerandomforest.py b/samples/python/apidocs/ee_classifier_smilerandomforest.py new file mode 100644 index 000000000..54ab7172f --- /dev/null +++ b/samples/python/apidocs/ee_classifier_smilerandomforest.py @@ -0,0 +1,99 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_classifier_smilerandomforest] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train a 10-tree random forest classifier from the training sample. +trained_classifier = ee.Classifier.smileRandomForest(10).train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_classifier_smilerandomforest] diff --git a/samples/python/apidocs/ee_featurecollection_distance.py b/samples/python/apidocs/ee_featurecollection_distance.py new file mode 100644 index 000000000..ef9107e67 --- /dev/null +++ b/samples/python/apidocs/ee_featurecollection_distance.py @@ -0,0 +1,30 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_featurecollection_distance] +# FeatureCollection of power plants in Belgium. +fc = ee.FeatureCollection('WRI/GPPD/power_plants').filter( + 'country_lg == "Belgium"' +) + +# Generate an image of distance to nearest power plant. +distance = fc.distance(searchRadius=50000, maxError=50) + +# Display the image and FeatureCollection on the map. +m = geemap.Map() +m.set_center(4.56, 50.78, 7) +m.add_ee_layer(distance, {'max': 50000}, 'Distance to power plants') +m.add_ee_layer(fc, {'color': 'red'}, 'Power plants') +m +# [END earthengine__apidocs__ee_featurecollection_distance] diff --git a/samples/python/apidocs/ee_image.py b/samples/python/apidocs/ee_image.py new file mode 100644 index 000000000..6f43b426f --- /dev/null +++ b/samples/python/apidocs/ee_image.py @@ -0,0 +1,66 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image] +image = ee.Image('JAXA/ALOS/AW3D30/V2_2') + +m = geemap.Map() +m.zoom = 3 +display(m) +m.add_ee_layer(image.select('AVE_DSM'), {'min': -1e3, 'max': 5e3}, 'AVE_DSM') +# Image JAXA/ALOS/AW3D30/V2_2 (3 bands) +# type: Image +# id: JAXA/ALOS/AW3D30/V2_2 +# version: 1595337806697615 +# 'bands': List (3 elements) +# properties: Object (21 properties) +display(image) + +transparent = ee.Image() +m.add_ee_layer(transparent, None, 'transparent', False) +# Image (1 band) +# type: Image +# 'bands': List (1 element) +# 0: "constant", int ∈ [0, 0], EPSG:4326 +display(transparent) + +# Create a multi-band image from a list of constants. +orange = ee.Image([0xFF, 0x88, 0x00]) +m.add_ee_layer(orange, {'min': 0, 'max': 0xFF}, 'orange', False) +# Image (3 bands) +# type: Image +# 'bands': List (3 elements) +# 0: "constant", int ∈ [255, 255], EPSG:4326 +# 1: "constant_1", int ∈ [136, 136], EPSG:4326 +# 2: "constant_2", int ∈ [0, 0], EPSG:4326 +display(orange) + +# Create a one band image where each pixel is an array of three values. +image_of_array = ee.Image(ee.Array([0x00, 0x00, 0xFF])) +m.add_ee_layer(image_of_array, None, 'image_of_array', False) +# Image (1 band) +# type: Image +# 'bands': List (1 element) +# 0: "constant", unsigned int8, 1 dimension, EPSG:4326 +# id: constant +# crs: EPSG:4326 +# crs_transform: [1,0,0,0,1,0] +# data_type: unsigned int8, 1 dimension +# type: PixelType +# dimensions: 1 +# 'max': 255 +# 'min': 0 +# precision: int +display(image_of_array) +# [END earthengine__apidocs__ee_image] diff --git a/samples/python/apidocs/ee_image_classify.py b/samples/python/apidocs/ee_image_classify.py new file mode 100644 index 000000000..725e61ae4 --- /dev/null +++ b/samples/python/apidocs/ee_image_classify.py @@ -0,0 +1,99 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_classify] +# A Sentinel-2 surface reflectance image, reflectance bands selected, +# serves as the source for training and prediction in this contrived example. +img = ee.Image( + 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG' +).select('B.*') + +# ESA WorldCover land cover map, used as label source in classifier training. +lc = ee.Image('ESA/WorldCover/v100/2020') + +# Remap the land cover class values to a 0-based sequential series. +class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] +remap_values = ee.List.sequence(0, 10) +label = 'lc' +lc = lc.remap(class_values, remap_values).rename(label).toByte() + +# Add land cover as a band of the reflectance image and sample 100 pixels at +# 10 m scale from each land cover class within a region of interest. +roi = ee.Geometry.Rectangle(-122.347, 37.743, -122.024, 37.838) +sample = img.addBands(lc).stratifiedSample( + numPoints=100, classBand=label, region=roi, scale=10, geometries=True +) + +# Add a random value field to the sample and use it to approximately split 80% +# of the features into a training set and 20% into a validation set. +sample = sample.randomColumn() +training_sample = sample.filter('random <= 0.8') +validation_sample = sample.filter('random > 0.8') + +# Train a 10-tree random forest classifier from the training sample. +trained_classifier = ee.Classifier.smileRandomForest(10).train( + features=training_sample, + classProperty=label, + inputProperties=img.bandNames(), +) + +# Get information about the trained classifier. +display('Results of trained classifier', trained_classifier.explain()) + +# Get a confusion matrix and overall accuracy for the training sample. +train_accuracy = trained_classifier.confusionMatrix() +display('Training error matrix', train_accuracy) +display('Training overall accuracy', train_accuracy.accuracy()) + +# Get a confusion matrix and overall accuracy for the validation sample. +validation_sample = validation_sample.classify(trained_classifier) +validation_accuracy = validation_sample.errorMatrix(label, 'classification') +display('Validation error matrix', validation_accuracy) +display('Validation accuracy', validation_accuracy.accuracy()) + +# Classify the reflectance image from the trained classifier. +img_classified = img.classify(trained_classifier) + +# Add the layers to the map. +class_vis = { + 'min': 0, + 'max': 10, + 'palette': [ + '006400', + 'ffbb22', + 'ffff4c', + 'f096ff', + 'fa0000', + 'b4b4b4', + 'f0f0f0', + '0064c8', + '0096a0', + '00cf75', + 'fae6a0', + ], +} +m = geemap.Map() +m.set_center(-122.184, 37.796, 12) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) +m.add_ee_layer(lc, class_vis, 'lc') +m.add_ee_layer(img_classified, class_vis, 'Classified') +m.add_ee_layer(roi, {'color': 'white'}, 'ROI', False, 0.5) +m.add_ee_layer(training_sample, {'color': 'black'}, 'Training sample', False) +m.add_ee_layer( + validation_sample, {'color': 'white'}, 'Validation sample', False +) +m +# [END earthengine__apidocs__ee_image_classify] diff --git a/samples/python/apidocs/ee_image_clip.py b/samples/python/apidocs/ee_image_clip.py new file mode 100644 index 000000000..f90b29beb --- /dev/null +++ b/samples/python/apidocs/ee_image_clip.py @@ -0,0 +1,57 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_clip] +# A digital elevation model. +dem = ee.Image('NASA/NASADEM_HGT/001') +dem_vis = {'bands': 'elevation', 'min': 0, 'max': 1500} + +# Clip the DEM by a polygon geometry. +geom_poly = ee.Geometry.BBox(-121.55, 39.01, -120.57, 39.38) +dem_clip = dem.clip(geom_poly) +display('Clipped image retains metadata and band names', dem_clip) +m = geemap.Map() +m.set_center(-121.12, 38.13, 8) +m.add_ee_layer(dem_clip, dem_vis, 'Polygon clip') +m.add_ee_layer(geom_poly, {'color': 'green'}, 'Polygon geometry', False) + +# Clip the DEM by a line geometry. +geom_line = ee.Geometry.LinearRing( + [[-121.19, 38.10], [-120.53, 38.54], [-120.22, 37.83], [-121.19, 38.10]] +) +m.add_ee_layer(dem.clip(geom_line), dem_vis, 'Line clip') +m.add_ee_layer(geom_line, {'color': 'orange'}, 'Line geometry', False) + +# Images have geometry clip the dem image by the geometry of an S2 image. +s_2_img = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG') +geom_s_2_img = s_2_img.geometry() +m.add_ee_layer(dem.clip(geom_s_2_img), dem_vis, 'Image geometry clip') +m.add_ee_layer(geom_s_2_img, {'color': 'blue'}, 'Image geometry', False) + +# Don't use ee.Image.clip prior to ee.Image.regionReduction, the "geometry" +# parameter handles it more efficiently. +zonal_max = dem.select('elevation').reduceRegion( + reducer=ee.Reducer.max(), geometry=geom_poly +) +display('Max elevation (m)', zonal_max.get('elevation')) + +# Don't use ee.Image.clip to clip an image by a FeatureCollection, use +# ee.Image.clipToCollection(collection). +watersheds = ee.FeatureCollection('USGS/WBD/2017/HUC10').filterBounds( + ee.Geometry.Point(-122.754, 38.606).buffer(2e4) +) +m.add_ee_layer(dem.clipToCollection(watersheds), dem_vis, 'Watersheds clip') +m.add_ee_layer(watersheds, {'color': 'red'}, 'Watersheds', False) +m +# [END earthengine__apidocs__ee_image_clip] diff --git a/samples/python/apidocs/ee_image_mask.py b/samples/python/apidocs/ee_image_mask.py new file mode 100644 index 000000000..d9896d68e --- /dev/null +++ b/samples/python/apidocs/ee_image_mask.py @@ -0,0 +1,40 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_mask] +# A Sentinel-2 surface reflectance image. +img = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG') +true_color_viz = { + 'bands': ['B4', 'B3', 'B2'], + 'min': 0, + 'max': 2700, + 'gamma': 1.3, +} +display('Sentinel-2 image', img) +m = geemap.Map() +m.set_center(-122.36, 37.47, 10) +m.add_ee_layer(img, true_color_viz, 'Sentinel-2 image') + +# Get masks for all image bands each band has an independent mask. +# Valid pixels are value 1, invalid are 0. +multi_band_mask_img = img.mask() +display('Multi-band mask image', multi_band_mask_img) +m.add_ee_layer(multi_band_mask_img, None, 'Multi-band mask image') + +# Get the mask for a single image band. +single_band_mask_img = img.select('B1').mask() +display('Single-band mask image', single_band_mask_img) +m.add_ee_layer(single_band_mask_img, None, 'Single-band mask image') +m +# [END earthengine__apidocs__ee_image_mask] diff --git a/samples/python/apidocs/ee_image_normalizeddifference.py b/samples/python/apidocs/ee_image_normalizeddifference.py new file mode 100644 index 000000000..a64704542 --- /dev/null +++ b/samples/python/apidocs/ee_image_normalizeddifference.py @@ -0,0 +1,29 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_normalizeddifference] +# A Landsat 8 surface reflectance image. +img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20210508') + +# Calculate normalized difference vegetation index: (NIR - Red) / (NIR + Red). +nir_band = 'SR_B5' +red_band = 'SR_B4' +ndvi = img.normalizedDifference([nir_band, red_band]) + +# Display NDVI result on the map. +m = geemap.Map() +m.set_center(-122.148, 37.377, 11) +m.add_ee_layer(ndvi, {'min': 0, 'max': 0.5}, 'NDVI') +m +# [END earthengine__apidocs__ee_image_normalizeddifference] diff --git a/samples/python/apidocs/ee_image_reduceregion.py b/samples/python/apidocs/ee_image_reduceregion.py new file mode 100644 index 000000000..a5ea2ed4c --- /dev/null +++ b/samples/python/apidocs/ee_image_reduceregion.py @@ -0,0 +1,62 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_reduceregion] +# A Landsat 8 surface reflectance image with SWIR1, NIR, and green bands. +img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20210508').select( + ['SR_B6', 'SR_B5', 'SR_B3'] +) + +# Santa Cruz Mountains ecoregion geometry. +geom = ( + ee.FeatureCollection('EPA/Ecoregions/2013/L4') + .filter('us_l4name == "Santa Cruz Mountains"') + .geometry() +) + +# Display layers on the map. +m = geemap.Map() +m.set_center(-122.08, 37.22, 9) +m.add_ee_layer(img, {'min': 10000, 'max': 20000}, 'Landsat image') +m.add_ee_layer(geom, {'color': 'white'}, 'Santa Cruz Mountains ecoregion') +display(m) + +# Calculate median band values within Santa Cruz Mountains ecoregion. It is +# good practice to explicitly define "scale" (or "crsTransform") and "crs" +# parameters of the analysis to avoid unexpected results from undesired +# defaults when e.g. reducing a composite image. +stats = img.reduceRegion( + reducer=ee.Reducer.median(), + geometry=geom, + scale=30, # meters + crs='EPSG:3310', # California Albers projection +) + +# A dictionary is returned keys are band names, values are the statistic. +display('Median band values, Santa Cruz Mountains ecoregion', stats) + +# You can combine reducers to calculate e.g. mean and standard deviation +# simultaneously. The output dictionary keys are the concatenation of the band +# names and statistic names, separated by an underscore. +reducer = ee.Reducer.mean().combine( + reducer2=ee.Reducer.stdDev(), sharedInputs=True +) +multi_stats = img.reduceRegion( + reducer=reducer, + geometry=geom, + scale=30, + crs='EPSG:3310', +) +display('Mean & SD band values, Santa Cruz Mountains ecoregion', multi_stats) +# [END earthengine__apidocs__ee_image_reduceregion] diff --git a/samples/python/apidocs/ee_image_reduceregions.py b/samples/python/apidocs/ee_image_reduceregions.py new file mode 100644 index 000000000..13b9c4348 --- /dev/null +++ b/samples/python/apidocs/ee_image_reduceregions.py @@ -0,0 +1,67 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_reduceregions] +# A Landsat 8 SR image with SWIR1, NIR, and green bands. +img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20210508').select( + ['SR_B6', 'SR_B5', 'SR_B3'] +) + +# Santa Cruz Mountains ecoregions feature collection. +region_col = ee.FeatureCollection('EPA/Ecoregions/2013/L4').filter( + 'us_l4name == "Santa Cruz Mountains" || ' + + 'us_l4name == "San Mateo Coastal Hills" || ' + + 'us_l4name == "Leeward Hills"' +) + +# Display layers on the map. +m = geemap.Map() +m.set_center(-122.08, 37.22, 9) +m.add_ee_layer(img, {'min': 10000, 'max': 20000}, 'Landsat image') +m.add_ee_layer( + region_col, {'color': 'white'}, 'Santa Cruz Mountains ecoregions' +) +display(m) + +# Calculate median band values within Santa Cruz Mountains ecoregions. It is +# good practice to explicitly define "scale" (or "crsTransform") and "crs" +# parameters of the analysis to avoid unexpected results from undesired +# defaults when e.g. reducing a composite image. +stats = img.reduceRegions( + collection=region_col, + reducer=ee.Reducer.median(), + scale=30, # meters + crs='EPSG:3310', # California Albers projection +) + +# The input feature collection is returned with new properties appended. +# The new properties are the outcome of the region reduction per image band, +# for each feature in the collection. Region reduction property names +# are the same as the input image band names. +display('Median band values, Santa Cruz Mountains ecoregions', stats) + +# You can combine reducers to calculate e.g. mean and standard deviation +# simultaneously. The resulting property names are the concatenation of the +# band names and statistic names, separated by an underscore. +reducer = ee.Reducer.mean().combine( + reducer2=ee.Reducer.stdDev(), sharedInputs=True +) +multi_stats = img.reduceRegions( + collection=region_col, + reducer=reducer, + scale=30, + crs='EPSG:3310', +) +display('Mean & SD band values, Santa Cruz Mountains ecoregions', multi_stats) +# [END earthengine__apidocs__ee_image_reduceregions] diff --git a/samples/python/apidocs/ee_image_sampleregions.py b/samples/python/apidocs/ee_image_sampleregions.py new file mode 100644 index 000000000..713c02051 --- /dev/null +++ b/samples/python/apidocs/ee_image_sampleregions.py @@ -0,0 +1,64 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_sampleregions] +# A Sentinel-2 surface reflectance image. +img = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG') +m = geemap.Map() +m.set_center(-122.503881, 37.765588, 18) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 4500}, 'img' +) +display(m) + +# A feature collection with two polygon regions each intersecting 36 +# pixels at 10 m scale. +fc_polygon = ee.FeatureCollection([ + ee.Feature( + ee.Geometry.Rectangle( + -122.50620929, 37.76502806, -122.50552264, 37.76556663 + ), + {'id': 0}, + ), + ee.Feature( + ee.Geometry.Rectangle( + -122.50530270, 37.76565568, -122.50460533, 37.76619425 + ), + {'id': 1}, + ), +]) +m.add_ee_layer(fc_polygon, {'color': 'yellow'}, 'fc_polygon') + +fc_polygon_samp = img.sampleRegions( + collection=fc_polygon, scale=10, geometries=True +) +# Note that 7 pixels are missing from the sample. If a pixel contains a masked +# band value it will be excluded from the sample. In this case, the TCI_B band +# is masked for each unsampled pixel. +display('A feature per pixel (at given scale) in each region', fc_polygon_samp) +m.add_ee_layer(fc_polygon_samp, {'color': 'purple'}, 'fc_polygon_samp') + +# A feature collection with two points intersecting two different pixels. +# This example is included to show the behavior for point geometries. In +# practice, if the feature collection is all points, ee.Image.reduceRegions +# should be used instead to save memory. +fc_point = ee.FeatureCollection([ + ee.Feature(ee.Geometry.Point([-122.50309256, 37.76605006]), {'id': 0}), + ee.Feature(ee.Geometry.Point([-122.50344661, 37.76560903]), {'id': 1}), +]) +m.add_ee_layer(fc_point, {'color': 'cyan'}, 'fc_point') + +fc_point_samp = img.sampleRegions(collection=fc_point, scale=10) +display('A feature per point', fc_point_samp) +# [END earthengine__apidocs__ee_image_sampleregions] diff --git a/samples/python/apidocs/ee_image_updatemask.py b/samples/python/apidocs/ee_image_updatemask.py new file mode 100644 index 000000000..74dd46cfb --- /dev/null +++ b/samples/python/apidocs/ee_image_updatemask.py @@ -0,0 +1,62 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_image_updatemask] +# A Sentinel-2 surface reflectance image. +img = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG') +true_color_viz = { + 'bands': ['B4', 'B3', 'B2'], + 'min': 0, + 'max': 2700, + 'gamma': 1.3, +} +display('Sentinel-2 image', img) +m = geemap.Map() +m.set_center(-122.36, 37.47, 10) +m.add_ee_layer(img, true_color_viz, 'Sentinel-2 image') + +# Create a Boolean land mask from the SWIR1 band water is value 0, land is 1. +land_mask = img.select('B11').gt(100) +display('Land mask', land_mask) +m.add_ee_layer(land_mask, {'palette': ['blue', 'lightgreen']}, 'Land mask') + +# Apply the single-band land mask to all image bands pixel values equal to 0 +# in the mask become invalid in the image. +img_masked = img.updateMask(land_mask) +display('Image, land only', img_masked) +m.add_ee_layer(img_masked, true_color_viz, 'Image, land only') + +# Masks are band-specific. Here, a multi-band mask image is used to update +# corresponding input image band masks. +img_band_subset = img.select(['B4', 'B3', 'B2']) +band_specific_masks = img_band_subset.gt(200) +img_band_subset_masked = img_band_subset.updateMask(band_specific_masks) +display('Multi-band mask image', band_specific_masks) +display('Image, variable band masks', img_band_subset_masked) +m.add_ee_layer(band_specific_masks, None, 'Multi-band mask image') +m.add_ee_layer( + img_band_subset_masked, true_color_viz, 'Image, variable band masks' +) +# Note that there is only a single alpha channel for visualization, so when +# the ee.Image is rendered as an RGB image or map tiles, a masked pixel in any +# band will result in transparency for all bands. + +# Floating point mask values between 0 and 1 will be used to define opacity +# in visualization via m.add_ee_layer and ee.Image.visualize. +land_mask_float = land_mask.add(0.65) +img_masked_float = img.updateMask(land_mask_float) +display('Image, partially transparent', img_masked_float) +m.add_ee_layer(img_masked_float, true_color_viz, 'Image, partially transparent') +m +# [END earthengine__apidocs__ee_image_updatemask] diff --git a/samples/python/apidocs/ee_imagecollection_reducetoimage.py b/samples/python/apidocs/ee_imagecollection_reducetoimage.py new file mode 100644 index 000000000..e1a0459d8 --- /dev/null +++ b/samples/python/apidocs/ee_imagecollection_reducetoimage.py @@ -0,0 +1,40 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_imagecollection_reducetoimage] +col = ( + ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA') + .filterBounds(ee.Geometry.BBox(-124.0, 43.2, -116.5, 46.3)) + .filterDate('2021', '2022') +) + +# Image visualization settings. +vis_params = {'bands': ['B4', 'B3', 'B2'], 'min': 0.01, 'max': 0.25} +m = geemap.Map() +m.add_ee_layer(col.mean(), vis_params, 'RGB mean') + +# Reduce the geometry (footprint) of images in the collection to an image. +# Image property values are applied to the pixels intersecting each +# image's geometry and then a per-pixel reduction is performed according +# to the selected reducer. Here, the image cloud cover property is assigned +# to the pixels intersecting image geometry and then reduced to a single +# image representing the per-pixel mean image cloud cover. +mean_cloud_cover = col.reduceToImage( + properties=['CLOUD_COVER'], reducer=ee.Reducer.mean() +) + +m.set_center(-119.87, 44.76, 6) +m.add_ee_layer(mean_cloud_cover, {'min': 0, 'max': 50}, 'Cloud cover mean') +m +# [END earthengine__apidocs__ee_imagecollection_reducetoimage] diff --git a/samples/python/apidocs/ee_terrain_products.py b/samples/python/apidocs/ee_terrain_products.py new file mode 100644 index 000000000..3fbf65750 --- /dev/null +++ b/samples/python/apidocs/ee_terrain_products.py @@ -0,0 +1,38 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_terrain_products] +# A digital elevation model. +dem = ee.Image('NASA/NASADEM_HGT/001').select('elevation') + +# Calculate slope. Units are degrees, range is [0,90). +slope = ee.Terrain.slope(dem) + +# Calculate aspect. Units are degrees where 0=N, 90=E, 180=S, 270=W. +aspect = ee.Terrain.aspect(dem) + +# Display slope and aspect layers on the map. +m = geemap.Map() +m.set_center(-123.457, 47.815, 11) +m.add_ee_layer(slope, {'min': 0, 'max': 89.99}, 'Slope') +m.add_ee_layer(aspect, {'min': 0, 'max': 359.99}, 'Aspect') + +# Use the ee.Terrain.products function to calculate slope, aspect, and +# hillshade simultaneously. The output bands are appended to the input image. +# Hillshade is calculated based on illumination azimuth=270, elevation=45. +terrain = ee.Terrain.products(dem) +display('ee.Terrain.products bands', terrain.bandNames()) +m.add_ee_layer(terrain.select('hillshade'), {'min': 0, 'max': 255}, 'Hillshade') +m +# [END earthengine__apidocs__ee_terrain_products] diff --git a/samples/python/apidocs/ee_terrain_slope.py b/samples/python/apidocs/ee_terrain_slope.py new file mode 100644 index 000000000..ceacabe86 --- /dev/null +++ b/samples/python/apidocs/ee_terrain_slope.py @@ -0,0 +1,38 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__ee_terrain_slope] +# A digital elevation model. +dem = ee.Image('NASA/NASADEM_HGT/001').select('elevation') + +# Calculate slope. Units are degrees, range is [0,90). +slope = ee.Terrain.slope(dem) + +# Calculate aspect. Units are degrees where 0=N, 90=E, 180=S, 270=W. +aspect = ee.Terrain.aspect(dem) + +# Display slope and aspect layers on the map. +m = geemap.Map() +m.set_center(-123.457, 47.815, 11) +m.add_ee_layer(slope, {'min': 0, 'max': 89.99}, 'Slope') +m.add_ee_layer(aspect, {'min': 0, 'max': 359.99}, 'Aspect') + +# Use the ee.Terrain.products function to calculate slope, aspect, and +# hillshade simultaneously. The output bands are appended to the input image. +# Hillshade is calculated based on illumination azimuth=270, elevation=45. +terrain = ee.Terrain.products(dem) +display('ee.Terrain.products bands', terrain.bandNames()) +m.add_ee_layer(terrain.select('hillshade'), {'min': 0, 'max': 255}, 'Hillshade') +m +# [END earthengine__apidocs__ee_terrain_slope] diff --git a/samples/python/apidocs/export_table_todrive.py b/samples/python/apidocs/export_table_todrive.py new file mode 100644 index 000000000..ce844c60b --- /dev/null +++ b/samples/python/apidocs/export_table_todrive.py @@ -0,0 +1,58 @@ +# Copyright 2023 The Google Earth Engine Community Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START earthengine__apidocs__export_table_todrive] +# A Sentinel-2 surface reflectance image. +img = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG') +m = geemap.Map() +m.set_center(-122.359, 37.428, 9) +m.add_ee_layer( + img, {'bands': ['B11', 'B8', 'B3'], 'min': 100, 'max': 3500}, 'img' +) + +# Sample the image at 20 m scale, a point feature collection is returned. +samp = img.sample(scale=20, numPixels=50, geometries=True) +m.add_ee_layer(samp, {'color': 'white'}, 'samp') +display(m) +display('Image sample feature collection', samp) + +# Export the image sample feature collection to Drive as a CSV file. +task = ee.batch.Export.table.toDrive( + collection=samp, + description='image_sample_demo_csv', + folder='earth_engine_demos', + fileFormat='CSV', +) +task.start() + +# Export a subset of collection properties: three bands and the geometry +# as GeoJSON. +task = ee.batch.Export.table.toDrive( + collection=samp, + description='image_sample_demo_prop_subset', + folder='earth_engine_demos', + fileFormat='GeoJSON', + selectors=['B8', 'B11', 'B12', '.geo'], +) +task.start() + +# Export the image sample feature collection to Drive as a shapefile. +task = ee.batch.Export.table.toDrive( + collection=samp, + description='image_sample_demo_shp', + folder='earth_engine_demos', + fileFormat='SHP', +) +task.start() +# [END earthengine__apidocs__export_table_todrive]