Earth Engine Python API 可部署在 Google Colaboratory 筆記本中。Colab 筆記本是 Jupyter 筆記本,可在雲端執行,並與 Google 雲端硬碟高度整合,方便設定、存取及共用。如果您不熟悉 Google Colab 或 Jupyter 筆記本,請花一些時間瀏覽 Colab 歡迎網站。
以下各節說明如何在 Google Colab 中部署 Earth Engine,以及如何使用第三方 Python 套件顯示地圖和圖表。
開啟 Colab 筆記本
您可以透過 Google 雲端硬碟或 Colaboratory 介面開啟筆記本。
新增筆記本
Google 雲端硬碟
開啟 Google 雲端硬碟並建立新檔案。
- 「新增」>「更多」>「Colaboratory」
- 在資料夾中按一下滑鼠右鍵,然後從內容選單中選取「更多」>「Colaboratory」。
Colab 介面
前往 Colab 網站並建立新檔案。
- 依序點選「File」>「New」>「New Python 3 notebook」
- 如果您先前曾與 Colab 互動,造訪上述連結的網站時,系統會提供檔案總管,您可以使用視窗底部的下拉式選單啟動新檔案。
現有筆記本
您可以從 Google 雲端硬碟和 Colab 介面開啟現有的筆記本檔案 (.ipynb)。
Google 雲端硬碟
Colab 筆記本可以位於 Google 雲端硬碟中的各種資料夾,具體取決於筆記本檔案的建立位置。在 Google 雲端硬碟中建立的記事本會儲存在建立或移入的資料夾中。透過 Colab 介面建立的筆記本,預設會儲存在名為「Colab Notebooks」的資料夾中。當你開始使用 Colab 時,這個資料夾會自動新增至 Google 雲端硬碟的「我的雲端硬碟」資料夾。
Colab 檔案會顯示黃色「CO」符號和「.ipynb」副檔名,如要開啟檔案,請按兩下檔案,然後依序選取結果頁面頂端按鈕中的「選擇開啟工具」>「Colaboratory」,或在檔案上按一下滑鼠右鍵,然後依序選取檔案內容選單中的「選擇開啟工具」>「Colaboratory」。
Colab 介面
從 Colab 介面開啟筆記本,即可存取 Google 雲端硬碟、GitHub 和本機硬體中的現有檔案。初次使用後,如果再次造訪 Colab 介面,系統會顯示檔案總管模式。在檔案總管頂端的分頁中選取來源,然後前往要開啟的 .ipynb 檔案。您也可以在 Colab 介面中依序選取「檔案」>「開啟筆記本」,或使用 Ctrl+O 鍵盤組合,存取檔案總管。
匯入 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 前必須先初始化。在新儲存格中執行下列 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()
在 Google Colab 中執行
在 GitHub 上查看來源