Post

Earth Engine 시작하기 with Python

본 문서는 Earth Engine Python API를 사용하는 방법을 담고 있다. Google Earth Engine에 대한 설명은 Google Earth Engine 시작하기에서 볼 수 있다.

1. Google Earth Eninge 시작하기

Google Earth Engine에 가입하여 승인을 받아야 하며, 어렵지 않게 가입할 수 있다. google 계정으로 가입하는 것이 좋다.

1-1. Google Earth Engine Python API 설치

1
!pip install earthengine-api --upgrade

1-2. Google 계정 인증 및 초기화

  • ee.Authenticate(): Earth Engine과 연결된 Google 계정으로 인증하고 인증 토큰을 얻는 역할
    • 한 번 인증이 완료되면, 그 이후에는 인증 코드를 다시 입력할 필요 없이 해당 인증 토큰을 사용하여 Earth Engine과 통신할 수 있다.
    • Goolgle 계정 로그인 후, 인증 코드를 복사해 입력하면 된다. 그림1
  • ee.Initialize(): Earth Engine 초기화
    • 가끔 아래와 같이 접근 오류가 뜨는 경우가 있다. ee.Initialize('my-project')와 같이 프로젝트 이름을 넣어준다면 해결될 것이다.
    • 프로젝트 이름은 확인이 필요하다. 그림1
1
2
3
import ee
# ee.Authenticate() # 처음에만
ee.Initialize()

2. 위성영상 불러오기

2-1. Image와 ImageCollection

Image는 한 시점에 측정된 데이터, ImageCollection은 동일한 지점에서 여러 시점 또는 다른 센서로부터 얻은 이미지를 모아 놓은 것이다.

getInfo()는 비동기적인 연산의 결과를 동기적으로 가져오기 위해 사용되는 메서드이다.

  • 큰 데이터셋이나 계산이 오래 걸리는 작업을 수행할 때는 브라우저가 장시간 응답하지 않을 수 있음
  • 서버에서 클라이언트로 데이터를 전송하려면 데이터 크기에 따라 처리 시간이 증가할 수 있음
1
2
3
img = ee.Image('LANDSAT/LT05/C01/T1_SR/LT05_034033_20000913')
print('img: ', img)
print("img's type: ", img.getInfo()['type'])
1
2
3
4
5
6
7
8
9
10
11
img:  ee.Image({
  "functionInvocationValue": {
    "functionName": "Image.load",
    "arguments": {
      "id": {
        "constantValue": "LANDSAT/LT05/C01/T1_SR/LT05_034033_20000913"
      }
    }
  }
})
img's type:  Image
1
2
3
img_collection = ee.ImageCollection('COPERNICUS/S2_SR')
print('img_collection: ', img_collection)
print("img_collection's title: ", img_collection.get('title').getInfo())
1
2
3
4
5
6
7
8
9
10
11
img_collection:  ee.ImageCollection({
  "functionInvocationValue": {
    "functionName": "ImageCollection.load",
    "arguments": {
      "id": {
        "constantValue": "COPERNICUS/S2_SR"
      }
    }
  }
})
img_collection's title:  Sentinel-2 MSI: MultiSpectral Instrument, Level-2A

2-2. Datetime

1
import datetime
1
2
3
4
# Google Earth Engine에서 얻은 ee.Date 객체를 Python의 datetime 객체로 변환
ee_date = ee.Date('2020-01-01')
py_date = datetime.datetime.utcfromtimestamp(ee_date.getInfo()['value']/1000.0)
print(f'ee_date: {ee_date},\npy_date: {py_date}')
1
2
3
4
5
6
7
8
9
10
11
ee_date: ee.Date({
  "functionInvocationValue": {
    "functionName": "Date",
    "arguments": {
      "value": {
        "constantValue": "2020-01-01"
      }
    }
  }
}),
py_date: 2020-01-01 00:00:00
1
2
3
4
# Python의 datetime 객체를 Google Earth Engine에서 얻은 ee.Date 객체로 변환
py_date = datetime.datetime.utcnow()
ee_date = ee.Date(py_date)
print(f'ee_date: {ee_date},\npy_date: {py_date}')
1
2
3
4
5
6
7
8
9
10
11
ee_date: ee.Date({
  "functionInvocationValue": {
    "functionName": "Date",
    "arguments": {
      "value": {
        "constantValue": 1705845372457
      }
    }
  }
}),
py_date: 2024-01-21 13:56:12.457062

2-3. Geometry

지리적인 공간을 나타내기 위한 객체로 지점, 선, 다각형 등 다양한 지리적인 요소를 정의하고 조작할 수 있다.

  • LineString: 선
  • Rectangle: 사각형
  • Point: 점
  • Polygon: 다각형
1
2
3
4
ee.Geometry.LineString(
  [[-122.088, 37.418], 
   [-122.086, 37.422], 
   [-122.082, 37.418]])

그림1

1
ee.Geometry.Rectangle(31.1330, 29.9782, 31.1353, 29.9802)

그림1

1
2
3
4
5
ee.Geometry.MultiPolygon(
    [[[[126.90885474205147, 36.01743572955867],
       [126.90820028305184, 36.017001833802304],
       [126.90887083530556, 36.016337968671635],
       [126.90953065872323, 36.0167848850283]]]])

그림1

1
ee.Geometry.Point(127.00, 37.56)

그림1

2-4. ImageCollection에서 Image 가져오기

1
2
3
4
5
6
7
collection2img = (
    ee.ImageCollection('COPERNICUS/S2_SR')              # ImageCollection
    .filterBounds(ee.Geometry.Point(127.00, 37.56))   # 특정 지역 선택(point)
    .filterDate('2019-01-01', '2019-01-31')             # 특정 기간의 이미지 선택
    .sort('CLOUDY_PIXEL_PERCENTAGE')                    # 구름의 양에 따라 이미지 정렬
    .first()                                            # 가장 첫번째 이미지 가져오기
)

3. Geemap과 지도에서 확인하기

Earth Engine의 지도는 일반적으로 Colab 환경에서 렌더링되며 로컬 환경에서는 표시되지 않을 수 있다. Colab은 Google Colaboratory에서 제공하는 클라우드 기반 환경이며, Earth Engine와의 통합이 잘 되어 있기 때문에 Colab에서는 지도가 잘 표시된다. folium 또는 ipyleaflet 같은 지도시각화 라이브러리를 활용하여 Earth Engine에서 가져온 이미지를 표시할 수 있다.

Colab에서 시도한 결과를 이미지로 첨부하였으며, folium으로도 시도해보았다. 지도상에서의 결과는 같다. Colab에서 geemap만을 사용해 그린 지도에서는 점, 선, 면, 다각형을 생성할 수 있지만, folium을 이용해 로컬에서 지도를 시각화하면 불가능하다는 점이 다르다.

1
!pip install geemap

3-1. Geemap in Google Colab

1
2
3
4
5
6
7
8
9
10
11
import geemap.core as geemap

# 지도 불러오기
roi = ee.Geometry.Rectangle([126.95, 37.5, 127.05, 37.7])
Map = geemap.Map()
Map.centerObject(ee.Geometry.Point(127.00, 37.56), 10)
landsat_image = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA").filterBounds(roi).first()
Map.addLayer(landsat_image, {"bands": ["B4", "B3", "B2"], "max": 0.3})

# 대화형 지도 표시
Map

그림1

3-2. Geemap with folium

1
!pip install folium
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import folium
roi = ee.Geometry.Rectangle([126.95, 37.5, 127.05, 37.7])

map_center = [37.6, 127.0]
map = folium.Map(location=map_center, zoom_start=10)

image = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA").filterBounds(roi).first()
vis_params = {"bands": ["B4", "B3", "B2"], "max": 0.3}
map_id_dict = image.getMapId(vis_params)

folium.TileLayer(
    tiles=map_id_dict["tile_fetcher"].url_format,
    attr="Google Earth Engine",
    overlay=True,
    name="RGB",
).add_to(map)

map

그림1

This post is licensed under CC BY 4.0 by the author.