簡體   English   中英

在循環中將所有 numpy arrays 寫入二進制文件

[英]Write all numpy arrays to binary file in a loop

我有這個代碼:

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")

結果,我得到了 convert.raw 文件,但它只包含來自 for 循環最后一次迭代的數據。 如何制作一個包含所有迭代數據的文件。

使用np.save

前任:

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'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM