11

I have a ascii raster format file. For example:

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 ...

How can I convert it to tiff or any other raster using Python?

  • GIS software can convert asci to geotiff. No coding necessary. I use QGIS. Its free. – Saul Sheard Mar 6 '18 at 19:17
13

The pseudo code version:

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.

A sample that will help you along - from here:

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)
  • and the values 14.97 and -34.54 are the top-left corner coordinates in WGS84 cooridanates? – Slava Oct 15 '15 at 13:51
9

Alternative using gdal_translate:

gdal_translate -of "GTiff" fname.asc outname.tif
6

It may be easier to do a create copy, as your file is an AAIGrid and GTiff supports 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

Any driver that supports CreateCopy can use this.

  • If you don't need to use python, bananafish is definitely right. – user10353 Jul 21 '13 at 20:37
  • amazing, thanks! My input .asc file does come without a CRS. Is there a way to specify this CRS (GCS WGS 84) before writing the raster? – RutgerH Jun 6 '16 at 21:20
  • use SetProjection and a string. You can get the string from osr. See answer edit. – user10353 Jun 7 '16 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.