I'm beginner to python. Each directory has two rasters named A.tiff and B.tiff. I need to subtract B.tiff from A.tiff and store the resultant file in the same directory. The directory paths are named by their date of creation(ex: /home/hash/images/20210121T123308/*A.tiff"). In a similar way I have directories created for each week from January with files A and B. Below is my example code to fetch A and B's path

import glob
A_path = glob.glob("/home/hash/images/**/*A.tiff", recursive = True)
B_path= glob.glob(("/home/hash/images/**/*B.tiff", recursive = True)

Note: Both the file's metadata are same.

  • You should find this answer useful for doing it with gdal gis.stackexchange.com/a/285685/72647 Once you have your A and B as arrays, it is simple as A-B for the calculation. This answer will show you how to open and save as tiffs that have projection info of original.
    – Beardsley
    Apr 22 at 5:48

Here is an example: https://www.earthdatascience.org/courses/use-data-open-source-python/intro-raster-data-python/raster-data-processing/subtract-rasters-in-python/

If they have the same CRS/resolution/boundary:

import rioxarray
lidar_dem_xr = rxr.open_rasterio(lidar_dem_path, masked=True).squeeze()
lidar_dsm_xr = rxr.open_rasterio(lidar_dsm_path, masked=True).squeeze()
lidar_chm_xr = lidar_dsm_xr - lidar_dem_xr

Otherwise, you may need to use rio.reproject_match: https://corteva.github.io/rioxarray/stable/examples/reproject_match.html

If you use reproject match, you may need to use assign_coords to make the coordinates the exact same: https://github.com/corteva/rioxarray/issues/298#issuecomment-820559379

Here is an example of raster calculations using reproject match: https://carpentries-incubator.github.io/geospatial-python/07-raster-calculations/index.html

  • Hi , I have tried doing it but my kernel is getting restarted (dying ) always when it's trying to perform that calculation. Apr 22 at 8:41
  • Are you able to run the calculation using python without a Jupiter notebook?
    – snowman2
    Apr 22 at 12:45
  • My raster files have zero values, willthat cause an issue? Apr 22 at 14:29
  • That shouldn't cause an issue. How is your memory in the computer? Are the rasters large?
    – snowman2
    Apr 22 at 14:33
  • What is the size of your RAM (memory)?
    – snowman2
    Apr 22 at 14:40

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.