다음을 통해 공유


빠른 시작: Python을 사용하여 Microsoft Planetary Computer Pro GeoCatalog에서 STAC 컬렉션 만들기

이 빠른 시작에서는 STAC(SpatioTemporal Asset Catalog) 컬렉션을 만들고 Python을 사용하여 Microsoft Planetary Computer Pro GeoCatalog에 추가하는 방법을 안내합니다.

필수 조건

이 빠른 시작을 완료하려면 다음이 필요합니다.

  • 활성 구독이 있는 Azure 계정. 무료로 계정 만들기 링크를 사용합니다.
  • Azure에 액세스하도록 구성된 환경(예를 들어 az login).
  • Planetary Computer Pro GeoCatalog에 액세스합니다. 아직 액세스 권한이 없는 경우 새 GeoCatalog를 만들 수 있습니다.
  • requestsazure-identity가 설치된 Python 환경입니다.
python3 -m pip install requests azure-identity

STAC 컬렉션 JSON 만들기

STAC 컬렉션을 만들려면 먼저 컬렉션 속성을 정의하는 json 파일이 필요합니다. STAC 컬렉션 개요에 설명된 대로 STAC 컬렉션을 만들 때 일부 속성이 필요합니다. 사용 사례 및 데이터 형식에 따라 다른 속성을 추가할 수 있습니다.

이 자습서에서는 Planetary Computer Pro의 STAC API에서 io-lulc-annual-v02 STAC 컬렉션을 읽어보십시오. GeoCatalog에서 STAC 컬렉션으로 이미 이 데이터를 가지고 있는 경우, 다음 섹션으로 건너뛸 수 있습니다.

import requests

collection = requests.get(
    "https://planetarycomputer.microsoft.com/api/stac/v1/collections/io-lulc-annual-v02"
).json()
collection.pop("assets", None)  # remove unused collection-level assets
collection["id"] = "mpc-quickstart"
collection["title"] += " (Planetary Computer Quickstart)"

컬렉션에 다른 ID를 사용하는 경우 id 필드를 올바른 값으로 바꾸어야 합니다.

탐색기에서 이 컬렉션 내의 데이터 자산을 시각화하려면 컬렉션 메타데이터에 항목 자산 확장이 포함되어야 하며 미디어 형식을 시각화할 수 있는 항목 자산이 하나 이상 있어야 합니다.

액세스 토큰 가져오기

GeoCatalog에 액세스하려면 요청을 인증하기 위한 토큰이 필요합니다. Python용 Azure ID 클라이언트 라이브러리를 사용하여 토큰을 검색합니다.

import azure.identity

credential = azure.identity.DefaultAzureCredential()
token = credential.get_token("https://geocatalog.spatio.azure.com")
headers = {
    "Authorization": f"Bearer {token.token}"
}

이 자격 증명은 GeoCatalog에 대한 요청에서 헤더에 Authorization 전달자 토큰으로 제공할 수 있습니다.

GeoCatalog에 컬렉션 추가

STAC 메타데이터, 토큰 및 GeoCatalog에 대한 URL을 사용하여 STAC API에 컬렉션을 추가하도록 요청합니다.

# Put the URL to your Planetary Computer Pro GeoCatalog (not including '/stac' or a trailing '/' ) here
geocatalog_url = "<your-geocatalog-url>"

response = requests.post(
    f"{geocatalog_url}/stac/collections",
    json=collection,
    headers=headers,
    params={"api-version": "2025-04-30-preview"},
)
print(response.status_code)

상태 코드는 201 컬렉션이 생성되었음을 나타냅니다. 상태 코드는 409 해당 ID가 있는 컬렉션이 이미 있음을 나타냅니다. 기존 컬렉션을 업데이트하는 방법은 컬렉션 업데이트를 참조하세요.

이제 /stac/collections/{collection_id} 엔드포인트에서 이 컬렉션을 읽을 수 있습니다.

geocatalog_collection = requests.get(
    f"{geocatalog_url}/stac/collections/{collection['id']}",
    headers=headers,
    params={"api-version": "2025-04-30-preview"},
).json()

브라우저에서 GeoCatalog를 보고 새 컬렉션을 볼 수도 있습니다.

컬렉션 구성

