Python 安装 - Colab 笔记本

Earth Engine Python API 可在 Google Colaboratory 笔记本中部署。Colab 笔记本是运行在云端的 Jupyter 笔记本,与 Google 云端硬盘高度集成,因此易于设置、访问和共享。如果您不熟悉 Google Colab 或 Jupyter 笔记本,请花些时间探索 Colab 欢迎网站

以下部分介绍了如何在 Google Colab 中部署 Earth Engine,以及如何使用第三方 Python 软件包可视化地图和图表。

打开 Colab 笔记本

您可以通过 Google 云端硬盘或 Colaboratory 界面打开笔记本。

新建笔记本

Google 云端硬盘

打开 Google 云端硬盘,然后创建一个新文件。

  • 新建 > 更多 > Colaboratory
  • 右键点击某个文件夹,然后从上下文菜单中选择 More > Colaboratory

Colab 界面

访问 Colab 网站,然后创建一个新文件。

  • 文件 > 新建 > 新建 Python 3 笔记本
  • 如果您之前使用过 Colab,访问上述链接的网站后,您会看到一个文件资源管理器,您可以在其中使用窗口底部的下拉菜单创建新文件。

现有记事本

您可以通过 Google 云端硬盘和 Colab 界面打开现有笔记本文件 (.ipynb)。

Google 云端硬盘

Colab 笔记本可以存在于 Google 云端硬盘的多个文件夹中,具体取决于笔记本文件的创建位置。在 Google 云端硬盘中创建的记事本将位于创建或移至该记事本的文件夹中。通过 Colab 界面创建的笔记本将默认保存到名为“Colab Notebooks”的文件夹中,该文件夹会在您开始使用 Colab 时自动添加到 Google 云端硬盘的“我的云端硬盘”文件夹中。

Colab 文件带有黄色“CO”符号和“.ipynb”文件扩展名。如需打开文件,请双击相应文件,然后从随即显示的页面顶部的按钮中选择 Open with > Colaboratory;或者右键点击相应文件,然后从文件的上下文菜单中选择 Open with > Colaboratory

Colab 界面

通过 Colab 界面打开笔记本后,您可以访问 Google 云端硬盘、GitHub 和本地硬件中的现有文件。首次使用后访问 Colab 界面会导致显示文件资源管理器模态窗口。从文件资源管理器顶部的标签页中,选择一个来源,然后前往要打开的 .ipynb 文件。您还可以通过 Colab 界面访问文件浏览器,方法是依次选择 File > Open notebook 或使用 Ctrl+O 键盘组合。

导入 API 并获取凭据

本部分演示了如何导入 Earth Engine Python API 并对访问进行身份验证。本内容还以 Colab 笔记本的形式提供:

Earth Engine API 默认包含在 Google Colaboratory 中,因此只需导入和进行身份验证即可。在每次开启新的 Colab 会话时,或者在您重启 Colab 内核或 Colab 虚拟机因闲置而被回收时,都必须完成这些步骤。

导入 API

运行以下单元格,将该 API 导入到您的会话中。

import ee

身份验证和初始化

运行 ee.Authenticate 函数以对您对 Earth Engine 服务器的访问权限进行身份验证,并运行 ee.Initialize 以对其进行初始化。添加一个代码单元,输入以下代码行,修改项目,然后运行该单元。

# Trigger the authentication flow.
ee.Authenticate()

# Initialize the library.
ee.Initialize(project='my-project')

系统会要求您授权访问您的 Earth Engine 账号。按照单元格中显示的说明完成此步骤。

测试 API

通过输出珠穆朗玛峰的海拔来测试该 API。请注意,您必须先初始化该 API,然后才能使用它。在新单元格中运行以下 Python 脚本。

# Print the elevation of Mount Everest.
dem = ee.Image('USGS/SRTMGL1_003')
xy = ee.Geometry.Point([86.9250, 27.9881])
elev = dem.sample(xy, 30).first().get('elevation').getInfo()
print('Mount Everest elevation (m):', elev)

