Creating and modifying rasters

Parameters used to create or copy rasters:

from girs.rast.raster import RasterReader
r = RasterReader('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
rp = r.get_parameters()
print rp.RasterXSize, rp.RasterYSize
print rp.number_of_bands
print rp.data_types
print rp.geo_trans
print rp.nodata
print rp.srs

Copy

from girs.rast.raster import RasterReader, copy
r = RasterReader('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
# 1)  Using the function from file to file
copy('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif', 'D:/tmp/chirps-v2.0.2016.01.10.tif')
r = RasterReader('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
# 2) Using the function from object to file
copy(r, 'D:/tmp/chirps-v2.0.2016.01.10.tif')
# 3) Using the method
r.copy('D:/tmp/chirps-v2.0.2016.01.10.tif')
# 4) Get a RAM copy
r_mem = copy(r, '')
print r_mem.get_parameters()
# DIM[17, 13] NB[1] ND[-9999.0] DT[6] DRV[GTiff] SRS[WGS 84]
# TRANS(-47.25, 0.25, 0.0, -18.0,... 0.0, -0.25)

Modify

RasterReader has not method to change data, although gdal dataset allows data editing also in read-only modus (without saving changes on disk). To change data, use RasterModifier or RasterWriter.

from girs.rast.raster import RasterReader, RasterUpdate
r = RasterUpdate('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
nodata = r.get_nodata()
print 1, r.get_nodata()  # check data
r.set_nodata(-8888.0)  # nodata = -8888.0, saved on disk

r = RasterReader('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
print 2, r.get_nodata()  # check

r = RasterUpdate('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
r.set_nodata(nodata)  # rollback

r = RasterReader('D:/tmp/girs/chirps_basin/chirps-v2.0.2016.01.10.tif')
print 3, r.get_nodata()  # check

Outputs:

1 [-9999.0]
2 [-8888.0]
3 [-9999.0]

Write

import numpy as np
import gdal
from girs.rast.parameter import RasterParameters
from girs.rast.raster import RasterWriter
from girs.srs import srs_from_epsg
columns, rows = 17, 13
geotransformation = (-47.25, 0.25, 0.0, -18.0, 0.0, -0.25)
srs = srs_from_epsg(4326).ExportToWkt()
number_of_bands = 1
nodata = 127
data_types = gdal.GDT_Byte
driver_short_name = 'GTiff'
raster_parameters = RasterParameters(columns, rows, geotransformation, srs,
                                     number_of_bands, nodata, data_types, driver_short_name)
r = RasterWriter(raster_parameters, source='D:/tmp/girs/write_example.tif')
r.set_array(np.random.randint(128, size=(rows, columns)))
r.show()
../_images/rasterwriter2.jpg