GeoCatalog의 각 컬렉션에는 STAC 항목 및 해당 데이터 자산이 저장, 인덱싱 및 시각화되는 방법을 제어하는 일부 구성이 포함되어 있습니다. 컬렉션을 구성하려면 다음을 수행합니다.

  1. 컬렉션에 대한 렌더링 구성을 정의합니다. 이 렌더링 구성은 GeoCatalog 탐색기에서 시각화될 때 컬렉션 내의 STAC 항목 자산이 렌더링되는 방식을 제어합니다. 여기서 사용되는 특정 매개 변수는 컬렉션의 자산에 따라 달라집니다.

    import json
    import urllib.parse
    
    colormap = {
        0: (0, 0, 0, 0),
        1: (65, 155, 223, 255),
        2: (57, 125, 73, 255),
        3: (136, 176, 83, 0),
        4: (122, 135, 198, 255),
        5: (228, 150, 53, 255),
        6: (223, 195, 90, 0),
        7: (196, 40, 27, 255),
        8: (165, 155, 143, 255),
        9: (168, 235, 255, 255),
        10: (97, 97, 97, 255),
        11: (227, 226, 195, 255),
    }
    colormap = urllib.parse.urlencode({"colormap": json.dumps(colormap)})
    render_option = {
        "id": "default",
        "name": "Default",
        "description": "Land cover classification using 9 class custom colormap",
        "type": "raster-tile",
        "options": f"assets=data&exitwhenfull=False&skipcovered=False&{colormap}",
        "minZoom": 6,
    }
    
    response = requests.post(
        f"{geocatalog_url}/stac/collections/{collection['id']}/configurations/render-options",
        json=render_option,
        headers=headers,
        params={"api-version": "2025-04-30-preview"}
    )
    print(response.status_code)
    
  2. 컬렉션을 위한 모자이크를 정의하십시오. 모자이크 구성은 항목을 쿼리, 필터링 및 결합하여 GeoCatalog 탐색기에서 데이터의 단일 보기를 만드는 방법을 제어합니다. 다음 샘플 모자이크 구성은 추가 쿼리 매개 변수 또는 필터를 적용하지 않습니다. 따라서 GeoCatalog 탐색기 내에서 이 구성을 선택하면 컬렉션 내의 모든 항목이 표시되고 가장 최근 항목이 먼저 표시됩니다.

    mosaic = {
        "id": "most-recent",
        "name": "Most recent available",
        "description": "Show the most recent available data",
        "cql": [],
    }
    response = requests.post(
        f"{geocatalog_url}/stac/collections/{collection['id']}/configurations/mosaics",
        json=mosaic,
        headers=headers,
        params={"api-version": "2025-04-30-preview"}
    )
    print(response.status_code)
    

    cql 모자이크 구성의 필드는 해당 속성에 따라 항목을 필터링하는 데 사용할 수 있습니다. 예를 들어 STAC 항목이 [eo 확장][eo]을 구현하는 경우 "저층 구름"(흐림이 10% 미만%) 필터를 사용해 정의할 수 있습니다.

    "cql": [{"op": "<=", "args": [{"property": "eo:cloud_cover"}, 10]}]
    
  3. 컬렉션에 대한 타일 설정을 정의합니다. 최소 확대/축소 수준과 같은 항목을 제어합니다.

    tile_settings = {
      "minZoom": 6,
      "maxItemsPerTile": 35,
    }
    requests.put(
        f"{geocatalog_url}/stac/collections/{collection['id']}/configurations/tile-settings",
        json=tile_settings,
        headers=headers,
        params={"api-version": "2025-04-30-preview"}
    )
    

컬렉션 업데이트

기존 컬렉션을 업데이트하려면 PUT 요청을 /stac/collections/{collection_id} 엔드포인트로 보낼 수 있습니다.

collection["description"] += " (Updated)"

response = requests.put(
    f"{geocatalog_url}/stac/collections/{collection['id']}",
    headers={"Authorization": f"Bearer {token.token}"},
    json=collection,
    params={"api-version": "2025-04-30-preview"},
)
print(response.status_code)

상태 코드는 200 컬렉션이 성공적으로 업데이트되었음을 나타냅니다.

자원을 정리하세요

요청을 사용하여 DELETE GeoCatalog에서 컬렉션을 제거할 수 있습니다. 컬렉션을 삭제하면 다음 항목도 삭제됩니다.

  1. 해당 컬렉션의 자식인 모든 STAC 항목입니다.
  2. 해당 항목의 자식인 모든 자산입니다.
  3. 해당 컬렉션의 모든 컬렉션 수준 자산입니다.

컬렉션에 STAC 항목 추가 빠른 시작에서는 이 컬렉션을 사용하므로 해당 빠른 시작을 완료하려는 경우 아직 삭제하지 마세요.

response = requests.delete(
    f"{geocatalog_url}/stac/collections/{collection['id']}",
    headers={"Authorization": f"Bearer {token.token}"},
    params={"api-version": "2025-04-30-preview"}
)
print(response.status_code)

상태 코드는 204 컬렉션이 삭제되었음을 나타냅니다.

경고

컬렉션을 삭제하는 경우 이름/ID가 동일한 새 컬렉션을 만들기 전에 45초 이상 기다려야 합니다. 삭제된 컬렉션과 동일한 이름을 사용하여 새 컬렉션을 만들려고 하면 오류가 발생합니다. 이 오류가 발생하면 45초 대기 후 컬렉션을 다시 만들어 보세요.

다음 단계