循环写入多个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
相关产品推荐
相关产品推荐

