python将数组保存至文件,在Python中将数组保存到栅格文件的最简单方法

With one 2-d array in the shape of (100, 100), I want to save it into raster file in .tiff format.

I can use gdal package to read tiff files which are already exist. But I still can't find a simple way to transform the 2-d array into tiff file.

Using plt.imsave("xx.tif",array) or

def array_to_raster(array):

"""Array > Raster

Save a raster from a C order array.

:param array: ndarray

"""

dst_filename = 'xxx.tiff'

x_pixels = 100 # number of pixels in x

y_pixels = 100 # number of pixels in y

driver = gdal.GetDriverByName('GTiff')

dataset = driver.Create(

dst_filename,

x_pixels,

y_pixels,

1,

gdal.GDT_Float32, )

dataset.GetRasterBand(1).WriteArray(array)

dataset.FlushCache() # Write to disk.

return dataset, dataset.GetRasterBand(1)

They all failed to achieve my target. The second method was adapted from here which can transform an array into a geotiff with a projection.

Is there some simple way to save array into .tiff, so I can call it by import the tiff file next time.

Any advices would be appreciate.

解决方案

A tif raster could be considered as 'array+proj+geotransforms'.

If you want to write a array to tif,you can refer to the following code

dst_filename = 'xxx.tiff'

x_pixels = 100 # number of pixels in x

y_pixels = 100 # number of pixels in y

driver = gdal.GetDriverByName('GTiff')

dataset = driver.Create(dst_filename,x_pixels, y_pixels, 1,gdal.GDT_Float32)

dataset.GetRasterBand(1).WriteArray(array)

# follow code is adding GeoTranform and Projection

geotrans=data0.GetGeoTransform() #get GeoTranform from existed 'data0'

proj=data0.GetProjection() #you can get from a exsited tif or import

outds.SetGeoTransform(geotrans)

outds.SetProjection(proj)

outds.FlushCache()

outds=None

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值