使用Python将ASCII网格文件转换为GeoTIFF?


11

我有一个ASCII网格栅格格式文件。例如:

ncols 480
nrows 450
xllcorner 378923
yllcorner 4072345
cellsize 30
nodata_value -32768
43 2 45 7 3 56 2 5 23 65 34 6 32 54 57 34 2 2 54 6 
35 45 65 34 2 6 78 4 2 6 89 3 2 7 45 23 5 8 4 1 62 ...

如何使用Python将其转换为TIFF或任何其他栅格?


GIS软件可以将asci转换为geotiff。无需编码。我使用QGIS。免费。
Saul Sheard

Answers:


13

伪代码版本:

import gdal
import numpy

create the gdal output file as geotiff
set the no data value
set the geotransform 

numpy.genfromtxt('your file', numpy.int8) #looks like int from you example
reshape your array to the shape you need

write out the array.

一个可以帮助您的示例- 从这里开始

if __name__ == '__main__':
    # Import libs
    import numpy, os
    from osgeo import osr, gdal

    # Set file vars
    output_file = "out.tif"

    # Create gtif
    driver = gdal.GetDriverByName("GTiff")
    dst_ds = driver.Create(output_file, 174, 115, 1, gdal.GDT_Byte )
    raster = numpy.zeros( (174, 115) )

    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    dst_ds.SetGeoTransform( [ 14.97, 0.11, 0, -34.54, 0, 0.11 ] )

    # set the reference info 
    srs = osr.SpatialReference()
    srs.SetWellKnownGeogCS("WGS84")
    dst_ds.SetProjection( srs.ExportToWkt() )

    # write the band
    dst_ds.GetRasterBand(1).WriteArray(raster)

而值14.97和-34.54是WGS84坐标的左上角坐标?
斯拉瓦(Slava),2015年


7

创建副本可能会更容易,因为您的文件是AAIGrid且GTiff支持CreateCopy():

from osgeo import gdal, osr
drv = gdal.GetDriverByName('GTiff')
ds_in = gdal.Open('in.asc')
ds_out = drv.CreateCopy('out.tif', ds_in)
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
ds_out.SetProjection(srs.ExportToWkt())
ds_in = None
ds_out = None

任何支持CreateCopy的驱动程序都可以使用它。


如果您不需要使用python,那么bananafish绝对是正确的。

太好了,谢谢!我的输入.asc文件没有CRS。有没有办法在写入栅格之前指定此CRS(GCS WGS 84)?
RutgerH

使用SetProjection和一个字符串。您可以从osr获取字符串。参见答案编辑。
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.