【问题标题】:Indicate a directory on Amazon's S3指示亚马逊 S3 上的目录
【发布时间】:2022-01-14 15:41:00
【问题描述】:

我是 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)

【问题讨论】:

    标签: python amazon-web-services amazon-s3


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      如果您是 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 和一个秘密来做到这一点。

      【讨论】:

        猜你喜欢
        • 2011-12-05
        • 1970-01-01
        • 1970-01-01
        • 2013-10-29
        • 2012-03-30
        • 1970-01-01
        • 2010-10-20
        • 2012-05-01
        • 2018-02-10
        相关资源
        最近更新 更多