You need to enable JavaScript to run this app. 循环写入多个NumPy数组到同一二进制文件仅保留最后数据的解决方法
优惠活动
大模型
产品
解决方案
定价
更多

循环写入多个NumPy数组到同一二进制文件仅保留最后数据的解决方法

问题原因

你当前每次调用ar.astype('uint16').tofile("converted.raw")时,numpy默认采用覆盖写入模式,会清空之前的文件内容再写入当前波段数据,所以最终只保留了最后一次循环的波段内容。

解决方法

方法1:循环追加写入(内存占用低,适合大尺寸影像)

提前删除已存在的目标文件,循环过程中指定tofile的写入模式为追加(mode='ab')即可:

from osgeo import gdal
import numpy as np
import os

# 提前删除旧文件,避免重复运行时内容累加
if os.path.exists("converted.raw"):
    os.remove("converted.raw")

ds = gdal.Open('image.tif')
# 遍历每个波段
for bi in range(ds.RasterCount):
    band = ds.GetRasterBand(bi + 1)
    # 将该波段读取为二维NumPy数组
    ar = band.ReadAsArray()
    print('Band %d has type %s'%(bi + 1, ar.dtype))   
    # 指定追加模式写入二进制文件
    ar.astype('uint16').tofile("converted.raw", mode='ab')

方法2:拼接所有波段后一次性写入(效率更高,适合中小尺寸影像)

先把所有波段的数组按顺序存到列表里,拼接成完整的三维数组后一次性写入文件:

from osgeo import gdal
import numpy as np

ds = gdal.Open('image.tif')
band_list = []
# 遍历每个波段
for bi in range(ds.RasterCount):
    band = ds.GetRasterBand(bi + 1)
    ar = band.ReadAsArray()
    print('Band %d has type %s'%(bi + 1, ar.dtype))   
    band_list.append(ar.astype('uint16'))

# 按波段顺序拼接为三维数组(维度为 [波段数, 行数, 列数])
full_ar = np.stack(band_list, axis=0)
# 一次性写入文件
full_ar.tofile("converted.raw")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 15:24:04