我使用了
osgeo.gdal
模块将numpy数组保存为GeoTIFF文件,并在python中成功保存一段时间。今天,我决定编写一个简单的模块来处理驱动程序和文件创建例程。调用我的模块以保存numpy数组会出现以下错误:
Traceback (most recent call last):
File "saveRaster.py", line 30, in <module>
save_raster(destination,1,array,srs,gt)
File "saveRaster.py", line 10, in save_raster
dataset_out = driver.Create(path, cols, rows, bands, dtype)
File "/Library/Frameworks/GDAL.framework/Versions/2.1/Python/2.7/site-packages/osgeo/gdal.py", line 1440, in Create
return _gdal.Driver_Create(self, *args, **kwargs)
TypeError: in method 'Driver_Create', argument 5 of type 'int'
这很奇怪,因为参数5是datatype参数,它应该采用gdal数据类型,例如
gdal.GDT_Float32
. 但是,如果它尝试
type(gdal.GDT_Float32)
它返回
<type 'int'>
. 那为什么gdal给我一个
TypeError
如果一个整数应该正好是它所期望的?
我的代码如下:
#! /usr/bin/env python
from osgeo import gdal,osr
import numpy as np
def save_raster(path, band_count, bands, srs, gt, format='GTiff', dtype=gdal.GDT_Float32):
cols,rows = bands.shape
# Initialize driver & create file
driver = gdal.GetDriverByName(format)
dataset_out = driver.Create(path, cols, rows, bands, dtype)
dataset_out.SetGeoTransform(gt)
dataset_out.SetProjection(srs)
# Write the array to raster bands
for b in range(band_count):
out_band = dataset_out.GetRasterBand(b+1)
out_band.WriteArray(bands[b])
# Write file to disk
dataset_out.FlushCache()
gt = [0,1,0,0,0,-1]
srs = osr.SpatialReference()
srs.ImportFromEPSG(epsg)
srs = srs.ExportToWkt()
destination = '~/Desktop/arr.tif'
array = np.arange(0,25).reshape(5,5)
save_raster(destination,1,array,srs,gt)