Skip to content

Instantly share code, notes, and snippets.

@nmathewa
Created March 4, 2021 15:14
Show Gist options
  • Save nmathewa/5cca19cce23f88a85d2e9d628fb2465b to your computer and use it in GitHub Desktop.
Save nmathewa/5cca19cce23f88a85d2e9d628fb2465b to your computer and use it in GitHub Desktop.
gdal_numpy_calc
"""
Created on Thu Mar 4 19:14:00 2021
@author: nma
"""
from osgeo import gdal,gdal_array,gdalconst,osr
import numpy as np
raster_f = "A_raster_file.tif"
raster_s = "B_raster_file.tif"
out_ = "outfile.tif"
ref_ras = gdal.Open(raster_f)
array_f = gdal_array.LoadFile(raster_f)
array_s= gdal_array.LoadFile(raster_s)
[cols, rows] = array_f.shape
r_array = array_f + array_s # addition
driver = gdal.GetDriverByName("GTiff")
out_ras = driver.Create(out_,rows,cols,1,gdal.GDT_Float64)
refe_trnas = ref_ras.GetGeoTransform()
out_ras.SetProjection(ref_ras.GetProjection())
out_ras.SetGeoTransform(refe_trnas)
srs = osr.SpatialReference()
out_ras.GetRasterBand(1).WriteArray(r_array)
out_ras.FlushCache() ##saves to disk!!
out_ras = None
band=None
ds_rs=None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment