Sunday 29 April 2018

Raster reclassify using python, gdal and numpy


I would like to reclassify a raster file from a raster with 10 classes to a raster with 8 classes using pyhton, gdal and/or numpy. The classes are represented as integers. I have tried following the steps from this post Reclassify rasters using GDAL and Python , the numpy.equal doc and also gdal_calc doc. However, to no avail.


The raster file to be reclassified has integer values ranging from 0 to 11 and also include values 100 and 255. The following show the reclass (from value : to value):


nodata : 4, 0 : 4, 1 : 1, 2 : 2, 3 : 3, 4 : 3, 5 : 4, 6 : 5, 7 : 5, 8 : 6, 9 : 7, 10 : 8, 100 : nodata, 255 : nodata,


What I have been able to do is select the raster file to be reclassified using tkinter.FileDialog and get the raster info such as geotransform, and pixel size with reclass = gdal.Open(raster, GA_ReadOnly).


How do I go about solving the above.


It might be worth mentioning that the rasters to be reclassified can be fairly large in some cases (500mb to 5gb).



Answer




Here you have a simple python script for reclassification, I wrote it and it works for me:


from osgeo import gdal

driver = gdal.GetDriverByName('GTiff')
file = gdal.Open('/home/user/workspace/raster.tif')
band = file.GetRasterBand(1)
lista = band.ReadAsArray()

# reclassification
for j in range(file.RasterXSize):

for i in range(file.RasterYSize):
if lista[i,j] < 200:
lista[i,j] = 1
elif 200 < lista[i,j] < 400:
lista[i,j] = 2
elif 400 < lista[i,j] < 600:
lista[i,j] = 3
elif 600 < lista[i,j] < 800:
lista[i,j] = 4
else:

lista[i,j] = 5

# create new file
file2 = driver.Create( 'raster2.tif', file.RasterXSize , file.RasterYSize , 1)
file2.GetRasterBand(1).WriteArray(lista)

# spatial ref system
proj = file.GetProjection()
georef = file.GetGeoTransform()
file2.SetProjection(proj)

file2.SetGeoTransform(georef)
file2.FlushCache()

Just change the ranges.


I hope it will help.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...