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」>「Collaboratory」

Colab 介面

前往 Colab 網站,然後建立新檔案。

  • 依序點選「File」>「New」>「New Python 3 notebook」
  • 如果您先前曾與 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 檔案。您也可以選取「File」>「Open notebook」,或使用 Ctrl+O 鍵盤組合,從 Colab 介面存取檔案總管。

匯入 API 並取得憑證

本節將示範如何匯入 Earth Engine Python API 並驗證存取權。這篇文章也有 Colab 筆記本版本:

根據預設,Google Colaboratory 會包含 Earth Engine API,因此只需要匯入及驗證即可。您必須為每個新的 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,才能使用該 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 圖塊,並使用該方法在 Leaflet 地圖上顯示高程模型。

# 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()