簡體   English   中英

指示亞馬遜 S3 上的目錄

[英]Indicate a directory on Amazon's S3

我是 AWS 服務的新手。 我一直使用下面的代碼來計算位於目錄中的圖像的 NDVI。

path = r'images'
dirContents = os.listdir(path)

for file in dirContents:
    if os.path.isdir(file):
        subDir = os.listdir(file)
        
        # Assuming only two files in each subdirectory, bands 4 and 8 here
        if "B04" in subDir[0]:
            band4 = rasterio.open(subDir[0])
            band8 = rasterio.open(subDir[1])
        else:
            band4 = rasterio.open(subDir[1])
            band8 = rasterio.open(subDir[0])

        red = band4.read(1).astype('float32')
        nir = band8.read(1).astype('float32')

        #compute the ndvi
        ndvi = (NIR.astype(float) - RED.astype(float)) / (NIR+RED)

        profile = red.meta
        profile.update(driver='GTiff')
        profile.update(dtype=rasterio.float32)

        with rasterio.open(outfile, 'w', **profile) as dst:
            dst.write(ndvi.astype(rasterio.float32))

現在所有必要的圖像都在 amazon S3 文件夾中。 如何替換下面的行?

 path = r'images' dirContents = os.listdir(path)

Amazon S3 不是文件系統。 您將需要使用不同的命令來:

  • 列出存儲桶/路徑的內容
  • 將文件下載到本地存儲
  • 然后訪問本地存儲上的文件

您可以使用boto3 AWS SDK for Python 來訪問存儲在 S3 中的對象。

例如:

import boto3

s3_resource = boto3.resource('s3')

# List objects
objects = s3_resource.Bucket('your-bucket').objects.Filter(Prefix='images/')

# Loop through each object
for object in objects:
  s3_resource.Object(object.bucket_name, object.key).download_file('local_filename')
  # Do something with the file here

如果您是 AWS 新手,您還可以考慮使用libcloud庫。 這是一個庫,允許您使用具有統一 API 的不同雲解決方案。 對於您可以執行的存儲解決方案(來自此處的代碼):

from libcloud.storage.types import Provider
from libcloud.storage.providers import get_driver

client = driver(StoreProvider.S3)
s3 = client(aws_id, aws_secret)

container = s3.get_container(container_name='name')
objects = s3.list_container_objects(container, prefix='path')

# Download a file
s3.download_object(objects[0], '/path/to/download')

需要注意的一些事項:

  • 文件存儲在 S3 存儲桶(容器)中。 盡管存儲桶具有平面層次結構,但您可以使用諸如“路徑/子路徑/文件 1”之類的鍵名來組織文件夾中的文件。
  • 您需要驗證對存儲桶的訪問權限。 在上面的代碼中,您通過提供一個 id 和一個秘密來做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM