从字节流加载栅格并设置其CRS



我想做的是:从内存中的s3桶加载栅格并将其CRS设置为4326(它没有CRS设置)

目前为止我有什么:

import boto3
import rasterio
from rasterio.crs import CRS
bucket = 'my bucket'
key = 'my_key'
s3 = boto3.client('s3')
file_byte_string = s3.get_object(Bucket=bucket,Key=key)['Body'].read()
with rasterio.open(BytesIO(file_byte_string), mode='r+') as ds:
crs = CRS({"init": "epsg:4326"}) 
ds.crs = crs

我已经找到了在这里构建代码的方法

设置用光栅读取文件的CRS

如果我给它一个本地文件的路径,它就会工作,但它不适用于字节流。

当我有'+r'模式时,我得到的错误:

rasterio.errors.PathError: invalid path '<_io.BytesIO object at 0x7fb4503ca4d0>'

当我有'r'模式时,我得到的错误:

rasterio.errors.DatasetAttributeError: read-only attribute

是否有办法在r+模式下加载字节流,以便我可以设置/修改CRS?

如果您将字节包装在NamedTemporaryFile中,则可以实现这一点。

import boto3
import rasterio
from rasterio.crs import CRS
import tempfile
bucket = 'asdf'
key = 'asdf'

s3 = boto3.client('s3')
file_byte_string = s3.get_object(Bucket=bucket,Key=key)['Body'].read()
with tempfile.NamedTemporaryFile() as tmpfile:
tmpfile.write(file_byte_string)
with rasterio.open(tmpfile.name, "r+") as ds:
crs = CRS({"init": "epsg:4326"}) 
ds.crs = crs

这种方法的一个重要限制是,您必须将整个文件从S3下载到内存中,而不是像这样远程挂载文件。

最新更新