File size: 5,884 Bytes
2839e12 1908732 2839e12 1908732 2839e12 1908732 2839e12 1908732 2839e12 1908732 2839e12 1908732 2839e12 1908732 2839e12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | import os
import rasterio
import matplotlib.pyplot as plt
import numpy as np
USED_BANDS = (1,2,3,8,11,12)
def check_ground_truth(gt_file):
with rasterio.open(gt_file) as src:
mask = src.read()
print(f"\n{'='*80}")
print(f"File: {os.path.basename(gt_file)}")
print(f"{'='*80}")
print(f"Shape: {mask.shape}")
print(f"Dtype: {mask.dtype}")
print(f"Number of bands: {mask.shape[0] if len(mask.shape) == 3 else 1}")
if len(mask.shape) == 3 and mask.shape[0] > 1:
print(f"\n{'='*80}")
print(f"PER-BAND ANALYSIS:")
print(f"{'='*80}")
for i in range(mask.shape[0]):
band_data = mask[i]
unique, counts = np.unique(band_data, return_counts=True)
print(f"\nBand {i}:")
print(f" Unique values: {unique}")
print(f" Value distribution:")
for val, count in zip(unique, counts):
percentage = (count / band_data.size) * 100
print(f" {val:>5}: {count:>10} pixels ({percentage:>6.2f}%)")
else:
print(f"\n{'='*80}")
print(f"VALUE DISTRIBUTION:")
print(f"{'='*80}")
unique, counts = np.unique(mask, return_counts=True)
print(f"Unique values: {unique}")
for val, count in zip(unique, counts):
percentage = (count / mask.size) * 100
print(f" {val:>5}: {count:>10} pixels ({percentage:>6.2f}%)")
return mask
def visualize_ground_truth(gt_file):
with rasterio.open(gt_file) as src:
mask = src.read()
if len(mask.shape) == 3 and mask.shape[0] > 1:
num_bands = mask.shape[0]
fig, axes = plt.subplots(1, num_bands, figsize=(6*num_bands, 5))
if num_bands == 1:
axes = [axes]
for i in range(num_bands):
im = axes[i].imshow(mask[i], cmap='viridis')
axes[i].set_title(f'Band {i}\nUnique: {np.unique(mask[i])}')
axes[i].axis('off')
plt.colorbar(im, ax=axes[i])
else:
fig, ax = plt.subplots(figsize=(10, 8))
im = ax.imshow(mask.squeeze(), cmap='viridis')
ax.set_title(f'Ground Truth\nUnique values: {np.unique(mask)}')
ax.axis('off')
plt.colorbar(im, ax=ax)
plt.suptitle(os.path.basename(gt_file), fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()
def get_category(use: str, data_root: str):
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:] # Extract "01", "02", etc.
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
SATELLITE_MAP = {
"tif01_s2": "pleiades",
"tif02_s2": "planet",
"tif03_s2": "planet",
"tif05_s2": "sentinel2",
"tif07_s2": "planet",
}
def plot_all_gt_with_labels():
gt_dict = get_category(use='s2', data_root='./datasets/Timor_ML4FLood')
for key, file_list in gt_dict.items():
satellite_key = key.replace('_gt', '_s2')
satellite = SATELLITE_MAP.get(satellite_key, "unknown")
print(f"\n{'='*80}")
print(f"Processing: {key} (Satellite: {satellite})")
print(f"Number of files: {len(file_list)}")
print(f"{'='*80}")
for i, gt_file in enumerate(file_list):
if not os.path.exists(gt_file):
print(f" File {i+1}/{len(file_list)}: {os.path.basename(gt_file)} - NOT FOUND")
continue
print(f" File {i+1}/{len(file_list)}: {os.path.basename(gt_file)}")
mask = check_ground_truth(gt_file)
with rasterio.open(gt_file) as src:
mask = src.read()
if len(mask.shape) == 3 and mask.shape[0] > 1:
num_bands = mask.shape[0]
fig, axes = plt.subplots(1, num_bands, figsize=(6*num_bands, 5))
if num_bands == 1:
axes = [axes]
for j in range(num_bands):
im = axes[j].imshow(mask[j], cmap='viridis')
axes[j].set_title(f'Band {j}\nUnique: {np.unique(mask[j])}')
axes[j].axis('off')
plt.colorbar(im, ax=axes[j])
else:
fig, ax = plt.subplots(figsize=(10, 8))
im = ax.imshow(mask.squeeze(), cmap='viridis')
ax.set_title(f'Ground Truth\nUnique values: {np.unique(mask)}')
ax.axis('off')
plt.colorbar(im, ax=ax)
plt.suptitle(f"{os.path.basename(gt_file)}\nSatellite: {satellite}",
fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()
plot_all_gt_with_labels()
|