import os import rasterio import numpy as np def calculate_cumulative_area(folder_path): total_area = 0.0 for filename in os.listdir(folder_path): if filename.endswith('.tif') or filename.endswith('.tiff'): filepath = os.path.join(folder_path, filename) with rasterio.open(filepath) as src: # Get pixel size (resolution) in meters transform = src.transform pixel_width = transform[0] pixel_height = -transform[4] # Note the negative sign to convert to positive meters # Calculate pixel area in square meters pixel_area_sqm = pixel_width * pixel_height # Read the data and count the valid (non-NaN) pixels data = src.read(1) # Read the first band valid_pixels = np.count_nonzero(~np.isnan(data)) # Calculate the area of valid pixels in square kilometers image_area_sqm = valid_pixels * pixel_area_sqm image_area_sqkm = image_area_sqm / 1e6 # Convert to square kilometers # Add to the total cumulative area total_area += image_area_sqkm return total_area # Example usage: folder_path = 'Downloads/gavl_processed_data/gavl_processed_data/tci/' cumulative_area = calculate_cumulative_area(folder_path) print(f'Total cumulative area: {cumulative_area} sq km')