地图可视化

ee.Image 对象可以显示在笔记本输出单元格中。以下两个示例演示了如何显示静态图片和互动地图。

静态图片

IPython.display 模块包含 Image 函数,该函数可以显示网址的结果,该网址表示通过调用 Earth Engine getThumbUrl 函数生成的图片。以下脚本将显示全球海拔模型的缩略图。

# Import libraries.
import ee
from IPython.display import Image

# Trigger the authentication flow.
ee.Authenticate()

# Initialize the library.
ee.Initialize(project='my-project')

# Import a DEM and display a thumbnail of it.
dem = ee.Image('USGS/SRTMGL1_003')
Image(url=dem.updateMask(dem.gt(0))
  .getThumbUrl({'min': 0, 'max': 4000, 'dimensions': 512,
                'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}))

互动地图

folium 软件包可用于在交互式 Leaflet 地图上显示 ee.Image 对象。Folium 没有用于处理 Earth Engine 中的图块的默认方法,因此必须先定义一个方法并将其添加到 folium.Map 模块,然后才能使用。

以下脚本提供了一个示例,展示了如何添加用于处理 Earth Engine 图块的方法,并使用该方法在地图项地图上显示海拔模型。

# Import libraries.
import ee
import folium

# Trigger the authentication flow.
ee.Authenticate()

# Initialize the library.
ee.Initialize(project='my-project')

# Define a method for displaying Earth Engine image tiles to folium map.
def add_ee_layer(self, ee_image_object, vis_params, name):
  map_id_dict = ee.Image(ee_image_object).getMapId(vis_params)
  folium.raster_layers.TileLayer(
    tiles = map_id_dict['tile_fetcher'].url_format,
    attr = "Map Data © Google Earth Engine",
    name = name,
    overlay = True,
    control = True
  ).add_to(self)

# Add EE drawing method to folium.
folium.Map.add_ee_layer = add_ee_layer

# Fetch an elevation model.
dem = ee.Image('USGS/SRTMGL1_003')
# Set visualization parameters.
vis_params = {
  'min': 0,
  'max': 4000,
  'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}

# Create a folium map object.
my_map = folium.Map(location=[20, 0], zoom_start=3)

# Add the elevation model to the map object.
my_map.add_ee_layer(dem.updateMask(dem.gt(0)), vis_params, 'DEM')

# Add a layer control panel to the map.
my_map.add_child(folium.LayerControl())

# Display the map.
display(my_map)

图表可视化

某些 Earth Engine 函数会生成表格数据,这些数据可以通过 matplotlib 等数据可视化软件包绘制图表。以下示例演示了如何将 Earth Engine 中的表格数据显示为散点图。如需了解详情,请参阅 Colaboratory 中的图表

# Import libraries.
import ee
import matplotlib.pyplot as plt

# Trigger the authentication flow.
ee.Authenticate()

# Initialize the Earth Engine module.
ee.Initialize(project='my-project')

# Fetch a Landsat TOA image.
img = ee.Image('LANDSAT/LT05/C02/T1_TOA/LT05_034033_20000913')

# Select Red and NIR bands, scale them, and sample 500 points.
samp_fc = img.select(['B3','B4']).sample(scale=30, numPixels=500)

# Arrange the sample as a list of lists.
samp_dict = samp_fc.reduceColumns(ee.Reducer.toList().repeat(2), ['B3', 'B4'])
samp_list = ee.List(samp_dict.get('list'))

# Save server-side ee.List as a client-side Python list.
samp_data = samp_list.getInfo()

# Display a scatter plot of Red-NIR sample pairs using matplotlib.
plt.scatter(samp_data[0], samp_data[1], alpha=0.2)
plt.xlabel('Red', fontsize=12)
plt.ylabel('NIR', fontsize=12)
plt.show()