Python 在循环中将所有numpy数组写入二进制文件
我有以下代码:Python 在循环中将所有numpy数组写入二进制文件,python,numpy,Python,Numpy,我有以下代码: from osgeo import gdal import numpy as np ds = gdal.Open('image.tif') # loop through each band for bi in range(ds.RasterCount): band = ds.GetRasterBand(bi + 1) # Read this band into a 2D NumPy array ar = band.ReadAsArray() p
from osgeo import gdal
import numpy as np
ds = gdal.Open('image.tif')
# loop through each band
for bi in range(ds.RasterCount):
band = ds.GetRasterBand(bi + 1)
# Read this band into a 2D NumPy array
ar = band.ReadAsArray()
print('Band %d has type %s'%(bi + 1, ar.dtype))
ar.astype('uint16').tofile("converted.raw")
结果,我得到了转换后的.raw文件,但它只包含来自for循环最后一次迭代的数据。如何制作一个包含所有迭代数据的文件。使用
np.save
Ex:
ds = gdal.Open('image.tif')
# loop through each band
with open("converted.raw", "wb") as outfile:
for bi in range(ds.RasterCount):
band = ds.GetRasterBand(bi + 1)
# Read this band into a 2D NumPy array
ar = band.ReadAsArray()
print('Band %d has type %s'%(bi + 1, ar.dtype))
np.save(outfile, ar.astype('uint16'))
几乎。它正在将128字节的numpy头写入文件。(重新)读取
tofile
docs。您给它一个文件名,这样它每次都会生成一个新文件。您可以给它一个fid
,一个已经打开的文件。