You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何加载S3内存中的栅格字节流并设置其CRS为EPSG:4326

解决方案

错误原因

  • rasterio的r+修改模式仅支持本地磁盘文件,无法识别内存BytesIO对象作为可修改路径,因此触发PathError
  • 只读r模式下所有数据集属性均为锁定状态,无法直接修改crs字段,因此触发只读属性报错

正确实现方式

无需尝试用r+模式加载内存流,可通过复制元数据并新建内存数据集的方式实现CRS设置,完整可运行代码如下:

import boto3
import rasterio
from rasterio.crs import CRS
from io import BytesIO

bucket = 'my_bucket'
key = 'my_key'
s3 = boto3.client('s3')
# 从S3读取栅格字节流
file_byte_string = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

# 只读模式打开原始内存栅格
with rasterio.open(BytesIO(file_byte_string), mode='r') as src_ds:
    # 复制原始栅格的所有元数据
    profile = src_ds.profile
    # 更新元数据中的CRS为EPSG:4326,替换旧的{"init": "epsg:4326"}写法避免警告
    profile.update(crs=CRS.from_epsg(4326))
    
    # 新建内存字节流存储修改后带CRS的栅格
    dst_byte_stream = BytesIO()
    with rasterio.open(dst_byte_stream, 'w', **profile) as dst_ds:
        # 写入原始栅格的全波段数据
        dst_ds.write(src_ds.read())
    
    # 字节流指针复位到起始位置,后续可直接用于读取或上传
    dst_byte_stream.seek(0)

后续使用说明

如果需要操作修改后的栅格,直接读取dst_byte_stream即可:

with rasterio.open(dst_byte_stream) as ds:
    print(ds.crs) # 输出EPSG:4326
    # 后续其他操作

如果需要将修改后的栅格写回S3,直接读取dst_byte_stream.getvalue()作为上传内容即可。


内容的提问来源于stack exchange,提问作者GStav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 02:54:02