在Python中将数组保存到栅格文件的最简单方法 [英] Simplest way to save array into raster file in Python

查看:1142
本文介绍了在Python中将数组保存到栅格文件的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个二维数组,其形状为(100,100),我想将其保存为.tiff格式的栅格文件.

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

我可以使用gdal包读取已经存在的tiff文件.但是我仍然找不到将二维数组转换为tiff文件的简单方法.

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.

使用plt.imsave("xx.tif",array)

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)  

他们都未能实现我的目标.第二种方法改编自此处可以将数组转换为带有投影的geotiff.

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.

是否有一些简单的方法可以将数组保存到.tiff中,因此下次可以通过导入tiff文件来调用它.

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

任何建议将不胜感激.

推荐答案

tif栅格可被视为"array + proj + geotransforms". 如果要向tif写一个数组,可以参考下面的代码

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

这篇关于在Python中将数组保存到栅格文件的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