I have downloaded a matching set of before and after insect invasion raster images from Google Earth Engine. I now want to loop through these images selecting the matching before and after invasion image and then calculating the difference between these sets of images.

How can I write a loop through this list selecting an after and before image to calculate the difference? The list has more than 300 sets of before and after rasters. I have tried writing a for loop function using rasterio but was stuck.

The code that I am working on is;

import geopandas as gpd
import pandas as pd
import folium 
import rasterio
from rasterio import plot
from rasterio.plot import show
import matplotlib.pyplot as plt
%matplotlib inline

import os
data_pkg_path = 'DATA_ANALYSIS'
filename = 'Before_After_Image_Composites'
composites = os.listdir(filename) 

Sample of the list I get when I print the composites;

['point_306_after_2020-07-07.tif', 'point_306_before_2020-07-07.tif', 'point_307_after_2020-07-12.tif', 'point_307_before_2020-07-12.tif', 'point_308_after_2020-07-01.tif', 'point_308_before_2020-07-01.tif']

1 Answer 1


Assuming your comparison is for the following pairs:

'point_306_after_2020-07-07.tif', 'point_306_before_2020-07-07.tif', 
'point_307_after_2020-07-12.tif', 'point_307_before_2020-07-12.tif', 
'point_308_after_2020-07-01.tif', 'point_308_before_2020-07-01.tif'

All you need to do is find the files with the relevant wildcard (say the after files), find the equivalent "before" file, read both and subtract:

from pathlib import Path
from osgeo import gdal
differences = {}
for after_file in Path("DATA_ANALYSIS").glob("point_*_after_*.tif"):
    s2 = after_file.as_posix()
    s1 = after.replace("_after_", "_before_")
    if not (Path("DATA_ANALYSIS")/s1).exists():
       print(f"Cannot find before file for {after_file}")
    output = after_file.name.replace("_after_", "_difference_")
    differences[output] = (gdal.Open(s2).ReadAsArray() -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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