Timor_ML4FLood / sen2_statistics.py
azzenn4's picture
update
e24a1f4
import os
import rasterio
import numpy as np
from tqdm import tqdm
USED_BANDS = (1, 2, 3, 8, 11, 12)
def get_category(use: str, data_root: str):
"""Get file paths for specified data type"""
if use == 'gt':
data_dir = f"{data_root}/GT"
elif use == 's2':
data_dir = f"{data_root}/S2"
else:
raise ValueError(f"Invalid use type: {use}. Must be 'gt' or 's2'")
aoi_configs = [
("AOI01", "DEL", "pleiades"),
("AOI02", "DEL", "planet"),
("AOI03", "DEL", "planet"),
("AOI05", "DEL", "sentinel2"),
("AOI07", "GRA", "planet"),
]
def read_include(path: str) -> list[str]:
if not os.path.exists(path):
return []
with open(path, 'r') as file:
return [line.strip() for line in file if line.strip()]
result = {}
for aoi_id, product_type, satellite in aoi_configs:
aoi_num = aoi_id[-2:]
aoi_dir = f"{data_dir}/EMSR507_{aoi_id}_{product_type}_PRODUCT"
include_path = f"{aoi_dir}/include.txt"
include_items = read_include(include_path)
tif_files = [
f"{aoi_dir}/EMSR507_{aoi_id}_{product_type}_PRODUCT_{item}.tif"
for item in include_items
]
key = f"tif{aoi_num}_{'gt' if use == 'gt' else 's2'}"
result[key] = tif_files
return result
def calculate_s2_statistics(data_root: str, used_bands=USED_BANDS):
print("Getting S2 file paths...")
s2_dict = get_category(use='s2', data_root=data_root)
all_files = []
for key, file_list in s2_dict.items():
all_files.extend(file_list)
all_files = [f for f in all_files if os.path.exists(f)]
band_indices = [b - 1 for b in used_bands]
num_bands = len(band_indices)
count = 0
mean = np.zeros(num_bands, dtype=np.float64)
m2 = np.zeros(num_bands, dtype=np.float64)
min_vals = np.full(num_bands, np.inf, dtype=np.float64)
max_vals = np.full(num_bands, -np.inf, dtype=np.float64)
for file_path in tqdm(all_files, desc="Computing statistics"):
try:
with rasterio.open(file_path) as src:
data = src.read()
if data.shape[0] < max(used_bands):
print(f"\nWarning: {os.path.basename(file_path)} has only {data.shape[0]} bands, skipping...")
continue
selected_bands = data[band_indices, :, :]
num_pixels = selected_bands.shape[1] * selected_bands.shape[2]
pixels = selected_bands.reshape(num_bands, -1)
for i in range(num_pixels):
pixel_values = pixels[:, i]
if np.any(np.isnan(pixel_values)) or np.any(np.isinf(pixel_values)):
continue
count += 1
delta = pixel_values - mean
mean += delta / count
delta2 = pixel_values - mean
m2 += delta * delta2
min_vals = np.minimum(min_vals, pixel_values)
max_vals = np.maximum(max_vals, pixel_values)
except Exception as e:
print(f"\nError processing {os.path.basename(file_path)}: {e}")
continue
if count == 0:
raise ValueError("No valid pixels found in dataset!")
variance = m2 / count
std = np.sqrt(variance)
mean_normalized = (mean - min_vals) / (max_vals - min_vals)
std_normalized = std / (max_vals - min_vals)
print("\nFormatted for code:")
print(f"MEANS = [{', '.join([f'{m:.8f}' for m in mean_normalized])}]")
print(f"STDS = [{', '.join([f'{s:.8f}' for s in std_normalized])}]")
return mean_normalized.tolist(), std_normalized.tolist()
if __name__ == "__main__":
data_root = "./datasets/Timor_ML4FLood"
means, stds = calculate_s2_statistics(data_root)