简体   繁体   中英

Write all numpy arrays to binary file in a loop

I have this code:

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

As a result, I get the converted.raw file, but it only contains data from the last iteration of the for loop. How to make a file that will contain data from all iterations together.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM